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.editor.ShowExternalPreviewAction;
45 import org.eclipse.core.resources.IFile;
46 import org.eclipse.core.resources.IWorkspaceRoot;
47 import org.eclipse.core.resources.ResourcesPlugin;
48 import org.eclipse.core.runtime.CoreException;
49 import org.eclipse.core.runtime.IPath;
50 import org.eclipse.core.runtime.IProgressMonitor;
51 import org.eclipse.core.runtime.IStatus;
52 import org.eclipse.core.runtime.Preferences;
53 import org.eclipse.jface.action.Action;
54 import org.eclipse.jface.action.IAction;
55 import org.eclipse.jface.action.IMenuManager;
56 import org.eclipse.jface.dialogs.ErrorDialog;
57 import org.eclipse.jface.dialogs.IMessageProvider;
58 import org.eclipse.jface.dialogs.MessageDialog;
59 import org.eclipse.jface.preference.IPreferenceStore;
60 //import org.eclipse.jface.preference.PreferenceConverter;
61 import org.eclipse.jface.text.BadLocationException;
62 import org.eclipse.jface.text.DocumentCommand;
63 import org.eclipse.jface.text.IAutoEditStrategy;
64 import org.eclipse.jface.text.IDocument;
65 import org.eclipse.jface.text.ILineTracker;
66 import org.eclipse.jface.text.IRegion;
67 import org.eclipse.jface.text.ITextOperationTarget;
68 import org.eclipse.jface.text.ITextViewerExtension;
69 import org.eclipse.jface.text.ITypedRegion;
70 import org.eclipse.jface.text.IWidgetTokenKeeper;
71 import org.eclipse.jface.text.contentassist.ContentAssistant;
72 import org.eclipse.jface.text.contentassist.IContentAssistant;
73 import org.eclipse.jface.text.formatter.FormattingContextProperties;
74 import org.eclipse.jface.text.formatter.IFormattingContext;
75 import org.eclipse.jface.text.source.IOverviewRuler;
76 import org.eclipse.jface.text.source.ISourceViewer;
77 import org.eclipse.jface.text.source.IVerticalRuler;
78 import org.eclipse.jface.text.source.SourceViewerConfiguration;
80 //import org.eclipse.jface.util.ListenerList;
81 import org.eclipse.core.runtime.ListenerList;
82 import org.eclipse.jface.util.PropertyChangeEvent;
83 import org.eclipse.jface.window.Window;
84 import org.eclipse.swt.SWT;
85 import org.eclipse.swt.custom.VerifyKeyListener;
86 import org.eclipse.swt.events.VerifyEvent;
87 import org.eclipse.swt.graphics.Color;
88 import org.eclipse.swt.graphics.Point;
89 //import org.eclipse.swt.graphics.RGB;
90 import org.eclipse.swt.widgets.Composite;
91 import org.eclipse.swt.widgets.Display;
92 import org.eclipse.swt.widgets.Shell;
93 import org.eclipse.ui.IEditorInput;
94 import org.eclipse.ui.IEditorPart;
95 import org.eclipse.ui.IFileEditorInput;
96 import org.eclipse.ui.IWorkbenchPage;
97 import org.eclipse.ui.IWorkbenchWindow;
98 import org.eclipse.ui.PlatformUI;
99 import org.eclipse.ui.actions.ActionContext;
100 import org.eclipse.ui.actions.ActionGroup;
101 import org.eclipse.ui.dialogs.SaveAsDialog;
102 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
103 import org.eclipse.ui.part.FileEditorInput;
104 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
105 import org.eclipse.ui.texteditor.ContentAssistAction;
106 import org.eclipse.ui.texteditor.IDocumentProvider;
107 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
108 import org.eclipse.ui.texteditor.TextOperationAction;
110 /*******************************************************************************
111 * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
112 * program and the accompanying materials are made available under the terms of
113 * the Common Public License v1.0 which accompanies this distribution, and is
114 * available at http://www.eclipse.org/legal/cpl-v10.html
116 * Contributors: IBM Corporation - Initial implementation
118 ******************************************************************************/
120 * PHP specific text editor.
122 public class PHPUnitEditor extends PHPEditor { // implements
123 // IJavaReconcilingListener {
124 interface ITextConverter {
125 void customizeDocumentCommand(IDocument document,
126 DocumentCommand command);
129 // class AdaptedSourceViewer extends JavaSourceViewer {
130 // private List fTextConverters;
132 // private boolean fIgnoreTextConverters = false;
134 // // private JavaCorrectionAssistant fCorrectionAssistant;
135 // public AdaptedSourceViewer(Composite parent, IVerticalRuler
137 // IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
138 // int styles, IPreferenceStore store) {
139 // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
143 // // public AdaptedSourceViewer(Composite parent,
144 // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
145 // // boolean showAnnotationsOverview, int styles) {
146 // // super(parent, verticalRuler, overviewRuler,
147 // // showAnnotationsOverview, styles);
149 // public IContentAssistant getContentAssistant() {
150 // return fContentAssistant;
154 // * @see ITextOperationTarget#doOperation(int)
156 // public void doOperation(int operation) {
157 // if (getTextWidget() == null)
159 // switch (operation) {
160 // case CONTENTASSIST_PROPOSALS:
161 // String msg = fContentAssistant.showPossibleCompletions();
162 // setStatusLineErrorMessage(msg);
164 // // case CORRECTIONASSIST_PROPOSALS:
165 // // fCorrectionAssistant.showPossibleCompletions();
168 // fIgnoreTextConverters = true;
171 // fIgnoreTextConverters = true;
174 // super.doOperation(operation);
178 // * @see ITextOperationTarget#canDoOperation(int)
180 // public boolean canDoOperation(int operation) {
181 // // if (operation == CORRECTIONASSIST_PROPOSALS)
182 // // return isEditable();
183 // return super.canDoOperation(operation);
187 // * @see TextViewer#handleDispose()
189 // protected void handleDispose() {
190 // // if (fCorrectionAssistant != null) {
191 // // fCorrectionAssistant.uninstall();
192 // // fCorrectionAssistant= null;
194 // super.handleDispose();
197 // public void insertTextConverter(ITextConverter textConverter, int index)
199 // throw new UnsupportedOperationException();
202 // public void addTextConverter(ITextConverter textConverter) {
203 // if (fTextConverters == null) {
204 // fTextConverters = new ArrayList(1);
205 // fTextConverters.add(textConverter);
206 // } else if (!fTextConverters.contains(textConverter))
207 // fTextConverters.add(textConverter);
210 // public void removeTextConverter(ITextConverter textConverter) {
211 // if (fTextConverters != null) {
212 // fTextConverters.remove(textConverter);
213 // if (fTextConverters.size() == 0)
214 // fTextConverters = null;
219 // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
221 // protected void customizeDocumentCommand(DocumentCommand command) {
222 // super.customizeDocumentCommand(command);
223 // if (!fIgnoreTextConverters && fTextConverters != null) {
224 // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
225 // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
228 // fIgnoreTextConverters = false;
231 // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
232 // public void updateIndentationPrefixes() {
233 // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
234 // String[] types = configuration.getConfiguredContentTypes(this);
235 // for (int i = 0; i < types.length; i++) {
236 // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
237 // if (prefixes != null && prefixes.length > 0)
238 // setIndentPrefixes(prefixes, types[i]);
243 // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
245 // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
246 // if (WorkbenchHelp.isContextHelpDisplayed())
248 // return super.requestWidgetToken(requester);
253 // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
255 // // public void configure(SourceViewerConfiguration configuration) {
256 // // super.configure(configuration);
257 // // // fCorrectionAssistant= new
258 // // // JavaCorrectionAssistant(CompilationUnitEditor.this);
259 // // // fCorrectionAssistant.install(this);
260 // // //TODO install SmartBracesAutoEditStrategy
261 // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
262 // // // IDocument.DEFAULT_CONTENT_TYPE);
264 // public void configure(SourceViewerConfiguration configuration) {
265 // super.configure(configuration);
266 // // fCorrectionAssistant= new
267 // JavaCorrectionAssistant(CompilationUnitEditor.this);
268 // // fCorrectionAssistant.install(this);
269 // IAutoEditStrategy smartSemi= new
270 // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING);
271 // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
272 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
273 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
274 // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER);
277 class AdaptedSourceViewer extends JavaSourceViewer {
279 private List fTextConverters;
281 private boolean fIgnoreTextConverters = false;
283 // private JavaCorrectionAssistant fCorrectionAssistant;
285 public AdaptedSourceViewer(Composite parent,
286 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
287 boolean showAnnotationsOverview, int styles,
288 IPreferenceStore store) {
289 super(parent, verticalRuler, overviewRuler,
290 showAnnotationsOverview, styles, store);
293 public IContentAssistant getContentAssistant() {
294 return fContentAssistant;
298 * @see ITextOperationTarget#doOperation(int)
300 public void doOperation(int operation) {
302 if (getTextWidget() == null)
306 case CONTENTASSIST_PROPOSALS:
307 String msg = fContentAssistant.showPossibleCompletions();
308 setStatusLineErrorMessage(msg);
310 // case CORRECTIONASSIST_PROPOSALS:
311 // msg = fCorrectionAssistant.showPossibleCompletions();
312 // setStatusLineErrorMessage(msg);
315 fIgnoreTextConverters = true;
316 super.doOperation(operation);
317 fIgnoreTextConverters = false;
320 fIgnoreTextConverters = true;
321 super.doOperation(operation);
322 fIgnoreTextConverters = false;
326 super.doOperation(operation);
330 * @see ITextOperationTarget#canDoOperation(int)
332 public boolean canDoOperation(int operation) {
333 // if (operation == CORRECTIONASSIST_PROPOSALS)
334 // return isEditable();
336 return super.canDoOperation(operation);
340 * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
343 public void unconfigure() {
344 // if (fCorrectionAssistant != null) {
345 // fCorrectionAssistant.uninstall();
346 // fCorrectionAssistant = null;
351 public void insertTextConverter(ITextConverter textConverter, int index) {
352 throw new UnsupportedOperationException();
355 public void addTextConverter(ITextConverter textConverter) {
356 if (fTextConverters == null) {
357 fTextConverters = new ArrayList(1);
358 fTextConverters.add(textConverter);
359 } else if (!fTextConverters.contains(textConverter))
360 fTextConverters.add(textConverter);
363 public void removeTextConverter(ITextConverter textConverter) {
364 if (fTextConverters != null) {
365 fTextConverters.remove(textConverter);
366 if (fTextConverters.size() == 0)
367 fTextConverters = null;
372 * @see TextViewer#customizeDocumentCommand(DocumentCommand)
374 protected void customizeDocumentCommand(DocumentCommand command) {
375 super.customizeDocumentCommand(command);
376 if (!fIgnoreTextConverters && fTextConverters != null) {
377 for (Iterator e = fTextConverters.iterator(); e.hasNext();) {
378 ((ITextConverter) e.next()).customizeDocumentCommand (getDocument(), command);
383 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
384 public void updateIndentationPrefixes() {
385 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
386 String[] types = configuration.getConfiguredContentTypes(this);
387 for (int i = 0; i < types.length; i++) {
388 String[] prefixes = configuration.getIndentPrefixes(this,
390 if (prefixes != null && prefixes.length > 0)
391 setIndentPrefixes(prefixes, types[i]);
396 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
398 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
399 if (PlatformUI.getWorkbench().getHelpSystem()
400 .isContextHelpDisplayed())
402 return super.requestWidgetToken(requester);
406 * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper,
410 public boolean requestWidgetToken(IWidgetTokenKeeper requester,
412 if (PlatformUI.getWorkbench().getHelpSystem()
413 .isContextHelpDisplayed())
415 return super.requestWidgetToken(requester, priority);
419 * Get the global 'Undo history size' setting
422 protected int getUndoHistorySize () {
423 IPreferenceStore store= getPreferenceStore ();
425 return store != null ? store.getInt("undoHistorySize") : 1000;
430 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
432 public void configure(SourceViewerConfiguration configuration) {
433 super.configure(configuration);
434 // fCorrectionAssistant = new
435 // JavaCorrectionAssistant(CompilationUnitEditor.this);
436 // fCorrectionAssistant.install(this);
437 IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy (IPHPPartitions.PHP_PARTITIONING);
438 prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
439 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
440 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
441 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_HEREDOC);
443 fUndoManager.setMaximalUndoLevel (this.getUndoHistorySize ()); // Set every editor to the global 'Undo history size'
447 * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
450 public IFormattingContext createFormattingContext() {
451 IFormattingContext context = new CommentFormattingContext();
454 IJavaElement inputJavaElement = getInputJavaElement();
455 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
458 if (javaProject == null)
459 preferences = new HashMap(JavaCore.getOptions());
461 preferences = new HashMap(javaProject.getOptions(true));
463 context.storeToMap(PreferenceConstants.getPreferenceStore(),
466 FormattingContextProperties.CONTEXT_PREFERENCES,
474 * Remembers data related to the current selection to be able to restore it
479 private class RememberedSelection {
480 /** The remembered selection start. */
481 private RememberedOffset fStartOffset = new RememberedOffset();
483 /** The remembered selection end. */
484 private RememberedOffset fEndOffset = new RememberedOffset();
487 * Remember current selection.
489 public void remember() {
491 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
492 * may be called inside an async call posted to the UI thread, so
493 * protect against intermediate disposal of the editor.
495 ISourceViewer viewer = getSourceViewer();
496 if (viewer != null) {
497 IRegion selection = getSignedSelection(viewer);
498 int startOffset = selection.getOffset();
499 int endOffset = startOffset + selection.getLength();
501 fStartOffset.setOffset(startOffset);
502 fEndOffset.setOffset(endOffset);
507 * Restore remembered selection.
509 public void restore() {
511 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
512 * may be called inside an async call posted to the UI thread, so
513 * protect against intermediate disposal of the editor.
515 if (getSourceViewer() == null)
520 int startOffset, endOffset;
521 int revealStartOffset, revealEndOffset;
522 if (showsHighlightRangeOnly()) {
523 IJavaElement newStartElement = fStartOffset.getElement();
524 startOffset = fStartOffset
525 .getRememberedOffset(newStartElement);
526 revealStartOffset = fStartOffset.getRevealOffset(
527 newStartElement, startOffset);
528 if (revealStartOffset == -1)
531 IJavaElement newEndElement = fEndOffset.getElement();
532 endOffset = fEndOffset.getRememberedOffset(newEndElement);
533 revealEndOffset = fEndOffset.getRevealOffset(newEndElement,
535 if (revealEndOffset == -1)
538 startOffset = fStartOffset.getOffset();
539 revealStartOffset = startOffset;
540 endOffset = fEndOffset.getOffset();
541 revealEndOffset = endOffset;
544 if (startOffset == -1) {
545 startOffset = endOffset; // fallback to caret offset
546 revealStartOffset = revealEndOffset;
549 if (endOffset == -1) {
550 endOffset = startOffset; // fallback to other offset
551 revealEndOffset = revealStartOffset;
554 IJavaElement element;
555 if (endOffset == -1) {
556 // fallback to element selection
557 element = fEndOffset.getElement();
559 element = fStartOffset.getElement();
561 setSelection(element);
565 if (isValidSelection(revealStartOffset, revealEndOffset
567 && isValidSelection(startOffset, endOffset
569 selectAndReveal(startOffset, endOffset - startOffset,
570 revealStartOffset, revealEndOffset
571 - revealStartOffset);
573 fStartOffset.clear();
578 private boolean isValidSelection(int offset, int length) {
579 IDocumentProvider provider = getDocumentProvider();
580 if (provider != null) {
581 IDocument document = provider.getDocument(getEditorInput());
582 if (document != null) {
583 int end = offset + length;
584 int documentLength = document.getLength();
585 return 0 <= offset && offset <= documentLength && 0 <= end
586 && end <= documentLength;
595 * Remembers additional data for a given offset to be able restore it later.
599 private class RememberedOffset {
600 /** Remembered line for the given offset */
603 /** Remembered column for the given offset */
606 /** Remembered Java element for the given offset */
607 private IJavaElement fElement;
609 /** Remembered Java element line for the given offset */
610 private int fElementLine;
613 * Store visual properties of the given offset.
616 * Offset in the document
618 public void setOffset(int offset) {
620 IDocument document = getSourceViewer().getDocument();
621 fLine = document.getLineOfOffset(offset);
622 fColumn = offset - document.getLineOffset(fLine);
623 fElement = getElementAt(offset, true);
626 if (fElement instanceof IMember) {
627 ISourceRange range = ((IMember) fElement).getNameRange();
629 fElementLine = document.getLineOfOffset(range
632 if (fElementLine == -1)
633 fElementLine = document
634 .getLineOfOffset(getOffset(fElement));
635 } catch (BadLocationException e) {
637 PHPeclipsePlugin.log(e);
639 } catch (JavaModelException e) {
641 PHPeclipsePlugin.log(e.getStatus());
647 * Return offset recomputed from stored visual properties.
649 * @return Offset in the document
651 public int getOffset() {
652 IJavaElement newElement = getElement();
654 int offset = getRememberedOffset(newElement);
656 if (offset != -1 && !containsOffset(newElement, offset)
657 && (offset == 0 || !containsOffset(newElement, offset - 1)))
664 * Return offset recomputed from stored visual properties.
668 * @return Offset in the document
670 public int getRememberedOffset(IJavaElement newElement) {
672 if (newElement == null)
675 IDocument document = getSourceViewer().getDocument();
676 int newElementLine = -1;
677 if (newElement instanceof IMember) {
678 ISourceRange range = ((IMember) newElement).getNameRange();
680 newElementLine = document.getLineOfOffset(range
683 if (newElementLine == -1)
684 newElementLine = document
685 .getLineOfOffset(getOffset(newElement));
686 if (newElementLine == -1)
689 int newLine = fLine + newElementLine - fElementLine;
690 if (newLine < 0 || newLine >= document.getNumberOfLines())
692 int maxColumn = document.getLineLength(newLine);
693 String lineDelimiter = document.getLineDelimiter(newLine);
694 if (lineDelimiter != null)
695 maxColumn = maxColumn - lineDelimiter.length();
697 if (fColumn > maxColumn)
698 offset = document.getLineOffset(newLine) + maxColumn;
700 offset = document.getLineOffset(newLine) + fColumn;
703 } catch (BadLocationException e) {
705 PHPeclipsePlugin.log(e);
707 } catch (JavaModelException e) {
709 PHPeclipsePlugin.log(e.getStatus());
715 * Returns the offset used to reveal the given element based on the
716 * given selection offset.
721 * the selection offset
722 * @return the offset to reveal the given element based on the given
725 public int getRevealOffset(IJavaElement element, int offset) {
726 if (element == null || offset == -1)
729 if (containsOffset(element, offset)) {
731 IJavaElement alternateElement = getElementAt(offset, false);
732 if (element.getHandleIdentifier().equals(
733 alternateElement.getParent().getHandleIdentifier()))
734 return offset - 1; // Solves test case 2 from
735 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
738 } else if (offset > 0 && containsOffset(element, offset - 1))
739 return offset - 1; // Solves test case 1 from
740 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
746 * Return Java element recomputed from stored visual properties.
748 * @return Java element
750 public IJavaElement getElement() {
751 if (fElement == null)
754 return findElement(fElement);
758 * Clears the stored position
760 public void clear() {
768 * Does the given Java element contain the given offset?
774 * @return <code>true</code> iff the Java element contains the offset
776 private boolean containsOffset(IJavaElement element, int offset) {
777 int elementOffset = getOffset(element);
778 int elementLength = getLength(element);
779 return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset
785 * Returns the offset of the given Java element.
789 * @return Offset of the given Java element
791 private int getOffset(IJavaElement element) {
792 if (element instanceof ISourceReference) {
793 ISourceReference sr = (ISourceReference) element;
795 ISourceRange srcRange = sr.getSourceRange();
796 if (srcRange != null)
797 return srcRange.getOffset();
798 } catch (JavaModelException e) {
805 * Returns the length of the given Java element.
809 * @return Length of the given Java element
811 private int getLength(IJavaElement element) {
812 if (element instanceof ISourceReference) {
813 ISourceReference sr = (ISourceReference) element;
815 ISourceRange srcRange = sr.getSourceRange();
816 if (srcRange != null)
817 return srcRange.getLength();
818 } catch (JavaModelException e) {
825 * Returns the updated java element for the old java element.
829 * @return Updated Java element
831 private IJavaElement findElement(IJavaElement element) {
836 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
837 .getWorkingCopyManager();
838 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
843 synchronized (unit) {
844 // unit.reconcile(ICompilationUnit.NO_AST, false, null,
848 IJavaElement[] findings = unit.findElements(element);
849 if (findings != null && findings.length > 0)
852 } catch (JavaModelException x) {
853 PHPeclipsePlugin.log(x.getStatus());
854 // nothing found, be tolerant and go on
863 static class TabConverter implements ITextConverter {
864 private int fTabRatio;
866 private ILineTracker fLineTracker;
868 public TabConverter() {
871 public void setNumberOfSpacesPerTab(int ratio) {
875 public void setLineTracker(ILineTracker lineTracker) {
876 fLineTracker = lineTracker;
879 private int insertTabString(StringBuffer buffer, int offsetInLine) {
882 int remainder = offsetInLine % fTabRatio;
883 remainder = fTabRatio - remainder;
884 for (int i = 0; i < remainder; i++)
889 public void customizeDocumentCommand(IDocument document,
890 DocumentCommand command) {
891 String text = command.text;
894 int index = text.indexOf('\t');
896 StringBuffer buffer = new StringBuffer();
897 fLineTracker.set(command.text);
898 int lines = fLineTracker.getNumberOfLines();
900 for (int i = 0; i < lines; i++) {
901 int offset = fLineTracker.getLineOffset(i);
902 int endOffset = offset + fLineTracker.getLineLength(i);
903 String line = text.substring(offset, endOffset);
906 IRegion firstLine = document
907 .getLineInformationOfOffset(command.offset);
908 position = command.offset - firstLine.getOffset();
910 int length = line.length();
911 for (int j = 0; j < length; j++) {
912 char c = line.charAt(j);
914 position += insertTabString(buffer, position);
921 command.text = buffer.toString();
922 } catch (BadLocationException x) {
928 private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
929 final char fExitCharacter;
931 public ExitPolicy(char exitCharacter) {
932 fExitCharacter = exitCharacter;
936 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
937 * org.eclipse.swt.events.VerifyEvent, int, int)
939 public ExitFlags doExit(LinkedPositionManager manager,
940 VerifyEvent event, int offset, int length) {
941 if (event.character == fExitCharacter) {
942 if (manager.anyPositionIncludes(offset, length))
943 return new ExitFlags(LinkedPositionUI.COMMIT
944 | LinkedPositionUI.UPDATE_CARET, false);
946 return new ExitFlags(LinkedPositionUI.COMMIT, true);
948 // Fix for #1380415 (toshihiro) start
949 switch (event.keyCode) {
952 return new ExitFlags(LinkedPositionUI.COMMIT, true);
954 case SWT.ARROW_RIGHT:
955 if (!manager.anyPositionIncludes(offset, length))
956 return new ExitFlags(LinkedPositionUI.COMMIT, true);
960 switch (event.character) {
962 if (manager.getFirstPosition().length == 0)
963 return new ExitFlags(0, false);
968 return new ExitFlags(LinkedPositionUI.COMMIT, true);
975 // private static class BracketLevel {
980 // LinkedPositionManager fManager;
982 // LinkedPositionUI fEditor;
985 private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener {
986 private boolean fCloseBracketsPHP = true;
988 private boolean fCloseStringsPHPDQ = true;
990 private boolean fCloseStringsPHPSQ = true;
996 public void setCloseBracketsPHPEnabled(boolean enabled) {
997 fCloseBracketsPHP = enabled;
1000 public void setCloseStringsPHPDQEnabled(boolean enabled) {
1001 fCloseStringsPHPDQ = enabled;
1004 public void setCloseStringsPHPSQEnabled(boolean enabled) {
1005 fCloseStringsPHPSQ = enabled;
1009 * Check whether there is a possible identifier to the right
1011 * @param document The source file which the user is currently modifying
1012 * @param offset The position we want to check whether there is a possible identifier to the right
1015 private boolean hasIdentifierToTheRight (IDocument document, int offset) {
1017 int posToCheck = offset;
1018 IRegion endLine = document.getLineInformationOfOffset(posToCheck);
1019 int endOfLine = endLine.getOffset() + endLine.getLength();
1021 while ((posToCheck != endOfLine) && // As long as we are at the current line
1022 (Character.isWhitespace(document.getChar (posToCheck)))) { // and the character is a white space
1023 ++posToCheck; // Go for the next position to check
1026 return (posToCheck != endOfLine) && // If it not the end of line
1027 Scanner.isPHPIdentifierPart(document.getChar(posToCheck)); // and it could be a identifier
1028 } catch (BadLocationException e) {
1034 // private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1036 // int start = offset;
1037 // IRegion startLine = document.getLineInformationOfOffset(start);
1038 // int minStart = startLine.getOffset();
1039 // while (start != minStart
1040 // && Character.isWhitespace(document.getChar(start - 1)))
1042 // return start != minStart
1043 // && Scanner.isPHPIdentifierPart(document.getChar(start - 1));
1044 // } catch (BadLocationException e) {
1049 private boolean hasCharacterToTheLeft (IDocument document, int offset, char character) {
1052 IRegion startLine = document.getLineInformationOfOffset(start);
1053 int minStart = startLine.getOffset();
1055 while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) {
1059 return start != minStart && document.getChar(start - 1) == character;
1060 } catch (BadLocationException e) {
1065 private boolean hasCharacterToTheRight (IDocument document, int offset, char character) {
1068 IRegion endLine = document.getLineInformationOfOffset(end);
1069 int maxEnd = endLine.getOffset() + endLine.getLength();
1071 while (end != maxEnd && Character.isWhitespace(document.getChar(end))) {
1075 return end != maxEnd && document.getChar(end) == character;
1076 } catch (BadLocationException e) {
1082 private boolean hasEscapeCharToTheLeft (IDocument document, int offset) {
1084 int posToCheck = offset;
1085 IRegion currentLine = document.getLineInformationOfOffset (posToCheck);
1086 int startOfLine = currentLine.getOffset ();
1087 int numberOfEscapes = 0;
1089 posToCheck--; // Set to the previous character
1091 while (posToCheck > startOfLine) { // while we are within the current line
1092 if (document.getChar (posToCheck) == '\\') { // If the character is a escape char
1093 numberOfEscapes++; // Count it
1095 else { // If we found the first non escape char
1096 break; // Leave counting
1099 posToCheck--; // Go for the next previous character
1102 if ((numberOfEscapes % 2) == 1) { // If we have a odd number of escape characters,
1103 return true; // the current character is escaped.
1107 } catch (BadLocationException e) {
1114 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1116 public void verifyKey(VerifyEvent event) {
1120 final ISourceViewer sourceViewer = getSourceViewer();
1121 IDocument document = sourceViewer.getDocument();
1122 final Point selection = sourceViewer.getSelectedRange();
1123 final int offset = selection.x;
1124 final int length = selection.y;
1127 ITypedRegion partition = document.getPartition(offset);
1128 String type = partition.getType();
1130 if (type.equals(IPHPPartitions.PHP_PARTITIONING) || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1131 // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP and HTML area
1132 switch (event.character) {
1134 if (hasCharacterToTheRight (document, offset + length, '('))
1138 if (!fCloseBracketsPHP)
1140 if (hasIdentifierToTheRight (document, offset + length))
1144 if (!fCloseBracketsPHP)
1146 if (hasIdentifierToTheRight (document, offset + length))
1150 if (event.character == '"') {
1151 if (!fCloseStringsPHPDQ) {
1155 // changed for statements like echo "" print ""
1156 // if (hasIdentifierToTheLeft(document, offset)
1158 // hasIdentifierToTheRight(document, offset +
1161 if (hasIdentifierToTheRight (document, offset + length)) {
1165 // We should check here whether the previous character of the typed '"' is a '\'.
1166 // In this case we should not issue a closing "
1168 if (hasEscapeCharToTheLeft (document, offset + length)) {
1173 // ITypedRegion partition=
1174 // document.getPartition(offset);
1176 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1178 // (partition.getOffset() != offset))
1181 final char characterDQ = event.character;
1182 final char closingCharacterDQ = getPeerCharacter (characterDQ);
1183 final StringBuffer bufferDQ = new StringBuffer ();
1185 bufferDQ.append (characterDQ);
1186 bufferDQ.append (closingCharacterDQ);
1187 document.replace (offset, length, bufferDQ.toString ());
1188 LinkedPositionManager managerDQ = new LinkedPositionManager (document);
1189 managerDQ.addPosition (offset + 1, 0);
1194 LinkedPositionUI editorDQ = new LinkedPositionUI (sourceViewer, managerDQ);
1195 editorDQ.setCancelListener (this);
1196 editorDQ.setExitPolicy (new ExitPolicy (closingCharacterDQ));
1197 editorDQ.setFinalCaretOffset (offset + 2);
1200 IRegion newSelectionDQ = editorDQ.getSelectedRegion ();
1201 sourceViewer.setSelectedRange (newSelectionDQ.getOffset(), newSelectionDQ.getLength());
1206 if (event.character == '\'') {
1207 if (!fCloseStringsPHPSQ) {
1211 // changed for statements like echo "" print ""
1212 // if (hasIdentifierToTheLeft(document, offset)
1214 // hasIdentifierToTheRight(document, offset +
1216 if (hasIdentifierToTheRight(document, offset + length)) {
1220 // We should check here whether the previous character of the typed '"' is a '\'.
1221 // In this case we should not issue a closing "
1223 if (hasEscapeCharToTheLeft (document, offset + length)) {
1227 // ITypedRegion partition=
1228 // document.getPartition(offset);
1230 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1232 // (partition.getOffset() != offset))
1234 final char characterSQ = event.character;
1235 final char closingCharacterSQ = getPeerCharacter (characterSQ);
1236 final StringBuffer bufferSQ = new StringBuffer ();
1238 bufferSQ.append (characterSQ);
1239 bufferSQ.append (closingCharacterSQ);
1240 document.replace (offset, length, bufferSQ.toString ());
1242 LinkedPositionManager managerSQ = new LinkedPositionManager (document);
1243 managerSQ.addPosition (offset + 1, 0);
1248 LinkedPositionUI editorSQ = new LinkedPositionUI (sourceViewer, managerSQ);
1249 editorSQ.setCancelListener (this);
1250 editorSQ.setExitPolicy (new ExitPolicy (closingCharacterSQ));
1251 editorSQ.setFinalCaretOffset (offset + 2);
1254 IRegion newSelectionSQ = editorSQ.getSelectedRegion ();
1255 sourceViewer.setSelectedRange (newSelectionSQ.getOffset(), newSelectionSQ.getLength());
1257 case '\r': { // insert linebreaks and new closing brace after brace and return
1258 if (!fCloseBracketsPHP) {
1262 if (hasCharacterToTheLeft(document, offset, '{') && hasCharacterToTheRight(document, offset, '}')) {
1263 String lineDelimiter = StubUtility.getLineDelimiterFor(document);
1264 int caretPos = sourceViewer.getTextWidget().getCaretOffset();
1265 final StringBuffer buffer = new StringBuffer(lineDelimiter);
1267 IRegion line = document.getLineInformationOfOffset(offset);
1268 String currentLine = document.get(line.getOffset(),line.getLength());
1270 int max = currentLine.length();
1271 StringBuffer indent = new StringBuffer();
1274 && Character.isWhitespace(currentLine.charAt(index))) {
1275 indent.append(currentLine.charAt(index));
1279 buffer.append(indent);
1280 JavaHeuristicScanner scanner = new JavaHeuristicScanner(document);
1281 JavaIndenter indenter = new JavaIndenter(document,scanner);
1282 buffer.append(indenter.createIndent(1));
1283 int cursorPos = buffer.length();
1284 buffer.append(lineDelimiter);
1285 buffer.append(indent);
1286 document.replace(offset, length, buffer.toString());
1287 sourceViewer.getTextWidget().setCaretOffset( caretPos + cursorPos);
1293 } catch (BadLocationException e) {
1298 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1300 public void exit(boolean accept) {
1305 final ISourceViewer sourceViewer = getSourceViewer();
1306 IDocument document = sourceViewer.getDocument();
1307 document.replace(fOffset, fLength, null);
1308 } catch (BadLocationException e) {
1313 /** The editor's save policy */
1314 protected ISavePolicy fSavePolicy;
1317 * Listener to annotation model changes that updates the error tick in the
1320 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1322 /** The editor's paint manager */
1323 // private PaintManager fPaintManager;
1324 /** The editor's bracket painter */
1325 // private BracketPainter fBracketPainter;
1326 /** The editor's bracket matcher */
1327 //private PHPPairMatcher fBracketMatcher;
1329 /** The editor's line painter */
1330 // private LinePainter fLinePainter;
1331 /** The editor's print margin ruler painter */
1332 // private PrintMarginPainter fPrintMarginPainter;
1333 /** The editor's problem painter */
1334 // private ProblemPainter fProblemPainter;
1335 /** The editor's tab converter */
1336 private TabConverter fTabConverter;
1338 /** History for structure select action */
1339 // private SelectionHistory fSelectionHistory;
1340 /** The preference property change listener for php core. */
1341 // private IPropertyChangeListener fPropertyChangeListener = new
1342 // PropertyChangeListener();
1343 /** The remembered java element */
1344 //private IJavaElement fRememberedElement;
1347 * The remembered selection.
1351 private RememberedSelection fRememberedSelection = new RememberedSelection();
1353 /** The remembered php element offset */
1354 //private int fRememberedElementOffset;
1356 /** The bracket inserter. */
1357 private BracketInserter fBracketInserter = new BracketInserter();
1359 /** The standard action groups added to the menu */
1360 private GenerateActionGroup fGenerateActionGroup;
1362 private CompositeActionGroup fContextMenuGroup;
1364 // private class PropertyChangeListener implements IPropertyChangeListener {
1366 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1369 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1371 // handlePreferencePropertyChanged(event);
1374 /* Preference key for code formatter tab size */
1375 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1377 /** Preference key for matching brackets */
1378 // private final static String MATCHING_BRACKETS =
1379 // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1380 /** Preference key for matching brackets color */
1381 // private final static String MATCHING_BRACKETS_COLOR =
1382 // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1383 /** Preference key for highlighting current line */
1384 // private final static String CURRENT_LINE =
1385 // PreferenceConstants.EDITOR_CURRENT_LINE;
1386 /** Preference key for highlight color of current line */
1387 // private final static String CURRENT_LINE_COLOR =
1388 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1389 /** Preference key for showing print marging ruler */
1390 // private final static String PRINT_MARGIN =
1391 // PreferenceConstants.EDITOR_PRINT_MARGIN;
1392 /** Preference key for print margin ruler color */
1393 // private final static String PRINT_MARGIN_COLOR =
1394 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1395 /** Preference key for print margin ruler column */
1396 // private final static String PRINT_MARGIN_COLUMN =
1397 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1398 /** Preference key for inserting spaces rather than tabs */
1399 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1401 /** Preference key for error indication */
1402 // private final static String ERROR_INDICATION =
1403 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1404 /** Preference key for error color */
1405 // private final static String ERROR_INDICATION_COLOR =
1406 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1407 /** Preference key for warning indication */
1408 // private final static String WARNING_INDICATION =
1409 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1410 /** Preference key for warning color */
1411 // private final static String WARNING_INDICATION_COLOR =
1412 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1413 /** Preference key for task indication */
1414 //private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1416 /** Preference key for task color */
1417 //private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1419 /** Preference key for bookmark indication */
1420 //private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1422 /** Preference key for bookmark color */
1423 //private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1425 /** Preference key for search result indication */
1426 //private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1428 /** Preference key for search result color */
1429 //private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1431 /** Preference key for unknown annotation indication */
1432 //private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1434 /** Preference key for unknown annotation color */
1435 //private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1437 /** Preference key for linked position color */
1438 //private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1440 /** Preference key for shwoing the overview ruler */
1441 //private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1443 /** Preference key for error indication in overview ruler */
1444 //private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1446 /** Preference key for warning indication in overview ruler */
1447 //private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1449 /** Preference key for task indication in overview ruler */
1450 //private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1452 /** Preference key for bookmark indication in overview ruler */
1453 //private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1455 /** Preference key for search result indication in overview ruler */
1456 //private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1458 /** Preference key for unknown annotation indication in overview ruler */
1459 //private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1461 /** Preference key for automatically closing double quoted strings */
1462 private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1464 /** Preference key for automatically closing single quoted strings */
1465 private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1467 /** Preference key for automatically wrapping Java strings */
1468 // private final static String WRAP_STRINGS =
1469 // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1470 /** Preference key for automatically closing brackets and parenthesis */
1471 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1473 /** Preference key for automatically closing phpdocs and comments */
1474 //private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1476 /** Preference key for automatically adding phpdoc tags */
1477 //private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1479 /** Preference key for automatically formatting phpdocs */
1480 // private final static String FORMAT_JAVADOCS =
1481 // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1482 /** Preference key for automatically closing strings */
1483 //private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1485 /** Preference key for automatically closing brackets and parenthesis */
1486 //private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1488 /** Preference key for smart paste */
1489 //private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1491 // private final static class AnnotationInfo {
1492 // public String fColorPreference;
1493 // public String fOverviewRulerPreference;
1494 // public String fEditorPreference;
1496 // private final static Map ANNOTATION_MAP;
1499 // AnnotationInfo info;
1500 // ANNOTATION_MAP = new HashMap();
1502 // info = new AnnotationInfo();
1503 // info.fColorPreference = TASK_INDICATION_COLOR;
1504 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1505 // info.fEditorPreference = TASK_INDICATION;
1506 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1508 // info = new AnnotationInfo();
1509 // info.fColorPreference = ERROR_INDICATION_COLOR;
1510 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1511 // info.fEditorPreference = ERROR_INDICATION;
1512 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1514 // info = new AnnotationInfo();
1515 // info.fColorPreference = WARNING_INDICATION_COLOR;
1516 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1517 // info.fEditorPreference = WARNING_INDICATION;
1518 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1520 // info = new AnnotationInfo();
1521 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1522 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1523 // info.fEditorPreference = BOOKMARK_INDICATION;
1524 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1526 // info = new AnnotationInfo();
1527 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1528 // info.fOverviewRulerPreference =
1529 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1530 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1531 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1533 // info = new AnnotationInfo();
1534 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1535 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1536 // info.fEditorPreference = UNKNOWN_INDICATION;
1537 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1540 // private final static AnnotationType[] ANNOTATION_LAYERS =
1541 // new AnnotationType[] {
1542 // AnnotationType.UNKNOWN,
1543 // AnnotationType.BOOKMARK,
1544 // AnnotationType.TASK,
1545 // AnnotationType.SEARCH,
1546 // AnnotationType.WARNING,
1547 // AnnotationType.ERROR };
1549 * Creates a new php unit editor.
1553 * Reconciling listeners.
1557 private ListenerList fReconcilingListeners = new ListenerList();
1560 * Mutex for the reconciler. See
1561 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1564 * TODO remove once the underlying problem is solved.
1567 private final Object fReconcilerLock = new Object();
1569 public PHPUnitEditor() {
1571 setDocumentProvider(PHPeclipsePlugin.getDefault()
1572 .getCompilationUnitDocumentProvider());
1573 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1574 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1575 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1576 // don't set help contextId, we install our own help context
1578 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1582 * @see AbstractTextEditor#createActions()
1584 protected void createActions() {
1585 super.createActions();
1587 // Action action= new
1588 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1589 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1591 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1592 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1593 // markAsStateDependentAction("CorrectionAssistProposal", true);
1595 // // WorkbenchHelp.setHelp(action,
1596 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1597 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1598 "ContentAssistProposal.", this); //$NON-NLS-1$
1600 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1601 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1602 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1603 // WorkbenchHelp.setHelp(action,
1604 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1606 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1607 // "ContentAssistContextInformation.", this,
1608 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1610 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1611 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1612 // markAsStateDependentAction("ContentAssistContextInformation", true);
1614 // WorkbenchHelp.setHelp(action,
1615 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1617 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1618 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1620 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1621 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1622 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1624 // // WorkbenchHelp.setHelp(action,
1625 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1626 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1627 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1628 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1629 setAction("Comment", action); //$NON-NLS-1$
1630 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1631 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1632 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1633 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1634 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1635 setAction("Uncomment", action); //$NON-NLS-1$
1636 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1637 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1639 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1640 "ToggleComment.", this); //$NON-NLS-1$
1642 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1643 setAction("ToggleComment", action); //$NON-NLS-1$
1644 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1645 // WorkbenchHelp.setHelp(action,
1646 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1647 configureToggleCommentAction();
1649 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1650 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1651 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1652 setAction("Format", action); //$NON-NLS-1$
1653 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1654 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1655 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1658 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1659 // "AddBlockComment.", this); //$NON-NLS-1$
1661 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1662 // setAction("AddBlockComment", action); //$NON-NLS-1$
1663 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1664 // markAsSelectionDependentAction("AddBlockComment", true);
1666 // // WorkbenchHelp.setHelp(action,
1667 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1668 // action = new RemoveBlockCommentAction(
1669 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1672 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1673 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1674 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1675 // markAsSelectionDependentAction("RemoveBlockComment", true);
1677 // WorkbenchHelp.setHelp(action,
1678 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1679 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1680 "Indent.", this, false); //$NON-NLS-1$
1681 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1682 setAction("Indent", action); //$NON-NLS-1$
1683 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1684 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1685 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1687 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1688 // "Indent.", this, true); //$NON-NLS-1$
1689 // setAction("IndentOnTab", action); //$NON-NLS-1$
1690 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1691 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1694 action = new AddBlockCommentAction(PHPEditorMessages
1695 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1697 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1698 setAction("AddBlockComment", action); //$NON-NLS-1$
1699 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1700 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1701 // WorkbenchHelp.setHelp(action,
1702 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1704 action = new RemoveBlockCommentAction(PHPEditorMessages
1705 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1707 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1708 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1709 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1710 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1711 // WorkbenchHelp.setHelp(action,
1712 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1714 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1715 // "Indent.", this, false); //$NON-NLS-1$
1716 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1717 // setAction("Indent", action); //$NON-NLS-1$
1718 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1719 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1720 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1722 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1723 "Indent.", this, true); //$NON-NLS-1$
1724 setAction("IndentOnTab", action); //$NON-NLS-1$
1725 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1726 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1728 if (getPreferenceStore().getBoolean(
1729 PreferenceConstants.EDITOR_SMART_TAB)) {
1730 // don't replace Shift Right - have to make sure their enablement is
1731 // mutually exclusive
1732 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1733 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1735 fGenerateActionGroup = new GenerateActionGroup(this,
1736 ITextEditorActionConstants.GROUP_EDIT);
1737 // ActionGroup rg= new RefactorActionGroup(this,
1738 // ITextEditorActionConstants.GROUP_EDIT);
1740 // fActionGroups.addGroup(rg);
1741 fActionGroups.addGroup(fGenerateActionGroup);
1743 // We have to keep the context menu group separate to have better
1744 // control over positioning
1745 fContextMenuGroup = new CompositeActionGroup(
1746 new ActionGroup[] { fGenerateActionGroup
1748 // new LocalHistoryActionGroup(this,
1749 // ITextEditorActionConstants.GROUP_EDIT)
1755 * @see JavaEditor#getElementAt(int)
1757 protected IJavaElement getElementAt(int offset) {
1758 return getElementAt(offset, true);
1762 * Returns the most narrow element including the given offset. If
1763 * <code>reconcile</code> is <code>true</code> the editor's input
1764 * element is reconciled in advance. If it is <code>false</code> this
1765 * method only returns a result if the editor's input element does not need
1769 * the offset included by the retrieved element
1771 * <code>true</code> if working copy should be reconciled
1773 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1774 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1775 .getWorkingCopyManager();
1776 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1780 synchronized (unit) {
1783 return unit.getElementAt(offset);
1784 } else if (unit.isConsistent())
1785 return unit.getElementAt(offset);
1786 } catch (JavaModelException x) {
1787 PHPeclipsePlugin.log(x.getStatus());
1788 // nothing found, be tolerant and go on
1795 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1797 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1799 return EditorUtility.getWorkingCopy(element, true);
1800 } catch (JavaModelException x) {
1801 PHPeclipsePlugin.log(x.getStatus());
1802 // nothing found, be tolerant and go on
1807 public void createPartControl(Composite parent) {
1808 super.createPartControl(parent);
1809 // fPaintManager = new PaintManager(getSourceViewer());
1810 LinePainter linePainter;
1811 linePainter = new LinePainter(getSourceViewer());
1812 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235, 224));
1814 // fPaintManager.addPainter(linePainter);
1815 // if (isBracketHighlightingEnabled())
1816 // startBracketHighlighting();
1817 // if (isLineHighlightingEnabled())
1818 // startLineHighlighting();
1819 // if (isPrintMarginVisible())
1820 // showPrintMargin();
1821 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1822 // while (e.hasNext()) {
1823 // AnnotationType type = (AnnotationType) e.next();
1824 // if (isAnnotationIndicationEnabled(type))
1825 // startAnnotationIndication(type);
1827 if (isTabConversionEnabled ()) {
1828 startTabConversion();
1830 // if (isOverviewRulerVisible())
1831 // showOverviewRuler();
1833 // Preferences preferences =
1834 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1835 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1836 IPreferenceStore preferenceStore = getPreferenceStore();
1837 boolean closeBracketsPHP = preferenceStore.getBoolean (CLOSE_BRACKETS_PHP);
1838 boolean closeStringsPHPDQ = preferenceStore.getBoolean (CLOSE_STRINGS_DQ_PHP);
1839 boolean closeStringsPHPSQ = preferenceStore.getBoolean (CLOSE_STRINGS_SQ_PHP);
1841 fBracketInserter.setCloseBracketsPHPEnabled (closeBracketsPHP);
1842 fBracketInserter.setCloseStringsPHPDQEnabled (closeStringsPHPDQ);
1843 fBracketInserter.setCloseStringsPHPSQEnabled (closeStringsPHPSQ);
1845 ISourceViewer sourceViewer = getSourceViewer();
1847 if (sourceViewer instanceof ITextViewerExtension) {
1848 ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
1852 private static char getPeerCharacter(char character) {
1853 switch (character) {
1869 throw new IllegalArgumentException();
1873 // private void startBracketHighlighting() {
1874 // if (fBracketPainter == null) {
1875 // ISourceViewer sourceViewer = getSourceViewer();
1876 // fBracketPainter = new BracketPainter(sourceViewer);
1877 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1878 // // fPaintManager.addPainter(fBracketPainter);
1882 // private void stopBracketHighlighting() {
1883 // if (fBracketPainter != null) {
1884 // // fPaintManager.removePainter(fBracketPainter);
1885 // fBracketPainter.deactivate(true);
1886 // fBracketPainter.dispose();
1887 // fBracketPainter = null;
1891 // private boolean isBracketHighlightingEnabled() {
1892 // IPreferenceStore store = getPreferenceStore();
1893 // return store.getBoolean(MATCHING_BRACKETS);
1896 // private void startLineHighlighting() {
1897 // if (fLinePainter == null) {
1898 // ISourceViewer sourceViewer = getSourceViewer();
1899 // fLinePainter = new LinePainter(sourceViewer);
1900 // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1901 // // fPaintManager.addPainter(fLinePainter);
1905 // private void stopLineHighlighting() {
1906 // if (fLinePainter != null) {
1907 // // fPaintManager.removePainter(fLinePainter);
1908 // fLinePainter.deactivate(true);
1909 // fLinePainter.dispose();
1910 // fLinePainter = null;
1914 // private boolean isLineHighlightingEnabled() {
1915 // IPreferenceStore store = getPreferenceStore();
1916 // return store.getBoolean(CURRENT_LINE);
1919 // private void showPrintMargin() {
1920 // if (fPrintMarginPainter == null) {
1921 // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1922 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1923 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1924 // // fPaintManager.addPainter(fPrintMarginPainter);
1928 // private void hidePrintMargin() {
1929 // if (fPrintMarginPainter != null) {
1930 // // fPaintManager.removePainter(fPrintMarginPainter);
1931 // fPrintMarginPainter.deactivate(true);
1932 // fPrintMarginPainter.dispose();
1933 // fPrintMarginPainter = null;
1937 // private boolean isPrintMarginVisible() {
1938 // IPreferenceStore store = getPreferenceStore();
1939 // return store.getBoolean(PRINT_MARGIN);
1942 private int getTabSize() {
1943 Preferences preferences = PHPeclipsePlugin.getDefault()
1944 .getPluginPreferences();
1945 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1948 private boolean isTabConversionEnabled() {
1949 IPreferenceStore store = getPreferenceStore();
1950 return store.getBoolean(SPACES_FOR_TABS);
1953 // private Color getColor(String key) {
1954 // RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1955 // return getColor(rgb);
1958 // private Color getColor(RGB rgb) {
1959 // JavaTextTools textTools = PHPeclipsePlugin.getDefault()
1960 // .getJavaTextTools();
1961 // return textTools.getColorManager().getColor(rgb);
1964 // private Color getColor(AnnotationType annotationType) {
1965 // AnnotationInfo info = (AnnotationInfo)
1966 // ANNOTATION_MAP.get(annotationType);
1967 // if (info != null)
1968 // return getColor(info.fColorPreference);
1971 public void dispose() {
1972 ISourceViewer sourceViewer = getSourceViewer();
1973 if (sourceViewer instanceof ITextViewerExtension)
1974 ((ITextViewerExtension) sourceViewer)
1975 .removeVerifyKeyListener(fBracketInserter);
1976 // if (fPropertyChangeListener != null) {
1977 // Preferences preferences =
1978 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1979 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1980 // fPropertyChangeListener = null;
1982 if (fJavaEditorErrorTickUpdater != null) {
1983 fJavaEditorErrorTickUpdater.dispose();
1984 fJavaEditorErrorTickUpdater = null;
1986 // if (fSelectionHistory != null)
1987 // fSelectionHistory.dispose();
1988 // if (fPaintManager != null) {
1989 // fPaintManager.dispose();
1990 // fPaintManager = null;
1992 if (fActionGroups != null) {
1993 fActionGroups.dispose();
1994 fActionGroups = null;
1999 // protected AnnotationType getAnnotationType(String preferenceKey) {
2000 // Iterator e = ANNOTATION_MAP.keySet().iterator();
2001 // while (e.hasNext()) {
2002 // AnnotationType type = (AnnotationType) e.next();
2003 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
2004 // if (info != null) {
2005 // if (preferenceKey.equals(info.fColorPreference)
2006 // || preferenceKey.equals(info.fEditorPreference)
2007 // || preferenceKey.equals(info.fOverviewRulerPreference))
2014 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
2016 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
2018 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2020 String p = event.getProperty();
2021 if (CLOSE_BRACKETS_PHP.equals(p)) {
2023 .setCloseBracketsPHPEnabled(getPreferenceStore()
2027 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
2029 .setCloseStringsPHPDQEnabled(getPreferenceStore()
2033 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
2035 .setCloseStringsPHPSQEnabled(getPreferenceStore()
2039 if (SPACES_FOR_TABS.equals(p)) {
2040 if (isTabConversionEnabled())
2041 startTabConversion();
2043 stopTabConversion();
2046 // if (MATCHING_BRACKETS.equals(p)) {
2047 // if (isBracketHighlightingEnabled())
2048 // startBracketHighlighting();
2050 // stopBracketHighlighting();
2053 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
2054 // if (fBracketPainter != null)
2055 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
2058 // if (CURRENT_LINE.equals(p)) {
2059 // if (isLineHighlightingEnabled())
2060 // startLineHighlighting();
2062 // stopLineHighlighting();
2065 // if (CURRENT_LINE_COLOR.equals(p)) {
2066 // if (fLinePainter != null) {
2067 // stopLineHighlighting();
2068 // startLineHighlighting();
2072 // if (PRINT_MARGIN.equals(p)) {
2073 // if (isPrintMarginVisible())
2074 // showPrintMargin();
2076 // hidePrintMargin();
2079 // if (PRINT_MARGIN_COLOR.equals(p)) {
2080 // if (fPrintMarginPainter != null)
2081 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2084 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2085 // if (fPrintMarginPainter != null)
2086 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2089 // if (OVERVIEW_RULER.equals(p)) {
2090 // if (isOverviewRulerVisible())
2091 // showOverviewRuler();
2093 // hideOverviewRuler();
2096 // AnnotationType type = getAnnotationType(p);
2097 // if (type != null) {
2099 // AnnotationInfo info = (AnnotationInfo)
2100 // ANNOTATION_MAP.get(type);
2101 // if (info.fColorPreference.equals(p)) {
2102 // Color color = getColor(type);
2103 // if (fProblemPainter != null) {
2104 // fProblemPainter.setColor(type, color);
2105 // fProblemPainter.paint(IPainter.CONFIGURATION);
2107 // setColorInOverviewRuler(type, color);
2111 // if (info.fEditorPreference.equals(p)) {
2112 // if (isAnnotationIndicationEnabled(type))
2113 // startAnnotationIndication(type);
2115 // stopAnnotationIndication(type);
2119 // if (info.fOverviewRulerPreference.equals(p)) {
2120 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2121 // showAnnotationIndicationInOverviewRuler(type, true);
2123 // showAnnotationIndicationInOverviewRuler(type, false);
2127 IContentAssistant c = asv.getContentAssistant();
2128 if (c instanceof ContentAssistant)
2129 ContentAssistPreference.changeConfiguration(
2130 (ContentAssistant) c, getPreferenceStore(), event);
2133 super.handlePreferenceStoreChanged(event);
2138 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2140 protected void handlePreferencePropertyChanged(
2141 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2142 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2144 String p = event.getProperty();
2145 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2146 asv.updateIndentationPrefixes();
2147 if (fTabConverter != null)
2148 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2151 super.handlePreferencePropertyChanged(event);
2155 * Handles a property change event describing a change of the php core's
2156 * preferences and updates the preference related editor properties.
2159 * the property change event
2162 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2164 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2165 // if (asv != null) {
2166 // String p = event.getProperty();
2167 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2168 // asv.updateIndentationPrefixes();
2169 // if (fTabConverter != null)
2170 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2175 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2176 * org.eclipse.jface.text.source.IVerticalRuler,
2177 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2179 protected ISourceViewer createJavaSourceViewer(Composite parent,
2180 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2181 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2182 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2183 isOverviewRulerVisible, styles, store);
2186 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2187 // IVerticalRuler ruler, int styles) {
2188 // return new AdaptedSourceViewer(parent, ruler, styles);
2190 // private boolean isValidSelection(int offset, int length) {
2191 // IDocumentProvider provider = getDocumentProvider();
2192 // if (provider != null) {
2193 // IDocument document = provider.getDocument(getEditorInput());
2194 // if (document != null) {
2195 // int end = offset + length;
2196 // int documentLength = document.getLength();
2197 // return 0 <= offset && offset <= documentLength && 0 <= end
2198 // && end <= documentLength;
2205 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2207 protected IJavaElement getInputJavaElement() {
2208 return PHPeclipsePlugin.getDefault().getWorkingCopyManager()
2209 .getWorkingCopy(getEditorInput());
2213 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2215 public void editorContextMenuAboutToShow(IMenuManager menu) {
2216 super.editorContextMenuAboutToShow(menu);
2217 ActionContext context = new ActionContext(getSelectionProvider()
2219 fContextMenuGroup.setContext(context);
2220 fContextMenuGroup.fillContextMenu(menu);
2221 fContextMenuGroup.setContext(null);
2225 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2227 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2229 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2230 .getWorkingCopyManager();
2231 page.setInput(manager.getWorkingCopy(input));
2236 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2239 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2240 // IProgressMonitor progressMonitor) {
2241 // IDocumentProvider p = getDocumentProvider();
2242 // if (p instanceof PHPDocumentProvider) {
2243 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2244 // cp.setSavePolicy(fSavePolicy);
2248 // super.performSaveOperation(operation, progressMonitor);
2250 // if (p instanceof PHPDocumentProvider) {
2251 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2252 // cp.setSavePolicy(null);
2257 * @see AbstractTextEditor#doSave(IProgressMonitor)
2259 public void doSave(IProgressMonitor progressMonitor) {
2261 IDocumentProvider p = getDocumentProvider();
2263 // editor has been closed
2267 if (p.isDeleted(getEditorInput())) {
2269 if (isSaveAsAllowed()) {
2272 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2273 * the editors. Changed Behavior to make sure that if called
2274 * inside a regular save (because of deletion of input element)
2275 * there is a way to report back to the caller.
2277 performSaveAs(progressMonitor);
2282 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2283 * there Missing resources.
2285 Shell shell = getSite().getShell();
2290 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2294 if (getPreferenceStore().getBoolean(
2295 PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2296 RTrimAction trimAction = new RTrimAction();
2297 trimAction.setActiveEditor(null, getSite().getPage()
2298 .getActiveEditor());
2299 trimAction.run(null);
2302 setStatusLineErrorMessage(null);
2304 updateState(getEditorInput());
2305 validateState(getEditorInput());
2307 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2308 .getWorkingCopyManager();
2309 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2312 synchronized (unit) {
2313 performSave(false, progressMonitor);
2316 performSave(false, progressMonitor);
2320 public boolean isSaveAsAllowed() {
2325 * The compilation unit editor implementation of this
2326 * <code>AbstractTextEditor</code> method asks the user for the workspace
2327 * path of a file resource and saves the document there. See
2328 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2330 * @param progressMonitor
2331 * the progress monitor
2333 protected void performSaveAs(IProgressMonitor progressMonitor) {
2335 Shell shell = getSite().getShell();
2336 IEditorInput input = getEditorInput();
2338 SaveAsDialog dialog = new SaveAsDialog(shell);
2340 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2343 if (original != null)
2344 dialog.setOriginalFile(original);
2348 IDocumentProvider provider = getDocumentProvider();
2349 if (provider == null) {
2350 // editor has been programmatically closed while the dialog was open
2354 if (provider.isDeleted(input) && original != null) {
2355 String message = PHPEditorMessages
2356 .getFormattedString(
2357 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2358 dialog.setErrorMessage(null);
2359 dialog.setMessage(message, IMessageProvider.WARNING);
2362 if (dialog.open() == Window.CANCEL) {
2363 if (progressMonitor != null)
2364 progressMonitor.setCanceled(true);
2368 IPath filePath = dialog.getResult();
2369 if (filePath == null) {
2370 if (progressMonitor != null)
2371 progressMonitor.setCanceled(true);
2375 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2376 IFile file = workspaceRoot.getFile(filePath);
2377 final IEditorInput newInput = new FileEditorInput(file);
2379 boolean success = false;
2382 provider.aboutToChange(newInput);
2383 getDocumentProvider().saveDocument(progressMonitor, newInput,
2384 getDocumentProvider().getDocument(getEditorInput()), true);
2387 } catch (CoreException x) {
2388 IStatus status = x.getStatus();
2389 if (status == null || status.getSeverity() != IStatus.CANCEL)
2394 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2396 provider.changed(newInput);
2401 if (progressMonitor != null)
2402 progressMonitor.setCanceled(!success);
2406 * @see AbstractTextEditor#doSetInput(IEditorInput)
2408 protected void doSetInput(IEditorInput input) throws CoreException {
2409 super.doSetInput(input);
2410 configureTabConverter();
2411 configureToggleCommentAction();
2416 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2419 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2420 // IAnnotationModel model=
2421 // getDocumentProvider().getAnnotationModel(getEditorInput());
2422 // if (!waitForReconcilation)
2423 // super.installOverrideIndicator(false);
2425 // uninstallOverrideIndicator();
2426 // IJavaElement inputElement= getInputJavaElement();
2427 // if (model == null || inputElement == null)
2430 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2431 // inputElement, null);
2432 // addReconcileListener(fOverrideIndicatorManager);
2438 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2441 // protected void uninstallOverrideIndicator() {
2442 // if (fOverrideIndicatorManager != null)
2443 // removeReconcileListener(fOverrideIndicatorManager);
2444 // super.uninstallOverrideIndicator();
2448 * Configures the toggle comment action
2452 private void configureToggleCommentAction() {
2453 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2454 if (action instanceof ToggleCommentAction) {
2455 ISourceViewer sourceViewer = getSourceViewer();
2456 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2457 ((ToggleCommentAction) action).configure(sourceViewer,
2462 // private void configureTabConverter() {
2463 // if (fTabConverter != null) {
2464 // IDocumentProvider provider = getDocumentProvider();
2465 // if (provider instanceof PHPDocumentProvider) {
2466 // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2467 // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2471 private void configureTabConverter() {
2472 if (fTabConverter != null) {
2473 IDocumentProvider provider = getDocumentProvider();
2474 if (provider instanceof ICompilationUnitDocumentProvider) {
2475 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2476 fTabConverter.setLineTracker(cup
2477 .createLineTracker(getEditorInput()));
2482 private void startTabConversion() {
2483 if (fTabConverter == null) {
2484 fTabConverter = new TabConverter();
2485 configureTabConverter();
2486 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2487 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2488 asv.addTextConverter(fTabConverter);
2489 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2490 asv.updateIndentationPrefixes();
2494 private void stopTabConversion() {
2495 if (fTabConverter != null) {
2496 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2497 asv.removeTextConverter(fTabConverter);
2498 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2499 asv.updateIndentationPrefixes();
2500 fTabConverter = null;
2505 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2506 * org.eclipse.core.runtime.IProgressMonitor)
2508 protected void performSave(boolean overwrite,
2509 IProgressMonitor progressMonitor) {
2510 // IDocumentProvider p = getDocumentProvider();
2511 // if (p instanceof PHPDocumentProvider) {
2512 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2513 // cp.setSavePolicy(fSavePolicy);
2516 // super.performSave(overwrite, progressMonitor);
2518 // if (p instanceof PHPDocumentProvider) {
2519 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2520 // cp.setSavePolicy(null);
2524 IDocumentProvider p = getDocumentProvider();
2525 if (p instanceof ICompilationUnitDocumentProvider) {
2526 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2527 cp.setSavePolicy(fSavePolicy);
2530 super.performSave(overwrite, progressMonitor);
2532 if (p instanceof ICompilationUnitDocumentProvider) {
2533 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2534 cp.setSavePolicy(null);
2540 * @see AbstractTextEditor#doSaveAs
2542 public void doSaveAs() {
2543 if (askIfNonWorkbenchEncodingIsOk()) {
2549 * Asks the user if it is ok to store in non-workbench encoding.
2551 * @return <true>if the user wants to continue
2553 private boolean askIfNonWorkbenchEncodingIsOk() {
2554 IDocumentProvider provider = getDocumentProvider();
2555 if (provider instanceof IStorageDocumentProvider) {
2556 IEditorInput input = getEditorInput();
2557 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2558 String encoding = storageProvider.getEncoding(input);
2559 String defaultEncoding = storageProvider.getDefaultEncoding();
2560 if (encoding != null && !encoding.equals(defaultEncoding)) {
2561 Shell shell = getSite().getShell();
2562 String title = PHPEditorMessages
2563 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2569 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2570 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2575 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2576 new String[] { encoding }); //$NON-NLS-1$
2577 return MessageDialog.openQuestion(shell, title, msg);
2584 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2587 public void aboutToBeReconciled() {
2589 // Notify AST provider
2590 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2593 Object[] listeners = fReconcilingListeners.getListeners();
2594 for (int i = 0, length = listeners.length; i < length; ++i)
2595 ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2599 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2600 * boolean, IProgressMonitor)
2603 public void reconciled(CompilationUnit ast, boolean forced,
2604 IProgressMonitor progressMonitor) {
2606 // Always notify AST provider
2607 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2608 // getInputJavaElement());
2611 // Object[] listeners = fReconcilingListeners.getListeners();
2612 // for (int i = 0, length= listeners.length; i < length; ++i)
2613 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2614 // progressMonitor);
2616 // Update Java Outline page selection
2617 if (!forced && !progressMonitor.isCanceled()) {
2618 Shell shell = getSite().getShell();
2619 if (shell != null && !shell.isDisposed()) {
2620 shell.getDisplay().asyncExec(new Runnable() {
2630 * Returns the updated java element for the old java element.
2632 // private IJavaElement findElement(IJavaElement element) {
2633 // if (element == null)
2635 // IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2636 // .getWorkingCopyManager();
2637 // ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2638 // if (unit != null) {
2640 // synchronized (unit) {
2641 // unit.reconcile();
2643 // IJavaElement[] findings = unit.findElements(element);
2644 // if (findings != null && findings.length > 0)
2645 // return findings[0];
2646 // } catch (JavaModelException x) {
2647 // PHPeclipsePlugin.log(x.getStatus());
2648 // // nothing found, be tolerant and go on
2655 * Returns the offset of the given Java element.
2657 // private int getOffset(IJavaElement element) {
2658 // if (element instanceof ISourceReference) {
2659 // ISourceReference sr = (ISourceReference) element;
2661 // ISourceRange srcRange = sr.getSourceRange();
2662 // if (srcRange != null)
2663 // return srcRange.getOffset();
2664 // } catch (JavaModelException e) {
2671 * @see AbstractTextEditor#restoreSelection()
2673 // protected void restoreSelection() {
2675 // if (getSourceViewer() == null || fRememberedSelection == null)
2677 // IJavaElement newElement = findElement(fRememberedElement);
2678 // int newOffset = getOffset(newElement);
2679 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2680 // - fRememberedElementOffset : 0;
2681 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2682 // fRememberedSelection.getLength()))
2683 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2684 // fRememberedSelection.getLength());
2686 // fRememberedSelection = null;
2687 // fRememberedElement = null;
2688 // fRememberedElementOffset = -1;
2692 * Tells whether this is the active editor in the active page.
2694 * @return <code>true</code> if this is the active editor in the active
2696 * @see IWorkbenchPage#getActiveEditor();
2698 protected final boolean isActiveEditor() {
2699 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2700 IWorkbenchPage page = window.getActivePage();
2703 IEditorPart activeEditor = page.getActiveEditor();
2704 return activeEditor != null && activeEditor.equals(this);
2708 * Adds the given listener. Has no effect if an identical listener was not
2709 * already registered.
2712 * The reconcile listener to be added
2715 final void addReconcileListener(IJavaReconcilingListener listener) {
2716 synchronized (fReconcilingListeners) {
2717 fReconcilingListeners.add(listener);
2722 * Removes the given listener. Has no effect if an identical listener was
2723 * not already registered.
2726 * the reconcile listener to be removed
2729 final void removeReconcileListener(IJavaReconcilingListener listener) {
2730 synchronized (fReconcilingListeners) {
2731 fReconcilingListeners.remove(listener);
2735 protected void updateStateDependentActions() {
2736 super.updateStateDependentActions();
2737 fGenerateActionGroup.editorStateChanged();
2741 * @see AbstractTextEditor#rememberSelection()
2743 protected void rememberSelection() {
2744 fRememberedSelection.remember();
2748 * @see AbstractTextEditor#restoreSelection()
2750 protected void restoreSelection() {
2751 fRememberedSelection.restore();
2755 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2757 protected boolean canHandleMove(IEditorInput originalElement,
2758 IEditorInput movedElement) {
2760 String oldExtension = ""; //$NON-NLS-1$
2761 if (originalElement instanceof IFileEditorInput) {
2762 IFile file = ((IFileEditorInput) originalElement).getFile();
2764 String ext = file.getFileExtension();
2770 String newExtension = ""; //$NON-NLS-1$
2771 if (movedElement instanceof IFileEditorInput) {
2772 IFile file = ((IFileEditorInput) movedElement).getFile();
2774 newExtension = file.getFileExtension();
2777 return oldExtension.equals(newExtension);
2781 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2783 protected boolean isPrefQuickDiffAlwaysOn() {
2784 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2785 // was hacked by JavaEditor
2786 // to disable the change bar for the class file (attached source) java
2788 IPreferenceStore store = getPreferenceStore();
2790 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2794 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2796 public Object getAdapter(Class required) {
2797 if (SmartBackspaceManager.class.equals(required)) {
2798 if (getSourceViewer() instanceof JavaSourceViewer) {
2799 return ((JavaSourceViewer) getSourceViewer())
2800 .getBackspaceManager();
2804 return super.getAdapter(required);
2808 * Returns the mutex for the reconciler. See
2809 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2812 * TODO remove once the underlying problem is solved.
2815 * @return the lock reconcilers may use to synchronize on
2817 public Object getReconcilerLock() {
2818 return fReconcilerLock;
2824 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2826 protected void editorSaved() {
2827 super.editorSaved();
2828 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2830 //a.refresh(ShowExternalPreviewAction.PHP_TYPE);
2831 a.doRun(ShowExternalPreviewAction.PHP_TYPE);