1 package net.sourceforge.phpeclipse.phpeditor;
3 import java.text.MessageFormat;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.Iterator;
10 import net.sourceforge.phpdt.core.ICompilationUnit;
11 import net.sourceforge.phpdt.core.IJavaElement;
12 import net.sourceforge.phpdt.core.IJavaProject;
13 import net.sourceforge.phpdt.core.IMember;
14 import net.sourceforge.phpdt.core.ISourceRange;
15 import net.sourceforge.phpdt.core.ISourceReference;
16 import net.sourceforge.phpdt.core.JavaCore;
17 import net.sourceforge.phpdt.core.JavaModelException;
18 import net.sourceforge.phpdt.core.dom.CompilationUnit;
19 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
20 import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility;
21 import net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction;
22 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
23 import net.sourceforge.phpdt.internal.ui.actions.IndentAction;
24 import net.sourceforge.phpdt.internal.ui.actions.RemoveBlockCommentAction;
25 import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference;
26 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
27 import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner;
28 import net.sourceforge.phpdt.internal.ui.text.JavaIndenter;
29 //import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
30 import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager;
31 import net.sourceforge.phpdt.internal.ui.text.SmartSemicolonAutoEditStrategy;
32 import net.sourceforge.phpdt.internal.ui.text.comment.CommentFormattingContext;
33 import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener;
34 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager;
35 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI;
36 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
37 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
38 import net.sourceforge.phpdt.ui.PreferenceConstants;
39 import net.sourceforge.phpdt.ui.actions.GenerateActionGroup;
40 //import net.sourceforge.phpdt.ui.text.JavaTextTools;
41 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
42 import net.sourceforge.phpeclipse.phpeditor.actions.RTrimAction;
43 import net.sourceforge.phpeclipse.ui.WebUI;
44 import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction;
46 import org.eclipse.core.resources.IFile;
47 import org.eclipse.core.resources.IWorkspaceRoot;
48 import org.eclipse.core.resources.ResourcesPlugin;
49 import org.eclipse.core.runtime.CoreException;
50 import org.eclipse.core.runtime.IPath;
51 import org.eclipse.core.runtime.IProgressMonitor;
52 import org.eclipse.core.runtime.IStatus;
53 import org.eclipse.core.runtime.Preferences;
54 import org.eclipse.jface.action.Action;
55 import org.eclipse.jface.action.IAction;
56 import org.eclipse.jface.action.IMenuManager;
57 import org.eclipse.jface.dialogs.ErrorDialog;
58 import org.eclipse.jface.dialogs.IMessageProvider;
59 import org.eclipse.jface.dialogs.MessageDialog;
60 import org.eclipse.jface.preference.IPreferenceStore;
61 //import org.eclipse.jface.preference.PreferenceConverter;
62 import org.eclipse.jface.text.BadLocationException;
63 import org.eclipse.jface.text.DocumentCommand;
64 import org.eclipse.jface.text.IAutoEditStrategy;
65 import org.eclipse.jface.text.IDocument;
66 import org.eclipse.jface.text.ILineTracker;
67 import org.eclipse.jface.text.IRegion;
68 import org.eclipse.jface.text.ITextOperationTarget;
69 import org.eclipse.jface.text.ITextViewerExtension;
70 import org.eclipse.jface.text.ITypedRegion;
71 import org.eclipse.jface.text.IWidgetTokenKeeper;
72 import org.eclipse.jface.text.contentassist.ContentAssistant;
73 import org.eclipse.jface.text.contentassist.IContentAssistant;
74 import org.eclipse.jface.text.formatter.FormattingContextProperties;
75 import org.eclipse.jface.text.formatter.IFormattingContext;
76 import org.eclipse.jface.text.source.IOverviewRuler;
77 import org.eclipse.jface.text.source.ISourceViewer;
78 import org.eclipse.jface.text.source.IVerticalRuler;
79 import org.eclipse.jface.text.source.SourceViewerConfiguration;
81 //import org.eclipse.jface.util.ListenerList;
82 import org.eclipse.core.runtime.ListenerList;
83 import org.eclipse.jface.util.PropertyChangeEvent;
84 import org.eclipse.jface.window.Window;
85 import org.eclipse.swt.SWT;
86 import org.eclipse.swt.custom.VerifyKeyListener;
87 import org.eclipse.swt.events.VerifyEvent;
88 import org.eclipse.swt.graphics.Color;
89 import org.eclipse.swt.graphics.Point;
90 //import org.eclipse.swt.graphics.RGB;
91 import org.eclipse.swt.widgets.Composite;
92 import org.eclipse.swt.widgets.Display;
93 import org.eclipse.swt.widgets.Shell;
94 import org.eclipse.ui.IEditorInput;
95 import org.eclipse.ui.IEditorPart;
96 import org.eclipse.ui.IFileEditorInput;
97 import org.eclipse.ui.IWorkbenchPage;
98 import org.eclipse.ui.IWorkbenchWindow;
99 import org.eclipse.ui.PlatformUI;
100 import org.eclipse.ui.actions.ActionContext;
101 import org.eclipse.ui.actions.ActionGroup;
102 import org.eclipse.ui.dialogs.SaveAsDialog;
103 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
104 import org.eclipse.ui.part.FileEditorInput;
105 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
106 import org.eclipse.ui.texteditor.ContentAssistAction;
107 import org.eclipse.ui.texteditor.IDocumentProvider;
108 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
109 import org.eclipse.ui.texteditor.TextOperationAction;
111 /*******************************************************************************
112 * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
113 * program and the accompanying materials are made available under the terms of
114 * the Common Public License v1.0 which accompanies this distribution, and is
115 * available at http://www.eclipse.org/legal/cpl-v10.html
117 * Contributors: IBM Corporation - Initial implementation
119 ******************************************************************************/
121 * PHP specific text editor.
123 public class PHPUnitEditor extends PHPEditor { // implements
124 // IJavaReconcilingListener {
125 interface ITextConverter {
126 void customizeDocumentCommand(IDocument document,
127 DocumentCommand command);
130 // class AdaptedSourceViewer extends JavaSourceViewer {
131 // private List fTextConverters;
133 // private boolean fIgnoreTextConverters = false;
135 // // private JavaCorrectionAssistant fCorrectionAssistant;
136 // public AdaptedSourceViewer(Composite parent, IVerticalRuler
138 // IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
139 // int styles, IPreferenceStore store) {
140 // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
144 // // public AdaptedSourceViewer(Composite parent,
145 // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
146 // // boolean showAnnotationsOverview, int styles) {
147 // // super(parent, verticalRuler, overviewRuler,
148 // // showAnnotationsOverview, styles);
150 // public IContentAssistant getContentAssistant() {
151 // return fContentAssistant;
155 // * @see ITextOperationTarget#doOperation(int)
157 // public void doOperation(int operation) {
158 // if (getTextWidget() == null)
160 // switch (operation) {
161 // case CONTENTASSIST_PROPOSALS:
162 // String msg = fContentAssistant.showPossibleCompletions();
163 // setStatusLineErrorMessage(msg);
165 // // case CORRECTIONASSIST_PROPOSALS:
166 // // fCorrectionAssistant.showPossibleCompletions();
169 // fIgnoreTextConverters = true;
172 // fIgnoreTextConverters = true;
175 // super.doOperation(operation);
179 // * @see ITextOperationTarget#canDoOperation(int)
181 // public boolean canDoOperation(int operation) {
182 // // if (operation == CORRECTIONASSIST_PROPOSALS)
183 // // return isEditable();
184 // return super.canDoOperation(operation);
188 // * @see TextViewer#handleDispose()
190 // protected void handleDispose() {
191 // // if (fCorrectionAssistant != null) {
192 // // fCorrectionAssistant.uninstall();
193 // // fCorrectionAssistant= null;
195 // super.handleDispose();
198 // public void insertTextConverter(ITextConverter textConverter, int index)
200 // throw new UnsupportedOperationException();
203 // public void addTextConverter(ITextConverter textConverter) {
204 // if (fTextConverters == null) {
205 // fTextConverters = new ArrayList(1);
206 // fTextConverters.add(textConverter);
207 // } else if (!fTextConverters.contains(textConverter))
208 // fTextConverters.add(textConverter);
211 // public void removeTextConverter(ITextConverter textConverter) {
212 // if (fTextConverters != null) {
213 // fTextConverters.remove(textConverter);
214 // if (fTextConverters.size() == 0)
215 // fTextConverters = null;
220 // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
222 // protected void customizeDocumentCommand(DocumentCommand command) {
223 // super.customizeDocumentCommand(command);
224 // if (!fIgnoreTextConverters && fTextConverters != null) {
225 // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
226 // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
229 // fIgnoreTextConverters = false;
232 // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
233 // public void updateIndentationPrefixes() {
234 // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
235 // String[] types = configuration.getConfiguredContentTypes(this);
236 // for (int i = 0; i < types.length; i++) {
237 // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
238 // if (prefixes != null && prefixes.length > 0)
239 // setIndentPrefixes(prefixes, types[i]);
244 // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
246 // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
247 // if (WorkbenchHelp.isContextHelpDisplayed())
249 // return super.requestWidgetToken(requester);
254 // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
256 // // public void configure(SourceViewerConfiguration configuration) {
257 // // super.configure(configuration);
258 // // // fCorrectionAssistant= new
259 // // // JavaCorrectionAssistant(CompilationUnitEditor.this);
260 // // // fCorrectionAssistant.install(this);
261 // // //TODO install SmartBracesAutoEditStrategy
262 // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
263 // // // IDocument.DEFAULT_CONTENT_TYPE);
265 // public void configure(SourceViewerConfiguration configuration) {
266 // super.configure(configuration);
267 // // fCorrectionAssistant= new
268 // JavaCorrectionAssistant(CompilationUnitEditor.this);
269 // // fCorrectionAssistant.install(this);
270 // IAutoEditStrategy smartSemi= new
271 // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING);
272 // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
273 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
274 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
275 // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER);
278 class AdaptedSourceViewer extends JavaSourceViewer {
280 private List fTextConverters;
282 private boolean fIgnoreTextConverters = false;
284 // private JavaCorrectionAssistant fCorrectionAssistant;
286 public AdaptedSourceViewer(Composite parent,
287 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
288 boolean showAnnotationsOverview, int styles,
289 IPreferenceStore store) {
290 super(parent, verticalRuler, overviewRuler,
291 showAnnotationsOverview, styles, store);
294 public IContentAssistant getContentAssistant() {
295 return fContentAssistant;
299 * @see ITextOperationTarget#doOperation(int)
301 public void doOperation(int operation) {
303 if (getTextWidget() == null)
307 case CONTENTASSIST_PROPOSALS:
308 String msg = fContentAssistant.showPossibleCompletions();
309 setStatusLineErrorMessage(msg);
311 // case CORRECTIONASSIST_PROPOSALS:
312 // msg = fCorrectionAssistant.showPossibleCompletions();
313 // setStatusLineErrorMessage(msg);
316 fIgnoreTextConverters = true;
317 super.doOperation(operation);
318 fIgnoreTextConverters = false;
321 fIgnoreTextConverters = true;
322 super.doOperation(operation);
323 fIgnoreTextConverters = false;
327 super.doOperation(operation);
331 * @see ITextOperationTarget#canDoOperation(int)
333 public boolean canDoOperation(int operation) {
334 // if (operation == CORRECTIONASSIST_PROPOSALS)
335 // return isEditable();
337 return super.canDoOperation(operation);
341 * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
344 public void unconfigure() {
345 // if (fCorrectionAssistant != null) {
346 // fCorrectionAssistant.uninstall();
347 // fCorrectionAssistant = null;
352 public void insertTextConverter(ITextConverter textConverter, int index) {
353 throw new UnsupportedOperationException();
356 public void addTextConverter(ITextConverter textConverter) {
357 if (fTextConverters == null) {
358 fTextConverters = new ArrayList(1);
359 fTextConverters.add(textConverter);
360 } else if (!fTextConverters.contains(textConverter))
361 fTextConverters.add(textConverter);
364 public void removeTextConverter(ITextConverter textConverter) {
365 if (fTextConverters != null) {
366 fTextConverters.remove(textConverter);
367 if (fTextConverters.size() == 0)
368 fTextConverters = null;
373 * @see TextViewer#customizeDocumentCommand(DocumentCommand)
375 protected void customizeDocumentCommand(DocumentCommand command) {
376 super.customizeDocumentCommand(command);
377 if (!fIgnoreTextConverters && fTextConverters != null) {
378 for (Iterator e = fTextConverters.iterator(); e.hasNext();)
379 ((ITextConverter) e.next()).customizeDocumentCommand(
380 getDocument(), command);
384 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
385 public void updateIndentationPrefixes() {
386 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
387 String[] types = configuration.getConfiguredContentTypes(this);
388 for (int i = 0; i < types.length; i++) {
389 String[] prefixes = configuration.getIndentPrefixes(this,
391 if (prefixes != null && prefixes.length > 0)
392 setIndentPrefixes(prefixes, types[i]);
397 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
399 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
400 if (PlatformUI.getWorkbench().getHelpSystem()
401 .isContextHelpDisplayed())
403 return super.requestWidgetToken(requester);
407 * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper,
411 public boolean requestWidgetToken(IWidgetTokenKeeper requester,
413 if (PlatformUI.getWorkbench().getHelpSystem()
414 .isContextHelpDisplayed())
416 return super.requestWidgetToken(requester, priority);
420 * Get the global 'Undo history size' setting
423 protected int getUndoHistorySize () {
424 IPreferenceStore store= getPreferenceStore ();
426 return store != null ? store.getInt("undoHistorySize") : 1000;
431 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
433 public void configure(SourceViewerConfiguration configuration) {
434 super.configure(configuration);
435 // fCorrectionAssistant = new
436 // JavaCorrectionAssistant(CompilationUnitEditor.this);
437 // fCorrectionAssistant.install(this);
438 IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(
439 IPHPPartitions.PHP_PARTITIONING);
440 prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
441 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
442 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
443 prependAutoEditStrategy(smartSemi,
444 IPHPPartitions.PHP_STRING_HEREDOC);
446 fUndoManager.setMaximalUndoLevel (this.getUndoHistorySize ()); // Set every editor to the global 'Undo history size'
450 * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
453 public IFormattingContext createFormattingContext() {
454 IFormattingContext context = new CommentFormattingContext();
457 IJavaElement inputJavaElement = getInputJavaElement();
458 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
461 if (javaProject == null)
462 preferences = new HashMap(JavaCore.getOptions());
464 preferences = new HashMap(javaProject.getOptions(true));
466 context.storeToMap(PreferenceConstants.getPreferenceStore(),
469 FormattingContextProperties.CONTEXT_PREFERENCES,
477 * Remembers data related to the current selection to be able to restore it
482 private class RememberedSelection {
483 /** The remembered selection start. */
484 private RememberedOffset fStartOffset = new RememberedOffset();
486 /** The remembered selection end. */
487 private RememberedOffset fEndOffset = new RememberedOffset();
490 * Remember current selection.
492 public void remember() {
494 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
495 * may be called inside an async call posted to the UI thread, so
496 * protect against intermediate disposal of the editor.
498 ISourceViewer viewer = getSourceViewer();
499 if (viewer != null) {
500 IRegion selection = getSignedSelection(viewer);
501 int startOffset = selection.getOffset();
502 int endOffset = startOffset + selection.getLength();
504 fStartOffset.setOffset(startOffset);
505 fEndOffset.setOffset(endOffset);
510 * Restore remembered selection.
512 public void restore() {
514 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
515 * may be called inside an async call posted to the UI thread, so
516 * protect against intermediate disposal of the editor.
518 if (getSourceViewer() == null)
523 int startOffset, endOffset;
524 int revealStartOffset, revealEndOffset;
525 if (showsHighlightRangeOnly()) {
526 IJavaElement newStartElement = fStartOffset.getElement();
527 startOffset = fStartOffset
528 .getRememberedOffset(newStartElement);
529 revealStartOffset = fStartOffset.getRevealOffset(
530 newStartElement, startOffset);
531 if (revealStartOffset == -1)
534 IJavaElement newEndElement = fEndOffset.getElement();
535 endOffset = fEndOffset.getRememberedOffset(newEndElement);
536 revealEndOffset = fEndOffset.getRevealOffset(newEndElement,
538 if (revealEndOffset == -1)
541 startOffset = fStartOffset.getOffset();
542 revealStartOffset = startOffset;
543 endOffset = fEndOffset.getOffset();
544 revealEndOffset = endOffset;
547 if (startOffset == -1) {
548 startOffset = endOffset; // fallback to caret offset
549 revealStartOffset = revealEndOffset;
552 if (endOffset == -1) {
553 endOffset = startOffset; // fallback to other offset
554 revealEndOffset = revealStartOffset;
557 IJavaElement element;
558 if (endOffset == -1) {
559 // fallback to element selection
560 element = fEndOffset.getElement();
562 element = fStartOffset.getElement();
564 setSelection(element);
568 if (isValidSelection(revealStartOffset, revealEndOffset
570 && isValidSelection(startOffset, endOffset
572 selectAndReveal(startOffset, endOffset - startOffset,
573 revealStartOffset, revealEndOffset
574 - revealStartOffset);
576 fStartOffset.clear();
581 private boolean isValidSelection(int offset, int length) {
582 IDocumentProvider provider = getDocumentProvider();
583 if (provider != null) {
584 IDocument document = provider.getDocument(getEditorInput());
585 if (document != null) {
586 int end = offset + length;
587 int documentLength = document.getLength();
588 return 0 <= offset && offset <= documentLength && 0 <= end
589 && end <= documentLength;
598 * Remembers additional data for a given offset to be able restore it later.
602 private class RememberedOffset {
603 /** Remembered line for the given offset */
606 /** Remembered column for the given offset */
609 /** Remembered Java element for the given offset */
610 private IJavaElement fElement;
612 /** Remembered Java element line for the given offset */
613 private int fElementLine;
616 * Store visual properties of the given offset.
619 * Offset in the document
621 public void setOffset(int offset) {
623 IDocument document = getSourceViewer().getDocument();
624 fLine = document.getLineOfOffset(offset);
625 fColumn = offset - document.getLineOffset(fLine);
626 fElement = getElementAt(offset, true);
629 if (fElement instanceof IMember) {
630 ISourceRange range = ((IMember) fElement).getNameRange();
632 fElementLine = document.getLineOfOffset(range
635 if (fElementLine == -1)
636 fElementLine = document
637 .getLineOfOffset(getOffset(fElement));
638 } catch (BadLocationException e) {
640 PHPeclipsePlugin.log(e);
642 } catch (JavaModelException e) {
644 PHPeclipsePlugin.log(e.getStatus());
650 * Return offset recomputed from stored visual properties.
652 * @return Offset in the document
654 public int getOffset() {
655 IJavaElement newElement = getElement();
657 int offset = getRememberedOffset(newElement);
659 if (offset != -1 && !containsOffset(newElement, offset)
660 && (offset == 0 || !containsOffset(newElement, offset - 1)))
667 * Return offset recomputed from stored visual properties.
671 * @return Offset in the document
673 public int getRememberedOffset(IJavaElement newElement) {
675 if (newElement == null)
678 IDocument document = getSourceViewer().getDocument();
679 int newElementLine = -1;
680 if (newElement instanceof IMember) {
681 ISourceRange range = ((IMember) newElement).getNameRange();
683 newElementLine = document.getLineOfOffset(range
686 if (newElementLine == -1)
687 newElementLine = document
688 .getLineOfOffset(getOffset(newElement));
689 if (newElementLine == -1)
692 int newLine = fLine + newElementLine - fElementLine;
693 if (newLine < 0 || newLine >= document.getNumberOfLines())
695 int maxColumn = document.getLineLength(newLine);
696 String lineDelimiter = document.getLineDelimiter(newLine);
697 if (lineDelimiter != null)
698 maxColumn = maxColumn - lineDelimiter.length();
700 if (fColumn > maxColumn)
701 offset = document.getLineOffset(newLine) + maxColumn;
703 offset = document.getLineOffset(newLine) + fColumn;
706 } catch (BadLocationException e) {
708 PHPeclipsePlugin.log(e);
710 } catch (JavaModelException e) {
712 PHPeclipsePlugin.log(e.getStatus());
718 * Returns the offset used to reveal the given element based on the
719 * given selection offset.
724 * the selection offset
725 * @return the offset to reveal the given element based on the given
728 public int getRevealOffset(IJavaElement element, int offset) {
729 if (element == null || offset == -1)
732 if (containsOffset(element, offset)) {
734 IJavaElement alternateElement = getElementAt(offset, false);
735 if (element.getHandleIdentifier().equals(
736 alternateElement.getParent().getHandleIdentifier()))
737 return offset - 1; // Solves test case 2 from
738 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
741 } else if (offset > 0 && containsOffset(element, offset - 1))
742 return offset - 1; // Solves test case 1 from
743 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
749 * Return Java element recomputed from stored visual properties.
751 * @return Java element
753 public IJavaElement getElement() {
754 if (fElement == null)
757 return findElement(fElement);
761 * Clears the stored position
763 public void clear() {
771 * Does the given Java element contain the given offset?
777 * @return <code>true</code> iff the Java element contains the offset
779 private boolean containsOffset(IJavaElement element, int offset) {
780 int elementOffset = getOffset(element);
781 int elementLength = getLength(element);
782 return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset
788 * Returns the offset of the given Java element.
792 * @return Offset of the given Java element
794 private int getOffset(IJavaElement element) {
795 if (element instanceof ISourceReference) {
796 ISourceReference sr = (ISourceReference) element;
798 ISourceRange srcRange = sr.getSourceRange();
799 if (srcRange != null)
800 return srcRange.getOffset();
801 } catch (JavaModelException e) {
808 * Returns the length of the given Java element.
812 * @return Length of the given Java element
814 private int getLength(IJavaElement element) {
815 if (element instanceof ISourceReference) {
816 ISourceReference sr = (ISourceReference) element;
818 ISourceRange srcRange = sr.getSourceRange();
819 if (srcRange != null)
820 return srcRange.getLength();
821 } catch (JavaModelException e) {
828 * Returns the updated java element for the old java element.
832 * @return Updated Java element
834 private IJavaElement findElement(IJavaElement element) {
839 IWorkingCopyManager manager = WebUI.getDefault()
840 .getWorkingCopyManager();
841 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
846 synchronized (unit) {
847 // unit.reconcile(ICompilationUnit.NO_AST, false, null,
851 IJavaElement[] findings = unit.findElements(element);
852 if (findings != null && findings.length > 0)
855 } catch (JavaModelException x) {
856 PHPeclipsePlugin.log(x.getStatus());
857 // nothing found, be tolerant and go on
866 static class TabConverter implements ITextConverter {
867 private int fTabRatio;
869 private ILineTracker fLineTracker;
871 public TabConverter() {
874 public void setNumberOfSpacesPerTab(int ratio) {
878 public void setLineTracker(ILineTracker lineTracker) {
879 fLineTracker = lineTracker;
882 private int insertTabString(StringBuffer buffer, int offsetInLine) {
885 int remainder = offsetInLine % fTabRatio;
886 remainder = fTabRatio - remainder;
887 for (int i = 0; i < remainder; i++)
892 public void customizeDocumentCommand(IDocument document,
893 DocumentCommand command) {
894 String text = command.text;
897 int index = text.indexOf('\t');
899 StringBuffer buffer = new StringBuffer();
900 fLineTracker.set(command.text);
901 int lines = fLineTracker.getNumberOfLines();
903 for (int i = 0; i < lines; i++) {
904 int offset = fLineTracker.getLineOffset(i);
905 int endOffset = offset + fLineTracker.getLineLength(i);
906 String line = text.substring(offset, endOffset);
909 IRegion firstLine = document
910 .getLineInformationOfOffset(command.offset);
911 position = command.offset - firstLine.getOffset();
913 int length = line.length();
914 for (int j = 0; j < length; j++) {
915 char c = line.charAt(j);
917 position += insertTabString(buffer, position);
924 command.text = buffer.toString();
925 } catch (BadLocationException x) {
931 private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
932 final char fExitCharacter;
934 public ExitPolicy(char exitCharacter) {
935 fExitCharacter = exitCharacter;
939 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
940 * org.eclipse.swt.events.VerifyEvent, int, int)
942 public ExitFlags doExit(LinkedPositionManager manager,
943 VerifyEvent event, int offset, int length) {
944 if (event.character == fExitCharacter) {
945 if (manager.anyPositionIncludes(offset, length))
946 return new ExitFlags(LinkedPositionUI.COMMIT
947 | LinkedPositionUI.UPDATE_CARET, false);
949 return new ExitFlags(LinkedPositionUI.COMMIT, true);
951 // Fix for #1380415 (toshihiro) start
952 switch (event.keyCode) {
955 return new ExitFlags(LinkedPositionUI.COMMIT, true);
957 case SWT.ARROW_RIGHT:
958 if (!manager.anyPositionIncludes(offset, length))
959 return new ExitFlags(LinkedPositionUI.COMMIT, true);
963 switch (event.character) {
965 if (manager.getFirstPosition().length == 0)
966 return new ExitFlags(0, false);
971 return new ExitFlags(LinkedPositionUI.COMMIT, true);
978 // private static class BracketLevel {
983 // LinkedPositionManager fManager;
985 // LinkedPositionUI fEditor;
988 private class BracketInserter implements VerifyKeyListener,
989 LinkedPositionUI.ExitListener {
990 private boolean fCloseBracketsPHP = true;
992 private boolean fCloseStringsPHPDQ = true;
994 private boolean fCloseStringsPHPSQ = true;
1000 public void setCloseBracketsPHPEnabled(boolean enabled) {
1001 fCloseBracketsPHP = enabled;
1004 public void setCloseStringsPHPDQEnabled(boolean enabled) {
1005 fCloseStringsPHPDQ = enabled;
1008 public void setCloseStringsPHPSQEnabled(boolean enabled) {
1009 fCloseStringsPHPSQ = enabled;
1012 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
1015 IRegion endLine = document.getLineInformationOfOffset(end);
1016 int maxEnd = endLine.getOffset() + endLine.getLength();
1017 while (end != maxEnd
1018 && Character.isWhitespace(document.getChar(end)))
1020 return end != maxEnd
1021 && Scanner.isPHPIdentifierPart(document.getChar(end));
1022 } catch (BadLocationException e) {
1028 // private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1030 // int start = offset;
1031 // IRegion startLine = document.getLineInformationOfOffset(start);
1032 // int minStart = startLine.getOffset();
1033 // while (start != minStart
1034 // && Character.isWhitespace(document.getChar(start - 1)))
1036 // return start != minStart
1037 // && Scanner.isPHPIdentifierPart(document
1038 // .getChar(start - 1));
1039 // } catch (BadLocationException e) {
1044 private boolean hasCharacterToTheLeft(IDocument document, int offset,
1048 IRegion startLine = document.getLineInformationOfOffset(start);
1049 int minStart = startLine.getOffset();
1050 while (start != minStart
1051 && Character.isWhitespace(document.getChar(start - 1)))
1053 return start != minStart
1054 && document.getChar(start - 1) == character;
1055 } catch (BadLocationException e) {
1060 private boolean hasCharacterToTheRight(IDocument document, int offset,
1064 IRegion endLine = document.getLineInformationOfOffset(end);
1065 int maxEnd = endLine.getOffset() + endLine.getLength();
1066 while (end != maxEnd
1067 && Character.isWhitespace(document.getChar(end)))
1069 return end != maxEnd && document.getChar(end) == character;
1070 } catch (BadLocationException e) {
1077 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1079 public void verifyKey(VerifyEvent event) {
1082 final ISourceViewer sourceViewer = getSourceViewer();
1083 IDocument document = sourceViewer.getDocument();
1084 final Point selection = sourceViewer.getSelectedRange();
1085 final int offset = selection.x;
1086 final int length = selection.y;
1088 ITypedRegion partition = document.getPartition(offset);
1089 String type = partition.getType();
1090 if (type.equals(IPHPPartitions.PHP_PARTITIONING)
1091 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1092 // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP
1094 switch (event.character) {
1096 if (hasCharacterToTheRight(document, offset + length,
1101 if (!fCloseBracketsPHP)
1103 if (hasIdentifierToTheRight(document, offset + length))
1107 if (!fCloseBracketsPHP)
1109 if (hasIdentifierToTheRight(document, offset + length))
1113 if (event.character == '"') {
1114 if (!fCloseStringsPHPDQ)
1116 // changed for statements like echo "" print ""
1117 // if (hasIdentifierToTheLeft(document, offset)
1119 // hasIdentifierToTheRight(document, offset +
1121 if (hasIdentifierToTheRight(document, offset
1125 // ITypedRegion partition=
1126 // document.getPartition(offset);
1128 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1130 // (partition.getOffset() != offset))
1132 final char characterDQ = event.character;
1133 final char closingCharacterDQ = getPeerCharacter(characterDQ);
1134 final StringBuffer bufferDQ = new StringBuffer();
1135 bufferDQ.append(characterDQ);
1136 bufferDQ.append(closingCharacterDQ);
1137 document.replace(offset, length, bufferDQ.toString());
1138 LinkedPositionManager managerDQ = new LinkedPositionManager(
1140 managerDQ.addPosition(offset + 1, 0);
1143 LinkedPositionUI editorDQ = new LinkedPositionUI(
1144 sourceViewer, managerDQ);
1145 editorDQ.setCancelListener(this);
1146 editorDQ.setExitPolicy(new ExitPolicy(
1147 closingCharacterDQ));
1148 editorDQ.setFinalCaretOffset(offset + 2);
1150 IRegion newSelectionDQ = editorDQ.getSelectedRegion();
1151 sourceViewer.setSelectedRange(newSelectionDQ
1152 .getOffset(), newSelectionDQ.getLength());
1156 if (event.character == '\'') {
1157 if (!fCloseStringsPHPSQ)
1159 // changed for statements like echo "" print ""
1160 // if (hasIdentifierToTheLeft(document, offset)
1162 // hasIdentifierToTheRight(document, offset +
1164 if (hasIdentifierToTheRight(document, offset
1168 // ITypedRegion partition=
1169 // document.getPartition(offset);
1171 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1173 // (partition.getOffset() != offset))
1175 final char characterSQ = event.character;
1176 final char closingCharacterSQ = getPeerCharacter(characterSQ);
1177 final StringBuffer bufferSQ = new StringBuffer();
1178 bufferSQ.append(characterSQ);
1179 bufferSQ.append(closingCharacterSQ);
1180 document.replace(offset, length, bufferSQ.toString());
1181 LinkedPositionManager managerSQ = new LinkedPositionManager(
1183 managerSQ.addPosition(offset + 1, 0);
1186 LinkedPositionUI editorSQ = new LinkedPositionUI(
1187 sourceViewer, managerSQ);
1188 editorSQ.setCancelListener(this);
1189 editorSQ.setExitPolicy(new ExitPolicy(
1190 closingCharacterSQ));
1191 editorSQ.setFinalCaretOffset(offset + 2);
1193 IRegion newSelectionSQ = editorSQ.getSelectedRegion();
1194 sourceViewer.setSelectedRange(newSelectionSQ
1195 .getOffset(), newSelectionSQ.getLength());
1197 case '\r': { // insert linebreaks and new closing brace
1198 // after brace and return
1199 if (!fCloseBracketsPHP) {
1202 if (hasCharacterToTheLeft(document, offset, '{')
1203 && hasCharacterToTheRight(document, offset, '}')) {
1204 String lineDelimiter = StubUtility
1205 .getLineDelimiterFor(document);
1206 int caretPos = sourceViewer.getTextWidget()
1208 final StringBuffer buffer = new StringBuffer(
1211 IRegion line = document
1212 .getLineInformationOfOffset(offset);
1213 String currentLine = document.get(line.getOffset(),
1216 int max = currentLine.length();
1217 StringBuffer indent = new StringBuffer();
1219 && Character.isWhitespace(currentLine
1221 indent.append(currentLine.charAt(index));
1224 buffer.append(indent);
1225 JavaHeuristicScanner scanner = new JavaHeuristicScanner(
1227 JavaIndenter indenter = new JavaIndenter(document,
1229 buffer.append(indenter.createIndent(1));
1230 int cursorPos = buffer.length();
1231 buffer.append(lineDelimiter);
1232 buffer.append(indent);
1233 document.replace(offset, length, buffer.toString());
1234 sourceViewer.getTextWidget().setCaretOffset(
1235 caretPos + cursorPos);
1241 } catch (BadLocationException e) {
1246 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1248 public void exit(boolean accept) {
1253 final ISourceViewer sourceViewer = getSourceViewer();
1254 IDocument document = sourceViewer.getDocument();
1255 document.replace(fOffset, fLength, null);
1256 } catch (BadLocationException e) {
1261 /** The editor's save policy */
1262 protected ISavePolicy fSavePolicy;
1265 * Listener to annotation model changes that updates the error tick in the
1268 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1270 /** The editor's paint manager */
1271 // private PaintManager fPaintManager;
1272 /** The editor's bracket painter */
1273 // private BracketPainter fBracketPainter;
1274 /** The editor's bracket matcher */
1275 //private PHPPairMatcher fBracketMatcher;
1277 /** The editor's line painter */
1278 // private LinePainter fLinePainter;
1279 /** The editor's print margin ruler painter */
1280 // private PrintMarginPainter fPrintMarginPainter;
1281 /** The editor's problem painter */
1282 // private ProblemPainter fProblemPainter;
1283 /** The editor's tab converter */
1284 private TabConverter fTabConverter;
1286 /** History for structure select action */
1287 // private SelectionHistory fSelectionHistory;
1288 /** The preference property change listener for php core. */
1289 // private IPropertyChangeListener fPropertyChangeListener = new
1290 // PropertyChangeListener();
1291 /** The remembered java element */
1292 //private IJavaElement fRememberedElement;
1295 * The remembered selection.
1299 private RememberedSelection fRememberedSelection = new RememberedSelection();
1301 /** The remembered php element offset */
1302 //private int fRememberedElementOffset;
1304 /** The bracket inserter. */
1305 private BracketInserter fBracketInserter = new BracketInserter();
1307 /** The standard action groups added to the menu */
1308 private GenerateActionGroup fGenerateActionGroup;
1310 private CompositeActionGroup fContextMenuGroup;
1312 // private class PropertyChangeListener implements IPropertyChangeListener {
1314 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1317 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1319 // handlePreferencePropertyChanged(event);
1322 /* Preference key for code formatter tab size */
1323 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1325 /** Preference key for matching brackets */
1326 // private final static String MATCHING_BRACKETS =
1327 // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1328 /** Preference key for matching brackets color */
1329 // private final static String MATCHING_BRACKETS_COLOR =
1330 // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1331 /** Preference key for highlighting current line */
1332 // private final static String CURRENT_LINE =
1333 // PreferenceConstants.EDITOR_CURRENT_LINE;
1334 /** Preference key for highlight color of current line */
1335 // private final static String CURRENT_LINE_COLOR =
1336 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1337 /** Preference key for showing print marging ruler */
1338 // private final static String PRINT_MARGIN =
1339 // PreferenceConstants.EDITOR_PRINT_MARGIN;
1340 /** Preference key for print margin ruler color */
1341 // private final static String PRINT_MARGIN_COLOR =
1342 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1343 /** Preference key for print margin ruler column */
1344 // private final static String PRINT_MARGIN_COLUMN =
1345 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1346 /** Preference key for inserting spaces rather than tabs */
1347 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1349 /** Preference key for error indication */
1350 // private final static String ERROR_INDICATION =
1351 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1352 /** Preference key for error color */
1353 // private final static String ERROR_INDICATION_COLOR =
1354 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1355 /** Preference key for warning indication */
1356 // private final static String WARNING_INDICATION =
1357 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1358 /** Preference key for warning color */
1359 // private final static String WARNING_INDICATION_COLOR =
1360 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1361 /** Preference key for task indication */
1362 //private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1364 /** Preference key for task color */
1365 //private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1367 /** Preference key for bookmark indication */
1368 //private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1370 /** Preference key for bookmark color */
1371 //private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1373 /** Preference key for search result indication */
1374 //private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1376 /** Preference key for search result color */
1377 //private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1379 /** Preference key for unknown annotation indication */
1380 //private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1382 /** Preference key for unknown annotation color */
1383 //private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1385 /** Preference key for linked position color */
1386 //private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1388 /** Preference key for shwoing the overview ruler */
1389 //private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1391 /** Preference key for error indication in overview ruler */
1392 //private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1394 /** Preference key for warning indication in overview ruler */
1395 //private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1397 /** Preference key for task indication in overview ruler */
1398 //private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1400 /** Preference key for bookmark indication in overview ruler */
1401 //private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1403 /** Preference key for search result indication in overview ruler */
1404 //private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1406 /** Preference key for unknown annotation indication in overview ruler */
1407 //private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1409 /** Preference key for automatically closing double quoted strings */
1410 private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1412 /** Preference key for automatically closing single quoted strings */
1413 private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1415 /** Preference key for automatically wrapping Java strings */
1416 // private final static String WRAP_STRINGS =
1417 // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1418 /** Preference key for automatically closing brackets and parenthesis */
1419 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1421 /** Preference key for automatically closing phpdocs and comments */
1422 //private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1424 /** Preference key for automatically adding phpdoc tags */
1425 //private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1427 /** Preference key for automatically formatting phpdocs */
1428 // private final static String FORMAT_JAVADOCS =
1429 // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1430 /** Preference key for automatically closing strings */
1431 //private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1433 /** Preference key for automatically closing brackets and parenthesis */
1434 //private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1436 /** Preference key for smart paste */
1437 //private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1439 // private final static class AnnotationInfo {
1440 // public String fColorPreference;
1441 // public String fOverviewRulerPreference;
1442 // public String fEditorPreference;
1444 // private final static Map ANNOTATION_MAP;
1447 // AnnotationInfo info;
1448 // ANNOTATION_MAP = new HashMap();
1450 // info = new AnnotationInfo();
1451 // info.fColorPreference = TASK_INDICATION_COLOR;
1452 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1453 // info.fEditorPreference = TASK_INDICATION;
1454 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1456 // info = new AnnotationInfo();
1457 // info.fColorPreference = ERROR_INDICATION_COLOR;
1458 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1459 // info.fEditorPreference = ERROR_INDICATION;
1460 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1462 // info = new AnnotationInfo();
1463 // info.fColorPreference = WARNING_INDICATION_COLOR;
1464 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1465 // info.fEditorPreference = WARNING_INDICATION;
1466 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1468 // info = new AnnotationInfo();
1469 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1470 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1471 // info.fEditorPreference = BOOKMARK_INDICATION;
1472 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1474 // info = new AnnotationInfo();
1475 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1476 // info.fOverviewRulerPreference =
1477 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1478 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1479 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1481 // info = new AnnotationInfo();
1482 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1483 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1484 // info.fEditorPreference = UNKNOWN_INDICATION;
1485 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1488 // private final static AnnotationType[] ANNOTATION_LAYERS =
1489 // new AnnotationType[] {
1490 // AnnotationType.UNKNOWN,
1491 // AnnotationType.BOOKMARK,
1492 // AnnotationType.TASK,
1493 // AnnotationType.SEARCH,
1494 // AnnotationType.WARNING,
1495 // AnnotationType.ERROR };
1497 * Creates a new php unit editor.
1501 * Reconciling listeners.
1505 private ListenerList fReconcilingListeners = new ListenerList();
1508 * Mutex for the reconciler. See
1509 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1512 * TODO remove once the underlying problem is solved.
1515 private final Object fReconcilerLock = new Object();
1517 public PHPUnitEditor() {
1519 setDocumentProvider(WebUI.getDefault()
1520 .getCompilationUnitDocumentProvider());
1521 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1522 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1523 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1524 // don't set help contextId, we install our own help context
1526 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1530 * @see AbstractTextEditor#createActions()
1532 protected void createActions() {
1533 super.createActions();
1535 // Action action= new
1536 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1537 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1539 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1540 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1541 // markAsStateDependentAction("CorrectionAssistProposal", true);
1543 // // WorkbenchHelp.setHelp(action,
1544 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1545 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1546 "ContentAssistProposal.", this); //$NON-NLS-1$
1548 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1549 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1550 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1551 // WorkbenchHelp.setHelp(action,
1552 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1554 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1555 // "ContentAssistContextInformation.", this,
1556 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1558 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1559 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1560 // markAsStateDependentAction("ContentAssistContextInformation", true);
1562 // WorkbenchHelp.setHelp(action,
1563 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1565 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1566 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1568 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1569 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1570 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1572 // // WorkbenchHelp.setHelp(action,
1573 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1574 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1575 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1576 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1577 setAction("Comment", action); //$NON-NLS-1$
1578 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1579 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1580 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1581 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1582 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1583 setAction("Uncomment", action); //$NON-NLS-1$
1584 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1585 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1587 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1588 "ToggleComment.", this); //$NON-NLS-1$
1590 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1591 setAction("ToggleComment", action); //$NON-NLS-1$
1592 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1593 // WorkbenchHelp.setHelp(action,
1594 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1595 configureToggleCommentAction();
1597 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1598 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1599 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1600 setAction("Format", action); //$NON-NLS-1$
1601 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1602 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1603 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1606 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1607 // "AddBlockComment.", this); //$NON-NLS-1$
1609 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1610 // setAction("AddBlockComment", action); //$NON-NLS-1$
1611 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1612 // markAsSelectionDependentAction("AddBlockComment", true);
1614 // // WorkbenchHelp.setHelp(action,
1615 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1616 // action = new RemoveBlockCommentAction(
1617 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1620 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1621 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1622 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1623 // markAsSelectionDependentAction("RemoveBlockComment", true);
1625 // WorkbenchHelp.setHelp(action,
1626 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1627 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1628 "Indent.", this, false); //$NON-NLS-1$
1629 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1630 setAction("Indent", action); //$NON-NLS-1$
1631 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1632 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1633 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1635 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1636 // "Indent.", this, true); //$NON-NLS-1$
1637 // setAction("IndentOnTab", action); //$NON-NLS-1$
1638 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1639 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1642 action = new AddBlockCommentAction(PHPEditorMessages
1643 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1645 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1646 setAction("AddBlockComment", action); //$NON-NLS-1$
1647 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1648 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1649 // WorkbenchHelp.setHelp(action,
1650 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1652 action = new RemoveBlockCommentAction(PHPEditorMessages
1653 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1655 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1656 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1657 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1658 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1659 // WorkbenchHelp.setHelp(action,
1660 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1662 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1663 // "Indent.", this, false); //$NON-NLS-1$
1664 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1665 // setAction("Indent", action); //$NON-NLS-1$
1666 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1667 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1668 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1670 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1671 "Indent.", this, true); //$NON-NLS-1$
1672 setAction("IndentOnTab", action); //$NON-NLS-1$
1673 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1674 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1676 if (getPreferenceStore().getBoolean(
1677 PreferenceConstants.EDITOR_SMART_TAB)) {
1678 // don't replace Shift Right - have to make sure their enablement is
1679 // mutually exclusive
1680 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1681 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1683 fGenerateActionGroup = new GenerateActionGroup(this,
1684 ITextEditorActionConstants.GROUP_EDIT);
1685 // ActionGroup rg= new RefactorActionGroup(this,
1686 // ITextEditorActionConstants.GROUP_EDIT);
1688 // fActionGroups.addGroup(rg);
1689 fActionGroups.addGroup(fGenerateActionGroup);
1691 // We have to keep the context menu group separate to have better
1692 // control over positioning
1693 fContextMenuGroup = new CompositeActionGroup(
1694 new ActionGroup[] { fGenerateActionGroup
1696 // new LocalHistoryActionGroup(this,
1697 // ITextEditorActionConstants.GROUP_EDIT)
1703 * @see JavaEditor#getElementAt(int)
1705 protected IJavaElement getElementAt(int offset) {
1706 return getElementAt(offset, true);
1710 * Returns the most narrow element including the given offset. If
1711 * <code>reconcile</code> is <code>true</code> the editor's input
1712 * element is reconciled in advance. If it is <code>false</code> this
1713 * method only returns a result if the editor's input element does not need
1717 * the offset included by the retrieved element
1719 * <code>true</code> if working copy should be reconciled
1721 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1722 IWorkingCopyManager manager = WebUI.getDefault()
1723 .getWorkingCopyManager();
1724 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1728 synchronized (unit) {
1731 return unit.getElementAt(offset);
1732 } else if (unit.isConsistent())
1733 return unit.getElementAt(offset);
1734 } catch (JavaModelException x) {
1735 PHPeclipsePlugin.log(x.getStatus());
1736 // nothing found, be tolerant and go on
1743 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1745 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1747 return EditorUtility.getWorkingCopy(element, true);
1748 } catch (JavaModelException x) {
1749 PHPeclipsePlugin.log(x.getStatus());
1750 // nothing found, be tolerant and go on
1755 public void createPartControl(Composite parent) {
1756 super.createPartControl(parent);
1757 // fPaintManager = new PaintManager(getSourceViewer());
1758 LinePainter linePainter;
1759 linePainter = new LinePainter(getSourceViewer());
1760 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
1762 // fPaintManager.addPainter(linePainter);
1763 // if (isBracketHighlightingEnabled())
1764 // startBracketHighlighting();
1765 // if (isLineHighlightingEnabled())
1766 // startLineHighlighting();
1767 // if (isPrintMarginVisible())
1768 // showPrintMargin();
1769 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1770 // while (e.hasNext()) {
1771 // AnnotationType type = (AnnotationType) e.next();
1772 // if (isAnnotationIndicationEnabled(type))
1773 // startAnnotationIndication(type);
1775 if (isTabConversionEnabled())
1776 startTabConversion();
1777 // if (isOverviewRulerVisible())
1778 // showOverviewRuler();
1780 // Preferences preferences =
1781 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1782 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1783 IPreferenceStore preferenceStore = getPreferenceStore();
1784 boolean closeBracketsPHP = preferenceStore
1785 .getBoolean(CLOSE_BRACKETS_PHP);
1786 boolean closeStringsPHPDQ = preferenceStore
1787 .getBoolean(CLOSE_STRINGS_DQ_PHP);
1788 boolean closeStringsPHPSQ = preferenceStore
1789 .getBoolean(CLOSE_STRINGS_SQ_PHP);
1790 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1791 fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ);
1792 fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ);
1793 ISourceViewer sourceViewer = getSourceViewer();
1794 if (sourceViewer instanceof ITextViewerExtension)
1795 ((ITextViewerExtension) sourceViewer)
1796 .prependVerifyKeyListener(fBracketInserter);
1799 private static char getPeerCharacter(char character) {
1800 switch (character) {
1816 throw new IllegalArgumentException();
1820 // private void startBracketHighlighting() {
1821 // if (fBracketPainter == null) {
1822 // ISourceViewer sourceViewer = getSourceViewer();
1823 // fBracketPainter = new BracketPainter(sourceViewer);
1824 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1825 // // fPaintManager.addPainter(fBracketPainter);
1829 // private void stopBracketHighlighting() {
1830 // if (fBracketPainter != null) {
1831 // // fPaintManager.removePainter(fBracketPainter);
1832 // fBracketPainter.deactivate(true);
1833 // fBracketPainter.dispose();
1834 // fBracketPainter = null;
1838 // private boolean isBracketHighlightingEnabled() {
1839 // IPreferenceStore store = getPreferenceStore();
1840 // return store.getBoolean(MATCHING_BRACKETS);
1843 // private void startLineHighlighting() {
1844 // if (fLinePainter == null) {
1845 // ISourceViewer sourceViewer = getSourceViewer();
1846 // fLinePainter = new LinePainter(sourceViewer);
1847 // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1848 // // fPaintManager.addPainter(fLinePainter);
1852 // private void stopLineHighlighting() {
1853 // if (fLinePainter != null) {
1854 // // fPaintManager.removePainter(fLinePainter);
1855 // fLinePainter.deactivate(true);
1856 // fLinePainter.dispose();
1857 // fLinePainter = null;
1861 // private boolean isLineHighlightingEnabled() {
1862 // IPreferenceStore store = getPreferenceStore();
1863 // return store.getBoolean(CURRENT_LINE);
1866 // private void showPrintMargin() {
1867 // if (fPrintMarginPainter == null) {
1868 // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1869 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1870 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1871 // // fPaintManager.addPainter(fPrintMarginPainter);
1875 // private void hidePrintMargin() {
1876 // if (fPrintMarginPainter != null) {
1877 // // fPaintManager.removePainter(fPrintMarginPainter);
1878 // fPrintMarginPainter.deactivate(true);
1879 // fPrintMarginPainter.dispose();
1880 // fPrintMarginPainter = null;
1884 // private boolean isPrintMarginVisible() {
1885 // IPreferenceStore store = getPreferenceStore();
1886 // return store.getBoolean(PRINT_MARGIN);
1889 private int getTabSize() {
1890 Preferences preferences = PHPeclipsePlugin.getDefault()
1891 .getPluginPreferences();
1892 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1895 private boolean isTabConversionEnabled() {
1896 IPreferenceStore store = getPreferenceStore();
1897 return store.getBoolean(SPACES_FOR_TABS);
1900 // private Color getColor(String key) {
1901 // RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1902 // return getColor(rgb);
1905 // private Color getColor(RGB rgb) {
1906 // JavaTextTools textTools = WebUI.getDefault()
1907 // .getJavaTextTools();
1908 // return textTools.getColorManager().getColor(rgb);
1911 // private Color getColor(AnnotationType annotationType) {
1912 // AnnotationInfo info = (AnnotationInfo)
1913 // ANNOTATION_MAP.get(annotationType);
1914 // if (info != null)
1915 // return getColor(info.fColorPreference);
1918 public void dispose() {
1919 ISourceViewer sourceViewer = getSourceViewer();
1920 if (sourceViewer instanceof ITextViewerExtension)
1921 ((ITextViewerExtension) sourceViewer)
1922 .removeVerifyKeyListener(fBracketInserter);
1923 // if (fPropertyChangeListener != null) {
1924 // Preferences preferences =
1925 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1926 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1927 // fPropertyChangeListener = null;
1929 if (fJavaEditorErrorTickUpdater != null) {
1930 fJavaEditorErrorTickUpdater.dispose();
1931 fJavaEditorErrorTickUpdater = null;
1933 // if (fSelectionHistory != null)
1934 // fSelectionHistory.dispose();
1935 // if (fPaintManager != null) {
1936 // fPaintManager.dispose();
1937 // fPaintManager = null;
1939 if (fActionGroups != null) {
1940 fActionGroups.dispose();
1941 fActionGroups = null;
1946 // protected AnnotationType getAnnotationType(String preferenceKey) {
1947 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1948 // while (e.hasNext()) {
1949 // AnnotationType type = (AnnotationType) e.next();
1950 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1951 // if (info != null) {
1952 // if (preferenceKey.equals(info.fColorPreference)
1953 // || preferenceKey.equals(info.fEditorPreference)
1954 // || preferenceKey.equals(info.fOverviewRulerPreference))
1961 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1963 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1965 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1967 String p = event.getProperty();
1968 if (CLOSE_BRACKETS_PHP.equals(p)) {
1970 .setCloseBracketsPHPEnabled(getPreferenceStore()
1974 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
1976 .setCloseStringsPHPDQEnabled(getPreferenceStore()
1980 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
1982 .setCloseStringsPHPSQEnabled(getPreferenceStore()
1986 if (SPACES_FOR_TABS.equals(p)) {
1987 if (isTabConversionEnabled())
1988 startTabConversion();
1990 stopTabConversion();
1993 // if (MATCHING_BRACKETS.equals(p)) {
1994 // if (isBracketHighlightingEnabled())
1995 // startBracketHighlighting();
1997 // stopBracketHighlighting();
2000 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
2001 // if (fBracketPainter != null)
2002 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
2005 // if (CURRENT_LINE.equals(p)) {
2006 // if (isLineHighlightingEnabled())
2007 // startLineHighlighting();
2009 // stopLineHighlighting();
2012 // if (CURRENT_LINE_COLOR.equals(p)) {
2013 // if (fLinePainter != null) {
2014 // stopLineHighlighting();
2015 // startLineHighlighting();
2019 // if (PRINT_MARGIN.equals(p)) {
2020 // if (isPrintMarginVisible())
2021 // showPrintMargin();
2023 // hidePrintMargin();
2026 // if (PRINT_MARGIN_COLOR.equals(p)) {
2027 // if (fPrintMarginPainter != null)
2028 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2031 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2032 // if (fPrintMarginPainter != null)
2033 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2036 // if (OVERVIEW_RULER.equals(p)) {
2037 // if (isOverviewRulerVisible())
2038 // showOverviewRuler();
2040 // hideOverviewRuler();
2043 // AnnotationType type = getAnnotationType(p);
2044 // if (type != null) {
2046 // AnnotationInfo info = (AnnotationInfo)
2047 // ANNOTATION_MAP.get(type);
2048 // if (info.fColorPreference.equals(p)) {
2049 // Color color = getColor(type);
2050 // if (fProblemPainter != null) {
2051 // fProblemPainter.setColor(type, color);
2052 // fProblemPainter.paint(IPainter.CONFIGURATION);
2054 // setColorInOverviewRuler(type, color);
2058 // if (info.fEditorPreference.equals(p)) {
2059 // if (isAnnotationIndicationEnabled(type))
2060 // startAnnotationIndication(type);
2062 // stopAnnotationIndication(type);
2066 // if (info.fOverviewRulerPreference.equals(p)) {
2067 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2068 // showAnnotationIndicationInOverviewRuler(type, true);
2070 // showAnnotationIndicationInOverviewRuler(type, false);
2074 IContentAssistant c = asv.getContentAssistant();
2075 if (c instanceof ContentAssistant)
2076 ContentAssistPreference.changeConfiguration(
2077 (ContentAssistant) c, getPreferenceStore(), event);
2080 super.handlePreferenceStoreChanged(event);
2085 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2087 protected void handlePreferencePropertyChanged(
2088 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2089 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2091 String p = event.getProperty();
2092 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2093 asv.updateIndentationPrefixes();
2094 if (fTabConverter != null)
2095 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2098 super.handlePreferencePropertyChanged(event);
2102 * Handles a property change event describing a change of the php core's
2103 * preferences and updates the preference related editor properties.
2106 * the property change event
2109 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2111 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2112 // if (asv != null) {
2113 // String p = event.getProperty();
2114 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2115 // asv.updateIndentationPrefixes();
2116 // if (fTabConverter != null)
2117 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2122 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2123 * org.eclipse.jface.text.source.IVerticalRuler,
2124 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2126 protected ISourceViewer createJavaSourceViewer(Composite parent,
2127 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2128 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2129 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2130 isOverviewRulerVisible, styles, store);
2133 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2134 // IVerticalRuler ruler, int styles) {
2135 // return new AdaptedSourceViewer(parent, ruler, styles);
2137 // private boolean isValidSelection(int offset, int length) {
2138 // IDocumentProvider provider = getDocumentProvider();
2139 // if (provider != null) {
2140 // IDocument document = provider.getDocument(getEditorInput());
2141 // if (document != null) {
2142 // int end = offset + length;
2143 // int documentLength = document.getLength();
2144 // return 0 <= offset && offset <= documentLength && 0 <= end
2145 // && end <= documentLength;
2152 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2154 protected IJavaElement getInputJavaElement() {
2155 return WebUI.getDefault().getWorkingCopyManager()
2156 .getWorkingCopy(getEditorInput());
2160 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2162 public void editorContextMenuAboutToShow(IMenuManager menu) {
2163 super.editorContextMenuAboutToShow(menu);
2164 ActionContext context = new ActionContext(getSelectionProvider()
2166 fContextMenuGroup.setContext(context);
2167 fContextMenuGroup.fillContextMenu(menu);
2168 fContextMenuGroup.setContext(null);
2172 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2174 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2176 IWorkingCopyManager manager = WebUI.getDefault()
2177 .getWorkingCopyManager();
2178 page.setInput(manager.getWorkingCopy(input));
2183 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2186 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2187 // IProgressMonitor progressMonitor) {
2188 // IDocumentProvider p = getDocumentProvider();
2189 // if (p instanceof PHPDocumentProvider) {
2190 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2191 // cp.setSavePolicy(fSavePolicy);
2195 // super.performSaveOperation(operation, progressMonitor);
2197 // if (p instanceof PHPDocumentProvider) {
2198 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2199 // cp.setSavePolicy(null);
2204 * @see AbstractTextEditor#doSave(IProgressMonitor)
2206 public void doSave(IProgressMonitor progressMonitor) {
2208 IDocumentProvider p = getDocumentProvider();
2210 // editor has been closed
2214 if (p.isDeleted(getEditorInput())) {
2216 if (isSaveAsAllowed()) {
2219 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2220 * the editors. Changed Behavior to make sure that if called
2221 * inside a regular save (because of deletion of input element)
2222 * there is a way to report back to the caller.
2224 performSaveAs(progressMonitor);
2229 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2230 * there Missing resources.
2232 Shell shell = getSite().getShell();
2237 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2241 if (getPreferenceStore().getBoolean(
2242 PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2243 RTrimAction trimAction = new RTrimAction();
2244 trimAction.setActiveEditor(null, getSite().getPage()
2245 .getActiveEditor());
2246 trimAction.run(null);
2249 setStatusLineErrorMessage(null);
2251 updateState(getEditorInput());
2252 validateState(getEditorInput());
2254 IWorkingCopyManager manager = WebUI.getDefault()
2255 .getWorkingCopyManager();
2256 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2259 synchronized (unit) {
2260 performSave(false, progressMonitor);
2263 performSave(false, progressMonitor);
2267 public boolean isSaveAsAllowed() {
2272 * The compilation unit editor implementation of this
2273 * <code>AbstractTextEditor</code> method asks the user for the workspace
2274 * path of a file resource and saves the document there. See
2275 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2277 * @param progressMonitor
2278 * the progress monitor
2280 protected void performSaveAs(IProgressMonitor progressMonitor) {
2282 Shell shell = getSite().getShell();
2283 IEditorInput input = getEditorInput();
2285 SaveAsDialog dialog = new SaveAsDialog(shell);
2287 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2290 if (original != null)
2291 dialog.setOriginalFile(original);
2295 IDocumentProvider provider = getDocumentProvider();
2296 if (provider == null) {
2297 // editor has been programmatically closed while the dialog was open
2301 if (provider.isDeleted(input) && original != null) {
2302 String message = PHPEditorMessages
2303 .getFormattedString(
2304 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2305 dialog.setErrorMessage(null);
2306 dialog.setMessage(message, IMessageProvider.WARNING);
2309 if (dialog.open() == Window.CANCEL) {
2310 if (progressMonitor != null)
2311 progressMonitor.setCanceled(true);
2315 IPath filePath = dialog.getResult();
2316 if (filePath == null) {
2317 if (progressMonitor != null)
2318 progressMonitor.setCanceled(true);
2322 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2323 IFile file = workspaceRoot.getFile(filePath);
2324 final IEditorInput newInput = new FileEditorInput(file);
2326 boolean success = false;
2329 provider.aboutToChange(newInput);
2330 getDocumentProvider().saveDocument(progressMonitor, newInput,
2331 getDocumentProvider().getDocument(getEditorInput()), true);
2334 } catch (CoreException x) {
2335 IStatus status = x.getStatus();
2336 if (status == null || status.getSeverity() != IStatus.CANCEL)
2341 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2343 provider.changed(newInput);
2348 if (progressMonitor != null)
2349 progressMonitor.setCanceled(!success);
2353 * @see AbstractTextEditor#doSetInput(IEditorInput)
2355 protected void doSetInput(IEditorInput input) throws CoreException {
2356 super.doSetInput(input);
2357 configureTabConverter();
2358 configureToggleCommentAction();
2363 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2366 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2367 // IAnnotationModel model=
2368 // getDocumentProvider().getAnnotationModel(getEditorInput());
2369 // if (!waitForReconcilation)
2370 // super.installOverrideIndicator(false);
2372 // uninstallOverrideIndicator();
2373 // IJavaElement inputElement= getInputJavaElement();
2374 // if (model == null || inputElement == null)
2377 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2378 // inputElement, null);
2379 // addReconcileListener(fOverrideIndicatorManager);
2385 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2388 // protected void uninstallOverrideIndicator() {
2389 // if (fOverrideIndicatorManager != null)
2390 // removeReconcileListener(fOverrideIndicatorManager);
2391 // super.uninstallOverrideIndicator();
2395 * Configures the toggle comment action
2399 private void configureToggleCommentAction() {
2400 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2401 if (action instanceof ToggleCommentAction) {
2402 ISourceViewer sourceViewer = getSourceViewer();
2403 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2404 ((ToggleCommentAction) action).configure(sourceViewer,
2409 // private void configureTabConverter() {
2410 // if (fTabConverter != null) {
2411 // IDocumentProvider provider = getDocumentProvider();
2412 // if (provider instanceof PHPDocumentProvider) {
2413 // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2414 // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2418 private void configureTabConverter() {
2419 if (fTabConverter != null) {
2420 IDocumentProvider provider = getDocumentProvider();
2421 if (provider instanceof ICompilationUnitDocumentProvider) {
2422 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2423 fTabConverter.setLineTracker(cup
2424 .createLineTracker(getEditorInput()));
2429 private void startTabConversion() {
2430 if (fTabConverter == null) {
2431 fTabConverter = new TabConverter();
2432 configureTabConverter();
2433 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2434 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2435 asv.addTextConverter(fTabConverter);
2436 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2437 asv.updateIndentationPrefixes();
2441 private void stopTabConversion() {
2442 if (fTabConverter != null) {
2443 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2444 asv.removeTextConverter(fTabConverter);
2445 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2446 asv.updateIndentationPrefixes();
2447 fTabConverter = null;
2452 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2453 * org.eclipse.core.runtime.IProgressMonitor)
2455 protected void performSave(boolean overwrite,
2456 IProgressMonitor progressMonitor) {
2457 // IDocumentProvider p = getDocumentProvider();
2458 // if (p instanceof PHPDocumentProvider) {
2459 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2460 // cp.setSavePolicy(fSavePolicy);
2463 // super.performSave(overwrite, progressMonitor);
2465 // if (p instanceof PHPDocumentProvider) {
2466 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2467 // cp.setSavePolicy(null);
2471 IDocumentProvider p = getDocumentProvider();
2472 if (p instanceof ICompilationUnitDocumentProvider) {
2473 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2474 cp.setSavePolicy(fSavePolicy);
2477 super.performSave(overwrite, progressMonitor);
2479 if (p instanceof ICompilationUnitDocumentProvider) {
2480 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2481 cp.setSavePolicy(null);
2487 * @see AbstractTextEditor#doSaveAs
2489 public void doSaveAs() {
2490 if (askIfNonWorkbenchEncodingIsOk()) {
2496 * Asks the user if it is ok to store in non-workbench encoding.
2498 * @return <true>if the user wants to continue
2500 private boolean askIfNonWorkbenchEncodingIsOk() {
2501 IDocumentProvider provider = getDocumentProvider();
2502 if (provider instanceof IStorageDocumentProvider) {
2503 IEditorInput input = getEditorInput();
2504 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2505 String encoding = storageProvider.getEncoding(input);
2506 String defaultEncoding = storageProvider.getDefaultEncoding();
2507 if (encoding != null && !encoding.equals(defaultEncoding)) {
2508 Shell shell = getSite().getShell();
2509 String title = PHPEditorMessages
2510 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2516 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2517 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2522 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2523 new String[] { encoding }); //$NON-NLS-1$
2524 return MessageDialog.openQuestion(shell, title, msg);
2531 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2534 public void aboutToBeReconciled() {
2536 // Notify AST provider
2537 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2540 Object[] listeners = fReconcilingListeners.getListeners();
2541 for (int i = 0, length = listeners.length; i < length; ++i)
2542 ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2546 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2547 * boolean, IProgressMonitor)
2550 public void reconciled(CompilationUnit ast, boolean forced,
2551 IProgressMonitor progressMonitor) {
2553 // Always notify AST provider
2554 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2555 // getInputJavaElement());
2558 // Object[] listeners = fReconcilingListeners.getListeners();
2559 // for (int i = 0, length= listeners.length; i < length; ++i)
2560 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2561 // progressMonitor);
2563 // Update Java Outline page selection
2564 if (!forced && !progressMonitor.isCanceled()) {
2565 Shell shell = getSite().getShell();
2566 if (shell != null && !shell.isDisposed()) {
2567 shell.getDisplay().asyncExec(new Runnable() {
2577 * Returns the updated java element for the old java element.
2579 // private IJavaElement findElement(IJavaElement element) {
2580 // if (element == null)
2582 // IWorkingCopyManager manager = WebUI.getDefault()
2583 // .getWorkingCopyManager();
2584 // ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2585 // if (unit != null) {
2587 // synchronized (unit) {
2588 // unit.reconcile();
2590 // IJavaElement[] findings = unit.findElements(element);
2591 // if (findings != null && findings.length > 0)
2592 // return findings[0];
2593 // } catch (JavaModelException x) {
2594 // PHPeclipsePlugin.log(x.getStatus());
2595 // // nothing found, be tolerant and go on
2602 * Returns the offset of the given Java element.
2604 // private int getOffset(IJavaElement element) {
2605 // if (element instanceof ISourceReference) {
2606 // ISourceReference sr = (ISourceReference) element;
2608 // ISourceRange srcRange = sr.getSourceRange();
2609 // if (srcRange != null)
2610 // return srcRange.getOffset();
2611 // } catch (JavaModelException e) {
2618 * @see AbstractTextEditor#restoreSelection()
2620 // protected void restoreSelection() {
2622 // if (getSourceViewer() == null || fRememberedSelection == null)
2624 // IJavaElement newElement = findElement(fRememberedElement);
2625 // int newOffset = getOffset(newElement);
2626 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2627 // - fRememberedElementOffset : 0;
2628 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2629 // fRememberedSelection.getLength()))
2630 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2631 // fRememberedSelection.getLength());
2633 // fRememberedSelection = null;
2634 // fRememberedElement = null;
2635 // fRememberedElementOffset = -1;
2639 * Tells whether this is the active editor in the active page.
2641 * @return <code>true</code> if this is the active editor in the active
2643 * @see IWorkbenchPage#getActiveEditor();
2645 protected final boolean isActiveEditor() {
2646 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2647 IWorkbenchPage page = window.getActivePage();
2650 IEditorPart activeEditor = page.getActiveEditor();
2651 return activeEditor != null && activeEditor.equals(this);
2655 * Adds the given listener. Has no effect if an identical listener was not
2656 * already registered.
2659 * The reconcile listener to be added
2662 final void addReconcileListener(IJavaReconcilingListener listener) {
2663 synchronized (fReconcilingListeners) {
2664 fReconcilingListeners.add(listener);
2669 * Removes the given listener. Has no effect if an identical listener was
2670 * not already registered.
2673 * the reconcile listener to be removed
2676 final void removeReconcileListener(IJavaReconcilingListener listener) {
2677 synchronized (fReconcilingListeners) {
2678 fReconcilingListeners.remove(listener);
2682 protected void updateStateDependentActions() {
2683 super.updateStateDependentActions();
2684 fGenerateActionGroup.editorStateChanged();
2688 * @see AbstractTextEditor#rememberSelection()
2690 protected void rememberSelection() {
2691 fRememberedSelection.remember();
2695 * @see AbstractTextEditor#restoreSelection()
2697 protected void restoreSelection() {
2698 fRememberedSelection.restore();
2702 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2704 protected boolean canHandleMove(IEditorInput originalElement,
2705 IEditorInput movedElement) {
2707 String oldExtension = ""; //$NON-NLS-1$
2708 if (originalElement instanceof IFileEditorInput) {
2709 IFile file = ((IFileEditorInput) originalElement).getFile();
2711 String ext = file.getFileExtension();
2717 String newExtension = ""; //$NON-NLS-1$
2718 if (movedElement instanceof IFileEditorInput) {
2719 IFile file = ((IFileEditorInput) movedElement).getFile();
2721 newExtension = file.getFileExtension();
2724 return oldExtension.equals(newExtension);
2728 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2730 protected boolean isPrefQuickDiffAlwaysOn() {
2731 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2732 // was hacked by JavaEditor
2733 // to disable the change bar for the class file (attached source) java
2735 IPreferenceStore store = getPreferenceStore();
2737 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2741 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2743 public Object getAdapter(Class required) {
2744 if (SmartBackspaceManager.class.equals(required)) {
2745 if (getSourceViewer() instanceof JavaSourceViewer) {
2746 return ((JavaSourceViewer) getSourceViewer())
2747 .getBackspaceManager();
2751 return super.getAdapter(required);
2755 * Returns the mutex for the reconciler. See
2756 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2759 * TODO remove once the underlying problem is solved.
2762 * @return the lock reconcilers may use to synchronize on
2764 public Object getReconcilerLock() {
2765 return fReconcilerLock;
2771 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2773 protected void editorSaved() {
2774 super.editorSaved();
2775 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2777 //a.refresh(ShowExternalPreviewAction.PHP_TYPE);
2778 a.doRun(ShowExternalPreviewAction.PHP_TYPE);