1 package net.sourceforge.phpeclipse.phpeditor;
3 import java.text.MessageFormat;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.Iterator;
10 import net.sourceforge.phpdt.core.ICompilationUnit;
11 import net.sourceforge.phpdt.core.IJavaElement;
12 import net.sourceforge.phpdt.core.IJavaProject;
13 import net.sourceforge.phpdt.core.IMember;
14 import net.sourceforge.phpdt.core.ISourceRange;
15 import net.sourceforge.phpdt.core.ISourceReference;
16 import net.sourceforge.phpdt.core.JavaCore;
17 import net.sourceforge.phpdt.core.JavaModelException;
18 import net.sourceforge.phpdt.core.dom.CompilationUnit;
19 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
20 import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility;
21 import net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction;
22 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
23 import net.sourceforge.phpdt.internal.ui.actions.IndentAction;
24 import net.sourceforge.phpdt.internal.ui.actions.RemoveBlockCommentAction;
25 import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference;
26 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
27 import net.sourceforge.phpdt.internal.ui.text.JavaHeuristicScanner;
28 import net.sourceforge.phpdt.internal.ui.text.JavaIndenter;
29 //import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
30 import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager;
31 import net.sourceforge.phpdt.internal.ui.text.SmartSemicolonAutoEditStrategy;
32 import net.sourceforge.phpdt.internal.ui.text.comment.CommentFormattingContext;
33 import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener;
34 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager;
35 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI;
36 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
37 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
38 import net.sourceforge.phpdt.ui.PreferenceConstants;
39 import net.sourceforge.phpdt.ui.actions.GenerateActionGroup;
40 //import net.sourceforge.phpdt.ui.text.JavaTextTools;
41 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
42 import net.sourceforge.phpeclipse.phpeditor.actions.RTrimAction;
43 import net.sourceforge.phpeclipse.ui.editor.ShowExternalPreviewAction;
45 import org.eclipse.core.resources.IFile;
46 import org.eclipse.core.resources.IWorkspaceRoot;
47 import org.eclipse.core.resources.ResourcesPlugin;
48 import org.eclipse.core.runtime.CoreException;
49 import org.eclipse.core.runtime.IPath;
50 import org.eclipse.core.runtime.IProgressMonitor;
51 import org.eclipse.core.runtime.IStatus;
52 import org.eclipse.core.runtime.Preferences;
53 import org.eclipse.jface.action.Action;
54 import org.eclipse.jface.action.IAction;
55 import org.eclipse.jface.action.IMenuManager;
56 import org.eclipse.jface.dialogs.ErrorDialog;
57 import org.eclipse.jface.dialogs.IMessageProvider;
58 import org.eclipse.jface.dialogs.MessageDialog;
59 import org.eclipse.jface.preference.IPreferenceStore;
60 //import org.eclipse.jface.preference.PreferenceConverter;
61 import org.eclipse.jface.text.BadLocationException;
62 import org.eclipse.jface.text.DocumentCommand;
63 import org.eclipse.jface.text.IAutoEditStrategy;
64 import org.eclipse.jface.text.IDocument;
65 import org.eclipse.jface.text.ILineTracker;
66 import org.eclipse.jface.text.IRegion;
67 import org.eclipse.jface.text.ITextOperationTarget;
68 import org.eclipse.jface.text.ITextViewerExtension;
69 import org.eclipse.jface.text.ITypedRegion;
70 import org.eclipse.jface.text.IWidgetTokenKeeper;
71 import org.eclipse.jface.text.contentassist.ContentAssistant;
72 import org.eclipse.jface.text.contentassist.IContentAssistant;
73 import org.eclipse.jface.text.formatter.FormattingContextProperties;
74 import org.eclipse.jface.text.formatter.IFormattingContext;
75 import org.eclipse.jface.text.source.IOverviewRuler;
76 import org.eclipse.jface.text.source.ISourceViewer;
77 import org.eclipse.jface.text.source.IVerticalRuler;
78 import org.eclipse.jface.text.source.SourceViewerConfiguration;
80 //import org.eclipse.jface.util.ListenerList;
81 import org.eclipse.core.runtime.ListenerList;
82 import org.eclipse.jface.util.PropertyChangeEvent;
83 import org.eclipse.jface.window.Window;
84 import org.eclipse.swt.SWT;
85 import org.eclipse.swt.custom.VerifyKeyListener;
86 import org.eclipse.swt.events.VerifyEvent;
87 import org.eclipse.swt.graphics.Color;
88 import org.eclipse.swt.graphics.Point;
89 //import org.eclipse.swt.graphics.RGB;
90 import org.eclipse.swt.widgets.Composite;
91 import org.eclipse.swt.widgets.Display;
92 import org.eclipse.swt.widgets.Shell;
93 import org.eclipse.ui.IEditorInput;
94 import org.eclipse.ui.IEditorPart;
95 import org.eclipse.ui.IFileEditorInput;
96 import org.eclipse.ui.IWorkbenchPage;
97 import org.eclipse.ui.IWorkbenchWindow;
98 import org.eclipse.ui.PlatformUI;
99 import org.eclipse.ui.actions.ActionContext;
100 import org.eclipse.ui.actions.ActionGroup;
101 import org.eclipse.ui.dialogs.SaveAsDialog;
102 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
103 import org.eclipse.ui.part.FileEditorInput;
104 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
105 import org.eclipse.ui.texteditor.ContentAssistAction;
106 import org.eclipse.ui.texteditor.IDocumentProvider;
107 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
108 import org.eclipse.ui.texteditor.TextOperationAction;
110 /*******************************************************************************
111 * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
112 * program and the accompanying materials are made available under the terms of
113 * the Common Public License v1.0 which accompanies this distribution, and is
114 * available at http://www.eclipse.org/legal/cpl-v10.html
116 * Contributors: IBM Corporation - Initial implementation
118 ******************************************************************************/
120 * PHP specific text editor.
122 public class PHPUnitEditor extends PHPEditor { // implements
123 // IJavaReconcilingListener {
124 interface ITextConverter {
125 void customizeDocumentCommand(IDocument document,
126 DocumentCommand command);
129 // class AdaptedSourceViewer extends JavaSourceViewer {
130 // private List fTextConverters;
132 // private boolean fIgnoreTextConverters = false;
134 // // private JavaCorrectionAssistant fCorrectionAssistant;
135 // public AdaptedSourceViewer(Composite parent, IVerticalRuler
137 // IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
138 // int styles, IPreferenceStore store) {
139 // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
143 // // public AdaptedSourceViewer(Composite parent,
144 // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
145 // // boolean showAnnotationsOverview, int styles) {
146 // // super(parent, verticalRuler, overviewRuler,
147 // // showAnnotationsOverview, styles);
149 // public IContentAssistant getContentAssistant() {
150 // return fContentAssistant;
154 // * @see ITextOperationTarget#doOperation(int)
156 // public void doOperation(int operation) {
157 // if (getTextWidget() == null)
159 // switch (operation) {
160 // case CONTENTASSIST_PROPOSALS:
161 // String msg = fContentAssistant.showPossibleCompletions();
162 // setStatusLineErrorMessage(msg);
164 // // case CORRECTIONASSIST_PROPOSALS:
165 // // fCorrectionAssistant.showPossibleCompletions();
168 // fIgnoreTextConverters = true;
171 // fIgnoreTextConverters = true;
174 // super.doOperation(operation);
178 // * @see ITextOperationTarget#canDoOperation(int)
180 // public boolean canDoOperation(int operation) {
181 // // if (operation == CORRECTIONASSIST_PROPOSALS)
182 // // return isEditable();
183 // return super.canDoOperation(operation);
187 // * @see TextViewer#handleDispose()
189 // protected void handleDispose() {
190 // // if (fCorrectionAssistant != null) {
191 // // fCorrectionAssistant.uninstall();
192 // // fCorrectionAssistant= null;
194 // super.handleDispose();
197 // public void insertTextConverter(ITextConverter textConverter, int index)
199 // throw new UnsupportedOperationException();
202 // public void addTextConverter(ITextConverter textConverter) {
203 // if (fTextConverters == null) {
204 // fTextConverters = new ArrayList(1);
205 // fTextConverters.add(textConverter);
206 // } else if (!fTextConverters.contains(textConverter))
207 // fTextConverters.add(textConverter);
210 // public void removeTextConverter(ITextConverter textConverter) {
211 // if (fTextConverters != null) {
212 // fTextConverters.remove(textConverter);
213 // if (fTextConverters.size() == 0)
214 // fTextConverters = null;
219 // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
221 // protected void customizeDocumentCommand(DocumentCommand command) {
222 // super.customizeDocumentCommand(command);
223 // if (!fIgnoreTextConverters && fTextConverters != null) {
224 // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
225 // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
228 // fIgnoreTextConverters = false;
231 // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
232 // public void updateIndentationPrefixes() {
233 // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
234 // String[] types = configuration.getConfiguredContentTypes(this);
235 // for (int i = 0; i < types.length; i++) {
236 // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
237 // if (prefixes != null && prefixes.length > 0)
238 // setIndentPrefixes(prefixes, types[i]);
243 // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
245 // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
246 // if (WorkbenchHelp.isContextHelpDisplayed())
248 // return super.requestWidgetToken(requester);
253 // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
255 // // public void configure(SourceViewerConfiguration configuration) {
256 // // super.configure(configuration);
257 // // // fCorrectionAssistant= new
258 // // // JavaCorrectionAssistant(CompilationUnitEditor.this);
259 // // // fCorrectionAssistant.install(this);
260 // // //TODO install SmartBracesAutoEditStrategy
261 // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
262 // // // IDocument.DEFAULT_CONTENT_TYPE);
264 // public void configure(SourceViewerConfiguration configuration) {
265 // super.configure(configuration);
266 // // fCorrectionAssistant= new
267 // JavaCorrectionAssistant(CompilationUnitEditor.this);
268 // // fCorrectionAssistant.install(this);
269 // IAutoEditStrategy smartSemi= new
270 // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING);
271 // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
272 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
273 // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
274 // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER);
277 class AdaptedSourceViewer extends JavaSourceViewer {
279 private List fTextConverters;
281 private boolean fIgnoreTextConverters = false;
283 // private JavaCorrectionAssistant fCorrectionAssistant;
285 public AdaptedSourceViewer(Composite parent,
286 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
287 boolean showAnnotationsOverview, int styles,
288 IPreferenceStore store) {
289 super(parent, verticalRuler, overviewRuler,
290 showAnnotationsOverview, styles, store);
293 public IContentAssistant getContentAssistant() {
294 return fContentAssistant;
298 * @see ITextOperationTarget#doOperation(int)
300 public void doOperation(int operation) {
302 if (getTextWidget() == null)
306 case CONTENTASSIST_PROPOSALS:
307 String msg = fContentAssistant.showPossibleCompletions();
308 setStatusLineErrorMessage(msg);
310 // case CORRECTIONASSIST_PROPOSALS:
311 // msg = fCorrectionAssistant.showPossibleCompletions();
312 // setStatusLineErrorMessage(msg);
315 fIgnoreTextConverters = true;
316 super.doOperation(operation);
317 fIgnoreTextConverters = false;
320 fIgnoreTextConverters = true;
321 super.doOperation(operation);
322 fIgnoreTextConverters = false;
326 super.doOperation(operation);
330 * @see ITextOperationTarget#canDoOperation(int)
332 public boolean canDoOperation(int operation) {
333 // if (operation == CORRECTIONASSIST_PROPOSALS)
334 // return isEditable();
336 return super.canDoOperation(operation);
340 * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
343 public void unconfigure() {
344 // if (fCorrectionAssistant != null) {
345 // fCorrectionAssistant.uninstall();
346 // fCorrectionAssistant = null;
351 public void insertTextConverter(ITextConverter textConverter, int index) {
352 throw new UnsupportedOperationException();
355 public void addTextConverter(ITextConverter textConverter) {
356 if (fTextConverters == null) {
357 fTextConverters = new ArrayList(1);
358 fTextConverters.add(textConverter);
359 } else if (!fTextConverters.contains(textConverter))
360 fTextConverters.add(textConverter);
363 public void removeTextConverter(ITextConverter textConverter) {
364 if (fTextConverters != null) {
365 fTextConverters.remove(textConverter);
366 if (fTextConverters.size() == 0)
367 fTextConverters = null;
372 * @see TextViewer#customizeDocumentCommand(DocumentCommand)
374 protected void customizeDocumentCommand(DocumentCommand command) {
375 super.customizeDocumentCommand(command);
376 if (!fIgnoreTextConverters && fTextConverters != null) {
377 for (Iterator e = fTextConverters.iterator(); e.hasNext();)
378 ((ITextConverter) e.next()).customizeDocumentCommand(
379 getDocument(), command);
383 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
384 public void updateIndentationPrefixes() {
385 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
386 String[] types = configuration.getConfiguredContentTypes(this);
387 for (int i = 0; i < types.length; i++) {
388 String[] prefixes = configuration.getIndentPrefixes(this,
390 if (prefixes != null && prefixes.length > 0)
391 setIndentPrefixes(prefixes, types[i]);
396 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
398 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
399 if (PlatformUI.getWorkbench().getHelpSystem()
400 .isContextHelpDisplayed())
402 return super.requestWidgetToken(requester);
406 * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper,
410 public boolean requestWidgetToken(IWidgetTokenKeeper requester,
412 if (PlatformUI.getWorkbench().getHelpSystem()
413 .isContextHelpDisplayed())
415 return super.requestWidgetToken(requester, priority);
419 * Get the global 'Undo history size' setting
422 protected int getUndoHistorySize () {
423 IPreferenceStore store= getPreferenceStore ();
425 return store != null ? store.getInt("undoHistorySize") : 1000;
430 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
432 public void configure(SourceViewerConfiguration configuration) {
433 super.configure(configuration);
434 // fCorrectionAssistant = new
435 // JavaCorrectionAssistant(CompilationUnitEditor.this);
436 // fCorrectionAssistant.install(this);
437 IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(
438 IPHPPartitions.PHP_PARTITIONING);
439 prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
440 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
441 prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
442 prependAutoEditStrategy(smartSemi,
443 IPHPPartitions.PHP_STRING_HEREDOC);
445 fUndoManager.setMaximalUndoLevel (this.getUndoHistorySize ()); // Set every editor to the global 'Undo history size'
449 * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
452 public IFormattingContext createFormattingContext() {
453 IFormattingContext context = new CommentFormattingContext();
456 IJavaElement inputJavaElement = getInputJavaElement();
457 IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
460 if (javaProject == null)
461 preferences = new HashMap(JavaCore.getOptions());
463 preferences = new HashMap(javaProject.getOptions(true));
465 context.storeToMap(PreferenceConstants.getPreferenceStore(),
468 FormattingContextProperties.CONTEXT_PREFERENCES,
476 * Remembers data related to the current selection to be able to restore it
481 private class RememberedSelection {
482 /** The remembered selection start. */
483 private RememberedOffset fStartOffset = new RememberedOffset();
485 /** The remembered selection end. */
486 private RememberedOffset fEndOffset = new RememberedOffset();
489 * Remember current selection.
491 public void remember() {
493 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
494 * may be called inside an async call posted to the UI thread, so
495 * protect against intermediate disposal of the editor.
497 ISourceViewer viewer = getSourceViewer();
498 if (viewer != null) {
499 IRegion selection = getSignedSelection(viewer);
500 int startOffset = selection.getOffset();
501 int endOffset = startOffset + selection.getLength();
503 fStartOffset.setOffset(startOffset);
504 fEndOffset.setOffset(endOffset);
509 * Restore remembered selection.
511 public void restore() {
513 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
514 * may be called inside an async call posted to the UI thread, so
515 * protect against intermediate disposal of the editor.
517 if (getSourceViewer() == null)
522 int startOffset, endOffset;
523 int revealStartOffset, revealEndOffset;
524 if (showsHighlightRangeOnly()) {
525 IJavaElement newStartElement = fStartOffset.getElement();
526 startOffset = fStartOffset
527 .getRememberedOffset(newStartElement);
528 revealStartOffset = fStartOffset.getRevealOffset(
529 newStartElement, startOffset);
530 if (revealStartOffset == -1)
533 IJavaElement newEndElement = fEndOffset.getElement();
534 endOffset = fEndOffset.getRememberedOffset(newEndElement);
535 revealEndOffset = fEndOffset.getRevealOffset(newEndElement,
537 if (revealEndOffset == -1)
540 startOffset = fStartOffset.getOffset();
541 revealStartOffset = startOffset;
542 endOffset = fEndOffset.getOffset();
543 revealEndOffset = endOffset;
546 if (startOffset == -1) {
547 startOffset = endOffset; // fallback to caret offset
548 revealStartOffset = revealEndOffset;
551 if (endOffset == -1) {
552 endOffset = startOffset; // fallback to other offset
553 revealEndOffset = revealStartOffset;
556 IJavaElement element;
557 if (endOffset == -1) {
558 // fallback to element selection
559 element = fEndOffset.getElement();
561 element = fStartOffset.getElement();
563 setSelection(element);
567 if (isValidSelection(revealStartOffset, revealEndOffset
569 && isValidSelection(startOffset, endOffset
571 selectAndReveal(startOffset, endOffset - startOffset,
572 revealStartOffset, revealEndOffset
573 - revealStartOffset);
575 fStartOffset.clear();
580 private boolean isValidSelection(int offset, int length) {
581 IDocumentProvider provider = getDocumentProvider();
582 if (provider != null) {
583 IDocument document = provider.getDocument(getEditorInput());
584 if (document != null) {
585 int end = offset + length;
586 int documentLength = document.getLength();
587 return 0 <= offset && offset <= documentLength && 0 <= end
588 && end <= documentLength;
597 * Remembers additional data for a given offset to be able restore it later.
601 private class RememberedOffset {
602 /** Remembered line for the given offset */
605 /** Remembered column for the given offset */
608 /** Remembered Java element for the given offset */
609 private IJavaElement fElement;
611 /** Remembered Java element line for the given offset */
612 private int fElementLine;
615 * Store visual properties of the given offset.
618 * Offset in the document
620 public void setOffset(int offset) {
622 IDocument document = getSourceViewer().getDocument();
623 fLine = document.getLineOfOffset(offset);
624 fColumn = offset - document.getLineOffset(fLine);
625 fElement = getElementAt(offset, true);
628 if (fElement instanceof IMember) {
629 ISourceRange range = ((IMember) fElement).getNameRange();
631 fElementLine = document.getLineOfOffset(range
634 if (fElementLine == -1)
635 fElementLine = document
636 .getLineOfOffset(getOffset(fElement));
637 } catch (BadLocationException e) {
639 PHPeclipsePlugin.log(e);
641 } catch (JavaModelException e) {
643 PHPeclipsePlugin.log(e.getStatus());
649 * Return offset recomputed from stored visual properties.
651 * @return Offset in the document
653 public int getOffset() {
654 IJavaElement newElement = getElement();
656 int offset = getRememberedOffset(newElement);
658 if (offset != -1 && !containsOffset(newElement, offset)
659 && (offset == 0 || !containsOffset(newElement, offset - 1)))
666 * Return offset recomputed from stored visual properties.
670 * @return Offset in the document
672 public int getRememberedOffset(IJavaElement newElement) {
674 if (newElement == null)
677 IDocument document = getSourceViewer().getDocument();
678 int newElementLine = -1;
679 if (newElement instanceof IMember) {
680 ISourceRange range = ((IMember) newElement).getNameRange();
682 newElementLine = document.getLineOfOffset(range
685 if (newElementLine == -1)
686 newElementLine = document
687 .getLineOfOffset(getOffset(newElement));
688 if (newElementLine == -1)
691 int newLine = fLine + newElementLine - fElementLine;
692 if (newLine < 0 || newLine >= document.getNumberOfLines())
694 int maxColumn = document.getLineLength(newLine);
695 String lineDelimiter = document.getLineDelimiter(newLine);
696 if (lineDelimiter != null)
697 maxColumn = maxColumn - lineDelimiter.length();
699 if (fColumn > maxColumn)
700 offset = document.getLineOffset(newLine) + maxColumn;
702 offset = document.getLineOffset(newLine) + fColumn;
705 } catch (BadLocationException e) {
707 PHPeclipsePlugin.log(e);
709 } catch (JavaModelException e) {
711 PHPeclipsePlugin.log(e.getStatus());
717 * Returns the offset used to reveal the given element based on the
718 * given selection offset.
723 * the selection offset
724 * @return the offset to reveal the given element based on the given
727 public int getRevealOffset(IJavaElement element, int offset) {
728 if (element == null || offset == -1)
731 if (containsOffset(element, offset)) {
733 IJavaElement alternateElement = getElementAt(offset, false);
734 if (element.getHandleIdentifier().equals(
735 alternateElement.getParent().getHandleIdentifier()))
736 return offset - 1; // Solves test case 2 from
737 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
740 } else if (offset > 0 && containsOffset(element, offset - 1))
741 return offset - 1; // Solves test case 1 from
742 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
748 * Return Java element recomputed from stored visual properties.
750 * @return Java element
752 public IJavaElement getElement() {
753 if (fElement == null)
756 return findElement(fElement);
760 * Clears the stored position
762 public void clear() {
770 * Does the given Java element contain the given offset?
776 * @return <code>true</code> iff the Java element contains the offset
778 private boolean containsOffset(IJavaElement element, int offset) {
779 int elementOffset = getOffset(element);
780 int elementLength = getLength(element);
781 return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset
787 * Returns the offset of the given Java element.
791 * @return Offset of the given Java element
793 private int getOffset(IJavaElement element) {
794 if (element instanceof ISourceReference) {
795 ISourceReference sr = (ISourceReference) element;
797 ISourceRange srcRange = sr.getSourceRange();
798 if (srcRange != null)
799 return srcRange.getOffset();
800 } catch (JavaModelException e) {
807 * Returns the length of the given Java element.
811 * @return Length of the given Java element
813 private int getLength(IJavaElement element) {
814 if (element instanceof ISourceReference) {
815 ISourceReference sr = (ISourceReference) element;
817 ISourceRange srcRange = sr.getSourceRange();
818 if (srcRange != null)
819 return srcRange.getLength();
820 } catch (JavaModelException e) {
827 * Returns the updated java element for the old java element.
831 * @return Updated Java element
833 private IJavaElement findElement(IJavaElement element) {
838 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
839 .getWorkingCopyManager();
840 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
845 synchronized (unit) {
846 // unit.reconcile(ICompilationUnit.NO_AST, false, null,
850 IJavaElement[] findings = unit.findElements(element);
851 if (findings != null && findings.length > 0)
854 } catch (JavaModelException x) {
855 PHPeclipsePlugin.log(x.getStatus());
856 // nothing found, be tolerant and go on
865 static class TabConverter implements ITextConverter {
866 private int fTabRatio;
868 private ILineTracker fLineTracker;
870 public TabConverter() {
873 public void setNumberOfSpacesPerTab(int ratio) {
877 public void setLineTracker(ILineTracker lineTracker) {
878 fLineTracker = lineTracker;
881 private int insertTabString(StringBuffer buffer, int offsetInLine) {
884 int remainder = offsetInLine % fTabRatio;
885 remainder = fTabRatio - remainder;
886 for (int i = 0; i < remainder; i++)
891 public void customizeDocumentCommand(IDocument document,
892 DocumentCommand command) {
893 String text = command.text;
896 int index = text.indexOf('\t');
898 StringBuffer buffer = new StringBuffer();
899 fLineTracker.set(command.text);
900 int lines = fLineTracker.getNumberOfLines();
902 for (int i = 0; i < lines; i++) {
903 int offset = fLineTracker.getLineOffset(i);
904 int endOffset = offset + fLineTracker.getLineLength(i);
905 String line = text.substring(offset, endOffset);
908 IRegion firstLine = document
909 .getLineInformationOfOffset(command.offset);
910 position = command.offset - firstLine.getOffset();
912 int length = line.length();
913 for (int j = 0; j < length; j++) {
914 char c = line.charAt(j);
916 position += insertTabString(buffer, position);
923 command.text = buffer.toString();
924 } catch (BadLocationException x) {
930 private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
931 final char fExitCharacter;
933 public ExitPolicy(char exitCharacter) {
934 fExitCharacter = exitCharacter;
938 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
939 * org.eclipse.swt.events.VerifyEvent, int, int)
941 public ExitFlags doExit(LinkedPositionManager manager,
942 VerifyEvent event, int offset, int length) {
943 if (event.character == fExitCharacter) {
944 if (manager.anyPositionIncludes(offset, length))
945 return new ExitFlags(LinkedPositionUI.COMMIT
946 | LinkedPositionUI.UPDATE_CARET, false);
948 return new ExitFlags(LinkedPositionUI.COMMIT, true);
950 // Fix for #1380415 (toshihiro) start
951 switch (event.keyCode) {
954 return new ExitFlags(LinkedPositionUI.COMMIT, true);
956 case SWT.ARROW_RIGHT:
957 if (!manager.anyPositionIncludes(offset, length))
958 return new ExitFlags(LinkedPositionUI.COMMIT, true);
962 switch (event.character) {
964 if (manager.getFirstPosition().length == 0)
965 return new ExitFlags(0, false);
970 return new ExitFlags(LinkedPositionUI.COMMIT, true);
977 // private static class BracketLevel {
982 // LinkedPositionManager fManager;
984 // LinkedPositionUI fEditor;
987 private class BracketInserter implements VerifyKeyListener,
988 LinkedPositionUI.ExitListener {
989 private boolean fCloseBracketsPHP = true;
991 private boolean fCloseStringsPHPDQ = true;
993 private boolean fCloseStringsPHPSQ = true;
999 public void setCloseBracketsPHPEnabled(boolean enabled) {
1000 fCloseBracketsPHP = enabled;
1003 public void setCloseStringsPHPDQEnabled(boolean enabled) {
1004 fCloseStringsPHPDQ = enabled;
1007 public void setCloseStringsPHPSQEnabled(boolean enabled) {
1008 fCloseStringsPHPSQ = enabled;
1011 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
1014 IRegion endLine = document.getLineInformationOfOffset(end);
1015 int maxEnd = endLine.getOffset() + endLine.getLength();
1016 while (end != maxEnd
1017 && Character.isWhitespace(document.getChar(end)))
1019 return end != maxEnd
1020 && Scanner.isPHPIdentifierPart(document.getChar(end));
1021 } catch (BadLocationException e) {
1027 // private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1029 // int start = offset;
1030 // IRegion startLine = document.getLineInformationOfOffset(start);
1031 // int minStart = startLine.getOffset();
1032 // while (start != minStart
1033 // && Character.isWhitespace(document.getChar(start - 1)))
1035 // return start != minStart
1036 // && Scanner.isPHPIdentifierPart(document
1037 // .getChar(start - 1));
1038 // } catch (BadLocationException e) {
1043 private boolean hasCharacterToTheLeft(IDocument document, int offset,
1047 IRegion startLine = document.getLineInformationOfOffset(start);
1048 int minStart = startLine.getOffset();
1049 while (start != minStart
1050 && Character.isWhitespace(document.getChar(start - 1)))
1052 return start != minStart
1053 && document.getChar(start - 1) == character;
1054 } catch (BadLocationException e) {
1059 private boolean hasCharacterToTheRight(IDocument document, int offset,
1063 IRegion endLine = document.getLineInformationOfOffset(end);
1064 int maxEnd = endLine.getOffset() + endLine.getLength();
1065 while (end != maxEnd
1066 && Character.isWhitespace(document.getChar(end)))
1068 return end != maxEnd && document.getChar(end) == character;
1069 } catch (BadLocationException e) {
1076 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1078 public void verifyKey(VerifyEvent event) {
1081 final ISourceViewer sourceViewer = getSourceViewer();
1082 IDocument document = sourceViewer.getDocument();
1083 final Point selection = sourceViewer.getSelectedRange();
1084 final int offset = selection.x;
1085 final int length = selection.y;
1087 ITypedRegion partition = document.getPartition(offset);
1088 String type = partition.getType();
1089 if (type.equals(IPHPPartitions.PHP_PARTITIONING)
1090 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1091 // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP
1093 switch (event.character) {
1095 if (hasCharacterToTheRight(document, offset + length,
1100 if (!fCloseBracketsPHP)
1102 if (hasIdentifierToTheRight(document, offset + length))
1106 if (!fCloseBracketsPHP)
1108 if (hasIdentifierToTheRight(document, offset + length))
1112 if (event.character == '"') {
1113 if (!fCloseStringsPHPDQ)
1115 // changed for statements like echo "" print ""
1116 // if (hasIdentifierToTheLeft(document, offset)
1118 // hasIdentifierToTheRight(document, offset +
1120 if (hasIdentifierToTheRight(document, offset
1124 // ITypedRegion partition=
1125 // document.getPartition(offset);
1127 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1129 // (partition.getOffset() != offset))
1131 final char characterDQ = event.character;
1132 final char closingCharacterDQ = getPeerCharacter(characterDQ);
1133 final StringBuffer bufferDQ = new StringBuffer();
1134 bufferDQ.append(characterDQ);
1135 bufferDQ.append(closingCharacterDQ);
1136 document.replace(offset, length, bufferDQ.toString());
1137 LinkedPositionManager managerDQ = new LinkedPositionManager(
1139 managerDQ.addPosition(offset + 1, 0);
1142 LinkedPositionUI editorDQ = new LinkedPositionUI(
1143 sourceViewer, managerDQ);
1144 editorDQ.setCancelListener(this);
1145 editorDQ.setExitPolicy(new ExitPolicy(
1146 closingCharacterDQ));
1147 editorDQ.setFinalCaretOffset(offset + 2);
1149 IRegion newSelectionDQ = editorDQ.getSelectedRegion();
1150 sourceViewer.setSelectedRange(newSelectionDQ
1151 .getOffset(), newSelectionDQ.getLength());
1155 if (event.character == '\'') {
1156 if (!fCloseStringsPHPSQ)
1158 // changed for statements like echo "" print ""
1159 // if (hasIdentifierToTheLeft(document, offset)
1161 // hasIdentifierToTheRight(document, offset +
1163 if (hasIdentifierToTheRight(document, offset
1167 // ITypedRegion partition=
1168 // document.getPartition(offset);
1170 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1172 // (partition.getOffset() != offset))
1174 final char characterSQ = event.character;
1175 final char closingCharacterSQ = getPeerCharacter(characterSQ);
1176 final StringBuffer bufferSQ = new StringBuffer();
1177 bufferSQ.append(characterSQ);
1178 bufferSQ.append(closingCharacterSQ);
1179 document.replace(offset, length, bufferSQ.toString());
1180 LinkedPositionManager managerSQ = new LinkedPositionManager(
1182 managerSQ.addPosition(offset + 1, 0);
1185 LinkedPositionUI editorSQ = new LinkedPositionUI(
1186 sourceViewer, managerSQ);
1187 editorSQ.setCancelListener(this);
1188 editorSQ.setExitPolicy(new ExitPolicy(
1189 closingCharacterSQ));
1190 editorSQ.setFinalCaretOffset(offset + 2);
1192 IRegion newSelectionSQ = editorSQ.getSelectedRegion();
1193 sourceViewer.setSelectedRange(newSelectionSQ
1194 .getOffset(), newSelectionSQ.getLength());
1196 case '\r': { // insert linebreaks and new closing brace
1197 // after brace and return
1198 if (!fCloseBracketsPHP) {
1201 if (hasCharacterToTheLeft(document, offset, '{')
1202 && hasCharacterToTheRight(document, offset, '}')) {
1203 String lineDelimiter = StubUtility
1204 .getLineDelimiterFor(document);
1205 int caretPos = sourceViewer.getTextWidget()
1207 final StringBuffer buffer = new StringBuffer(
1210 IRegion line = document
1211 .getLineInformationOfOffset(offset);
1212 String currentLine = document.get(line.getOffset(),
1215 int max = currentLine.length();
1216 StringBuffer indent = new StringBuffer();
1218 && Character.isWhitespace(currentLine
1220 indent.append(currentLine.charAt(index));
1223 buffer.append(indent);
1224 JavaHeuristicScanner scanner = new JavaHeuristicScanner(
1226 JavaIndenter indenter = new JavaIndenter(document,
1228 buffer.append(indenter.createIndent(1));
1229 int cursorPos = buffer.length();
1230 buffer.append(lineDelimiter);
1231 buffer.append(indent);
1232 document.replace(offset, length, buffer.toString());
1233 sourceViewer.getTextWidget().setCaretOffset(
1234 caretPos + cursorPos);
1240 } catch (BadLocationException e) {
1245 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1247 public void exit(boolean accept) {
1252 final ISourceViewer sourceViewer = getSourceViewer();
1253 IDocument document = sourceViewer.getDocument();
1254 document.replace(fOffset, fLength, null);
1255 } catch (BadLocationException e) {
1260 /** The editor's save policy */
1261 protected ISavePolicy fSavePolicy;
1264 * Listener to annotation model changes that updates the error tick in the
1267 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1269 /** The editor's paint manager */
1270 // private PaintManager fPaintManager;
1271 /** The editor's bracket painter */
1272 // private BracketPainter fBracketPainter;
1273 /** The editor's bracket matcher */
1274 //private PHPPairMatcher fBracketMatcher;
1276 /** The editor's line painter */
1277 // private LinePainter fLinePainter;
1278 /** The editor's print margin ruler painter */
1279 // private PrintMarginPainter fPrintMarginPainter;
1280 /** The editor's problem painter */
1281 // private ProblemPainter fProblemPainter;
1282 /** The editor's tab converter */
1283 private TabConverter fTabConverter;
1285 /** History for structure select action */
1286 // private SelectionHistory fSelectionHistory;
1287 /** The preference property change listener for php core. */
1288 // private IPropertyChangeListener fPropertyChangeListener = new
1289 // PropertyChangeListener();
1290 /** The remembered java element */
1291 //private IJavaElement fRememberedElement;
1294 * The remembered selection.
1298 private RememberedSelection fRememberedSelection = new RememberedSelection();
1300 /** The remembered php element offset */
1301 //private int fRememberedElementOffset;
1303 /** The bracket inserter. */
1304 private BracketInserter fBracketInserter = new BracketInserter();
1306 /** The standard action groups added to the menu */
1307 private GenerateActionGroup fGenerateActionGroup;
1309 private CompositeActionGroup fContextMenuGroup;
1311 // private class PropertyChangeListener implements IPropertyChangeListener {
1313 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1316 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1318 // handlePreferencePropertyChanged(event);
1321 /* Preference key for code formatter tab size */
1322 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1324 /** Preference key for matching brackets */
1325 // private final static String MATCHING_BRACKETS =
1326 // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1327 /** Preference key for matching brackets color */
1328 // private final static String MATCHING_BRACKETS_COLOR =
1329 // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1330 /** Preference key for highlighting current line */
1331 // private final static String CURRENT_LINE =
1332 // PreferenceConstants.EDITOR_CURRENT_LINE;
1333 /** Preference key for highlight color of current line */
1334 // private final static String CURRENT_LINE_COLOR =
1335 // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1336 /** Preference key for showing print marging ruler */
1337 // private final static String PRINT_MARGIN =
1338 // PreferenceConstants.EDITOR_PRINT_MARGIN;
1339 /** Preference key for print margin ruler color */
1340 // private final static String PRINT_MARGIN_COLOR =
1341 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1342 /** Preference key for print margin ruler column */
1343 // private final static String PRINT_MARGIN_COLUMN =
1344 // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1345 /** Preference key for inserting spaces rather than tabs */
1346 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1348 /** Preference key for error indication */
1349 // private final static String ERROR_INDICATION =
1350 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1351 /** Preference key for error color */
1352 // private final static String ERROR_INDICATION_COLOR =
1353 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1354 /** Preference key for warning indication */
1355 // private final static String WARNING_INDICATION =
1356 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1357 /** Preference key for warning color */
1358 // private final static String WARNING_INDICATION_COLOR =
1359 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1360 /** Preference key for task indication */
1361 //private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1363 /** Preference key for task color */
1364 //private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1366 /** Preference key for bookmark indication */
1367 //private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1369 /** Preference key for bookmark color */
1370 //private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1372 /** Preference key for search result indication */
1373 //private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1375 /** Preference key for search result color */
1376 //private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1378 /** Preference key for unknown annotation indication */
1379 //private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1381 /** Preference key for unknown annotation color */
1382 //private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1384 /** Preference key for linked position color */
1385 //private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1387 /** Preference key for shwoing the overview ruler */
1388 //private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1390 /** Preference key for error indication in overview ruler */
1391 //private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1393 /** Preference key for warning indication in overview ruler */
1394 //private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1396 /** Preference key for task indication in overview ruler */
1397 //private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1399 /** Preference key for bookmark indication in overview ruler */
1400 //private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1402 /** Preference key for search result indication in overview ruler */
1403 //private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1405 /** Preference key for unknown annotation indication in overview ruler */
1406 //private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1408 /** Preference key for automatically closing double quoted strings */
1409 private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1411 /** Preference key for automatically closing single quoted strings */
1412 private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1414 /** Preference key for automatically wrapping Java strings */
1415 // private final static String WRAP_STRINGS =
1416 // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1417 /** Preference key for automatically closing brackets and parenthesis */
1418 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1420 /** Preference key for automatically closing phpdocs and comments */
1421 //private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1423 /** Preference key for automatically adding phpdoc tags */
1424 //private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1426 /** Preference key for automatically formatting phpdocs */
1427 // private final static String FORMAT_JAVADOCS =
1428 // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1429 /** Preference key for automatically closing strings */
1430 //private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1432 /** Preference key for automatically closing brackets and parenthesis */
1433 //private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1435 /** Preference key for smart paste */
1436 //private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1438 // private final static class AnnotationInfo {
1439 // public String fColorPreference;
1440 // public String fOverviewRulerPreference;
1441 // public String fEditorPreference;
1443 // private final static Map ANNOTATION_MAP;
1446 // AnnotationInfo info;
1447 // ANNOTATION_MAP = new HashMap();
1449 // info = new AnnotationInfo();
1450 // info.fColorPreference = TASK_INDICATION_COLOR;
1451 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1452 // info.fEditorPreference = TASK_INDICATION;
1453 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1455 // info = new AnnotationInfo();
1456 // info.fColorPreference = ERROR_INDICATION_COLOR;
1457 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1458 // info.fEditorPreference = ERROR_INDICATION;
1459 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1461 // info = new AnnotationInfo();
1462 // info.fColorPreference = WARNING_INDICATION_COLOR;
1463 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1464 // info.fEditorPreference = WARNING_INDICATION;
1465 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1467 // info = new AnnotationInfo();
1468 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1469 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1470 // info.fEditorPreference = BOOKMARK_INDICATION;
1471 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1473 // info = new AnnotationInfo();
1474 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1475 // info.fOverviewRulerPreference =
1476 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1477 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1478 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1480 // info = new AnnotationInfo();
1481 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1482 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1483 // info.fEditorPreference = UNKNOWN_INDICATION;
1484 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1487 // private final static AnnotationType[] ANNOTATION_LAYERS =
1488 // new AnnotationType[] {
1489 // AnnotationType.UNKNOWN,
1490 // AnnotationType.BOOKMARK,
1491 // AnnotationType.TASK,
1492 // AnnotationType.SEARCH,
1493 // AnnotationType.WARNING,
1494 // AnnotationType.ERROR };
1496 * Creates a new php unit editor.
1500 * Reconciling listeners.
1504 private ListenerList fReconcilingListeners = new ListenerList();
1507 * Mutex for the reconciler. See
1508 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1511 * TODO remove once the underlying problem is solved.
1514 private final Object fReconcilerLock = new Object();
1516 public PHPUnitEditor() {
1518 setDocumentProvider(PHPeclipsePlugin.getDefault()
1519 .getCompilationUnitDocumentProvider());
1520 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1521 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1522 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1523 // don't set help contextId, we install our own help context
1525 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1529 * @see AbstractTextEditor#createActions()
1531 protected void createActions() {
1532 super.createActions();
1534 // Action action= new
1535 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1536 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1538 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1539 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1540 // markAsStateDependentAction("CorrectionAssistProposal", true);
1542 // // WorkbenchHelp.setHelp(action,
1543 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1544 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1545 "ContentAssistProposal.", this); //$NON-NLS-1$
1547 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1548 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1549 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1550 // WorkbenchHelp.setHelp(action,
1551 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1553 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1554 // "ContentAssistContextInformation.", this,
1555 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1557 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1558 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1559 // markAsStateDependentAction("ContentAssistContextInformation", true);
1561 // WorkbenchHelp.setHelp(action,
1562 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1564 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1565 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1567 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1568 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1569 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1571 // // WorkbenchHelp.setHelp(action,
1572 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1573 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1574 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1575 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1576 setAction("Comment", action); //$NON-NLS-1$
1577 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1578 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1579 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1580 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1581 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1582 setAction("Uncomment", action); //$NON-NLS-1$
1583 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1584 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1586 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1587 "ToggleComment.", this); //$NON-NLS-1$
1589 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1590 setAction("ToggleComment", action); //$NON-NLS-1$
1591 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1592 // WorkbenchHelp.setHelp(action,
1593 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1594 configureToggleCommentAction();
1596 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1597 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1598 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1599 setAction("Format", action); //$NON-NLS-1$
1600 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1601 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1602 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1605 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1606 // "AddBlockComment.", this); //$NON-NLS-1$
1608 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1609 // setAction("AddBlockComment", action); //$NON-NLS-1$
1610 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1611 // markAsSelectionDependentAction("AddBlockComment", true);
1613 // // WorkbenchHelp.setHelp(action,
1614 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1615 // action = new RemoveBlockCommentAction(
1616 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1619 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1620 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1621 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1622 // markAsSelectionDependentAction("RemoveBlockComment", true);
1624 // WorkbenchHelp.setHelp(action,
1625 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1626 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1627 "Indent.", this, false); //$NON-NLS-1$
1628 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1629 setAction("Indent", action); //$NON-NLS-1$
1630 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1631 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1632 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1634 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1635 // "Indent.", this, true); //$NON-NLS-1$
1636 // setAction("IndentOnTab", action); //$NON-NLS-1$
1637 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1638 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1641 action = new AddBlockCommentAction(PHPEditorMessages
1642 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1644 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1645 setAction("AddBlockComment", action); //$NON-NLS-1$
1646 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1647 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1648 // WorkbenchHelp.setHelp(action,
1649 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1651 action = new RemoveBlockCommentAction(PHPEditorMessages
1652 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1654 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1655 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1656 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1657 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1658 // WorkbenchHelp.setHelp(action,
1659 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1661 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1662 // "Indent.", this, false); //$NON-NLS-1$
1663 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1664 // setAction("Indent", action); //$NON-NLS-1$
1665 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1666 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1667 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1669 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1670 "Indent.", this, true); //$NON-NLS-1$
1671 setAction("IndentOnTab", action); //$NON-NLS-1$
1672 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1673 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1675 if (getPreferenceStore().getBoolean(
1676 PreferenceConstants.EDITOR_SMART_TAB)) {
1677 // don't replace Shift Right - have to make sure their enablement is
1678 // mutually exclusive
1679 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1680 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1682 fGenerateActionGroup = new GenerateActionGroup(this,
1683 ITextEditorActionConstants.GROUP_EDIT);
1684 // ActionGroup rg= new RefactorActionGroup(this,
1685 // ITextEditorActionConstants.GROUP_EDIT);
1687 // fActionGroups.addGroup(rg);
1688 fActionGroups.addGroup(fGenerateActionGroup);
1690 // We have to keep the context menu group separate to have better
1691 // control over positioning
1692 fContextMenuGroup = new CompositeActionGroup(
1693 new ActionGroup[] { fGenerateActionGroup
1695 // new LocalHistoryActionGroup(this,
1696 // ITextEditorActionConstants.GROUP_EDIT)
1702 * @see JavaEditor#getElementAt(int)
1704 protected IJavaElement getElementAt(int offset) {
1705 return getElementAt(offset, true);
1709 * Returns the most narrow element including the given offset. If
1710 * <code>reconcile</code> is <code>true</code> the editor's input
1711 * element is reconciled in advance. If it is <code>false</code> this
1712 * method only returns a result if the editor's input element does not need
1716 * the offset included by the retrieved element
1718 * <code>true</code> if working copy should be reconciled
1720 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1721 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1722 .getWorkingCopyManager();
1723 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1727 synchronized (unit) {
1730 return unit.getElementAt(offset);
1731 } else if (unit.isConsistent())
1732 return unit.getElementAt(offset);
1733 } catch (JavaModelException x) {
1734 PHPeclipsePlugin.log(x.getStatus());
1735 // nothing found, be tolerant and go on
1742 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1744 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1746 return EditorUtility.getWorkingCopy(element, true);
1747 } catch (JavaModelException x) {
1748 PHPeclipsePlugin.log(x.getStatus());
1749 // nothing found, be tolerant and go on
1754 public void createPartControl(Composite parent) {
1755 super.createPartControl(parent);
1756 // fPaintManager = new PaintManager(getSourceViewer());
1757 LinePainter linePainter;
1758 linePainter = new LinePainter(getSourceViewer());
1759 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
1761 // fPaintManager.addPainter(linePainter);
1762 // if (isBracketHighlightingEnabled())
1763 // startBracketHighlighting();
1764 // if (isLineHighlightingEnabled())
1765 // startLineHighlighting();
1766 // if (isPrintMarginVisible())
1767 // showPrintMargin();
1768 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1769 // while (e.hasNext()) {
1770 // AnnotationType type = (AnnotationType) e.next();
1771 // if (isAnnotationIndicationEnabled(type))
1772 // startAnnotationIndication(type);
1774 if (isTabConversionEnabled())
1775 startTabConversion();
1776 // if (isOverviewRulerVisible())
1777 // showOverviewRuler();
1779 // Preferences preferences =
1780 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1781 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1782 IPreferenceStore preferenceStore = getPreferenceStore();
1783 boolean closeBracketsPHP = preferenceStore
1784 .getBoolean(CLOSE_BRACKETS_PHP);
1785 boolean closeStringsPHPDQ = preferenceStore
1786 .getBoolean(CLOSE_STRINGS_DQ_PHP);
1787 boolean closeStringsPHPSQ = preferenceStore
1788 .getBoolean(CLOSE_STRINGS_SQ_PHP);
1789 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1790 fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ);
1791 fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ);
1792 ISourceViewer sourceViewer = getSourceViewer();
1793 if (sourceViewer instanceof ITextViewerExtension)
1794 ((ITextViewerExtension) sourceViewer)
1795 .prependVerifyKeyListener(fBracketInserter);
1798 private static char getPeerCharacter(char character) {
1799 switch (character) {
1815 throw new IllegalArgumentException();
1819 // private void startBracketHighlighting() {
1820 // if (fBracketPainter == null) {
1821 // ISourceViewer sourceViewer = getSourceViewer();
1822 // fBracketPainter = new BracketPainter(sourceViewer);
1823 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1824 // // fPaintManager.addPainter(fBracketPainter);
1828 // private void stopBracketHighlighting() {
1829 // if (fBracketPainter != null) {
1830 // // fPaintManager.removePainter(fBracketPainter);
1831 // fBracketPainter.deactivate(true);
1832 // fBracketPainter.dispose();
1833 // fBracketPainter = null;
1837 // private boolean isBracketHighlightingEnabled() {
1838 // IPreferenceStore store = getPreferenceStore();
1839 // return store.getBoolean(MATCHING_BRACKETS);
1842 // private void startLineHighlighting() {
1843 // if (fLinePainter == null) {
1844 // ISourceViewer sourceViewer = getSourceViewer();
1845 // fLinePainter = new LinePainter(sourceViewer);
1846 // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1847 // // fPaintManager.addPainter(fLinePainter);
1851 // private void stopLineHighlighting() {
1852 // if (fLinePainter != null) {
1853 // // fPaintManager.removePainter(fLinePainter);
1854 // fLinePainter.deactivate(true);
1855 // fLinePainter.dispose();
1856 // fLinePainter = null;
1860 // private boolean isLineHighlightingEnabled() {
1861 // IPreferenceStore store = getPreferenceStore();
1862 // return store.getBoolean(CURRENT_LINE);
1865 // private void showPrintMargin() {
1866 // if (fPrintMarginPainter == null) {
1867 // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1868 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1869 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1870 // // fPaintManager.addPainter(fPrintMarginPainter);
1874 // private void hidePrintMargin() {
1875 // if (fPrintMarginPainter != null) {
1876 // // fPaintManager.removePainter(fPrintMarginPainter);
1877 // fPrintMarginPainter.deactivate(true);
1878 // fPrintMarginPainter.dispose();
1879 // fPrintMarginPainter = null;
1883 // private boolean isPrintMarginVisible() {
1884 // IPreferenceStore store = getPreferenceStore();
1885 // return store.getBoolean(PRINT_MARGIN);
1888 private int getTabSize() {
1889 Preferences preferences = PHPeclipsePlugin.getDefault()
1890 .getPluginPreferences();
1891 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1894 private boolean isTabConversionEnabled() {
1895 IPreferenceStore store = getPreferenceStore();
1896 return store.getBoolean(SPACES_FOR_TABS);
1899 // private Color getColor(String key) {
1900 // RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1901 // return getColor(rgb);
1904 // private Color getColor(RGB rgb) {
1905 // JavaTextTools textTools = PHPeclipsePlugin.getDefault()
1906 // .getJavaTextTools();
1907 // return textTools.getColorManager().getColor(rgb);
1910 // private Color getColor(AnnotationType annotationType) {
1911 // AnnotationInfo info = (AnnotationInfo)
1912 // ANNOTATION_MAP.get(annotationType);
1913 // if (info != null)
1914 // return getColor(info.fColorPreference);
1917 public void dispose() {
1918 ISourceViewer sourceViewer = getSourceViewer();
1919 if (sourceViewer instanceof ITextViewerExtension)
1920 ((ITextViewerExtension) sourceViewer)
1921 .removeVerifyKeyListener(fBracketInserter);
1922 // if (fPropertyChangeListener != null) {
1923 // Preferences preferences =
1924 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1925 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1926 // fPropertyChangeListener = null;
1928 if (fJavaEditorErrorTickUpdater != null) {
1929 fJavaEditorErrorTickUpdater.dispose();
1930 fJavaEditorErrorTickUpdater = null;
1932 // if (fSelectionHistory != null)
1933 // fSelectionHistory.dispose();
1934 // if (fPaintManager != null) {
1935 // fPaintManager.dispose();
1936 // fPaintManager = null;
1938 if (fActionGroups != null) {
1939 fActionGroups.dispose();
1940 fActionGroups = null;
1945 // protected AnnotationType getAnnotationType(String preferenceKey) {
1946 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1947 // while (e.hasNext()) {
1948 // AnnotationType type = (AnnotationType) e.next();
1949 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1950 // if (info != null) {
1951 // if (preferenceKey.equals(info.fColorPreference)
1952 // || preferenceKey.equals(info.fEditorPreference)
1953 // || preferenceKey.equals(info.fOverviewRulerPreference))
1960 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1962 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1964 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1966 String p = event.getProperty();
1967 if (CLOSE_BRACKETS_PHP.equals(p)) {
1969 .setCloseBracketsPHPEnabled(getPreferenceStore()
1973 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
1975 .setCloseStringsPHPDQEnabled(getPreferenceStore()
1979 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
1981 .setCloseStringsPHPSQEnabled(getPreferenceStore()
1985 if (SPACES_FOR_TABS.equals(p)) {
1986 if (isTabConversionEnabled())
1987 startTabConversion();
1989 stopTabConversion();
1992 // if (MATCHING_BRACKETS.equals(p)) {
1993 // if (isBracketHighlightingEnabled())
1994 // startBracketHighlighting();
1996 // stopBracketHighlighting();
1999 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
2000 // if (fBracketPainter != null)
2001 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
2004 // if (CURRENT_LINE.equals(p)) {
2005 // if (isLineHighlightingEnabled())
2006 // startLineHighlighting();
2008 // stopLineHighlighting();
2011 // if (CURRENT_LINE_COLOR.equals(p)) {
2012 // if (fLinePainter != null) {
2013 // stopLineHighlighting();
2014 // startLineHighlighting();
2018 // if (PRINT_MARGIN.equals(p)) {
2019 // if (isPrintMarginVisible())
2020 // showPrintMargin();
2022 // hidePrintMargin();
2025 // if (PRINT_MARGIN_COLOR.equals(p)) {
2026 // if (fPrintMarginPainter != null)
2027 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2030 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2031 // if (fPrintMarginPainter != null)
2032 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2035 // if (OVERVIEW_RULER.equals(p)) {
2036 // if (isOverviewRulerVisible())
2037 // showOverviewRuler();
2039 // hideOverviewRuler();
2042 // AnnotationType type = getAnnotationType(p);
2043 // if (type != null) {
2045 // AnnotationInfo info = (AnnotationInfo)
2046 // ANNOTATION_MAP.get(type);
2047 // if (info.fColorPreference.equals(p)) {
2048 // Color color = getColor(type);
2049 // if (fProblemPainter != null) {
2050 // fProblemPainter.setColor(type, color);
2051 // fProblemPainter.paint(IPainter.CONFIGURATION);
2053 // setColorInOverviewRuler(type, color);
2057 // if (info.fEditorPreference.equals(p)) {
2058 // if (isAnnotationIndicationEnabled(type))
2059 // startAnnotationIndication(type);
2061 // stopAnnotationIndication(type);
2065 // if (info.fOverviewRulerPreference.equals(p)) {
2066 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2067 // showAnnotationIndicationInOverviewRuler(type, true);
2069 // showAnnotationIndicationInOverviewRuler(type, false);
2073 IContentAssistant c = asv.getContentAssistant();
2074 if (c instanceof ContentAssistant)
2075 ContentAssistPreference.changeConfiguration(
2076 (ContentAssistant) c, getPreferenceStore(), event);
2079 super.handlePreferenceStoreChanged(event);
2084 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2086 protected void handlePreferencePropertyChanged(
2087 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2088 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2090 String p = event.getProperty();
2091 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2092 asv.updateIndentationPrefixes();
2093 if (fTabConverter != null)
2094 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2097 super.handlePreferencePropertyChanged(event);
2101 * Handles a property change event describing a change of the php core's
2102 * preferences and updates the preference related editor properties.
2105 * the property change event
2108 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2110 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2111 // if (asv != null) {
2112 // String p = event.getProperty();
2113 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2114 // asv.updateIndentationPrefixes();
2115 // if (fTabConverter != null)
2116 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2121 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2122 * org.eclipse.jface.text.source.IVerticalRuler,
2123 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2125 protected ISourceViewer createJavaSourceViewer(Composite parent,
2126 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2127 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2128 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2129 isOverviewRulerVisible, styles, store);
2132 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2133 // IVerticalRuler ruler, int styles) {
2134 // return new AdaptedSourceViewer(parent, ruler, styles);
2136 // private boolean isValidSelection(int offset, int length) {
2137 // IDocumentProvider provider = getDocumentProvider();
2138 // if (provider != null) {
2139 // IDocument document = provider.getDocument(getEditorInput());
2140 // if (document != null) {
2141 // int end = offset + length;
2142 // int documentLength = document.getLength();
2143 // return 0 <= offset && offset <= documentLength && 0 <= end
2144 // && end <= documentLength;
2151 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2153 protected IJavaElement getInputJavaElement() {
2154 return PHPeclipsePlugin.getDefault().getWorkingCopyManager()
2155 .getWorkingCopy(getEditorInput());
2159 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2161 public void editorContextMenuAboutToShow(IMenuManager menu) {
2162 super.editorContextMenuAboutToShow(menu);
2163 ActionContext context = new ActionContext(getSelectionProvider()
2165 fContextMenuGroup.setContext(context);
2166 fContextMenuGroup.fillContextMenu(menu);
2167 fContextMenuGroup.setContext(null);
2171 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2173 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2175 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2176 .getWorkingCopyManager();
2177 page.setInput(manager.getWorkingCopy(input));
2182 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2185 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2186 // IProgressMonitor progressMonitor) {
2187 // IDocumentProvider p = getDocumentProvider();
2188 // if (p instanceof PHPDocumentProvider) {
2189 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2190 // cp.setSavePolicy(fSavePolicy);
2194 // super.performSaveOperation(operation, progressMonitor);
2196 // if (p instanceof PHPDocumentProvider) {
2197 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2198 // cp.setSavePolicy(null);
2203 * @see AbstractTextEditor#doSave(IProgressMonitor)
2205 public void doSave(IProgressMonitor progressMonitor) {
2207 IDocumentProvider p = getDocumentProvider();
2209 // editor has been closed
2213 if (p.isDeleted(getEditorInput())) {
2215 if (isSaveAsAllowed()) {
2218 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2219 * the editors. Changed Behavior to make sure that if called
2220 * inside a regular save (because of deletion of input element)
2221 * there is a way to report back to the caller.
2223 performSaveAs(progressMonitor);
2228 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2229 * there Missing resources.
2231 Shell shell = getSite().getShell();
2236 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2240 if (getPreferenceStore().getBoolean(
2241 PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2242 RTrimAction trimAction = new RTrimAction();
2243 trimAction.setActiveEditor(null, getSite().getPage()
2244 .getActiveEditor());
2245 trimAction.run(null);
2248 setStatusLineErrorMessage(null);
2250 updateState(getEditorInput());
2251 validateState(getEditorInput());
2253 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2254 .getWorkingCopyManager();
2255 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2258 synchronized (unit) {
2259 performSave(false, progressMonitor);
2262 performSave(false, progressMonitor);
2266 public boolean isSaveAsAllowed() {
2271 * The compilation unit editor implementation of this
2272 * <code>AbstractTextEditor</code> method asks the user for the workspace
2273 * path of a file resource and saves the document there. See
2274 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2276 * @param progressMonitor
2277 * the progress monitor
2279 protected void performSaveAs(IProgressMonitor progressMonitor) {
2281 Shell shell = getSite().getShell();
2282 IEditorInput input = getEditorInput();
2284 SaveAsDialog dialog = new SaveAsDialog(shell);
2286 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2289 if (original != null)
2290 dialog.setOriginalFile(original);
2294 IDocumentProvider provider = getDocumentProvider();
2295 if (provider == null) {
2296 // editor has been programmatically closed while the dialog was open
2300 if (provider.isDeleted(input) && original != null) {
2301 String message = PHPEditorMessages
2302 .getFormattedString(
2303 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2304 dialog.setErrorMessage(null);
2305 dialog.setMessage(message, IMessageProvider.WARNING);
2308 if (dialog.open() == Window.CANCEL) {
2309 if (progressMonitor != null)
2310 progressMonitor.setCanceled(true);
2314 IPath filePath = dialog.getResult();
2315 if (filePath == null) {
2316 if (progressMonitor != null)
2317 progressMonitor.setCanceled(true);
2321 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2322 IFile file = workspaceRoot.getFile(filePath);
2323 final IEditorInput newInput = new FileEditorInput(file);
2325 boolean success = false;
2328 provider.aboutToChange(newInput);
2329 getDocumentProvider().saveDocument(progressMonitor, newInput,
2330 getDocumentProvider().getDocument(getEditorInput()), true);
2333 } catch (CoreException x) {
2334 IStatus status = x.getStatus();
2335 if (status == null || status.getSeverity() != IStatus.CANCEL)
2340 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2342 provider.changed(newInput);
2347 if (progressMonitor != null)
2348 progressMonitor.setCanceled(!success);
2352 * @see AbstractTextEditor#doSetInput(IEditorInput)
2354 protected void doSetInput(IEditorInput input) throws CoreException {
2355 super.doSetInput(input);
2356 configureTabConverter();
2357 configureToggleCommentAction();
2362 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2365 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2366 // IAnnotationModel model=
2367 // getDocumentProvider().getAnnotationModel(getEditorInput());
2368 // if (!waitForReconcilation)
2369 // super.installOverrideIndicator(false);
2371 // uninstallOverrideIndicator();
2372 // IJavaElement inputElement= getInputJavaElement();
2373 // if (model == null || inputElement == null)
2376 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2377 // inputElement, null);
2378 // addReconcileListener(fOverrideIndicatorManager);
2384 // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2387 // protected void uninstallOverrideIndicator() {
2388 // if (fOverrideIndicatorManager != null)
2389 // removeReconcileListener(fOverrideIndicatorManager);
2390 // super.uninstallOverrideIndicator();
2394 * Configures the toggle comment action
2398 private void configureToggleCommentAction() {
2399 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2400 if (action instanceof ToggleCommentAction) {
2401 ISourceViewer sourceViewer = getSourceViewer();
2402 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2403 ((ToggleCommentAction) action).configure(sourceViewer,
2408 // private void configureTabConverter() {
2409 // if (fTabConverter != null) {
2410 // IDocumentProvider provider = getDocumentProvider();
2411 // if (provider instanceof PHPDocumentProvider) {
2412 // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2413 // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2417 private void configureTabConverter() {
2418 if (fTabConverter != null) {
2419 IDocumentProvider provider = getDocumentProvider();
2420 if (provider instanceof ICompilationUnitDocumentProvider) {
2421 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2422 fTabConverter.setLineTracker(cup
2423 .createLineTracker(getEditorInput()));
2428 private void startTabConversion() {
2429 if (fTabConverter == null) {
2430 fTabConverter = new TabConverter();
2431 configureTabConverter();
2432 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2433 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2434 asv.addTextConverter(fTabConverter);
2435 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2436 asv.updateIndentationPrefixes();
2440 private void stopTabConversion() {
2441 if (fTabConverter != null) {
2442 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2443 asv.removeTextConverter(fTabConverter);
2444 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2445 asv.updateIndentationPrefixes();
2446 fTabConverter = null;
2451 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2452 * org.eclipse.core.runtime.IProgressMonitor)
2454 protected void performSave(boolean overwrite,
2455 IProgressMonitor progressMonitor) {
2456 // IDocumentProvider p = getDocumentProvider();
2457 // if (p instanceof PHPDocumentProvider) {
2458 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2459 // cp.setSavePolicy(fSavePolicy);
2462 // super.performSave(overwrite, progressMonitor);
2464 // if (p instanceof PHPDocumentProvider) {
2465 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2466 // cp.setSavePolicy(null);
2470 IDocumentProvider p = getDocumentProvider();
2471 if (p instanceof ICompilationUnitDocumentProvider) {
2472 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2473 cp.setSavePolicy(fSavePolicy);
2476 super.performSave(overwrite, progressMonitor);
2478 if (p instanceof ICompilationUnitDocumentProvider) {
2479 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2480 cp.setSavePolicy(null);
2486 * @see AbstractTextEditor#doSaveAs
2488 public void doSaveAs() {
2489 if (askIfNonWorkbenchEncodingIsOk()) {
2495 * Asks the user if it is ok to store in non-workbench encoding.
2497 * @return <true>if the user wants to continue
2499 private boolean askIfNonWorkbenchEncodingIsOk() {
2500 IDocumentProvider provider = getDocumentProvider();
2501 if (provider instanceof IStorageDocumentProvider) {
2502 IEditorInput input = getEditorInput();
2503 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2504 String encoding = storageProvider.getEncoding(input);
2505 String defaultEncoding = storageProvider.getDefaultEncoding();
2506 if (encoding != null && !encoding.equals(defaultEncoding)) {
2507 Shell shell = getSite().getShell();
2508 String title = PHPEditorMessages
2509 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2515 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2516 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2521 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2522 new String[] { encoding }); //$NON-NLS-1$
2523 return MessageDialog.openQuestion(shell, title, msg);
2530 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2533 public void aboutToBeReconciled() {
2535 // Notify AST provider
2536 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2539 Object[] listeners = fReconcilingListeners.getListeners();
2540 for (int i = 0, length = listeners.length; i < length; ++i)
2541 ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2545 * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2546 * boolean, IProgressMonitor)
2549 public void reconciled(CompilationUnit ast, boolean forced,
2550 IProgressMonitor progressMonitor) {
2552 // Always notify AST provider
2553 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2554 // getInputJavaElement());
2557 // Object[] listeners = fReconcilingListeners.getListeners();
2558 // for (int i = 0, length= listeners.length; i < length; ++i)
2559 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2560 // progressMonitor);
2562 // Update Java Outline page selection
2563 if (!forced && !progressMonitor.isCanceled()) {
2564 Shell shell = getSite().getShell();
2565 if (shell != null && !shell.isDisposed()) {
2566 shell.getDisplay().asyncExec(new Runnable() {
2576 * Returns the updated java element for the old java element.
2578 // private IJavaElement findElement(IJavaElement element) {
2579 // if (element == null)
2581 // IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2582 // .getWorkingCopyManager();
2583 // ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2584 // if (unit != null) {
2586 // synchronized (unit) {
2587 // unit.reconcile();
2589 // IJavaElement[] findings = unit.findElements(element);
2590 // if (findings != null && findings.length > 0)
2591 // return findings[0];
2592 // } catch (JavaModelException x) {
2593 // PHPeclipsePlugin.log(x.getStatus());
2594 // // nothing found, be tolerant and go on
2601 * Returns the offset of the given Java element.
2603 // private int getOffset(IJavaElement element) {
2604 // if (element instanceof ISourceReference) {
2605 // ISourceReference sr = (ISourceReference) element;
2607 // ISourceRange srcRange = sr.getSourceRange();
2608 // if (srcRange != null)
2609 // return srcRange.getOffset();
2610 // } catch (JavaModelException e) {
2617 * @see AbstractTextEditor#restoreSelection()
2619 // protected void restoreSelection() {
2621 // if (getSourceViewer() == null || fRememberedSelection == null)
2623 // IJavaElement newElement = findElement(fRememberedElement);
2624 // int newOffset = getOffset(newElement);
2625 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2626 // - fRememberedElementOffset : 0;
2627 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2628 // fRememberedSelection.getLength()))
2629 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2630 // fRememberedSelection.getLength());
2632 // fRememberedSelection = null;
2633 // fRememberedElement = null;
2634 // fRememberedElementOffset = -1;
2638 * Tells whether this is the active editor in the active page.
2640 * @return <code>true</code> if this is the active editor in the active
2642 * @see IWorkbenchPage#getActiveEditor();
2644 protected final boolean isActiveEditor() {
2645 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2646 IWorkbenchPage page = window.getActivePage();
2649 IEditorPart activeEditor = page.getActiveEditor();
2650 return activeEditor != null && activeEditor.equals(this);
2654 * Adds the given listener. Has no effect if an identical listener was not
2655 * already registered.
2658 * The reconcile listener to be added
2661 final void addReconcileListener(IJavaReconcilingListener listener) {
2662 synchronized (fReconcilingListeners) {
2663 fReconcilingListeners.add(listener);
2668 * Removes the given listener. Has no effect if an identical listener was
2669 * not already registered.
2672 * the reconcile listener to be removed
2675 final void removeReconcileListener(IJavaReconcilingListener listener) {
2676 synchronized (fReconcilingListeners) {
2677 fReconcilingListeners.remove(listener);
2681 protected void updateStateDependentActions() {
2682 super.updateStateDependentActions();
2683 fGenerateActionGroup.editorStateChanged();
2687 * @see AbstractTextEditor#rememberSelection()
2689 protected void rememberSelection() {
2690 fRememberedSelection.remember();
2694 * @see AbstractTextEditor#restoreSelection()
2696 protected void restoreSelection() {
2697 fRememberedSelection.restore();
2701 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2703 protected boolean canHandleMove(IEditorInput originalElement,
2704 IEditorInput movedElement) {
2706 String oldExtension = ""; //$NON-NLS-1$
2707 if (originalElement instanceof IFileEditorInput) {
2708 IFile file = ((IFileEditorInput) originalElement).getFile();
2710 String ext = file.getFileExtension();
2716 String newExtension = ""; //$NON-NLS-1$
2717 if (movedElement instanceof IFileEditorInput) {
2718 IFile file = ((IFileEditorInput) movedElement).getFile();
2720 newExtension = file.getFileExtension();
2723 return oldExtension.equals(newExtension);
2727 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2729 protected boolean isPrefQuickDiffAlwaysOn() {
2730 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2731 // was hacked by JavaEditor
2732 // to disable the change bar for the class file (attached source) java
2734 IPreferenceStore store = getPreferenceStore();
2736 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2740 * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2742 public Object getAdapter(Class required) {
2743 if (SmartBackspaceManager.class.equals(required)) {
2744 if (getSourceViewer() instanceof JavaSourceViewer) {
2745 return ((JavaSourceViewer) getSourceViewer())
2746 .getBackspaceManager();
2750 return super.getAdapter(required);
2754 * Returns the mutex for the reconciler. See
2755 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2758 * TODO remove once the underlying problem is solved.
2761 * @return the lock reconcilers may use to synchronize on
2763 public Object getReconcilerLock() {
2764 return fReconcilerLock;
2770 * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2772 protected void editorSaved() {
2773 super.editorSaved();
2774 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2776 //a.refresh(ShowExternalPreviewAction.PHP_TYPE);
2777 a.doRun(ShowExternalPreviewAction.PHP_TYPE);