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 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
419 public void configure(SourceViewerConfiguration configuration) {
420 super.configure(configuration);
421 // fCorrectionAssistant = new
422 // JavaCorrectionAssistant(CompilationUnitEditor.this);
423 // fCorrectionAssistant.install(this);
424 IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(
425 IPHPPartitions.PHP_PARTITIONING);
426 prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
427 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
428 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
429 prependAutoEditStrategy(smartSemi,
430 IPHPPartitions.PHP_STRING_HEREDOC);
434 * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
437 public IFormattingContext createFormattingContext() {
438 IFormattingContext context = new CommentFormattingContext();
441 IJavaElement inputJavaElement = getInputJavaElement();
442 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
445 if (javaProject == null)
446 preferences = new HashMap(JavaCore.getOptions());
448 preferences = new HashMap(javaProject.getOptions(true));
450 context.storeToMap(PreferenceConstants.getPreferenceStore(),
453 FormattingContextProperties.CONTEXT_PREFERENCES,
461 * Remembers data related to the current selection to be able to restore it
466 private class RememberedSelection {
467 /** The remembered selection start. */
468 private RememberedOffset fStartOffset = new RememberedOffset();
470 /** The remembered selection end. */
471 private RememberedOffset fEndOffset = new RememberedOffset();
474 * Remember current selection.
476 public void remember() {
478 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
479 * may be called inside an async call posted to the UI thread, so
480 * protect against intermediate disposal of the editor.
482 ISourceViewer viewer = getSourceViewer();
483 if (viewer != null) {
484 IRegion selection = getSignedSelection(viewer);
485 int startOffset = selection.getOffset();
486 int endOffset = startOffset + selection.getLength();
488 fStartOffset.setOffset(startOffset);
489 fEndOffset.setOffset(endOffset);
494 * Restore remembered selection.
496 public void restore() {
498 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
499 * may be called inside an async call posted to the UI thread, so
500 * protect against intermediate disposal of the editor.
502 if (getSourceViewer() == null)
507 int startOffset, endOffset;
508 int revealStartOffset, revealEndOffset;
509 if (showsHighlightRangeOnly()) {
510 IJavaElement newStartElement = fStartOffset.getElement();
511 startOffset = fStartOffset
512 .getRememberedOffset(newStartElement);
513 revealStartOffset = fStartOffset.getRevealOffset(
514 newStartElement, startOffset);
515 if (revealStartOffset == -1)
518 IJavaElement newEndElement = fEndOffset.getElement();
519 endOffset = fEndOffset.getRememberedOffset(newEndElement);
520 revealEndOffset = fEndOffset.getRevealOffset(newEndElement,
522 if (revealEndOffset == -1)
525 startOffset = fStartOffset.getOffset();
526 revealStartOffset = startOffset;
527 endOffset = fEndOffset.getOffset();
528 revealEndOffset = endOffset;
531 if (startOffset == -1) {
532 startOffset = endOffset; // fallback to caret offset
533 revealStartOffset = revealEndOffset;
536 if (endOffset == -1) {
537 endOffset = startOffset; // fallback to other offset
538 revealEndOffset = revealStartOffset;
541 IJavaElement element;
542 if (endOffset == -1) {
543 // fallback to element selection
544 element = fEndOffset.getElement();
546 element = fStartOffset.getElement();
548 setSelection(element);
552 if (isValidSelection(revealStartOffset, revealEndOffset
554 && isValidSelection(startOffset, endOffset
556 selectAndReveal(startOffset, endOffset - startOffset,
557 revealStartOffset, revealEndOffset
558 - revealStartOffset);
560 fStartOffset.clear();
565 private boolean isValidSelection(int offset, int length) {
566 IDocumentProvider provider = getDocumentProvider();
567 if (provider != null) {
568 IDocument document = provider.getDocument(getEditorInput());
569 if (document != null) {
570 int end = offset + length;
571 int documentLength = document.getLength();
572 return 0 <= offset && offset <= documentLength && 0 <= end
573 && end <= documentLength;
582 * Remembers additional data for a given offset to be able restore it later.
586 private class RememberedOffset {
587 /** Remembered line for the given offset */
590 /** Remembered column for the given offset */
593 /** Remembered Java element for the given offset */
594 private IJavaElement fElement;
596 /** Remembered Java element line for the given offset */
597 private int fElementLine;
600 * Store visual properties of the given offset.
603 * Offset in the document
605 public void setOffset(int offset) {
607 IDocument document = getSourceViewer().getDocument();
608 fLine = document.getLineOfOffset(offset);
609 fColumn = offset - document.getLineOffset(fLine);
610 fElement = getElementAt(offset, true);
613 if (fElement instanceof IMember) {
614 ISourceRange range = ((IMember) fElement).getNameRange();
616 fElementLine = document.getLineOfOffset(range
619 if (fElementLine == -1)
620 fElementLine = document
621 .getLineOfOffset(getOffset(fElement));
622 } catch (BadLocationException e) {
624 PHPeclipsePlugin.log(e);
626 } catch (JavaModelException e) {
628 PHPeclipsePlugin.log(e.getStatus());
634 * Return offset recomputed from stored visual properties.
636 * @return Offset in the document
638 public int getOffset() {
639 IJavaElement newElement = getElement();
641 int offset = getRememberedOffset(newElement);
643 if (offset != -1 && !containsOffset(newElement, offset)
644 && (offset == 0 || !containsOffset(newElement, offset - 1)))
651 * Return offset recomputed from stored visual properties.
655 * @return Offset in the document
657 public int getRememberedOffset(IJavaElement newElement) {
659 if (newElement == null)
662 IDocument document = getSourceViewer().getDocument();
663 int newElementLine = -1;
664 if (newElement instanceof IMember) {
665 ISourceRange range = ((IMember) newElement).getNameRange();
667 newElementLine = document.getLineOfOffset(range
670 if (newElementLine == -1)
671 newElementLine = document
672 .getLineOfOffset(getOffset(newElement));
673 if (newElementLine == -1)
676 int newLine = fLine + newElementLine - fElementLine;
677 if (newLine < 0 || newLine >= document.getNumberOfLines())
679 int maxColumn = document.getLineLength(newLine);
680 String lineDelimiter = document.getLineDelimiter(newLine);
681 if (lineDelimiter != null)
682 maxColumn = maxColumn - lineDelimiter.length();
684 if (fColumn > maxColumn)
685 offset = document.getLineOffset(newLine) + maxColumn;
687 offset = document.getLineOffset(newLine) + fColumn;
690 } catch (BadLocationException e) {
692 PHPeclipsePlugin.log(e);
694 } catch (JavaModelException e) {
696 PHPeclipsePlugin.log(e.getStatus());
702 * Returns the offset used to reveal the given element based on the
703 * given selection offset.
708 * the selection offset
709 * @return the offset to reveal the given element based on the given
712 public int getRevealOffset(IJavaElement element, int offset) {
713 if (element == null || offset == -1)
716 if (containsOffset(element, offset)) {
718 IJavaElement alternateElement = getElementAt(offset, false);
719 if (element.getHandleIdentifier().equals(
720 alternateElement.getParent().getHandleIdentifier()))
721 return offset - 1; // Solves test case 2 from
722 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
725 } else if (offset > 0 && containsOffset(element, offset - 1))
726 return offset - 1; // Solves test case 1 from
727 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
733 * Return Java element recomputed from stored visual properties.
735 * @return Java element
737 public IJavaElement getElement() {
738 if (fElement == null)
741 return findElement(fElement);
745 * Clears the stored position
747 public void clear() {
755 * Does the given Java element contain the given offset?
761 * @return <code>true</code> iff the Java element contains the offset
763 private boolean containsOffset(IJavaElement element, int offset) {
764 int elementOffset = getOffset(element);
765 int elementLength = getLength(element);
766 return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset
772 * Returns the offset of the given Java element.
776 * @return Offset of the given Java element
778 private int getOffset(IJavaElement element) {
779 if (element instanceof ISourceReference) {
780 ISourceReference sr = (ISourceReference) element;
782 ISourceRange srcRange = sr.getSourceRange();
783 if (srcRange != null)
784 return srcRange.getOffset();
785 } catch (JavaModelException e) {
792 * Returns the length of the given Java element.
796 * @return Length of the given Java element
798 private int getLength(IJavaElement element) {
799 if (element instanceof ISourceReference) {
800 ISourceReference sr = (ISourceReference) element;
802 ISourceRange srcRange = sr.getSourceRange();
803 if (srcRange != null)
804 return srcRange.getLength();
805 } catch (JavaModelException e) {
812 * Returns the updated java element for the old java element.
816 * @return Updated Java element
818 private IJavaElement findElement(IJavaElement element) {
823 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
824 .getWorkingCopyManager();
825 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
830 synchronized (unit) {
831 // unit.reconcile(ICompilationUnit.NO_AST, false, null,
835 IJavaElement[] findings = unit.findElements(element);
836 if (findings != null && findings.length > 0)
839 } catch (JavaModelException x) {
840 PHPeclipsePlugin.log(x.getStatus());
841 // nothing found, be tolerant and go on
850 static class TabConverter implements ITextConverter {
851 private int fTabRatio;
853 private ILineTracker fLineTracker;
855 public TabConverter() {
858 public void setNumberOfSpacesPerTab(int ratio) {
862 public void setLineTracker(ILineTracker lineTracker) {
863 fLineTracker = lineTracker;
866 private int insertTabString(StringBuffer buffer, int offsetInLine) {
869 int remainder = offsetInLine % fTabRatio;
870 remainder = fTabRatio - remainder;
871 for (int i = 0; i < remainder; i++)
876 public void customizeDocumentCommand(IDocument document,
877 DocumentCommand command) {
878 String text = command.text;
881 int index = text.indexOf('\t');
883 StringBuffer buffer = new StringBuffer();
884 fLineTracker.set(command.text);
885 int lines = fLineTracker.getNumberOfLines();
887 for (int i = 0; i < lines; i++) {
888 int offset = fLineTracker.getLineOffset(i);
889 int endOffset = offset + fLineTracker.getLineLength(i);
890 String line = text.substring(offset, endOffset);
893 IRegion firstLine = document
894 .getLineInformationOfOffset(command.offset);
895 position = command.offset - firstLine.getOffset();
897 int length = line.length();
898 for (int j = 0; j < length; j++) {
899 char c = line.charAt(j);
901 position += insertTabString(buffer, position);
908 command.text = buffer.toString();
909 } catch (BadLocationException x) {
915 private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
916 final char fExitCharacter;
918 public ExitPolicy(char exitCharacter) {
919 fExitCharacter = exitCharacter;
923 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
924 * org.eclipse.swt.events.VerifyEvent, int, int)
926 public ExitFlags doExit(LinkedPositionManager manager,
927 VerifyEvent event, int offset, int length) {
928 if (event.character == fExitCharacter) {
929 if (manager.anyPositionIncludes(offset, length))
930 return new ExitFlags(LinkedPositionUI.COMMIT
931 | LinkedPositionUI.UPDATE_CARET, false);
933 return new ExitFlags(LinkedPositionUI.COMMIT, true);
935 switch (event.character) {
937 if (manager.getFirstPosition().length == 0)
938 return new ExitFlags(0, false);
943 return new ExitFlags(LinkedPositionUI.COMMIT, true);
950 private static class BracketLevel {
955 LinkedPositionManager fManager;
957 LinkedPositionUI fEditor;
960 private class BracketInserter implements VerifyKeyListener,
961 LinkedPositionUI.ExitListener {
962 private boolean fCloseBracketsPHP = true;
964 private boolean fCloseStringsPHPDQ = true;
966 private boolean fCloseStringsPHPSQ = true;
972 public void setCloseBracketsPHPEnabled(boolean enabled) {
973 fCloseBracketsPHP = enabled;
976 public void setCloseStringsPHPDQEnabled(boolean enabled) {
977 fCloseStringsPHPDQ = enabled;
980 public void setCloseStringsPHPSQEnabled(boolean enabled) {
981 fCloseStringsPHPSQ = enabled;
984 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
987 IRegion endLine = document.getLineInformationOfOffset(end);
988 int maxEnd = endLine.getOffset() + endLine.getLength();
990 && Character.isWhitespace(document.getChar(end)))
993 && Scanner.isPHPIdentifierPart(document.getChar(end));
994 } catch (BadLocationException e) {
1000 private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1003 IRegion startLine = document.getLineInformationOfOffset(start);
1004 int minStart = startLine.getOffset();
1005 while (start != minStart
1006 && Character.isWhitespace(document.getChar(start - 1)))
1008 return start != minStart
1009 && Scanner.isPHPIdentifierPart(document
1010 .getChar(start - 1));
1011 } catch (BadLocationException e) {
1016 private boolean hasCharacterToTheLeft(IDocument document, int offset,
1020 IRegion startLine = document.getLineInformationOfOffset(start);
1021 int minStart = startLine.getOffset();
1022 while (start != minStart
1023 && Character.isWhitespace(document.getChar(start - 1)))
1025 return start != minStart
1026 && document.getChar(start - 1) == character;
1027 } catch (BadLocationException e) {
1032 private boolean hasCharacterToTheRight(IDocument document, int offset,
1036 IRegion endLine = document.getLineInformationOfOffset(end);
1037 int maxEnd = endLine.getOffset() + endLine.getLength();
1038 while (end != maxEnd
1039 && Character.isWhitespace(document.getChar(end)))
1041 return end != maxEnd && document.getChar(end) == character;
1042 } catch (BadLocationException e) {
1049 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1051 public void verifyKey(VerifyEvent event) {
1054 final ISourceViewer sourceViewer = getSourceViewer();
1055 IDocument document = sourceViewer.getDocument();
1056 final Point selection = sourceViewer.getSelectedRange();
1057 final int offset = selection.x;
1058 final int length = selection.y;
1060 ITypedRegion partition = document.getPartition(offset);
1061 String type = partition.getType();
1062 if (type.equals(IPHPPartitions.PHP_PARTITIONING)
1063 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1064 // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP
1066 switch (event.character) {
1068 if (hasCharacterToTheRight(document, offset + length,
1073 if (!fCloseBracketsPHP)
1075 if (hasIdentifierToTheRight(document, offset + length))
1079 if (!fCloseBracketsPHP)
1081 if (hasIdentifierToTheRight(document, offset + length))
1085 if (event.character == '"') {
1086 if (!fCloseStringsPHPDQ)
1088 // changed for statements like echo "" print ""
1089 // if (hasIdentifierToTheLeft(document, offset)
1091 // hasIdentifierToTheRight(document, offset +
1093 if (hasIdentifierToTheRight(document, offset
1097 // ITypedRegion partition=
1098 // document.getPartition(offset);
1100 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1102 // (partition.getOffset() != offset))
1104 final char characterDQ = event.character;
1105 final char closingCharacterDQ = getPeerCharacter(characterDQ);
1106 final StringBuffer bufferDQ = new StringBuffer();
1107 bufferDQ.append(characterDQ);
1108 bufferDQ.append(closingCharacterDQ);
1109 document.replace(offset, length, bufferDQ.toString());
1110 LinkedPositionManager managerDQ = new LinkedPositionManager(
1112 managerDQ.addPosition(offset + 1, 0);
1115 LinkedPositionUI editorDQ = new LinkedPositionUI(
1116 sourceViewer, managerDQ);
1117 editorDQ.setCancelListener(this);
1118 editorDQ.setExitPolicy(new ExitPolicy(
1119 closingCharacterDQ));
1120 editorDQ.setFinalCaretOffset(offset + 2);
1122 IRegion newSelectionDQ = editorDQ.getSelectedRegion();
1123 sourceViewer.setSelectedRange(newSelectionDQ
1124 .getOffset(), newSelectionDQ.getLength());
1128 if (event.character == '\'') {
1129 if (!fCloseStringsPHPSQ)
1131 // changed for statements like echo "" print ""
1132 // if (hasIdentifierToTheLeft(document, offset)
1134 // hasIdentifierToTheRight(document, offset +
1136 if (hasIdentifierToTheRight(document, offset
1140 // ITypedRegion partition=
1141 // document.getPartition(offset);
1143 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1145 // (partition.getOffset() != offset))
1147 final char characterSQ = event.character;
1148 final char closingCharacterSQ = getPeerCharacter(characterSQ);
1149 final StringBuffer bufferSQ = new StringBuffer();
1150 bufferSQ.append(characterSQ);
1151 bufferSQ.append(closingCharacterSQ);
1152 document.replace(offset, length, bufferSQ.toString());
1153 LinkedPositionManager managerSQ = new LinkedPositionManager(
1155 managerSQ.addPosition(offset + 1, 0);
1158 LinkedPositionUI editorSQ = new LinkedPositionUI(
1159 sourceViewer, managerSQ);
1160 editorSQ.setCancelListener(this);
1161 editorSQ.setExitPolicy(new ExitPolicy(
1162 closingCharacterSQ));
1163 editorSQ.setFinalCaretOffset(offset + 2);
1165 IRegion newSelectionSQ = editorSQ.getSelectedRegion();
1166 sourceViewer.setSelectedRange(newSelectionSQ
1167 .getOffset(), newSelectionSQ.getLength());
1169 case '\r': { // insert linebreaks and new closing brace
1170 // after brace and return
1171 if (!fCloseBracketsPHP) {
1174 if (hasCharacterToTheLeft(document, offset, '{')
1175 && hasCharacterToTheRight(document, offset, '}')) {
1176 String lineDelimiter = StubUtility
1177 .getLineDelimiterFor(document);
1178 int caretPos = sourceViewer.getTextWidget()
1180 final StringBuffer buffer = new StringBuffer(
1183 IRegion line = document
1184 .getLineInformationOfOffset(offset);
1185 String currentLine = document.get(line.getOffset(),
1188 int max = currentLine.length();
1189 StringBuffer indent = new StringBuffer();
1191 && Character.isWhitespace(currentLine
1193 indent.append(currentLine.charAt(index));
1196 buffer.append(indent);
1197 JavaHeuristicScanner scanner = new JavaHeuristicScanner(
1199 JavaIndenter indenter = new JavaIndenter(document,
1201 buffer.append(indenter.createIndent(1));
1202 int cursorPos = buffer.length();
1203 buffer.append(lineDelimiter);
1204 buffer.append(indent);
1205 document.replace(offset, length, buffer.toString());
1206 sourceViewer.getTextWidget().setCaretOffset(
1207 caretPos + cursorPos);
1213 } catch (BadLocationException e) {
1218 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1220 public void exit(boolean accept) {
1225 final ISourceViewer sourceViewer = getSourceViewer();
1226 IDocument document = sourceViewer.getDocument();
1227 document.replace(fOffset, fLength, null);
1228 } catch (BadLocationException e) {
1233 /** The editor's save policy */
1234 protected ISavePolicy fSavePolicy;
1237 * Listener to annotation model changes that updates the error tick in the
1240 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1242 /** The editor's paint manager */
1243 // private PaintManager fPaintManager;
1244 /** The editor's bracket painter */
1245 // private BracketPainter fBracketPainter;
1246 /** The editor's bracket matcher */
1247 private PHPPairMatcher fBracketMatcher;
1249 /** The editor's line painter */
1250 // private LinePainter fLinePainter;
1251 /** The editor's print margin ruler painter */
1252 // private PrintMarginPainter fPrintMarginPainter;
1253 /** The editor's problem painter */
1254 // private ProblemPainter fProblemPainter;
1255 /** The editor's tab converter */
1256 private TabConverter fTabConverter;
1258 /** History for structure select action */
1259 // private SelectionHistory fSelectionHistory;
1260 /** The preference property change listener for php core. */
1261 // private IPropertyChangeListener fPropertyChangeListener = new
1262 // PropertyChangeListener();
1263 /** The remembered java element */
1264 private IJavaElement fRememberedElement;
1267 * The remembered selection.
1271 private RememberedSelection fRememberedSelection = new RememberedSelection();
1273 /** The remembered php element offset */
1274 private int fRememberedElementOffset;
1276 /** The bracket inserter. */
1277 private BracketInserter fBracketInserter = new BracketInserter();
1279 /** The standard action groups added to the menu */
1280 private GenerateActionGroup fGenerateActionGroup;
1282 private CompositeActionGroup fContextMenuGroup;
1284 // private class PropertyChangeListener implements IPropertyChangeListener {
1286 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1289 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1291 // handlePreferencePropertyChanged(event);
1294 /* Preference key for code formatter tab size */
1295 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1297 /** Preference key for matching brackets */
1298 // private final static String MATCHING_BRACKETS =
1299 // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1300 /** Preference key for matching brackets color */
1301 // private final static String MATCHING_BRACKETS_COLOR =
1302 // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1303 /** Preference key for highlighting current line */
1304 // private final static String CURRENT_LINE =
1305 // PreferenceConstants.EDITOR_CURRENT_LINE;
1306 /** Preference key for highlight color of current line */
1307 // private final static String CURRENT_LINE_COLOR =
1308 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1309 /** Preference key for showing print marging ruler */
1310 // private final static String PRINT_MARGIN =
1311 // PreferenceConstants.EDITOR_PRINT_MARGIN;
1312 /** Preference key for print margin ruler color */
1313 // private final static String PRINT_MARGIN_COLOR =
1314 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1315 /** Preference key for print margin ruler column */
1316 // private final static String PRINT_MARGIN_COLUMN =
1317 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1318 /** Preference key for inserting spaces rather than tabs */
1319 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1321 /** Preference key for error indication */
1322 // private final static String ERROR_INDICATION =
1323 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1324 /** Preference key for error color */
1325 // private final static String ERROR_INDICATION_COLOR =
1326 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1327 /** Preference key for warning indication */
1328 // private final static String WARNING_INDICATION =
1329 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1330 /** Preference key for warning color */
1331 // private final static String WARNING_INDICATION_COLOR =
1332 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1333 /** Preference key for task indication */
1334 private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1336 /** Preference key for task color */
1337 private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1339 /** Preference key for bookmark indication */
1340 private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1342 /** Preference key for bookmark color */
1343 private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1345 /** Preference key for search result indication */
1346 private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1348 /** Preference key for search result color */
1349 private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1351 /** Preference key for unknown annotation indication */
1352 private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1354 /** Preference key for unknown annotation color */
1355 private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1357 /** Preference key for linked position color */
1358 private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1360 /** Preference key for shwoing the overview ruler */
1361 private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1363 /** Preference key for error indication in overview ruler */
1364 private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1366 /** Preference key for warning indication in overview ruler */
1367 private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1369 /** Preference key for task indication in overview ruler */
1370 private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1372 /** Preference key for bookmark indication in overview ruler */
1373 private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1375 /** Preference key for search result indication in overview ruler */
1376 private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1378 /** Preference key for unknown annotation indication in overview ruler */
1379 private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1381 /** Preference key for automatically closing double quoted strings */
1382 private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1384 /** Preference key for automatically closing single quoted strings */
1385 private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1387 /** Preference key for automatically wrapping Java strings */
1388 // private final static String WRAP_STRINGS =
1389 // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1390 /** Preference key for automatically closing brackets and parenthesis */
1391 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1393 /** Preference key for automatically closing phpdocs and comments */
1394 private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1396 /** Preference key for automatically adding phpdoc tags */
1397 private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1399 /** Preference key for automatically formatting phpdocs */
1400 // private final static String FORMAT_JAVADOCS =
1401 // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1402 /** Preference key for automatically closing strings */
1403 private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1405 /** Preference key for automatically closing brackets and parenthesis */
1406 private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1408 /** Preference key for smart paste */
1409 private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1411 // private final static class AnnotationInfo {
1412 // public String fColorPreference;
1413 // public String fOverviewRulerPreference;
1414 // public String fEditorPreference;
1416 // private final static Map ANNOTATION_MAP;
1419 // AnnotationInfo info;
1420 // ANNOTATION_MAP = new HashMap();
1422 // info = new AnnotationInfo();
1423 // info.fColorPreference = TASK_INDICATION_COLOR;
1424 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1425 // info.fEditorPreference = TASK_INDICATION;
1426 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1428 // info = new AnnotationInfo();
1429 // info.fColorPreference = ERROR_INDICATION_COLOR;
1430 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1431 // info.fEditorPreference = ERROR_INDICATION;
1432 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1434 // info = new AnnotationInfo();
1435 // info.fColorPreference = WARNING_INDICATION_COLOR;
1436 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1437 // info.fEditorPreference = WARNING_INDICATION;
1438 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1440 // info = new AnnotationInfo();
1441 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1442 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1443 // info.fEditorPreference = BOOKMARK_INDICATION;
1444 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1446 // info = new AnnotationInfo();
1447 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1448 // info.fOverviewRulerPreference =
1449 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1450 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1451 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1453 // info = new AnnotationInfo();
1454 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1455 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1456 // info.fEditorPreference = UNKNOWN_INDICATION;
1457 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1460 // private final static AnnotationType[] ANNOTATION_LAYERS =
1461 // new AnnotationType[] {
1462 // AnnotationType.UNKNOWN,
1463 // AnnotationType.BOOKMARK,
1464 // AnnotationType.TASK,
1465 // AnnotationType.SEARCH,
1466 // AnnotationType.WARNING,
1467 // AnnotationType.ERROR };
1469 * Creates a new php unit editor.
1473 * Reconciling listeners.
1477 private ListenerList fReconcilingListeners = new ListenerList();
1480 * Mutex for the reconciler. See
1481 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1484 * TODO remove once the underlying problem is solved.
1487 private final Object fReconcilerLock = new Object();
1489 public PHPUnitEditor() {
1491 setDocumentProvider(PHPeclipsePlugin.getDefault()
1492 .getCompilationUnitDocumentProvider());
1493 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1494 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1495 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1496 // don't set help contextId, we install our own help context
1498 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1502 * @see AbstractTextEditor#createActions()
1504 protected void createActions() {
1505 super.createActions();
1507 // Action action= new
1508 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1509 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1511 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1512 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1513 // markAsStateDependentAction("CorrectionAssistProposal", true);
1515 // // WorkbenchHelp.setHelp(action,
1516 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1517 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1518 "ContentAssistProposal.", this); //$NON-NLS-1$
1520 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1521 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1522 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1523 // WorkbenchHelp.setHelp(action,
1524 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1526 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1527 // "ContentAssistContextInformation.", this,
1528 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1530 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1531 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1532 // markAsStateDependentAction("ContentAssistContextInformation", true);
1534 // WorkbenchHelp.setHelp(action,
1535 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1537 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1538 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1540 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1541 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1542 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1544 // // WorkbenchHelp.setHelp(action,
1545 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1546 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1547 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1548 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1549 setAction("Comment", action); //$NON-NLS-1$
1550 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1551 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1552 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1553 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1554 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1555 setAction("Uncomment", action); //$NON-NLS-1$
1556 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1557 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1559 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1560 "ToggleComment.", this); //$NON-NLS-1$
1562 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1563 setAction("ToggleComment", action); //$NON-NLS-1$
1564 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1565 // WorkbenchHelp.setHelp(action,
1566 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1567 configureToggleCommentAction();
1569 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1570 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1571 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1572 setAction("Format", action); //$NON-NLS-1$
1573 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1574 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1575 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1578 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1579 // "AddBlockComment.", this); //$NON-NLS-1$
1581 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1582 // setAction("AddBlockComment", action); //$NON-NLS-1$
1583 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1584 // markAsSelectionDependentAction("AddBlockComment", true);
1586 // // WorkbenchHelp.setHelp(action,
1587 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1588 // action = new RemoveBlockCommentAction(
1589 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1592 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1593 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1594 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1595 // markAsSelectionDependentAction("RemoveBlockComment", true);
1597 // WorkbenchHelp.setHelp(action,
1598 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1599 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1600 "Indent.", this, false); //$NON-NLS-1$
1601 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1602 setAction("Indent", action); //$NON-NLS-1$
1603 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1604 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1605 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1607 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1608 // "Indent.", this, true); //$NON-NLS-1$
1609 // setAction("IndentOnTab", action); //$NON-NLS-1$
1610 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1611 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1614 action = new AddBlockCommentAction(PHPEditorMessages
1615 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1617 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1618 setAction("AddBlockComment", action); //$NON-NLS-1$
1619 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1620 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1621 // WorkbenchHelp.setHelp(action,
1622 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1624 action = new RemoveBlockCommentAction(PHPEditorMessages
1625 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1627 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1628 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1629 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1630 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1631 // WorkbenchHelp.setHelp(action,
1632 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1634 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1635 // "Indent.", this, false); //$NON-NLS-1$
1636 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1637 // setAction("Indent", action); //$NON-NLS-1$
1638 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1639 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1640 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1642 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1643 "Indent.", this, true); //$NON-NLS-1$
1644 setAction("IndentOnTab", action); //$NON-NLS-1$
1645 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1646 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1648 if (getPreferenceStore().getBoolean(
1649 PreferenceConstants.EDITOR_SMART_TAB)) {
1650 // don't replace Shift Right - have to make sure their enablement is
1651 // mutually exclusive
1652 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1653 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1655 fGenerateActionGroup = new GenerateActionGroup(this,
1656 ITextEditorActionConstants.GROUP_EDIT);
1657 // ActionGroup rg= new RefactorActionGroup(this,
1658 // ITextEditorActionConstants.GROUP_EDIT);
1660 // fActionGroups.addGroup(rg);
1661 fActionGroups.addGroup(fGenerateActionGroup);
1663 // We have to keep the context menu group separate to have better
1664 // control over positioning
1665 fContextMenuGroup = new CompositeActionGroup(
1666 new ActionGroup[] { fGenerateActionGroup
1668 // new LocalHistoryActionGroup(this,
1669 // ITextEditorActionConstants.GROUP_EDIT)
1675 * @see JavaEditor#getElementAt(int)
1677 protected IJavaElement getElementAt(int offset) {
1678 return getElementAt(offset, true);
1682 * Returns the most narrow element including the given offset. If
1683 * <code>reconcile</code> is <code>true</code> the editor's input
1684 * element is reconciled in advance. If it is <code>false</code> this
1685 * method only returns a result if the editor's input element does not need
1689 * the offset included by the retrieved element
1691 * <code>true</code> if working copy should be reconciled
1693 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1694 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1695 .getWorkingCopyManager();
1696 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1700 synchronized (unit) {
1703 return unit.getElementAt(offset);
1704 } else if (unit.isConsistent())
1705 return unit.getElementAt(offset);
1706 } catch (JavaModelException x) {
1707 PHPeclipsePlugin.log(x.getStatus());
1708 // nothing found, be tolerant and go on
1715 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1717 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1719 return EditorUtility.getWorkingCopy(element, true);
1720 } catch (JavaModelException x) {
1721 PHPeclipsePlugin.log(x.getStatus());
1722 // nothing found, be tolerant and go on
1727 public void createPartControl(Composite parent) {
1728 super.createPartControl(parent);
1729 // fPaintManager = new PaintManager(getSourceViewer());
1730 LinePainter linePainter;
1731 linePainter = new LinePainter(getSourceViewer());
1732 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
1734 // fPaintManager.addPainter(linePainter);
1735 // if (isBracketHighlightingEnabled())
1736 // startBracketHighlighting();
1737 // if (isLineHighlightingEnabled())
1738 // startLineHighlighting();
1739 // if (isPrintMarginVisible())
1740 // showPrintMargin();
1741 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1742 // while (e.hasNext()) {
1743 // AnnotationType type = (AnnotationType) e.next();
1744 // if (isAnnotationIndicationEnabled(type))
1745 // startAnnotationIndication(type);
1747 if (isTabConversionEnabled())
1748 startTabConversion();
1749 // if (isOverviewRulerVisible())
1750 // showOverviewRuler();
1752 // Preferences preferences =
1753 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1754 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1755 IPreferenceStore preferenceStore = getPreferenceStore();
1756 boolean closeBracketsPHP = preferenceStore
1757 .getBoolean(CLOSE_BRACKETS_PHP);
1758 boolean closeStringsPHPDQ = preferenceStore
1759 .getBoolean(CLOSE_STRINGS_DQ_PHP);
1760 boolean closeStringsPHPSQ = preferenceStore
1761 .getBoolean(CLOSE_STRINGS_SQ_PHP);
1762 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1763 fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ);
1764 fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ);
1765 ISourceViewer sourceViewer = getSourceViewer();
1766 if (sourceViewer instanceof ITextViewerExtension)
1767 ((ITextViewerExtension) sourceViewer)
1768 .prependVerifyKeyListener(fBracketInserter);
1771 private static char getPeerCharacter(char character) {
1772 switch (character) {
1788 throw new IllegalArgumentException();
1792 // private void startBracketHighlighting() {
1793 // if (fBracketPainter == null) {
1794 // ISourceViewer sourceViewer = getSourceViewer();
1795 // fBracketPainter = new BracketPainter(sourceViewer);
1796 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1797 // // fPaintManager.addPainter(fBracketPainter);
1801 // private void stopBracketHighlighting() {
1802 // if (fBracketPainter != null) {
1803 // // fPaintManager.removePainter(fBracketPainter);
1804 // fBracketPainter.deactivate(true);
1805 // fBracketPainter.dispose();
1806 // fBracketPainter = null;
1810 // private boolean isBracketHighlightingEnabled() {
1811 // IPreferenceStore store = getPreferenceStore();
1812 // return store.getBoolean(MATCHING_BRACKETS);
1815 // private void startLineHighlighting() {
1816 // if (fLinePainter == null) {
1817 // ISourceViewer sourceViewer = getSourceViewer();
1818 // fLinePainter = new LinePainter(sourceViewer);
1819 // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1820 // // fPaintManager.addPainter(fLinePainter);
1824 // private void stopLineHighlighting() {
1825 // if (fLinePainter != null) {
1826 // // fPaintManager.removePainter(fLinePainter);
1827 // fLinePainter.deactivate(true);
1828 // fLinePainter.dispose();
1829 // fLinePainter = null;
1833 // private boolean isLineHighlightingEnabled() {
1834 // IPreferenceStore store = getPreferenceStore();
1835 // return store.getBoolean(CURRENT_LINE);
1838 // private void showPrintMargin() {
1839 // if (fPrintMarginPainter == null) {
1840 // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1841 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1842 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1843 // // fPaintManager.addPainter(fPrintMarginPainter);
1847 // private void hidePrintMargin() {
1848 // if (fPrintMarginPainter != null) {
1849 // // fPaintManager.removePainter(fPrintMarginPainter);
1850 // fPrintMarginPainter.deactivate(true);
1851 // fPrintMarginPainter.dispose();
1852 // fPrintMarginPainter = null;
1856 // private boolean isPrintMarginVisible() {
1857 // IPreferenceStore store = getPreferenceStore();
1858 // return store.getBoolean(PRINT_MARGIN);
1861 private int getTabSize() {
1862 Preferences preferences = PHPeclipsePlugin.getDefault()
1863 .getPluginPreferences();
1864 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1867 private boolean isTabConversionEnabled() {
1868 IPreferenceStore store = getPreferenceStore();
1869 return store.getBoolean(SPACES_FOR_TABS);
1872 private Color getColor(String key) {
1873 RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1874 return getColor(rgb);
1877 private Color getColor(RGB rgb) {
1878 JavaTextTools textTools = PHPeclipsePlugin.getDefault()
1879 .getJavaTextTools();
1880 return textTools.getColorManager().getColor(rgb);
1883 // private Color getColor(AnnotationType annotationType) {
1884 // AnnotationInfo info = (AnnotationInfo)
1885 // ANNOTATION_MAP.get(annotationType);
1886 // if (info != null)
1887 // return getColor(info.fColorPreference);
1890 public void dispose() {
1891 ISourceViewer sourceViewer = getSourceViewer();
1892 if (sourceViewer instanceof ITextViewerExtension)
1893 ((ITextViewerExtension) sourceViewer)
1894 .removeVerifyKeyListener(fBracketInserter);
1895 // if (fPropertyChangeListener != null) {
1896 // Preferences preferences =
1897 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1898 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1899 // fPropertyChangeListener = null;
1901 if (fJavaEditorErrorTickUpdater != null) {
1902 fJavaEditorErrorTickUpdater.dispose();
1903 fJavaEditorErrorTickUpdater = null;
1905 // if (fSelectionHistory != null)
1906 // fSelectionHistory.dispose();
1907 // if (fPaintManager != null) {
1908 // fPaintManager.dispose();
1909 // fPaintManager = null;
1911 if (fActionGroups != null) {
1912 fActionGroups.dispose();
1913 fActionGroups = null;
1918 // protected AnnotationType getAnnotationType(String preferenceKey) {
1919 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1920 // while (e.hasNext()) {
1921 // AnnotationType type = (AnnotationType) e.next();
1922 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1923 // if (info != null) {
1924 // if (preferenceKey.equals(info.fColorPreference)
1925 // || preferenceKey.equals(info.fEditorPreference)
1926 // || preferenceKey.equals(info.fOverviewRulerPreference))
1933 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1935 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1937 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1939 String p = event.getProperty();
1940 if (CLOSE_BRACKETS_PHP.equals(p)) {
1942 .setCloseBracketsPHPEnabled(getPreferenceStore()
1946 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
1948 .setCloseStringsPHPDQEnabled(getPreferenceStore()
1952 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
1954 .setCloseStringsPHPSQEnabled(getPreferenceStore()
1958 if (SPACES_FOR_TABS.equals(p)) {
1959 if (isTabConversionEnabled())
1960 startTabConversion();
1962 stopTabConversion();
1965 // if (MATCHING_BRACKETS.equals(p)) {
1966 // if (isBracketHighlightingEnabled())
1967 // startBracketHighlighting();
1969 // stopBracketHighlighting();
1972 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
1973 // if (fBracketPainter != null)
1974 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1977 // if (CURRENT_LINE.equals(p)) {
1978 // if (isLineHighlightingEnabled())
1979 // startLineHighlighting();
1981 // stopLineHighlighting();
1984 // if (CURRENT_LINE_COLOR.equals(p)) {
1985 // if (fLinePainter != null) {
1986 // stopLineHighlighting();
1987 // startLineHighlighting();
1991 // if (PRINT_MARGIN.equals(p)) {
1992 // if (isPrintMarginVisible())
1993 // showPrintMargin();
1995 // hidePrintMargin();
1998 // if (PRINT_MARGIN_COLOR.equals(p)) {
1999 // if (fPrintMarginPainter != null)
2000 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2003 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2004 // if (fPrintMarginPainter != null)
2005 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2008 // if (OVERVIEW_RULER.equals(p)) {
2009 // if (isOverviewRulerVisible())
2010 // showOverviewRuler();
2012 // hideOverviewRuler();
2015 // AnnotationType type = getAnnotationType(p);
2016 // if (type != null) {
2018 // AnnotationInfo info = (AnnotationInfo)
2019 // ANNOTATION_MAP.get(type);
2020 // if (info.fColorPreference.equals(p)) {
2021 // Color color = getColor(type);
2022 // if (fProblemPainter != null) {
2023 // fProblemPainter.setColor(type, color);
2024 // fProblemPainter.paint(IPainter.CONFIGURATION);
2026 // setColorInOverviewRuler(type, color);
2030 // if (info.fEditorPreference.equals(p)) {
2031 // if (isAnnotationIndicationEnabled(type))
2032 // startAnnotationIndication(type);
2034 // stopAnnotationIndication(type);
2038 // if (info.fOverviewRulerPreference.equals(p)) {
2039 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2040 // showAnnotationIndicationInOverviewRuler(type, true);
2042 // showAnnotationIndicationInOverviewRuler(type, false);
2046 IContentAssistant c = asv.getContentAssistant();
2047 if (c instanceof ContentAssistant)
2048 ContentAssistPreference.changeConfiguration(
2049 (ContentAssistant) c, getPreferenceStore(), event);
2052 super.handlePreferenceStoreChanged(event);
2057 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2059 protected void handlePreferencePropertyChanged(
2060 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2061 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2063 String p = event.getProperty();
2064 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2065 asv.updateIndentationPrefixes();
2066 if (fTabConverter != null)
2067 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2070 super.handlePreferencePropertyChanged(event);
2074 * Handles a property change event describing a change of the php core's
2075 * preferences and updates the preference related editor properties.
2078 * the property change event
2081 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2083 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2084 // if (asv != null) {
2085 // String p = event.getProperty();
2086 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2087 // asv.updateIndentationPrefixes();
2088 // if (fTabConverter != null)
2089 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2094 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2095 * org.eclipse.jface.text.source.IVerticalRuler,
2096 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2098 protected ISourceViewer createJavaSourceViewer(Composite parent,
2099 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2100 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2101 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2102 isOverviewRulerVisible, styles, store);
2105 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2106 // IVerticalRuler ruler, int styles) {
2107 // return new AdaptedSourceViewer(parent, ruler, styles);
2109 private boolean isValidSelection(int offset, int length) {
2110 IDocumentProvider provider = getDocumentProvider();
2111 if (provider != null) {
2112 IDocument document = provider.getDocument(getEditorInput());
2113 if (document != null) {
2114 int end = offset + length;
2115 int documentLength = document.getLength();
2116 return 0 <= offset && offset <= documentLength && 0 <= end
2117 && end <= documentLength;
2124 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2126 protected IJavaElement getInputJavaElement() {
2127 return PHPeclipsePlugin.getDefault().getWorkingCopyManager()
2128 .getWorkingCopy(getEditorInput());
2132 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2134 public void editorContextMenuAboutToShow(IMenuManager menu) {
2135 super.editorContextMenuAboutToShow(menu);
2136 ActionContext context = new ActionContext(getSelectionProvider()
2138 fContextMenuGroup.setContext(context);
2139 fContextMenuGroup.fillContextMenu(menu);
2140 fContextMenuGroup.setContext(null);
2144 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2146 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2148 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2149 .getWorkingCopyManager();
2150 page.setInput(manager.getWorkingCopy(input));
2155 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2158 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2159 // IProgressMonitor progressMonitor) {
2160 // IDocumentProvider p = getDocumentProvider();
2161 // if (p instanceof PHPDocumentProvider) {
2162 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2163 // cp.setSavePolicy(fSavePolicy);
2167 // super.performSaveOperation(operation, progressMonitor);
2169 // if (p instanceof PHPDocumentProvider) {
2170 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2171 // cp.setSavePolicy(null);
2176 * @see AbstractTextEditor#doSave(IProgressMonitor)
2178 public void doSave(IProgressMonitor progressMonitor) {
2180 IDocumentProvider p = getDocumentProvider();
2182 // editor has been closed
2186 if (p.isDeleted(getEditorInput())) {
2188 if (isSaveAsAllowed()) {
2191 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2192 * the editors. Changed Behavior to make sure that if called
2193 * inside a regular save (because of deletion of input element)
2194 * there is a way to report back to the caller.
2196 performSaveAs(progressMonitor);
2201 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2202 * there Missing resources.
2204 Shell shell = getSite().getShell();
2209 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2213 if (getPreferenceStore().getBoolean(
2214 PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2215 RTrimAction trimAction = new RTrimAction();
2216 trimAction.setActiveEditor(null, getSite().getPage()
2217 .getActiveEditor());
2218 trimAction.run(null);
2221 setStatusLineErrorMessage(null);
2223 updateState(getEditorInput());
2224 validateState(getEditorInput());
2226 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2227 .getWorkingCopyManager();
2228 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2231 synchronized (unit) {
2232 performSave(false, progressMonitor);
2235 performSave(false, progressMonitor);
2239 public boolean isSaveAsAllowed() {
2244 * The compilation unit editor implementation of this
2245 * <code>AbstractTextEditor</code> method asks the user for the workspace
2246 * path of a file resource and saves the document there. See
2247 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2249 * @param progressMonitor
2250 * the progress monitor
2252 protected void performSaveAs(IProgressMonitor progressMonitor) {
2254 Shell shell = getSite().getShell();
2255 IEditorInput input = getEditorInput();
2257 SaveAsDialog dialog = new SaveAsDialog(shell);
2259 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2262 if (original != null)
2263 dialog.setOriginalFile(original);
2267 IDocumentProvider provider = getDocumentProvider();
2268 if (provider == null) {
2269 // editor has been programmatically closed while the dialog was open
2273 if (provider.isDeleted(input) && original != null) {
2274 String message = PHPEditorMessages
2275 .getFormattedString(
2276 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2277 dialog.setErrorMessage(null);
2278 dialog.setMessage(message, IMessageProvider.WARNING);
2281 if (dialog.open() == Window.CANCEL) {
2282 if (progressMonitor != null)
2283 progressMonitor.setCanceled(true);
2287 IPath filePath = dialog.getResult();
2288 if (filePath == null) {
2289 if (progressMonitor != null)
2290 progressMonitor.setCanceled(true);
2294 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2295 IFile file = workspaceRoot.getFile(filePath);
2296 final IEditorInput newInput = new FileEditorInput(file);
2298 boolean success = false;
2301 provider.aboutToChange(newInput);
2302 getDocumentProvider().saveDocument(progressMonitor, newInput,
2303 getDocumentProvider().getDocument(getEditorInput()), true);
2306 } catch (CoreException x) {
2307 IStatus status = x.getStatus();
2308 if (status == null || status.getSeverity() != IStatus.CANCEL)
2313 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2315 provider.changed(newInput);
2320 if (progressMonitor != null)
2321 progressMonitor.setCanceled(!success);
2325 * @see AbstractTextEditor#doSetInput(IEditorInput)
2327 protected void doSetInput(IEditorInput input) throws CoreException {
2328 super.doSetInput(input);
2329 configureTabConverter();
2330 configureToggleCommentAction();
2335 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2338 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2339 // IAnnotationModel model=
2340 // getDocumentProvider().getAnnotationModel(getEditorInput());
2341 // if (!waitForReconcilation)
2342 // super.installOverrideIndicator(false);
2344 // uninstallOverrideIndicator();
2345 // IJavaElement inputElement= getInputJavaElement();
2346 // if (model == null || inputElement == null)
2349 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2350 // inputElement, null);
2351 // addReconcileListener(fOverrideIndicatorManager);
2357 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2360 // protected void uninstallOverrideIndicator() {
2361 // if (fOverrideIndicatorManager != null)
2362 // removeReconcileListener(fOverrideIndicatorManager);
2363 // super.uninstallOverrideIndicator();
2367 * Configures the toggle comment action
2371 private void configureToggleCommentAction() {
2372 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2373 if (action instanceof ToggleCommentAction) {
2374 ISourceViewer sourceViewer = getSourceViewer();
2375 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2376 ((ToggleCommentAction) action).configure(sourceViewer,
2381 // private void configureTabConverter() {
2382 // if (fTabConverter != null) {
2383 // IDocumentProvider provider = getDocumentProvider();
2384 // if (provider instanceof PHPDocumentProvider) {
2385 // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2386 // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2390 private void configureTabConverter() {
2391 if (fTabConverter != null) {
2392 IDocumentProvider provider = getDocumentProvider();
2393 if (provider instanceof ICompilationUnitDocumentProvider) {
2394 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2395 fTabConverter.setLineTracker(cup
2396 .createLineTracker(getEditorInput()));
2401 private void startTabConversion() {
2402 if (fTabConverter == null) {
2403 fTabConverter = new TabConverter();
2404 configureTabConverter();
2405 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2406 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2407 asv.addTextConverter(fTabConverter);
2408 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2409 asv.updateIndentationPrefixes();
2413 private void stopTabConversion() {
2414 if (fTabConverter != null) {
2415 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2416 asv.removeTextConverter(fTabConverter);
2417 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2418 asv.updateIndentationPrefixes();
2419 fTabConverter = null;
2424 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2425 * org.eclipse.core.runtime.IProgressMonitor)
2427 protected void performSave(boolean overwrite,
2428 IProgressMonitor progressMonitor) {
2429 // IDocumentProvider p = getDocumentProvider();
2430 // if (p instanceof PHPDocumentProvider) {
2431 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2432 // cp.setSavePolicy(fSavePolicy);
2435 // super.performSave(overwrite, progressMonitor);
2437 // if (p instanceof PHPDocumentProvider) {
2438 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2439 // cp.setSavePolicy(null);
2443 IDocumentProvider p = getDocumentProvider();
2444 if (p instanceof ICompilationUnitDocumentProvider) {
2445 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2446 cp.setSavePolicy(fSavePolicy);
2449 super.performSave(overwrite, progressMonitor);
2451 if (p instanceof ICompilationUnitDocumentProvider) {
2452 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2453 cp.setSavePolicy(null);
2459 * @see AbstractTextEditor#doSaveAs
2461 public void doSaveAs() {
2462 if (askIfNonWorkbenchEncodingIsOk()) {
2468 * Asks the user if it is ok to store in non-workbench encoding.
2470 * @return <true>if the user wants to continue
2472 private boolean askIfNonWorkbenchEncodingIsOk() {
2473 IDocumentProvider provider = getDocumentProvider();
2474 if (provider instanceof IStorageDocumentProvider) {
2475 IEditorInput input = getEditorInput();
2476 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2477 String encoding = storageProvider.getEncoding(input);
2478 String defaultEncoding = storageProvider.getDefaultEncoding();
2479 if (encoding != null && !encoding.equals(defaultEncoding)) {
2480 Shell shell = getSite().getShell();
2481 String title = PHPEditorMessages
2482 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2488 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2489 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2494 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2495 new String[] { encoding }); //$NON-NLS-1$
2496 return MessageDialog.openQuestion(shell, title, msg);
2503 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2506 public void aboutToBeReconciled() {
2508 // Notify AST provider
2509 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2512 Object[] listeners = fReconcilingListeners.getListeners();
2513 for (int i = 0, length = listeners.length; i < length; ++i)
2514 ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2518 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2519 * boolean, IProgressMonitor)
2522 public void reconciled(CompilationUnit ast, boolean forced,
2523 IProgressMonitor progressMonitor) {
2525 // Always notify AST provider
2526 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2527 // getInputJavaElement());
2530 // Object[] listeners = fReconcilingListeners.getListeners();
2531 // for (int i = 0, length= listeners.length; i < length; ++i)
2532 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2533 // progressMonitor);
2535 // Update Java Outline page selection
2536 if (!forced && !progressMonitor.isCanceled()) {
2537 Shell shell = getSite().getShell();
2538 if (shell != null && !shell.isDisposed()) {
2539 shell.getDisplay().asyncExec(new Runnable() {
2549 * Returns the updated java element for the old java element.
2551 private IJavaElement findElement(IJavaElement element) {
2552 if (element == null)
2554 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2555 .getWorkingCopyManager();
2556 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2559 synchronized (unit) {
2562 IJavaElement[] findings = unit.findElements(element);
2563 if (findings != null && findings.length > 0)
2565 } catch (JavaModelException x) {
2566 PHPeclipsePlugin.log(x.getStatus());
2567 // nothing found, be tolerant and go on
2574 * Returns the offset of the given Java element.
2576 private int getOffset(IJavaElement element) {
2577 if (element instanceof ISourceReference) {
2578 ISourceReference sr = (ISourceReference) element;
2580 ISourceRange srcRange = sr.getSourceRange();
2581 if (srcRange != null)
2582 return srcRange.getOffset();
2583 } catch (JavaModelException e) {
2590 * @see AbstractTextEditor#restoreSelection()
2592 // protected void restoreSelection() {
2594 // if (getSourceViewer() == null || fRememberedSelection == null)
2596 // IJavaElement newElement = findElement(fRememberedElement);
2597 // int newOffset = getOffset(newElement);
2598 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2599 // - fRememberedElementOffset : 0;
2600 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2601 // fRememberedSelection.getLength()))
2602 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2603 // fRememberedSelection.getLength());
2605 // fRememberedSelection = null;
2606 // fRememberedElement = null;
2607 // fRememberedElementOffset = -1;
2611 * Tells whether this is the active editor in the active page.
2613 * @return <code>true</code> if this is the active editor in the active
2615 * @see IWorkbenchPage#getActiveEditor();
2617 protected final boolean isActiveEditor() {
2618 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2619 IWorkbenchPage page = window.getActivePage();
2622 IEditorPart activeEditor = page.getActiveEditor();
2623 return activeEditor != null && activeEditor.equals(this);
2627 * Adds the given listener. Has no effect if an identical listener was not
2628 * already registered.
2631 * The reconcile listener to be added
2634 final void addReconcileListener(IJavaReconcilingListener listener) {
2635 synchronized (fReconcilingListeners) {
2636 fReconcilingListeners.add(listener);
2641 * Removes the given listener. Has no effect if an identical listener was
2642 * not already registered.
2645 * the reconcile listener to be removed
2648 final void removeReconcileListener(IJavaReconcilingListener listener) {
2649 synchronized (fReconcilingListeners) {
2650 fReconcilingListeners.remove(listener);
2654 protected void updateStateDependentActions() {
2655 super.updateStateDependentActions();
2656 fGenerateActionGroup.editorStateChanged();
2660 * @see AbstractTextEditor#rememberSelection()
2662 protected void rememberSelection() {
2663 fRememberedSelection.remember();
2667 * @see AbstractTextEditor#restoreSelection()
2669 protected void restoreSelection() {
2670 fRememberedSelection.restore();
2674 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2676 protected boolean canHandleMove(IEditorInput originalElement,
2677 IEditorInput movedElement) {
2679 String oldExtension = ""; //$NON-NLS-1$
2680 if (originalElement instanceof IFileEditorInput) {
2681 IFile file = ((IFileEditorInput) originalElement).getFile();
2683 String ext = file.getFileExtension();
2689 String newExtension = ""; //$NON-NLS-1$
2690 if (movedElement instanceof IFileEditorInput) {
2691 IFile file = ((IFileEditorInput) movedElement).getFile();
2693 newExtension = file.getFileExtension();
2696 return oldExtension.equals(newExtension);
2700 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2702 protected boolean isPrefQuickDiffAlwaysOn() {
2703 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2704 // was hacked by JavaEditor
2705 // to disable the change bar for the class file (attached source) java
2707 IPreferenceStore store = getPreferenceStore();
2709 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2713 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2715 public Object getAdapter(Class required) {
2716 if (SmartBackspaceManager.class.equals(required)) {
2717 if (getSourceViewer() instanceof JavaSourceViewer) {
2718 return ((JavaSourceViewer) getSourceViewer())
2719 .getBackspaceManager();
2723 return super.getAdapter(required);
2727 * Returns the mutex for the reconciler. See
2728 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2731 * TODO remove once the underlying problem is solved.
2734 * @return the lock reconcilers may use to synchronize on
2736 public Object getReconcilerLock() {
2737 return fReconcilerLock;
2743 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2745 protected void editorSaved() {
2746 super.editorSaved();
2747 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2749 a.refresh(ShowExternalPreviewAction.PHP_TYPE);