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;
79 import org.eclipse.jface.util.ListenerList;
80 import org.eclipse.jface.util.PropertyChangeEvent;
81 import org.eclipse.jface.window.Window;
82 import org.eclipse.swt.SWT;
83 import org.eclipse.swt.custom.VerifyKeyListener;
84 import org.eclipse.swt.events.VerifyEvent;
85 import org.eclipse.swt.graphics.Color;
86 import org.eclipse.swt.graphics.Point;
87 import org.eclipse.swt.graphics.RGB;
88 import org.eclipse.swt.widgets.Composite;
89 import org.eclipse.swt.widgets.Display;
90 import org.eclipse.swt.widgets.Shell;
91 import org.eclipse.ui.IEditorInput;
92 import org.eclipse.ui.IEditorPart;
93 import org.eclipse.ui.IFileEditorInput;
94 import org.eclipse.ui.IWorkbenchPage;
95 import org.eclipse.ui.IWorkbenchWindow;
96 import org.eclipse.ui.PlatformUI;
97 import org.eclipse.ui.actions.ActionContext;
98 import org.eclipse.ui.actions.ActionGroup;
99 import org.eclipse.ui.dialogs.SaveAsDialog;
100 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
101 import org.eclipse.ui.part.FileEditorInput;
102 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
103 import org.eclipse.ui.texteditor.ContentAssistAction;
104 import org.eclipse.ui.texteditor.IDocumentProvider;
105 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
106 import org.eclipse.ui.texteditor.TextOperationAction;
108 /*******************************************************************************
109 * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
110 * program and the accompanying materials are made available under the terms of
111 * the Common Public License v1.0 which accompanies this distribution, and is
112 * available at http://www.eclipse.org/legal/cpl-v10.html
114 * Contributors: IBM Corporation - Initial implementation
116 ******************************************************************************/
118 * PHP specific text editor.
120 public class PHPUnitEditor extends PHPEditor { // implements
121 // IJavaReconcilingListener {
122 interface ITextConverter {
123 void customizeDocumentCommand(IDocument document,
124 DocumentCommand command);
127 // class AdaptedSourceViewer extends JavaSourceViewer {
128 // private List fTextConverters;
130 // private boolean fIgnoreTextConverters = false;
132 // // private JavaCorrectionAssistant fCorrectionAssistant;
133 // public AdaptedSourceViewer(Composite parent, IVerticalRuler
135 // IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
136 // int styles, IPreferenceStore store) {
137 // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
141 // // public AdaptedSourceViewer(Composite parent,
142 // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
143 // // boolean showAnnotationsOverview, int styles) {
144 // // super(parent, verticalRuler, overviewRuler,
145 // // showAnnotationsOverview, styles);
147 // public IContentAssistant getContentAssistant() {
148 // return fContentAssistant;
152 // * @see ITextOperationTarget#doOperation(int)
154 // public void doOperation(int operation) {
155 // if (getTextWidget() == null)
157 // switch (operation) {
158 // case CONTENTASSIST_PROPOSALS:
159 // String msg = fContentAssistant.showPossibleCompletions();
160 // setStatusLineErrorMessage(msg);
162 // // case CORRECTIONASSIST_PROPOSALS:
163 // // fCorrectionAssistant.showPossibleCompletions();
166 // fIgnoreTextConverters = true;
169 // fIgnoreTextConverters = true;
172 // super.doOperation(operation);
176 // * @see ITextOperationTarget#canDoOperation(int)
178 // public boolean canDoOperation(int operation) {
179 // // if (operation == CORRECTIONASSIST_PROPOSALS)
180 // // return isEditable();
181 // return super.canDoOperation(operation);
185 // * @see TextViewer#handleDispose()
187 // protected void handleDispose() {
188 // // if (fCorrectionAssistant != null) {
189 // // fCorrectionAssistant.uninstall();
190 // // fCorrectionAssistant= null;
192 // super.handleDispose();
195 // public void insertTextConverter(ITextConverter textConverter, int index)
197 // throw new UnsupportedOperationException();
200 // public void addTextConverter(ITextConverter textConverter) {
201 // if (fTextConverters == null) {
202 // fTextConverters = new ArrayList(1);
203 // fTextConverters.add(textConverter);
204 // } else if (!fTextConverters.contains(textConverter))
205 // fTextConverters.add(textConverter);
208 // public void removeTextConverter(ITextConverter textConverter) {
209 // if (fTextConverters != null) {
210 // fTextConverters.remove(textConverter);
211 // if (fTextConverters.size() == 0)
212 // fTextConverters = null;
217 // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
219 // protected void customizeDocumentCommand(DocumentCommand command) {
220 // super.customizeDocumentCommand(command);
221 // if (!fIgnoreTextConverters && fTextConverters != null) {
222 // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
223 // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
226 // fIgnoreTextConverters = false;
229 // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
230 // public void updateIndentationPrefixes() {
231 // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
232 // String[] types = configuration.getConfiguredContentTypes(this);
233 // for (int i = 0; i < types.length; i++) {
234 // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
235 // if (prefixes != null && prefixes.length > 0)
236 // setIndentPrefixes(prefixes, types[i]);
241 // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
243 // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
244 // if (WorkbenchHelp.isContextHelpDisplayed())
246 // return super.requestWidgetToken(requester);
251 // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
253 // // public void configure(SourceViewerConfiguration configuration) {
254 // // super.configure(configuration);
255 // // // fCorrectionAssistant= new
256 // // // JavaCorrectionAssistant(CompilationUnitEditor.this);
257 // // // fCorrectionAssistant.install(this);
258 // // //TODO install SmartBracesAutoEditStrategy
259 // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
260 // // // IDocument.DEFAULT_CONTENT_TYPE);
262 // public void configure(SourceViewerConfiguration configuration) {
263 // super.configure(configuration);
264 // // fCorrectionAssistant= new
265 // JavaCorrectionAssistant(CompilationUnitEditor.this);
266 // // fCorrectionAssistant.install(this);
267 // IAutoEditStrategy smartSemi= new
268 // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING);
269 // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
270 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
271 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
272 // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER);
275 class AdaptedSourceViewer extends JavaSourceViewer {
277 private List fTextConverters;
279 private boolean fIgnoreTextConverters = false;
281 // private JavaCorrectionAssistant fCorrectionAssistant;
283 public AdaptedSourceViewer(Composite parent,
284 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
285 boolean showAnnotationsOverview, int styles,
286 IPreferenceStore store) {
287 super(parent, verticalRuler, overviewRuler,
288 showAnnotationsOverview, styles, store);
291 public IContentAssistant getContentAssistant() {
292 return fContentAssistant;
296 * @see ITextOperationTarget#doOperation(int)
298 public void doOperation(int operation) {
300 if (getTextWidget() == null)
304 case CONTENTASSIST_PROPOSALS:
305 String msg = fContentAssistant.showPossibleCompletions();
306 setStatusLineErrorMessage(msg);
308 // case CORRECTIONASSIST_PROPOSALS:
309 // msg = fCorrectionAssistant.showPossibleCompletions();
310 // setStatusLineErrorMessage(msg);
313 fIgnoreTextConverters = true;
314 super.doOperation(operation);
315 fIgnoreTextConverters = false;
318 fIgnoreTextConverters = true;
319 super.doOperation(operation);
320 fIgnoreTextConverters = false;
324 super.doOperation(operation);
328 * @see ITextOperationTarget#canDoOperation(int)
330 public boolean canDoOperation(int operation) {
331 // if (operation == CORRECTIONASSIST_PROPOSALS)
332 // return isEditable();
334 return super.canDoOperation(operation);
338 * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
341 public void unconfigure() {
342 // if (fCorrectionAssistant != null) {
343 // fCorrectionAssistant.uninstall();
344 // fCorrectionAssistant = null;
349 public void insertTextConverter(ITextConverter textConverter, int index) {
350 throw new UnsupportedOperationException();
353 public void addTextConverter(ITextConverter textConverter) {
354 if (fTextConverters == null) {
355 fTextConverters = new ArrayList(1);
356 fTextConverters.add(textConverter);
357 } else if (!fTextConverters.contains(textConverter))
358 fTextConverters.add(textConverter);
361 public void removeTextConverter(ITextConverter textConverter) {
362 if (fTextConverters != null) {
363 fTextConverters.remove(textConverter);
364 if (fTextConverters.size() == 0)
365 fTextConverters = null;
370 * @see TextViewer#customizeDocumentCommand(DocumentCommand)
372 protected void customizeDocumentCommand(DocumentCommand command) {
373 super.customizeDocumentCommand(command);
374 if (!fIgnoreTextConverters && fTextConverters != null) {
375 for (Iterator e = fTextConverters.iterator(); e.hasNext();)
376 ((ITextConverter) e.next()).customizeDocumentCommand(
377 getDocument(), command);
381 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
382 public void updateIndentationPrefixes() {
383 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
384 String[] types = configuration.getConfiguredContentTypes(this);
385 for (int i = 0; i < types.length; i++) {
386 String[] prefixes = configuration.getIndentPrefixes(this,
388 if (prefixes != null && prefixes.length > 0)
389 setIndentPrefixes(prefixes, types[i]);
394 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
396 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
397 if (PlatformUI.getWorkbench().getHelpSystem()
398 .isContextHelpDisplayed())
400 return super.requestWidgetToken(requester);
404 * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper,
408 public boolean requestWidgetToken(IWidgetTokenKeeper requester,
410 if (PlatformUI.getWorkbench().getHelpSystem()
411 .isContextHelpDisplayed())
413 return super.requestWidgetToken(requester, priority);
417 * Get the global 'Undo history size' setting
420 protected int getUndoHistorySize () {
421 IPreferenceStore store= getPreferenceStore ();
423 return store != null ? store.getInt("undoHistorySize") : 1000;
428 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
430 public void configure(SourceViewerConfiguration configuration) {
431 super.configure(configuration);
432 // fCorrectionAssistant = new
433 // JavaCorrectionAssistant(CompilationUnitEditor.this);
434 // fCorrectionAssistant.install(this);
435 IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(
436 IPHPPartitions.PHP_PARTITIONING);
437 prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
438 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
439 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
440 prependAutoEditStrategy(smartSemi,
441 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,
986 LinkedPositionUI.ExitListener {
987 private boolean fCloseBracketsPHP = true;
989 private boolean fCloseStringsPHPDQ = true;
991 private boolean fCloseStringsPHPSQ = true;
997 public void setCloseBracketsPHPEnabled(boolean enabled) {
998 fCloseBracketsPHP = enabled;
1001 public void setCloseStringsPHPDQEnabled(boolean enabled) {
1002 fCloseStringsPHPDQ = enabled;
1005 public void setCloseStringsPHPSQEnabled(boolean enabled) {
1006 fCloseStringsPHPSQ = enabled;
1009 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
1012 IRegion endLine = document.getLineInformationOfOffset(end);
1013 int maxEnd = endLine.getOffset() + endLine.getLength();
1014 while (end != maxEnd
1015 && Character.isWhitespace(document.getChar(end)))
1017 return end != maxEnd
1018 && Scanner.isPHPIdentifierPart(document.getChar(end));
1019 } catch (BadLocationException e) {
1025 private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1028 IRegion startLine = document.getLineInformationOfOffset(start);
1029 int minStart = startLine.getOffset();
1030 while (start != minStart
1031 && Character.isWhitespace(document.getChar(start - 1)))
1033 return start != minStart
1034 && Scanner.isPHPIdentifierPart(document
1035 .getChar(start - 1));
1036 } catch (BadLocationException e) {
1041 private boolean hasCharacterToTheLeft(IDocument document, int offset,
1045 IRegion startLine = document.getLineInformationOfOffset(start);
1046 int minStart = startLine.getOffset();
1047 while (start != minStart
1048 && Character.isWhitespace(document.getChar(start - 1)))
1050 return start != minStart
1051 && document.getChar(start - 1) == character;
1052 } catch (BadLocationException e) {
1057 private boolean hasCharacterToTheRight(IDocument document, int offset,
1061 IRegion endLine = document.getLineInformationOfOffset(end);
1062 int maxEnd = endLine.getOffset() + endLine.getLength();
1063 while (end != maxEnd
1064 && Character.isWhitespace(document.getChar(end)))
1066 return end != maxEnd && document.getChar(end) == character;
1067 } catch (BadLocationException e) {
1074 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1076 public void verifyKey(VerifyEvent event) {
1079 final ISourceViewer sourceViewer = getSourceViewer();
1080 IDocument document = sourceViewer.getDocument();
1081 final Point selection = sourceViewer.getSelectedRange();
1082 final int offset = selection.x;
1083 final int length = selection.y;
1085 ITypedRegion partition = document.getPartition(offset);
1086 String type = partition.getType();
1087 if (type.equals(IPHPPartitions.PHP_PARTITIONING)
1088 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1089 // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP
1091 switch (event.character) {
1093 if (hasCharacterToTheRight(document, offset + length,
1098 if (!fCloseBracketsPHP)
1100 if (hasIdentifierToTheRight(document, offset + length))
1104 if (!fCloseBracketsPHP)
1106 if (hasIdentifierToTheRight(document, offset + length))
1110 if (event.character == '"') {
1111 if (!fCloseStringsPHPDQ)
1113 // changed for statements like echo "" print ""
1114 // if (hasIdentifierToTheLeft(document, offset)
1116 // hasIdentifierToTheRight(document, offset +
1118 if (hasIdentifierToTheRight(document, offset
1122 // ITypedRegion partition=
1123 // document.getPartition(offset);
1125 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1127 // (partition.getOffset() != offset))
1129 final char characterDQ = event.character;
1130 final char closingCharacterDQ = getPeerCharacter(characterDQ);
1131 final StringBuffer bufferDQ = new StringBuffer();
1132 bufferDQ.append(characterDQ);
1133 bufferDQ.append(closingCharacterDQ);
1134 document.replace(offset, length, bufferDQ.toString());
1135 LinkedPositionManager managerDQ = new LinkedPositionManager(
1137 managerDQ.addPosition(offset + 1, 0);
1140 LinkedPositionUI editorDQ = new LinkedPositionUI(
1141 sourceViewer, managerDQ);
1142 editorDQ.setCancelListener(this);
1143 editorDQ.setExitPolicy(new ExitPolicy(
1144 closingCharacterDQ));
1145 editorDQ.setFinalCaretOffset(offset + 2);
1147 IRegion newSelectionDQ = editorDQ.getSelectedRegion();
1148 sourceViewer.setSelectedRange(newSelectionDQ
1149 .getOffset(), newSelectionDQ.getLength());
1153 if (event.character == '\'') {
1154 if (!fCloseStringsPHPSQ)
1156 // changed for statements like echo "" print ""
1157 // if (hasIdentifierToTheLeft(document, offset)
1159 // hasIdentifierToTheRight(document, offset +
1161 if (hasIdentifierToTheRight(document, offset
1165 // ITypedRegion partition=
1166 // document.getPartition(offset);
1168 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1170 // (partition.getOffset() != offset))
1172 final char characterSQ = event.character;
1173 final char closingCharacterSQ = getPeerCharacter(characterSQ);
1174 final StringBuffer bufferSQ = new StringBuffer();
1175 bufferSQ.append(characterSQ);
1176 bufferSQ.append(closingCharacterSQ);
1177 document.replace(offset, length, bufferSQ.toString());
1178 LinkedPositionManager managerSQ = new LinkedPositionManager(
1180 managerSQ.addPosition(offset + 1, 0);
1183 LinkedPositionUI editorSQ = new LinkedPositionUI(
1184 sourceViewer, managerSQ);
1185 editorSQ.setCancelListener(this);
1186 editorSQ.setExitPolicy(new ExitPolicy(
1187 closingCharacterSQ));
1188 editorSQ.setFinalCaretOffset(offset + 2);
1190 IRegion newSelectionSQ = editorSQ.getSelectedRegion();
1191 sourceViewer.setSelectedRange(newSelectionSQ
1192 .getOffset(), newSelectionSQ.getLength());
1194 case '\r': { // insert linebreaks and new closing brace
1195 // after brace and return
1196 if (!fCloseBracketsPHP) {
1199 if (hasCharacterToTheLeft(document, offset, '{')
1200 && hasCharacterToTheRight(document, offset, '}')) {
1201 String lineDelimiter = StubUtility
1202 .getLineDelimiterFor(document);
1203 int caretPos = sourceViewer.getTextWidget()
1205 final StringBuffer buffer = new StringBuffer(
1208 IRegion line = document
1209 .getLineInformationOfOffset(offset);
1210 String currentLine = document.get(line.getOffset(),
1213 int max = currentLine.length();
1214 StringBuffer indent = new StringBuffer();
1216 && Character.isWhitespace(currentLine
1218 indent.append(currentLine.charAt(index));
1221 buffer.append(indent);
1222 JavaHeuristicScanner scanner = new JavaHeuristicScanner(
1224 JavaIndenter indenter = new JavaIndenter(document,
1226 buffer.append(indenter.createIndent(1));
1227 int cursorPos = buffer.length();
1228 buffer.append(lineDelimiter);
1229 buffer.append(indent);
1230 document.replace(offset, length, buffer.toString());
1231 sourceViewer.getTextWidget().setCaretOffset(
1232 caretPos + cursorPos);
1238 } catch (BadLocationException e) {
1243 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1245 public void exit(boolean accept) {
1250 final ISourceViewer sourceViewer = getSourceViewer();
1251 IDocument document = sourceViewer.getDocument();
1252 document.replace(fOffset, fLength, null);
1253 } catch (BadLocationException e) {
1258 /** The editor's save policy */
1259 protected ISavePolicy fSavePolicy;
1262 * Listener to annotation model changes that updates the error tick in the
1265 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1267 /** The editor's paint manager */
1268 // private PaintManager fPaintManager;
1269 /** The editor's bracket painter */
1270 // private BracketPainter fBracketPainter;
1271 /** The editor's bracket matcher */
1272 private PHPPairMatcher fBracketMatcher;
1274 /** The editor's line painter */
1275 // private LinePainter fLinePainter;
1276 /** The editor's print margin ruler painter */
1277 // private PrintMarginPainter fPrintMarginPainter;
1278 /** The editor's problem painter */
1279 // private ProblemPainter fProblemPainter;
1280 /** The editor's tab converter */
1281 private TabConverter fTabConverter;
1283 /** History for structure select action */
1284 // private SelectionHistory fSelectionHistory;
1285 /** The preference property change listener for php core. */
1286 // private IPropertyChangeListener fPropertyChangeListener = new
1287 // PropertyChangeListener();
1288 /** The remembered java element */
1289 private IJavaElement fRememberedElement;
1292 * The remembered selection.
1296 private RememberedSelection fRememberedSelection = new RememberedSelection();
1298 /** The remembered php element offset */
1299 private int fRememberedElementOffset;
1301 /** The bracket inserter. */
1302 private BracketInserter fBracketInserter = new BracketInserter();
1304 /** The standard action groups added to the menu */
1305 private GenerateActionGroup fGenerateActionGroup;
1307 private CompositeActionGroup fContextMenuGroup;
1309 // private class PropertyChangeListener implements IPropertyChangeListener {
1311 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1314 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1316 // handlePreferencePropertyChanged(event);
1319 /* Preference key for code formatter tab size */
1320 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1322 /** Preference key for matching brackets */
1323 // private final static String MATCHING_BRACKETS =
1324 // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1325 /** Preference key for matching brackets color */
1326 // private final static String MATCHING_BRACKETS_COLOR =
1327 // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1328 /** Preference key for highlighting current line */
1329 // private final static String CURRENT_LINE =
1330 // PreferenceConstants.EDITOR_CURRENT_LINE;
1331 /** Preference key for highlight color of current line */
1332 // private final static String CURRENT_LINE_COLOR =
1333 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1334 /** Preference key for showing print marging ruler */
1335 // private final static String PRINT_MARGIN =
1336 // PreferenceConstants.EDITOR_PRINT_MARGIN;
1337 /** Preference key for print margin ruler color */
1338 // private final static String PRINT_MARGIN_COLOR =
1339 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1340 /** Preference key for print margin ruler column */
1341 // private final static String PRINT_MARGIN_COLUMN =
1342 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1343 /** Preference key for inserting spaces rather than tabs */
1344 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1346 /** Preference key for error indication */
1347 // private final static String ERROR_INDICATION =
1348 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1349 /** Preference key for error color */
1350 // private final static String ERROR_INDICATION_COLOR =
1351 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1352 /** Preference key for warning indication */
1353 // private final static String WARNING_INDICATION =
1354 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1355 /** Preference key for warning color */
1356 // private final static String WARNING_INDICATION_COLOR =
1357 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1358 /** Preference key for task indication */
1359 private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1361 /** Preference key for task color */
1362 private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1364 /** Preference key for bookmark indication */
1365 private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1367 /** Preference key for bookmark color */
1368 private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1370 /** Preference key for search result indication */
1371 private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1373 /** Preference key for search result color */
1374 private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1376 /** Preference key for unknown annotation indication */
1377 private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1379 /** Preference key for unknown annotation color */
1380 private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1382 /** Preference key for linked position color */
1383 private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1385 /** Preference key for shwoing the overview ruler */
1386 private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1388 /** Preference key for error indication in overview ruler */
1389 private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1391 /** Preference key for warning indication in overview ruler */
1392 private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1394 /** Preference key for task indication in overview ruler */
1395 private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1397 /** Preference key for bookmark indication in overview ruler */
1398 private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1400 /** Preference key for search result indication in overview ruler */
1401 private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1403 /** Preference key for unknown annotation indication in overview ruler */
1404 private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1406 /** Preference key for automatically closing double quoted strings */
1407 private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1409 /** Preference key for automatically closing single quoted strings */
1410 private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1412 /** Preference key for automatically wrapping Java strings */
1413 // private final static String WRAP_STRINGS =
1414 // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1415 /** Preference key for automatically closing brackets and parenthesis */
1416 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1418 /** Preference key for automatically closing phpdocs and comments */
1419 private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1421 /** Preference key for automatically adding phpdoc tags */
1422 private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1424 /** Preference key for automatically formatting phpdocs */
1425 // private final static String FORMAT_JAVADOCS =
1426 // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1427 /** Preference key for automatically closing strings */
1428 private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1430 /** Preference key for automatically closing brackets and parenthesis */
1431 private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1433 /** Preference key for smart paste */
1434 private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1436 // private final static class AnnotationInfo {
1437 // public String fColorPreference;
1438 // public String fOverviewRulerPreference;
1439 // public String fEditorPreference;
1441 // private final static Map ANNOTATION_MAP;
1444 // AnnotationInfo info;
1445 // ANNOTATION_MAP = new HashMap();
1447 // info = new AnnotationInfo();
1448 // info.fColorPreference = TASK_INDICATION_COLOR;
1449 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1450 // info.fEditorPreference = TASK_INDICATION;
1451 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1453 // info = new AnnotationInfo();
1454 // info.fColorPreference = ERROR_INDICATION_COLOR;
1455 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1456 // info.fEditorPreference = ERROR_INDICATION;
1457 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1459 // info = new AnnotationInfo();
1460 // info.fColorPreference = WARNING_INDICATION_COLOR;
1461 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1462 // info.fEditorPreference = WARNING_INDICATION;
1463 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1465 // info = new AnnotationInfo();
1466 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1467 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1468 // info.fEditorPreference = BOOKMARK_INDICATION;
1469 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1471 // info = new AnnotationInfo();
1472 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1473 // info.fOverviewRulerPreference =
1474 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1475 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1476 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1478 // info = new AnnotationInfo();
1479 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1480 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1481 // info.fEditorPreference = UNKNOWN_INDICATION;
1482 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1485 // private final static AnnotationType[] ANNOTATION_LAYERS =
1486 // new AnnotationType[] {
1487 // AnnotationType.UNKNOWN,
1488 // AnnotationType.BOOKMARK,
1489 // AnnotationType.TASK,
1490 // AnnotationType.SEARCH,
1491 // AnnotationType.WARNING,
1492 // AnnotationType.ERROR };
1494 * Creates a new php unit editor.
1498 * Reconciling listeners.
1502 private ListenerList fReconcilingListeners = new ListenerList();
1505 * Mutex for the reconciler. See
1506 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1509 * TODO remove once the underlying problem is solved.
1512 private final Object fReconcilerLock = new Object();
1514 public PHPUnitEditor() {
1516 setDocumentProvider(PHPeclipsePlugin.getDefault()
1517 .getCompilationUnitDocumentProvider());
1518 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1519 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1520 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1521 // don't set help contextId, we install our own help context
1523 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1527 * @see AbstractTextEditor#createActions()
1529 protected void createActions() {
1530 super.createActions();
1532 // Action action= new
1533 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1534 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1536 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1537 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1538 // markAsStateDependentAction("CorrectionAssistProposal", true);
1540 // // WorkbenchHelp.setHelp(action,
1541 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1542 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1543 "ContentAssistProposal.", this); //$NON-NLS-1$
1545 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1546 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1547 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1548 // WorkbenchHelp.setHelp(action,
1549 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1551 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1552 // "ContentAssistContextInformation.", this,
1553 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1555 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1556 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1557 // markAsStateDependentAction("ContentAssistContextInformation", true);
1559 // WorkbenchHelp.setHelp(action,
1560 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1562 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1563 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1565 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1566 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1567 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1569 // // WorkbenchHelp.setHelp(action,
1570 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1571 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1572 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1573 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1574 setAction("Comment", action); //$NON-NLS-1$
1575 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1576 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1577 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1578 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1579 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1580 setAction("Uncomment", action); //$NON-NLS-1$
1581 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1582 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1584 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1585 "ToggleComment.", this); //$NON-NLS-1$
1587 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1588 setAction("ToggleComment", action); //$NON-NLS-1$
1589 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1590 // WorkbenchHelp.setHelp(action,
1591 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1592 configureToggleCommentAction();
1594 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1595 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1596 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1597 setAction("Format", action); //$NON-NLS-1$
1598 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1599 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1600 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1603 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1604 // "AddBlockComment.", this); //$NON-NLS-1$
1606 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1607 // setAction("AddBlockComment", action); //$NON-NLS-1$
1608 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1609 // markAsSelectionDependentAction("AddBlockComment", true);
1611 // // WorkbenchHelp.setHelp(action,
1612 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1613 // action = new RemoveBlockCommentAction(
1614 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1617 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1618 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1619 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1620 // markAsSelectionDependentAction("RemoveBlockComment", true);
1622 // WorkbenchHelp.setHelp(action,
1623 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1624 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1625 "Indent.", this, false); //$NON-NLS-1$
1626 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1627 setAction("Indent", action); //$NON-NLS-1$
1628 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1629 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1630 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1632 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1633 // "Indent.", this, true); //$NON-NLS-1$
1634 // setAction("IndentOnTab", action); //$NON-NLS-1$
1635 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1636 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1639 action = new AddBlockCommentAction(PHPEditorMessages
1640 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1642 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1643 setAction("AddBlockComment", action); //$NON-NLS-1$
1644 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1645 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1646 // WorkbenchHelp.setHelp(action,
1647 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1649 action = new RemoveBlockCommentAction(PHPEditorMessages
1650 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1652 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1653 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1654 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1655 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1656 // WorkbenchHelp.setHelp(action,
1657 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1659 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1660 // "Indent.", this, false); //$NON-NLS-1$
1661 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1662 // setAction("Indent", action); //$NON-NLS-1$
1663 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1664 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1665 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1667 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1668 "Indent.", this, true); //$NON-NLS-1$
1669 setAction("IndentOnTab", action); //$NON-NLS-1$
1670 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1671 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1673 if (getPreferenceStore().getBoolean(
1674 PreferenceConstants.EDITOR_SMART_TAB)) {
1675 // don't replace Shift Right - have to make sure their enablement is
1676 // mutually exclusive
1677 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1678 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1680 fGenerateActionGroup = new GenerateActionGroup(this,
1681 ITextEditorActionConstants.GROUP_EDIT);
1682 // ActionGroup rg= new RefactorActionGroup(this,
1683 // ITextEditorActionConstants.GROUP_EDIT);
1685 // fActionGroups.addGroup(rg);
1686 fActionGroups.addGroup(fGenerateActionGroup);
1688 // We have to keep the context menu group separate to have better
1689 // control over positioning
1690 fContextMenuGroup = new CompositeActionGroup(
1691 new ActionGroup[] { fGenerateActionGroup
1693 // new LocalHistoryActionGroup(this,
1694 // ITextEditorActionConstants.GROUP_EDIT)
1700 * @see JavaEditor#getElementAt(int)
1702 protected IJavaElement getElementAt(int offset) {
1703 return getElementAt(offset, true);
1707 * Returns the most narrow element including the given offset. If
1708 * <code>reconcile</code> is <code>true</code> the editor's input
1709 * element is reconciled in advance. If it is <code>false</code> this
1710 * method only returns a result if the editor's input element does not need
1714 * the offset included by the retrieved element
1716 * <code>true</code> if working copy should be reconciled
1718 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1719 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1720 .getWorkingCopyManager();
1721 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1725 synchronized (unit) {
1728 return unit.getElementAt(offset);
1729 } else if (unit.isConsistent())
1730 return unit.getElementAt(offset);
1731 } catch (JavaModelException x) {
1732 PHPeclipsePlugin.log(x.getStatus());
1733 // nothing found, be tolerant and go on
1740 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1742 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1744 return EditorUtility.getWorkingCopy(element, true);
1745 } catch (JavaModelException x) {
1746 PHPeclipsePlugin.log(x.getStatus());
1747 // nothing found, be tolerant and go on
1752 public void createPartControl(Composite parent) {
1753 super.createPartControl(parent);
1754 // fPaintManager = new PaintManager(getSourceViewer());
1755 LinePainter linePainter;
1756 linePainter = new LinePainter(getSourceViewer());
1757 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
1759 // fPaintManager.addPainter(linePainter);
1760 // if (isBracketHighlightingEnabled())
1761 // startBracketHighlighting();
1762 // if (isLineHighlightingEnabled())
1763 // startLineHighlighting();
1764 // if (isPrintMarginVisible())
1765 // showPrintMargin();
1766 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1767 // while (e.hasNext()) {
1768 // AnnotationType type = (AnnotationType) e.next();
1769 // if (isAnnotationIndicationEnabled(type))
1770 // startAnnotationIndication(type);
1772 if (isTabConversionEnabled())
1773 startTabConversion();
1774 // if (isOverviewRulerVisible())
1775 // showOverviewRuler();
1777 // Preferences preferences =
1778 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1779 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1780 IPreferenceStore preferenceStore = getPreferenceStore();
1781 boolean closeBracketsPHP = preferenceStore
1782 .getBoolean(CLOSE_BRACKETS_PHP);
1783 boolean closeStringsPHPDQ = preferenceStore
1784 .getBoolean(CLOSE_STRINGS_DQ_PHP);
1785 boolean closeStringsPHPSQ = preferenceStore
1786 .getBoolean(CLOSE_STRINGS_SQ_PHP);
1787 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1788 fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ);
1789 fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ);
1790 ISourceViewer sourceViewer = getSourceViewer();
1791 if (sourceViewer instanceof ITextViewerExtension)
1792 ((ITextViewerExtension) sourceViewer)
1793 .prependVerifyKeyListener(fBracketInserter);
1796 private static char getPeerCharacter(char character) {
1797 switch (character) {
1813 throw new IllegalArgumentException();
1817 // private void startBracketHighlighting() {
1818 // if (fBracketPainter == null) {
1819 // ISourceViewer sourceViewer = getSourceViewer();
1820 // fBracketPainter = new BracketPainter(sourceViewer);
1821 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1822 // // fPaintManager.addPainter(fBracketPainter);
1826 // private void stopBracketHighlighting() {
1827 // if (fBracketPainter != null) {
1828 // // fPaintManager.removePainter(fBracketPainter);
1829 // fBracketPainter.deactivate(true);
1830 // fBracketPainter.dispose();
1831 // fBracketPainter = null;
1835 // private boolean isBracketHighlightingEnabled() {
1836 // IPreferenceStore store = getPreferenceStore();
1837 // return store.getBoolean(MATCHING_BRACKETS);
1840 // private void startLineHighlighting() {
1841 // if (fLinePainter == null) {
1842 // ISourceViewer sourceViewer = getSourceViewer();
1843 // fLinePainter = new LinePainter(sourceViewer);
1844 // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1845 // // fPaintManager.addPainter(fLinePainter);
1849 // private void stopLineHighlighting() {
1850 // if (fLinePainter != null) {
1851 // // fPaintManager.removePainter(fLinePainter);
1852 // fLinePainter.deactivate(true);
1853 // fLinePainter.dispose();
1854 // fLinePainter = null;
1858 // private boolean isLineHighlightingEnabled() {
1859 // IPreferenceStore store = getPreferenceStore();
1860 // return store.getBoolean(CURRENT_LINE);
1863 // private void showPrintMargin() {
1864 // if (fPrintMarginPainter == null) {
1865 // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1866 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1867 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1868 // // fPaintManager.addPainter(fPrintMarginPainter);
1872 // private void hidePrintMargin() {
1873 // if (fPrintMarginPainter != null) {
1874 // // fPaintManager.removePainter(fPrintMarginPainter);
1875 // fPrintMarginPainter.deactivate(true);
1876 // fPrintMarginPainter.dispose();
1877 // fPrintMarginPainter = null;
1881 // private boolean isPrintMarginVisible() {
1882 // IPreferenceStore store = getPreferenceStore();
1883 // return store.getBoolean(PRINT_MARGIN);
1886 private int getTabSize() {
1887 Preferences preferences = PHPeclipsePlugin.getDefault()
1888 .getPluginPreferences();
1889 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1892 private boolean isTabConversionEnabled() {
1893 IPreferenceStore store = getPreferenceStore();
1894 return store.getBoolean(SPACES_FOR_TABS);
1897 private Color getColor(String key) {
1898 RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1899 return getColor(rgb);
1902 private Color getColor(RGB rgb) {
1903 JavaTextTools textTools = PHPeclipsePlugin.getDefault()
1904 .getJavaTextTools();
1905 return textTools.getColorManager().getColor(rgb);
1908 // private Color getColor(AnnotationType annotationType) {
1909 // AnnotationInfo info = (AnnotationInfo)
1910 // ANNOTATION_MAP.get(annotationType);
1911 // if (info != null)
1912 // return getColor(info.fColorPreference);
1915 public void dispose() {
1916 ISourceViewer sourceViewer = getSourceViewer();
1917 if (sourceViewer instanceof ITextViewerExtension)
1918 ((ITextViewerExtension) sourceViewer)
1919 .removeVerifyKeyListener(fBracketInserter);
1920 // if (fPropertyChangeListener != null) {
1921 // Preferences preferences =
1922 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1923 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1924 // fPropertyChangeListener = null;
1926 if (fJavaEditorErrorTickUpdater != null) {
1927 fJavaEditorErrorTickUpdater.dispose();
1928 fJavaEditorErrorTickUpdater = null;
1930 // if (fSelectionHistory != null)
1931 // fSelectionHistory.dispose();
1932 // if (fPaintManager != null) {
1933 // fPaintManager.dispose();
1934 // fPaintManager = null;
1936 if (fActionGroups != null) {
1937 fActionGroups.dispose();
1938 fActionGroups = null;
1943 // protected AnnotationType getAnnotationType(String preferenceKey) {
1944 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1945 // while (e.hasNext()) {
1946 // AnnotationType type = (AnnotationType) e.next();
1947 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1948 // if (info != null) {
1949 // if (preferenceKey.equals(info.fColorPreference)
1950 // || preferenceKey.equals(info.fEditorPreference)
1951 // || preferenceKey.equals(info.fOverviewRulerPreference))
1958 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1960 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1962 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1964 String p = event.getProperty();
1965 if (CLOSE_BRACKETS_PHP.equals(p)) {
1967 .setCloseBracketsPHPEnabled(getPreferenceStore()
1971 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
1973 .setCloseStringsPHPDQEnabled(getPreferenceStore()
1977 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
1979 .setCloseStringsPHPSQEnabled(getPreferenceStore()
1983 if (SPACES_FOR_TABS.equals(p)) {
1984 if (isTabConversionEnabled())
1985 startTabConversion();
1987 stopTabConversion();
1990 // if (MATCHING_BRACKETS.equals(p)) {
1991 // if (isBracketHighlightingEnabled())
1992 // startBracketHighlighting();
1994 // stopBracketHighlighting();
1997 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
1998 // if (fBracketPainter != null)
1999 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
2002 // if (CURRENT_LINE.equals(p)) {
2003 // if (isLineHighlightingEnabled())
2004 // startLineHighlighting();
2006 // stopLineHighlighting();
2009 // if (CURRENT_LINE_COLOR.equals(p)) {
2010 // if (fLinePainter != null) {
2011 // stopLineHighlighting();
2012 // startLineHighlighting();
2016 // if (PRINT_MARGIN.equals(p)) {
2017 // if (isPrintMarginVisible())
2018 // showPrintMargin();
2020 // hidePrintMargin();
2023 // if (PRINT_MARGIN_COLOR.equals(p)) {
2024 // if (fPrintMarginPainter != null)
2025 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2028 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2029 // if (fPrintMarginPainter != null)
2030 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2033 // if (OVERVIEW_RULER.equals(p)) {
2034 // if (isOverviewRulerVisible())
2035 // showOverviewRuler();
2037 // hideOverviewRuler();
2040 // AnnotationType type = getAnnotationType(p);
2041 // if (type != null) {
2043 // AnnotationInfo info = (AnnotationInfo)
2044 // ANNOTATION_MAP.get(type);
2045 // if (info.fColorPreference.equals(p)) {
2046 // Color color = getColor(type);
2047 // if (fProblemPainter != null) {
2048 // fProblemPainter.setColor(type, color);
2049 // fProblemPainter.paint(IPainter.CONFIGURATION);
2051 // setColorInOverviewRuler(type, color);
2055 // if (info.fEditorPreference.equals(p)) {
2056 // if (isAnnotationIndicationEnabled(type))
2057 // startAnnotationIndication(type);
2059 // stopAnnotationIndication(type);
2063 // if (info.fOverviewRulerPreference.equals(p)) {
2064 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2065 // showAnnotationIndicationInOverviewRuler(type, true);
2067 // showAnnotationIndicationInOverviewRuler(type, false);
2071 IContentAssistant c = asv.getContentAssistant();
2072 if (c instanceof ContentAssistant)
2073 ContentAssistPreference.changeConfiguration(
2074 (ContentAssistant) c, getPreferenceStore(), event);
2077 super.handlePreferenceStoreChanged(event);
2082 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2084 protected void handlePreferencePropertyChanged(
2085 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2086 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2088 String p = event.getProperty();
2089 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2090 asv.updateIndentationPrefixes();
2091 if (fTabConverter != null)
2092 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2095 super.handlePreferencePropertyChanged(event);
2099 * Handles a property change event describing a change of the php core's
2100 * preferences and updates the preference related editor properties.
2103 * the property change event
2106 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2108 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2109 // if (asv != null) {
2110 // String p = event.getProperty();
2111 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2112 // asv.updateIndentationPrefixes();
2113 // if (fTabConverter != null)
2114 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2119 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2120 * org.eclipse.jface.text.source.IVerticalRuler,
2121 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2123 protected ISourceViewer createJavaSourceViewer(Composite parent,
2124 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2125 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2126 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2127 isOverviewRulerVisible, styles, store);
2130 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2131 // IVerticalRuler ruler, int styles) {
2132 // return new AdaptedSourceViewer(parent, ruler, styles);
2134 private boolean isValidSelection(int offset, int length) {
2135 IDocumentProvider provider = getDocumentProvider();
2136 if (provider != null) {
2137 IDocument document = provider.getDocument(getEditorInput());
2138 if (document != null) {
2139 int end = offset + length;
2140 int documentLength = document.getLength();
2141 return 0 <= offset && offset <= documentLength && 0 <= end
2142 && end <= documentLength;
2149 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2151 protected IJavaElement getInputJavaElement() {
2152 return PHPeclipsePlugin.getDefault().getWorkingCopyManager()
2153 .getWorkingCopy(getEditorInput());
2157 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2159 public void editorContextMenuAboutToShow(IMenuManager menu) {
2160 super.editorContextMenuAboutToShow(menu);
2161 ActionContext context = new ActionContext(getSelectionProvider()
2163 fContextMenuGroup.setContext(context);
2164 fContextMenuGroup.fillContextMenu(menu);
2165 fContextMenuGroup.setContext(null);
2169 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2171 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2173 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2174 .getWorkingCopyManager();
2175 page.setInput(manager.getWorkingCopy(input));
2180 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2183 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2184 // IProgressMonitor progressMonitor) {
2185 // IDocumentProvider p = getDocumentProvider();
2186 // if (p instanceof PHPDocumentProvider) {
2187 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2188 // cp.setSavePolicy(fSavePolicy);
2192 // super.performSaveOperation(operation, progressMonitor);
2194 // if (p instanceof PHPDocumentProvider) {
2195 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2196 // cp.setSavePolicy(null);
2201 * @see AbstractTextEditor#doSave(IProgressMonitor)
2203 public void doSave(IProgressMonitor progressMonitor) {
2205 IDocumentProvider p = getDocumentProvider();
2207 // editor has been closed
2211 if (p.isDeleted(getEditorInput())) {
2213 if (isSaveAsAllowed()) {
2216 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2217 * the editors. Changed Behavior to make sure that if called
2218 * inside a regular save (because of deletion of input element)
2219 * there is a way to report back to the caller.
2221 performSaveAs(progressMonitor);
2226 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2227 * there Missing resources.
2229 Shell shell = getSite().getShell();
2234 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2238 if (getPreferenceStore().getBoolean(
2239 PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2240 RTrimAction trimAction = new RTrimAction();
2241 trimAction.setActiveEditor(null, getSite().getPage()
2242 .getActiveEditor());
2243 trimAction.run(null);
2246 setStatusLineErrorMessage(null);
2248 updateState(getEditorInput());
2249 validateState(getEditorInput());
2251 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2252 .getWorkingCopyManager();
2253 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2256 synchronized (unit) {
2257 performSave(false, progressMonitor);
2260 performSave(false, progressMonitor);
2264 public boolean isSaveAsAllowed() {
2269 * The compilation unit editor implementation of this
2270 * <code>AbstractTextEditor</code> method asks the user for the workspace
2271 * path of a file resource and saves the document there. See
2272 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2274 * @param progressMonitor
2275 * the progress monitor
2277 protected void performSaveAs(IProgressMonitor progressMonitor) {
2279 Shell shell = getSite().getShell();
2280 IEditorInput input = getEditorInput();
2282 SaveAsDialog dialog = new SaveAsDialog(shell);
2284 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2287 if (original != null)
2288 dialog.setOriginalFile(original);
2292 IDocumentProvider provider = getDocumentProvider();
2293 if (provider == null) {
2294 // editor has been programmatically closed while the dialog was open
2298 if (provider.isDeleted(input) && original != null) {
2299 String message = PHPEditorMessages
2300 .getFormattedString(
2301 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2302 dialog.setErrorMessage(null);
2303 dialog.setMessage(message, IMessageProvider.WARNING);
2306 if (dialog.open() == Window.CANCEL) {
2307 if (progressMonitor != null)
2308 progressMonitor.setCanceled(true);
2312 IPath filePath = dialog.getResult();
2313 if (filePath == null) {
2314 if (progressMonitor != null)
2315 progressMonitor.setCanceled(true);
2319 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2320 IFile file = workspaceRoot.getFile(filePath);
2321 final IEditorInput newInput = new FileEditorInput(file);
2323 boolean success = false;
2326 provider.aboutToChange(newInput);
2327 getDocumentProvider().saveDocument(progressMonitor, newInput,
2328 getDocumentProvider().getDocument(getEditorInput()), true);
2331 } catch (CoreException x) {
2332 IStatus status = x.getStatus();
2333 if (status == null || status.getSeverity() != IStatus.CANCEL)
2338 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2340 provider.changed(newInput);
2345 if (progressMonitor != null)
2346 progressMonitor.setCanceled(!success);
2350 * @see AbstractTextEditor#doSetInput(IEditorInput)
2352 protected void doSetInput(IEditorInput input) throws CoreException {
2353 super.doSetInput(input);
2354 configureTabConverter();
2355 configureToggleCommentAction();
2360 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2363 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2364 // IAnnotationModel model=
2365 // getDocumentProvider().getAnnotationModel(getEditorInput());
2366 // if (!waitForReconcilation)
2367 // super.installOverrideIndicator(false);
2369 // uninstallOverrideIndicator();
2370 // IJavaElement inputElement= getInputJavaElement();
2371 // if (model == null || inputElement == null)
2374 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2375 // inputElement, null);
2376 // addReconcileListener(fOverrideIndicatorManager);
2382 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2385 // protected void uninstallOverrideIndicator() {
2386 // if (fOverrideIndicatorManager != null)
2387 // removeReconcileListener(fOverrideIndicatorManager);
2388 // super.uninstallOverrideIndicator();
2392 * Configures the toggle comment action
2396 private void configureToggleCommentAction() {
2397 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2398 if (action instanceof ToggleCommentAction) {
2399 ISourceViewer sourceViewer = getSourceViewer();
2400 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2401 ((ToggleCommentAction) action).configure(sourceViewer,
2406 // private void configureTabConverter() {
2407 // if (fTabConverter != null) {
2408 // IDocumentProvider provider = getDocumentProvider();
2409 // if (provider instanceof PHPDocumentProvider) {
2410 // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2411 // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2415 private void configureTabConverter() {
2416 if (fTabConverter != null) {
2417 IDocumentProvider provider = getDocumentProvider();
2418 if (provider instanceof ICompilationUnitDocumentProvider) {
2419 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2420 fTabConverter.setLineTracker(cup
2421 .createLineTracker(getEditorInput()));
2426 private void startTabConversion() {
2427 if (fTabConverter == null) {
2428 fTabConverter = new TabConverter();
2429 configureTabConverter();
2430 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2431 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2432 asv.addTextConverter(fTabConverter);
2433 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2434 asv.updateIndentationPrefixes();
2438 private void stopTabConversion() {
2439 if (fTabConverter != null) {
2440 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2441 asv.removeTextConverter(fTabConverter);
2442 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2443 asv.updateIndentationPrefixes();
2444 fTabConverter = null;
2449 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2450 * org.eclipse.core.runtime.IProgressMonitor)
2452 protected void performSave(boolean overwrite,
2453 IProgressMonitor progressMonitor) {
2454 // IDocumentProvider p = getDocumentProvider();
2455 // if (p instanceof PHPDocumentProvider) {
2456 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2457 // cp.setSavePolicy(fSavePolicy);
2460 // super.performSave(overwrite, progressMonitor);
2462 // if (p instanceof PHPDocumentProvider) {
2463 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2464 // cp.setSavePolicy(null);
2468 IDocumentProvider p = getDocumentProvider();
2469 if (p instanceof ICompilationUnitDocumentProvider) {
2470 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2471 cp.setSavePolicy(fSavePolicy);
2474 super.performSave(overwrite, progressMonitor);
2476 if (p instanceof ICompilationUnitDocumentProvider) {
2477 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2478 cp.setSavePolicy(null);
2484 * @see AbstractTextEditor#doSaveAs
2486 public void doSaveAs() {
2487 if (askIfNonWorkbenchEncodingIsOk()) {
2493 * Asks the user if it is ok to store in non-workbench encoding.
2495 * @return <true>if the user wants to continue
2497 private boolean askIfNonWorkbenchEncodingIsOk() {
2498 IDocumentProvider provider = getDocumentProvider();
2499 if (provider instanceof IStorageDocumentProvider) {
2500 IEditorInput input = getEditorInput();
2501 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2502 String encoding = storageProvider.getEncoding(input);
2503 String defaultEncoding = storageProvider.getDefaultEncoding();
2504 if (encoding != null && !encoding.equals(defaultEncoding)) {
2505 Shell shell = getSite().getShell();
2506 String title = PHPEditorMessages
2507 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2513 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2514 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2519 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2520 new String[] { encoding }); //$NON-NLS-1$
2521 return MessageDialog.openQuestion(shell, title, msg);
2528 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2531 public void aboutToBeReconciled() {
2533 // Notify AST provider
2534 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2537 Object[] listeners = fReconcilingListeners.getListeners();
2538 for (int i = 0, length = listeners.length; i < length; ++i)
2539 ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2543 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2544 * boolean, IProgressMonitor)
2547 public void reconciled(CompilationUnit ast, boolean forced,
2548 IProgressMonitor progressMonitor) {
2550 // Always notify AST provider
2551 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2552 // getInputJavaElement());
2555 // Object[] listeners = fReconcilingListeners.getListeners();
2556 // for (int i = 0, length= listeners.length; i < length; ++i)
2557 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2558 // progressMonitor);
2560 // Update Java Outline page selection
2561 if (!forced && !progressMonitor.isCanceled()) {
2562 Shell shell = getSite().getShell();
2563 if (shell != null && !shell.isDisposed()) {
2564 shell.getDisplay().asyncExec(new Runnable() {
2574 * Returns the updated java element for the old java element.
2576 private IJavaElement findElement(IJavaElement element) {
2577 if (element == null)
2579 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2580 .getWorkingCopyManager();
2581 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2584 synchronized (unit) {
2587 IJavaElement[] findings = unit.findElements(element);
2588 if (findings != null && findings.length > 0)
2590 } catch (JavaModelException x) {
2591 PHPeclipsePlugin.log(x.getStatus());
2592 // nothing found, be tolerant and go on
2599 * Returns the offset of the given Java element.
2601 private int getOffset(IJavaElement element) {
2602 if (element instanceof ISourceReference) {
2603 ISourceReference sr = (ISourceReference) element;
2605 ISourceRange srcRange = sr.getSourceRange();
2606 if (srcRange != null)
2607 return srcRange.getOffset();
2608 } catch (JavaModelException e) {
2615 * @see AbstractTextEditor#restoreSelection()
2617 // protected void restoreSelection() {
2619 // if (getSourceViewer() == null || fRememberedSelection == null)
2621 // IJavaElement newElement = findElement(fRememberedElement);
2622 // int newOffset = getOffset(newElement);
2623 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2624 // - fRememberedElementOffset : 0;
2625 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2626 // fRememberedSelection.getLength()))
2627 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2628 // fRememberedSelection.getLength());
2630 // fRememberedSelection = null;
2631 // fRememberedElement = null;
2632 // fRememberedElementOffset = -1;
2636 * Tells whether this is the active editor in the active page.
2638 * @return <code>true</code> if this is the active editor in the active
2640 * @see IWorkbenchPage#getActiveEditor();
2642 protected final boolean isActiveEditor() {
2643 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2644 IWorkbenchPage page = window.getActivePage();
2647 IEditorPart activeEditor = page.getActiveEditor();
2648 return activeEditor != null && activeEditor.equals(this);
2652 * Adds the given listener. Has no effect if an identical listener was not
2653 * already registered.
2656 * The reconcile listener to be added
2659 final void addReconcileListener(IJavaReconcilingListener listener) {
2660 synchronized (fReconcilingListeners) {
2661 fReconcilingListeners.add(listener);
2666 * Removes the given listener. Has no effect if an identical listener was
2667 * not already registered.
2670 * the reconcile listener to be removed
2673 final void removeReconcileListener(IJavaReconcilingListener listener) {
2674 synchronized (fReconcilingListeners) {
2675 fReconcilingListeners.remove(listener);
2679 protected void updateStateDependentActions() {
2680 super.updateStateDependentActions();
2681 fGenerateActionGroup.editorStateChanged();
2685 * @see AbstractTextEditor#rememberSelection()
2687 protected void rememberSelection() {
2688 fRememberedSelection.remember();
2692 * @see AbstractTextEditor#restoreSelection()
2694 protected void restoreSelection() {
2695 fRememberedSelection.restore();
2699 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2701 protected boolean canHandleMove(IEditorInput originalElement,
2702 IEditorInput movedElement) {
2704 String oldExtension = ""; //$NON-NLS-1$
2705 if (originalElement instanceof IFileEditorInput) {
2706 IFile file = ((IFileEditorInput) originalElement).getFile();
2708 String ext = file.getFileExtension();
2714 String newExtension = ""; //$NON-NLS-1$
2715 if (movedElement instanceof IFileEditorInput) {
2716 IFile file = ((IFileEditorInput) movedElement).getFile();
2718 newExtension = file.getFileExtension();
2721 return oldExtension.equals(newExtension);
2725 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2727 protected boolean isPrefQuickDiffAlwaysOn() {
2728 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2729 // was hacked by JavaEditor
2730 // to disable the change bar for the class file (attached source) java
2732 IPreferenceStore store = getPreferenceStore();
2734 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2738 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2740 public Object getAdapter(Class required) {
2741 if (SmartBackspaceManager.class.equals(required)) {
2742 if (getSourceViewer() instanceof JavaSourceViewer) {
2743 return ((JavaSourceViewer) getSourceViewer())
2744 .getBackspaceManager();
2748 return super.getAdapter(required);
2752 * Returns the mutex for the reconciler. See
2753 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2756 * TODO remove once the underlying problem is solved.
2759 * @return the lock reconcilers may use to synchronize on
2761 public Object getReconcilerLock() {
2762 return fReconcilerLock;
2768 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2770 protected void editorSaved() {
2771 super.editorSaved();
2772 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2774 //a.refresh(ShowExternalPreviewAction.PHP_TYPE);
2775 a.doRun(ShowExternalPreviewAction.PHP_TYPE);