1 package net.sourceforge.phpeclipse.phpeditor;
3 import java.text.MessageFormat;
4 import java.util.ArrayList;
5 import java.util.Iterator;
8 import net.sourceforge.phpdt.core.ICompilationUnit;
9 import net.sourceforge.phpdt.core.IJavaElement;
10 import net.sourceforge.phpdt.core.IMember;
11 import net.sourceforge.phpdt.core.ISourceRange;
12 import net.sourceforge.phpdt.core.ISourceReference;
13 import net.sourceforge.phpdt.core.JavaCore;
14 import net.sourceforge.phpdt.core.JavaModelException;
15 import net.sourceforge.phpdt.core.dom.CompilationUnit;
16 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
17 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
18 import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference;
19 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
20 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
21 import net.sourceforge.phpdt.internal.ui.text.SmartBackspaceManager;
22 import net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener;
23 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager;
24 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI;
25 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
26 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
27 import net.sourceforge.phpdt.ui.PreferenceConstants;
28 import net.sourceforge.phpdt.ui.actions.GenerateActionGroup;
29 import net.sourceforge.phpdt.ui.text.JavaTextTools;
30 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
32 import org.eclipse.core.internal.runtime.ListenerList;
33 import org.eclipse.core.resources.IFile;
34 import org.eclipse.core.resources.IWorkspaceRoot;
35 import org.eclipse.core.resources.ResourcesPlugin;
36 import org.eclipse.core.runtime.CoreException;
37 import org.eclipse.core.runtime.IPath;
38 import org.eclipse.core.runtime.IProgressMonitor;
39 import org.eclipse.core.runtime.IStatus;
40 import org.eclipse.core.runtime.Preferences;
41 import org.eclipse.jface.action.Action;
42 import org.eclipse.jface.action.IAction;
43 import org.eclipse.jface.action.IMenuManager;
44 import org.eclipse.jface.dialogs.ErrorDialog;
45 import org.eclipse.jface.dialogs.IMessageProvider;
46 import org.eclipse.jface.dialogs.MessageDialog;
47 import org.eclipse.jface.preference.IPreferenceStore;
48 import org.eclipse.jface.preference.PreferenceConverter;
49 import org.eclipse.jface.text.BadLocationException;
50 import org.eclipse.jface.text.DocumentCommand;
51 import org.eclipse.jface.text.IDocument;
52 import org.eclipse.jface.text.ILineTracker;
53 import org.eclipse.jface.text.IRegion;
54 import org.eclipse.jface.text.ITextOperationTarget;
55 import org.eclipse.jface.text.ITextViewerExtension;
56 import org.eclipse.jface.text.ITypedRegion;
57 import org.eclipse.jface.text.IWidgetTokenKeeper;
58 import org.eclipse.jface.text.contentassist.ContentAssistant;
59 import org.eclipse.jface.text.contentassist.IContentAssistant;
60 import org.eclipse.jface.text.source.IOverviewRuler;
61 import org.eclipse.jface.text.source.ISourceViewer;
62 import org.eclipse.jface.text.source.IVerticalRuler;
63 import org.eclipse.jface.text.source.SourceViewerConfiguration;
64 import org.eclipse.jface.util.PropertyChangeEvent;
65 import org.eclipse.jface.window.Window;
66 import org.eclipse.swt.SWT;
67 import org.eclipse.swt.custom.VerifyKeyListener;
68 import org.eclipse.swt.events.VerifyEvent;
69 import org.eclipse.swt.graphics.Color;
70 import org.eclipse.swt.graphics.Point;
71 import org.eclipse.swt.graphics.RGB;
72 import org.eclipse.swt.widgets.Composite;
73 import org.eclipse.swt.widgets.Display;
74 import org.eclipse.swt.widgets.Shell;
75 import org.eclipse.ui.IEditorInput;
76 import org.eclipse.ui.IEditorPart;
77 import org.eclipse.ui.IFileEditorInput;
78 import org.eclipse.ui.IWorkbenchPage;
79 import org.eclipse.ui.IWorkbenchWindow;
80 import org.eclipse.ui.actions.ActionContext;
81 import org.eclipse.ui.actions.ActionGroup;
82 import org.eclipse.ui.dialogs.SaveAsDialog;
83 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
84 import org.eclipse.ui.help.WorkbenchHelp;
85 import org.eclipse.ui.part.FileEditorInput;
86 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
87 import org.eclipse.ui.texteditor.ContentAssistAction;
88 import org.eclipse.ui.texteditor.IDocumentProvider;
89 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
90 import org.eclipse.ui.texteditor.TextOperationAction;
92 /*******************************************************************************
93 * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
94 * program and the accompanying materials are made available under the terms of
95 * the Common Public License v1.0 which accompanies this distribution, and is
96 * available at http://www.eclipse.org/legal/cpl-v10.html
98 * Contributors: IBM Corporation - Initial implementation Klaus Hartlage -
99 * www.eclipseproject.de
100 ******************************************************************************/
102 * PHP specific text editor.
104 public class PHPUnitEditor extends PHPEditor { //implements
105 // IJavaReconcilingListener {
106 interface ITextConverter {
107 void customizeDocumentCommand(IDocument document, DocumentCommand command);
110 // class AdaptedRulerLayout extends Layout {
112 // protected int fGap;
113 // protected AdaptedSourceViewer fAdaptedSourceViewer;
115 // protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
117 // fAdaptedSourceViewer = asv;
120 // protected Point computeSize(Composite composite, int wHint, int hHint,
121 // boolean flushCache) {
122 // Control[] children = composite.getChildren();
123 // Point s = children[children.length - 1].computeSize(SWT.DEFAULT,
124 // SWT.DEFAULT, flushCache);
125 // if (fAdaptedSourceViewer.isVerticalRulerVisible())
126 // s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
130 // protected void layout(Composite composite, boolean flushCache) {
131 // Rectangle clArea = composite.getClientArea();
132 // if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
134 // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
135 // Rectangle trim = textWidget.computeTrim(0, 0, 0, 0);
136 // int scrollbarHeight = trim.height;
138 // IVerticalRuler vr = fAdaptedSourceViewer.getVerticalRuler();
139 // int vrWidth = vr.getWidth();
142 // if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
143 // OverviewRuler or = fAdaptedSourceViewer.getOverviewRuler();
144 // orWidth = or.getWidth();
145 // or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight,
146 // orWidth, clArea.height - 3 * scrollbarHeight);
149 // textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth
151 // 2 * fGap, clArea.height);
152 // vr.getControl().setBounds(0, 0, vrWidth, clArea.height -
156 // StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
157 // textWidget.setBounds(0, 0, clArea.width, clArea.height);
162 // class AdaptedSourceViewer extends SourceViewer { // extends
163 // JavaCorrectionSourceViewer {
165 // private List fTextConverters;
167 // private OverviewRuler fOverviewRuler;
168 // private boolean fIsOverviewRulerVisible;
169 // /** The viewer's overview ruler hovering controller */
170 // private AbstractHoverInformationControlManager
171 // fOverviewRulerHoveringController;
173 // private boolean fIgnoreTextConverters = false;
175 // private IVerticalRuler fCachedVerticalRuler;
176 // private boolean fCachedIsVerticalRulerVisible;
178 // public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int
180 // super(parent, ruler, styles); //, CompilationUnitEditor.this);
182 // fCachedVerticalRuler = ruler;
183 // fCachedIsVerticalRulerVisible = (ruler != null);
184 // fOverviewRuler = new OverviewRuler(VERTICAL_RULER_WIDTH);
186 // delayedCreateControl(parent, styles);
190 // * @see ISourceViewer#showAnnotations(boolean)
192 // public void showAnnotations(boolean show) {
193 // fCachedIsVerticalRulerVisible = (show && fCachedVerticalRuler != null);
194 // // super.showAnnotations(show);
197 // public IContentAssistant getContentAssistant() {
198 // return fContentAssistant;
202 // * @see ITextOperationTarget#doOperation(int)
204 // public void doOperation(int operation) {
206 // if (getTextWidget() == null)
209 // switch (operation) {
210 // case CONTENTASSIST_PROPOSALS :
211 // String msg = fContentAssistant.showPossibleCompletions();
212 // setStatusLineErrorMessage(msg);
215 // fIgnoreTextConverters = true;
218 // fIgnoreTextConverters = true;
222 // super.doOperation(operation);
225 // public void insertTextConverter(ITextConverter textConverter, int index)
227 // throw new UnsupportedOperationException();
230 // public void addTextConverter(ITextConverter textConverter) {
231 // if (fTextConverters == null) {
232 // fTextConverters = new ArrayList(1);
233 // fTextConverters.add(textConverter);
234 // } else if (!fTextConverters.contains(textConverter))
235 // fTextConverters.add(textConverter);
238 // public void removeTextConverter(ITextConverter textConverter) {
239 // if (fTextConverters != null) {
240 // fTextConverters.remove(textConverter);
241 // if (fTextConverters.size() == 0)
242 // fTextConverters = null;
247 // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
249 // protected void customizeDocumentCommand(DocumentCommand command) {
250 // super.customizeDocumentCommand(command);
251 // if (!fIgnoreTextConverters && fTextConverters != null) {
252 // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
253 // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
256 // fIgnoreTextConverters = false;
259 // public IVerticalRuler getVerticalRuler() {
260 // return fCachedVerticalRuler;
263 // public boolean isVerticalRulerVisible() {
264 // return fCachedIsVerticalRulerVisible;
267 // public OverviewRuler getOverviewRuler() {
268 // return fOverviewRuler;
272 // * @see TextViewer#createControl(Composite, int)
274 // protected void createControl(Composite parent, int styles) {
275 // // do nothing here
278 // protected void delayedCreateControl(Composite parent, int styles) {
279 // //create the viewer
280 // super.createControl(parent, styles);
282 // Control control = getControl();
283 // if (control instanceof Composite) {
284 // Composite composite = (Composite) control;
285 // composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
286 // fOverviewRuler.createControl(composite, this);
289 // protected void ensureOverviewHoverManagerInstalled() {
290 // if (fOverviewRulerHoveringController == null && fAnnotationHover != null
291 // && fHoverControlCreator != null) {
292 // fOverviewRulerHoveringController =
293 // new OverviewRulerHoverManager(fOverviewRuler, this, fAnnotationHover,
294 // fHoverControlCreator);
295 // fOverviewRulerHoveringController.install(fOverviewRuler.getControl());
299 // public void hideOverviewRuler() {
300 // fIsOverviewRulerVisible = false;
301 // Control control = getControl();
302 // if (control instanceof Composite) {
303 // Composite composite = (Composite) control;
304 // composite.layout();
306 // if (fOverviewRulerHoveringController != null) {
307 // fOverviewRulerHoveringController.dispose();
308 // fOverviewRulerHoveringController = null;
312 // public void showOverviewRuler() {
313 // fIsOverviewRulerVisible = true;
314 // Control control = getControl();
315 // if (control instanceof Composite) {
316 // Composite composite = (Composite) control;
317 // composite.layout();
319 // ensureOverviewHoverManagerInstalled();
322 // public boolean isOverviewRulerVisible() {
323 // return fIsOverviewRulerVisible;
327 // * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
329 // public void setDocument(
330 // IDocument document,
331 // IAnnotationModel annotationModel,
332 // int visibleRegionOffset,
333 // int visibleRegionLength) {
334 // super.setDocument(document, annotationModel, visibleRegionOffset,
335 // visibleRegionLength);
336 // fOverviewRuler.setModel(annotationModel);
339 // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
340 // public void updateIndentationPrefixes() {
341 // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
342 // String[] types = configuration.getConfiguredContentTypes(this);
343 // for (int i = 0; i < types.length; i++) {
344 // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
345 // if (prefixes != null && prefixes.length > 0)
346 // setIndentPrefixes(prefixes, types[i]);
351 // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
353 // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
354 // if (WorkbenchHelp.isContextHelpDisplayed())
356 // return super.requestWidgetToken(requester);
361 // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
363 // public void configure(SourceViewerConfiguration configuration) {
364 // super.configure(configuration);
365 // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
366 // IDocument.DEFAULT_CONTENT_TYPE);
369 // protected void handleDispose() {
370 // fOverviewRuler = null;
372 // if (fOverviewRulerHoveringController != null) {
373 // fOverviewRulerHoveringController.dispose();
374 // fOverviewRulerHoveringController = null;
377 // super.handleDispose();
381 class AdaptedSourceViewer extends JavaSourceViewer {
382 private List fTextConverters;
384 private boolean fIgnoreTextConverters = false;
386 // private JavaCorrectionAssistant fCorrectionAssistant;
387 public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler,
388 IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
389 int styles, IPreferenceStore store) {
390 super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
394 // public AdaptedSourceViewer(Composite parent,
395 // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
396 // boolean showAnnotationsOverview, int styles) {
397 // super(parent, verticalRuler, overviewRuler,
398 // showAnnotationsOverview, styles);
400 public IContentAssistant getContentAssistant() {
401 return fContentAssistant;
405 * @see ITextOperationTarget#doOperation(int)
407 public void doOperation(int operation) {
408 if (getTextWidget() == null)
411 case CONTENTASSIST_PROPOSALS:
412 String msg = fContentAssistant.showPossibleCompletions();
413 setStatusLineErrorMessage(msg);
415 // case CORRECTIONASSIST_PROPOSALS:
416 // fCorrectionAssistant.showPossibleCompletions();
419 fIgnoreTextConverters = true;
422 fIgnoreTextConverters = true;
425 super.doOperation(operation);
429 * @see ITextOperationTarget#canDoOperation(int)
431 public boolean canDoOperation(int operation) {
432 // if (operation == CORRECTIONASSIST_PROPOSALS)
433 // return isEditable();
434 return super.canDoOperation(operation);
438 * @see TextViewer#handleDispose()
440 protected void handleDispose() {
441 // if (fCorrectionAssistant != null) {
442 // fCorrectionAssistant.uninstall();
443 // fCorrectionAssistant= null;
445 super.handleDispose();
448 public void insertTextConverter(ITextConverter textConverter, int index) {
449 throw new UnsupportedOperationException();
452 public void addTextConverter(ITextConverter textConverter) {
453 if (fTextConverters == null) {
454 fTextConverters = new ArrayList(1);
455 fTextConverters.add(textConverter);
456 } else if (!fTextConverters.contains(textConverter))
457 fTextConverters.add(textConverter);
460 public void removeTextConverter(ITextConverter textConverter) {
461 if (fTextConverters != null) {
462 fTextConverters.remove(textConverter);
463 if (fTextConverters.size() == 0)
464 fTextConverters = null;
469 * @see TextViewer#customizeDocumentCommand(DocumentCommand)
471 protected void customizeDocumentCommand(DocumentCommand command) {
472 super.customizeDocumentCommand(command);
473 if (!fIgnoreTextConverters && fTextConverters != null) {
474 for (Iterator e = fTextConverters.iterator(); e.hasNext();)
475 ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
478 fIgnoreTextConverters = false;
481 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
482 public void updateIndentationPrefixes() {
483 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
484 String[] types = configuration.getConfiguredContentTypes(this);
485 for (int i = 0; i < types.length; i++) {
486 String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
487 if (prefixes != null && prefixes.length > 0)
488 setIndentPrefixes(prefixes, types[i]);
493 * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
495 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
496 if (WorkbenchHelp.isContextHelpDisplayed())
498 return super.requestWidgetToken(requester);
502 * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
504 public void configure(SourceViewerConfiguration configuration) {
505 super.configure(configuration);
506 // fCorrectionAssistant= new
507 // JavaCorrectionAssistant(CompilationUnitEditor.this);
508 // fCorrectionAssistant.install(this);
509 //TODO install SmartBracesAutoEditStrategy
510 // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
511 // IDocument.DEFAULT_CONTENT_TYPE);
515 * Remembers data related to the current selection to be able to
520 private class RememberedSelection {
521 /** The remembered selection start. */
522 private RememberedOffset fStartOffset= new RememberedOffset();
523 /** The remembered selection end. */
524 private RememberedOffset fEndOffset= new RememberedOffset();
527 * Remember current selection.
529 public void remember() {
530 /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
531 * This method may be called inside an async call posted
532 * to the UI thread, so protect against intermediate disposal
535 ISourceViewer viewer= getSourceViewer();
536 if (viewer != null) {
537 IRegion selection= getSignedSelection(viewer);
538 int startOffset= selection.getOffset();
539 int endOffset= startOffset + selection.getLength();
541 fStartOffset.setOffset(startOffset);
542 fEndOffset.setOffset(endOffset);
547 * Restore remembered selection.
549 public void restore() {
550 /* https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257
551 * This method may be called inside an async call posted
552 * to the UI thread, so protect against intermediate disposal
555 if (getSourceViewer() == null)
560 int startOffset, endOffset;
561 int revealStartOffset, revealEndOffset;
562 if (showsHighlightRangeOnly()) {
563 IJavaElement newStartElement= fStartOffset.getElement();
564 startOffset= fStartOffset.getRememberedOffset(newStartElement);
565 revealStartOffset= fStartOffset.getRevealOffset(newStartElement, startOffset);
566 if (revealStartOffset == -1)
569 IJavaElement newEndElement= fEndOffset.getElement();
570 endOffset= fEndOffset.getRememberedOffset(newEndElement);
571 revealEndOffset= fEndOffset.getRevealOffset(newEndElement, endOffset);
572 if (revealEndOffset == -1)
575 startOffset= fStartOffset.getOffset();
576 revealStartOffset= startOffset;
577 endOffset= fEndOffset.getOffset();
578 revealEndOffset= endOffset;
581 if (startOffset == -1) {
582 startOffset= endOffset; // fallback to caret offset
583 revealStartOffset= revealEndOffset;
586 if (endOffset == -1) {
587 endOffset= startOffset; // fallback to other offset
588 revealEndOffset= revealStartOffset;
591 IJavaElement element;
592 if (endOffset == -1) {
593 // fallback to element selection
594 element= fEndOffset.getElement();
596 element= fStartOffset.getElement();
598 setSelection(element);
602 if (isValidSelection(revealStartOffset, revealEndOffset - revealStartOffset) && isValidSelection(startOffset, endOffset - startOffset))
603 selectAndReveal(startOffset, endOffset - startOffset, revealStartOffset, revealEndOffset - revealStartOffset);
605 fStartOffset.clear();
610 private boolean isValidSelection(int offset, int length) {
611 IDocumentProvider provider= getDocumentProvider();
612 if (provider != null) {
613 IDocument document= provider.getDocument(getEditorInput());
614 if (document != null) {
615 int end= offset + length;
616 int documentLength= document.getLength();
617 return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength;
626 * Remembers additional data for a given
627 * offset to be able restore it later.
631 private class RememberedOffset {
632 /** Remembered line for the given offset */
634 /** Remembered column for the given offset*/
636 /** Remembered Java element for the given offset*/
637 private IJavaElement fElement;
638 /** Remembered Java element line for the given offset*/
639 private int fElementLine;
642 * Store visual properties of the given offset.
644 * @param offset Offset in the document
646 public void setOffset(int offset) {
648 IDocument document= getSourceViewer().getDocument();
649 fLine= document.getLineOfOffset(offset);
650 fColumn= offset - document.getLineOffset(fLine);
651 fElement= getElementAt(offset, true);
654 if (fElement instanceof IMember) {
655 ISourceRange range= ((IMember) fElement).getNameRange();
657 fElementLine= document.getLineOfOffset(range.getOffset());
659 if (fElementLine == -1)
660 fElementLine= document.getLineOfOffset(getOffset(fElement));
661 } catch (BadLocationException e) {
663 PHPeclipsePlugin.log(e);
665 } catch (JavaModelException e) {
667 PHPeclipsePlugin.log(e.getStatus());
673 * Return offset recomputed from stored visual properties.
675 * @return Offset in the document
677 public int getOffset() {
678 IJavaElement newElement= getElement();
680 int offset= getRememberedOffset(newElement);
682 if (offset != -1 && !containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1)))
689 * Return offset recomputed from stored visual properties.
691 * @param newElement Enclosing element
692 * @return Offset in the document
694 public int getRememberedOffset(IJavaElement newElement) {
696 if (newElement == null)
699 IDocument document= getSourceViewer().getDocument();
700 int newElementLine= -1;
701 if (newElement instanceof IMember) {
702 ISourceRange range= ((IMember) newElement).getNameRange();
704 newElementLine= document.getLineOfOffset(range.getOffset());
706 if (newElementLine == -1)
707 newElementLine= document.getLineOfOffset(getOffset(newElement));
708 if (newElementLine == -1)
711 int newLine= fLine + newElementLine - fElementLine;
712 if (newLine < 0 || newLine >= document.getNumberOfLines())
714 int maxColumn= document.getLineLength(newLine);
715 String lineDelimiter= document.getLineDelimiter(newLine);
716 if (lineDelimiter != null)
717 maxColumn= maxColumn - lineDelimiter.length();
719 if (fColumn > maxColumn)
720 offset= document.getLineOffset(newLine) + maxColumn;
722 offset= document.getLineOffset(newLine) + fColumn;
725 } catch (BadLocationException e) {
727 PHPeclipsePlugin.log(e);
729 } catch (JavaModelException e) {
731 PHPeclipsePlugin.log(e.getStatus());
737 * Returns the offset used to reveal the given element based on the given selection offset.
738 * @param element the element
739 * @param offset the selection offset
740 * @return the offset to reveal the given element based on the given selection offset
742 public int getRevealOffset(IJavaElement element, int offset) {
743 if (element == null || offset == -1)
746 if (containsOffset(element, offset)) {
748 IJavaElement alternateElement= getElementAt(offset, false);
749 if (element.getHandleIdentifier().equals(alternateElement.getParent().getHandleIdentifier()))
750 return offset - 1; // Solves test case 2 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
753 } else if (offset > 0 && containsOffset(element, offset - 1))
754 return offset - 1; // Solves test case 1 from https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
760 * Return Java element recomputed from stored visual properties.
762 * @return Java element
764 public IJavaElement getElement() {
765 if (fElement == null)
768 return findElement(fElement);
772 * Clears the stored position
774 public void clear() {
782 * Does the given Java element contain the given offset?
783 * @param element Java element
784 * @param offset Offset
785 * @return <code>true</code> iff the Java element contains the offset
787 private boolean containsOffset(IJavaElement element, int offset) {
788 int elementOffset= getOffset(element);
789 int elementLength= getLength(element);
790 return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false;
793 * Returns the offset of the given Java element.
795 * @param element Java element
796 * @return Offset of the given Java element
798 private int getOffset(IJavaElement element) {
799 if (element instanceof ISourceReference) {
800 ISourceReference sr= (ISourceReference) element;
802 ISourceRange srcRange= sr.getSourceRange();
803 if (srcRange != null)
804 return srcRange.getOffset();
805 } catch (JavaModelException e) {
812 * Returns the length of the given Java element.
814 * @param element Java element
815 * @return Length of the given Java element
817 private int getLength(IJavaElement element) {
818 if (element instanceof ISourceReference) {
819 ISourceReference sr= (ISourceReference) element;
821 ISourceRange srcRange= sr.getSourceRange();
822 if (srcRange != null)
823 return srcRange.getLength();
824 } catch (JavaModelException e) {
831 * Returns the updated java element for the old java element.
833 * @param element Old Java element
834 * @return Updated Java element
836 private IJavaElement findElement(IJavaElement element) {
841 IWorkingCopyManager manager= PHPeclipsePlugin.getDefault().getWorkingCopyManager();
842 ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
847 synchronized (unit) {
848 // unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
851 IJavaElement[] findings= unit.findElements(element);
852 if (findings != null && findings.length > 0)
855 } catch (JavaModelException x) {
856 PHPeclipsePlugin.log(x.getStatus());
857 // nothing found, be tolerant and go on
866 static class TabConverter implements ITextConverter {
867 private int fTabRatio;
869 private ILineTracker fLineTracker;
871 public TabConverter() {
874 public void setNumberOfSpacesPerTab(int ratio) {
878 public void setLineTracker(ILineTracker lineTracker) {
879 fLineTracker = lineTracker;
882 private int insertTabString(StringBuffer buffer, int offsetInLine) {
885 int remainder = offsetInLine % fTabRatio;
886 remainder = fTabRatio - remainder;
887 for (int i = 0; i < remainder; i++)
892 public void customizeDocumentCommand(IDocument document,
893 DocumentCommand command) {
894 String text = command.text;
897 int index = text.indexOf('\t');
899 StringBuffer buffer = new StringBuffer();
900 fLineTracker.set(command.text);
901 int lines = fLineTracker.getNumberOfLines();
903 for (int i = 0; i < lines; i++) {
904 int offset = fLineTracker.getLineOffset(i);
905 int endOffset = offset + fLineTracker.getLineLength(i);
906 String line = text.substring(offset, endOffset);
909 IRegion firstLine = document
910 .getLineInformationOfOffset(command.offset);
911 position = command.offset - firstLine.getOffset();
913 int length = line.length();
914 for (int j = 0; j < length; j++) {
915 char c = line.charAt(j);
917 position += insertTabString(buffer, position);
924 command.text = buffer.toString();
925 } catch (BadLocationException x) {
931 private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
932 final char fExitCharacter;
934 public ExitPolicy(char exitCharacter) {
935 fExitCharacter = exitCharacter;
939 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
940 * org.eclipse.swt.events.VerifyEvent, int, int)
942 public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event,
943 int offset, int length) {
944 if (event.character == fExitCharacter) {
945 if (manager.anyPositionIncludes(offset, length))
946 return new ExitFlags(LinkedPositionUI.COMMIT
947 | LinkedPositionUI.UPDATE_CARET, false);
949 return new ExitFlags(LinkedPositionUI.COMMIT, true);
951 switch (event.character) {
953 if (manager.getFirstPosition().length == 0)
954 return new ExitFlags(0, false);
959 return new ExitFlags(LinkedPositionUI.COMMIT, true);
966 private static class BracketLevel {
971 LinkedPositionManager fManager;
973 LinkedPositionUI fEditor;
976 private class BracketInserter implements VerifyKeyListener,
977 LinkedPositionUI.ExitListener {
978 private boolean fCloseBracketsPHP = true;
980 private boolean fCloseStringsPHP = true;
982 private boolean fCloseBracketsHTML = true;
984 private boolean fCloseStringsHTML = true;
990 public void setCloseBracketsPHPEnabled(boolean enabled) {
991 fCloseBracketsPHP = enabled;
994 public void setCloseStringsPHPEnabled(boolean enabled) {
995 fCloseStringsPHP = enabled;
998 public void setCloseBracketsHTMLEnabled(boolean enabled) {
999 fCloseBracketsHTML = enabled;
1002 public void setCloseStringsHTMLEnabled(boolean enabled) {
1003 fCloseStringsHTML = enabled;
1006 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
1009 IRegion endLine = document.getLineInformationOfOffset(end);
1010 int maxEnd = endLine.getOffset() + endLine.getLength();
1011 while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
1013 return end != maxEnd
1014 && Scanner.isPHPIdentifierPart(document.getChar(end));
1015 } catch (BadLocationException e) {
1021 private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1024 IRegion startLine = document.getLineInformationOfOffset(start);
1025 int minStart = startLine.getOffset();
1026 while (start != minStart
1027 && Character.isWhitespace(document.getChar(start - 1)))
1029 return start != minStart
1030 && Scanner.isPHPIdentifierPart(document.getChar(start - 1));
1031 } catch (BadLocationException e) {
1036 private boolean hasCharacterToTheRight(IDocument document, int offset,
1040 IRegion endLine = document.getLineInformationOfOffset(end);
1041 int maxEnd = endLine.getOffset() + endLine.getLength();
1042 while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
1044 return end != maxEnd && document.getChar(end) == character;
1045 } catch (BadLocationException e) {
1052 * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1054 public void verifyKey(VerifyEvent event) {
1057 final ISourceViewer sourceViewer = getSourceViewer();
1058 IDocument document = sourceViewer.getDocument();
1059 final Point selection = sourceViewer.getSelectedRange();
1060 final int offset = selection.x;
1061 final int length = selection.y;
1063 ITypedRegion partition = document.getPartition(offset);
1064 String type = partition.getType();
1065 if (type.equals(IPHPPartitions.PHP_PARTITIONING)) {
1066 switch (event.character) {
1068 if (hasCharacterToTheRight(document, offset + length, '('))
1072 if (!fCloseBracketsPHP)
1074 if (hasIdentifierToTheRight(document, offset + length))
1078 if (event.character == '"') {
1079 if (!fCloseStringsPHP)
1081 // changed for statements like echo "" print ""
1082 // if (hasIdentifierToTheLeft(document, offset)
1084 // hasIdentifierToTheRight(document, offset +
1086 if (hasIdentifierToTheRight(document, offset + length))
1089 // ITypedRegion partition=
1090 // document.getPartition(offset);
1092 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1094 // (partition.getOffset() != offset))
1096 final char character = event.character;
1097 final char closingCharacter = getPeerCharacter(character);
1098 final StringBuffer buffer = new StringBuffer();
1099 buffer.append(character);
1100 buffer.append(closingCharacter);
1101 document.replace(offset, length, buffer.toString());
1102 LinkedPositionManager manager = new LinkedPositionManager(document);
1103 manager.addPosition(offset + 1, 0);
1106 LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
1108 editor.setCancelListener(this);
1109 editor.setExitPolicy(new ExitPolicy(closingCharacter));
1110 editor.setFinalCaretOffset(offset + 2);
1112 IRegion newSelection = editor.getSelectedRegion();
1113 sourceViewer.setSelectedRange(newSelection.getOffset(),
1114 newSelection.getLength());
1117 } else if (type.equals(IPHPPartitions.HTML)
1118 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1119 switch (event.character) {
1121 if (hasCharacterToTheRight(document, offset + length, '('))
1125 if (!fCloseBracketsHTML)
1127 if (hasIdentifierToTheRight(document, offset + length))
1131 if (event.character == '"') {
1132 if (!fCloseStringsHTML)
1134 if (hasIdentifierToTheLeft(document, offset)
1135 || hasIdentifierToTheRight(document, offset + length))
1138 // ITypedRegion partition=
1139 // document.getPartition(offset);
1141 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1143 // (partition.getOffset() != offset))
1145 final char character = event.character;
1146 final char closingCharacter = getPeerCharacter(character);
1147 final StringBuffer buffer = new StringBuffer();
1148 buffer.append(character);
1149 buffer.append(closingCharacter);
1150 document.replace(offset, length, buffer.toString());
1151 LinkedPositionManager manager = new LinkedPositionManager(document);
1152 manager.addPosition(offset + 1, 0);
1155 LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
1157 editor.setCancelListener(this);
1158 editor.setExitPolicy(new ExitPolicy(closingCharacter));
1159 editor.setFinalCaretOffset(offset + 2);
1161 IRegion newSelection = editor.getSelectedRegion();
1162 sourceViewer.setSelectedRange(newSelection.getOffset(),
1163 newSelection.getLength());
1167 } catch (BadLocationException e) {
1172 * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1174 public void exit(boolean accept) {
1179 final ISourceViewer sourceViewer = getSourceViewer();
1180 IDocument document = sourceViewer.getDocument();
1181 document.replace(fOffset, fLength, null);
1182 } catch (BadLocationException e) {
1187 /** The editor's save policy */
1188 protected ISavePolicy fSavePolicy;
1191 * Listener to annotation model changes that updates the error tick in the tab
1194 private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1196 /** The editor's paint manager */
1197 // private PaintManager fPaintManager;
1198 /** The editor's bracket painter */
1199 private BracketPainter fBracketPainter;
1201 /** The editor's bracket matcher */
1202 private PHPPairMatcher fBracketMatcher;
1204 /** The editor's line painter */
1205 private LinePainter fLinePainter;
1207 /** The editor's print margin ruler painter */
1208 private PrintMarginPainter fPrintMarginPainter;
1210 /** The editor's problem painter */
1211 // private ProblemPainter fProblemPainter;
1212 /** The editor's tab converter */
1213 private TabConverter fTabConverter;
1215 /** History for structure select action */
1216 //private SelectionHistory fSelectionHistory;
1217 /** The preference property change listener for php core. */
1218 // private IPropertyChangeListener fPropertyChangeListener = new
1219 // PropertyChangeListener();
1220 /** The remembered java element */
1221 private IJavaElement fRememberedElement;
1224 * The remembered selection.
1227 private RememberedSelection fRememberedSelection= new RememberedSelection();
1230 /** The remembered php element offset */
1231 private int fRememberedElementOffset;
1233 /** The bracket inserter. */
1234 private BracketInserter fBracketInserter = new BracketInserter();
1236 /** The standard action groups added to the menu */
1237 private GenerateActionGroup fGenerateActionGroup;
1239 private CompositeActionGroup fContextMenuGroup;
1241 // private class PropertyChangeListener implements IPropertyChangeListener {
1243 // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1246 // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1248 // handlePreferencePropertyChanged(event);
1251 /* Preference key for code formatter tab size */
1252 private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1254 /** Preference key for matching brackets */
1255 private final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1257 /** Preference key for matching brackets color */
1258 private final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1260 /** Preference key for highlighting current line */
1261 private final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
1263 /** Preference key for highlight color of current line */
1264 private final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1266 /** Preference key for showing print marging ruler */
1267 private final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
1269 /** Preference key for print margin ruler color */
1270 private final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1272 /** Preference key for print margin ruler column */
1273 private final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1275 /** Preference key for inserting spaces rather than tabs */
1276 private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1278 /** Preference key for error indication */
1279 // private final static String ERROR_INDICATION =
1280 // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1281 /** Preference key for error color */
1282 // private final static String ERROR_INDICATION_COLOR =
1283 // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1284 /** Preference key for warning indication */
1285 // private final static String WARNING_INDICATION =
1286 // PreferenceConstants.EDITOR_WARNING_INDICATION;
1287 /** Preference key for warning color */
1288 // private final static String WARNING_INDICATION_COLOR =
1289 // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1290 /** Preference key for task indication */
1291 private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1293 /** Preference key for task color */
1294 private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1296 /** Preference key for bookmark indication */
1297 private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1299 /** Preference key for bookmark color */
1300 private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1302 /** Preference key for search result indication */
1303 private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1305 /** Preference key for search result color */
1306 private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1308 /** Preference key for unknown annotation indication */
1309 private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1311 /** Preference key for unknown annotation color */
1312 private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1314 /** Preference key for linked position color */
1315 private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1317 /** Preference key for shwoing the overview ruler */
1318 private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1320 /** Preference key for error indication in overview ruler */
1321 private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1323 /** Preference key for warning indication in overview ruler */
1324 private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1326 /** Preference key for task indication in overview ruler */
1327 private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1329 /** Preference key for bookmark indication in overview ruler */
1330 private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1332 /** Preference key for search result indication in overview ruler */
1333 private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1335 /** Preference key for unknown annotation indication in overview ruler */
1336 private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1338 /** Preference key for automatically closing strings */
1339 private final static String CLOSE_STRINGS_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP;
1341 /** Preference key for automatically wrapping Java strings */
1342 private final static String WRAP_STRINGS = PreferenceConstants.EDITOR_WRAP_STRINGS;
1344 /** Preference key for automatically closing brackets and parenthesis */
1345 private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1347 /** Preference key for automatically closing phpdocs and comments */
1348 private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1350 /** Preference key for automatically adding phpdoc tags */
1351 private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1353 /** Preference key for automatically formatting phpdocs */
1354 private final static String FORMAT_JAVADOCS = PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1356 /** Preference key for automatically closing strings */
1357 private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1359 /** Preference key for automatically closing brackets and parenthesis */
1360 private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1362 /** Preference key for smart paste */
1363 private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1365 // private final static class AnnotationInfo {
1366 // public String fColorPreference;
1367 // public String fOverviewRulerPreference;
1368 // public String fEditorPreference;
1370 // private final static Map ANNOTATION_MAP;
1373 // AnnotationInfo info;
1374 // ANNOTATION_MAP = new HashMap();
1376 // info = new AnnotationInfo();
1377 // info.fColorPreference = TASK_INDICATION_COLOR;
1378 // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1379 // info.fEditorPreference = TASK_INDICATION;
1380 // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1382 // info = new AnnotationInfo();
1383 // info.fColorPreference = ERROR_INDICATION_COLOR;
1384 // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1385 // info.fEditorPreference = ERROR_INDICATION;
1386 // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1388 // info = new AnnotationInfo();
1389 // info.fColorPreference = WARNING_INDICATION_COLOR;
1390 // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1391 // info.fEditorPreference = WARNING_INDICATION;
1392 // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1394 // info = new AnnotationInfo();
1395 // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1396 // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1397 // info.fEditorPreference = BOOKMARK_INDICATION;
1398 // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1400 // info = new AnnotationInfo();
1401 // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1402 // info.fOverviewRulerPreference =
1403 // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1404 // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1405 // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1407 // info = new AnnotationInfo();
1408 // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1409 // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1410 // info.fEditorPreference = UNKNOWN_INDICATION;
1411 // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1414 // private final static AnnotationType[] ANNOTATION_LAYERS =
1415 // new AnnotationType[] {
1416 // AnnotationType.UNKNOWN,
1417 // AnnotationType.BOOKMARK,
1418 // AnnotationType.TASK,
1419 // AnnotationType.SEARCH,
1420 // AnnotationType.WARNING,
1421 // AnnotationType.ERROR };
1423 * Creates a new php unit editor.
1427 * Reconciling listeners.
1430 private ListenerList fReconcilingListeners= new ListenerList();
1433 * Mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898
1434 * for a description of the problem.
1436 * TODO remove once the underlying problem is solved.
1439 private final Object fReconcilerLock= new Object();
1441 public PHPUnitEditor() {
1443 setDocumentProvider(PHPeclipsePlugin.getDefault()
1444 .getCompilationUnitDocumentProvider());
1445 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1446 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1447 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1448 // don't set help contextId, we install our own help context
1450 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1454 * @see AbstractTextEditor#createActions()
1456 protected void createActions() {
1457 super.createActions();
1459 // Action action= new
1460 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1461 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1463 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1464 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1465 // markAsStateDependentAction("CorrectionAssistProposal", true);
1467 //// WorkbenchHelp.setHelp(action,
1468 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1469 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1470 "ContentAssistProposal.", this); //$NON-NLS-1$
1472 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1473 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1474 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1475 // WorkbenchHelp.setHelp(action,
1476 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1477 // action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1478 // "ContentAssistContextInformation.", this,
1479 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1481 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1482 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1483 // markAsStateDependentAction("ContentAssistContextInformation", true);
1485 // WorkbenchHelp.setHelp(action,
1486 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1488 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1489 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1491 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1492 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1493 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1495 //// WorkbenchHelp.setHelp(action,
1496 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1497 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1498 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1499 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1500 setAction("Comment", action); //$NON-NLS-1$
1501 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1502 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1503 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1504 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1505 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1506 setAction("Uncomment", action); //$NON-NLS-1$
1507 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1508 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1510 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1511 "ToggleComment.", this); //$NON-NLS-1$
1512 action.setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1513 setAction("ToggleComment", action); //$NON-NLS-1$
1514 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1515 //WorkbenchHelp.setHelp(action,
1516 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1517 configureToggleCommentAction();
1519 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1520 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1521 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1522 setAction("Format", action); //$NON-NLS-1$
1523 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1524 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1525 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1527 // action = new AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1528 // "AddBlockComment.", this); //$NON-NLS-1$
1530 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1531 // setAction("AddBlockComment", action); //$NON-NLS-1$
1532 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1533 // markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1534 // // WorkbenchHelp.setHelp(action,
1535 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1536 // action = new RemoveBlockCommentAction(
1537 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1539 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1540 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1541 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1542 // markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1543 // WorkbenchHelp.setHelp(action,
1544 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1545 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1546 // "Indent.", this, false); //$NON-NLS-1$
1547 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1548 // setAction("Indent", action); //$NON-NLS-1$
1549 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1550 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1551 //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1553 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1554 // "Indent.", this, true); //$NON-NLS-1$
1555 // setAction("IndentOnTab", action); //$NON-NLS-1$
1556 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1557 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1559 if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
1560 // don't replace Shift Right - have to make sure their enablement is
1561 // mutually exclusive
1562 // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1563 setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1565 fGenerateActionGroup = new GenerateActionGroup(this,
1566 ITextEditorActionConstants.GROUP_EDIT);
1567 fActionGroups = new CompositeActionGroup(
1568 new ActionGroup[] { fGenerateActionGroup });
1569 // We have to keep the context menu group separate to have better
1572 fContextMenuGroup = new CompositeActionGroup(
1573 new ActionGroup[] { fGenerateActionGroup });
1575 // new LocalHistoryActionGroup(this,
1576 // ITextEditorActionConstants.GROUP_EDIT)});
1581 * @see JavaEditor#getElementAt(int)
1583 protected IJavaElement getElementAt(int offset) {
1584 return getElementAt(offset, true);
1588 * Returns the most narrow element including the given offset. If
1589 * <code>reconcile</code> is <code>true</code> the editor's input element
1590 * is reconciled in advance. If it is <code>false</code> this method only
1591 * returns a result if the editor's input element does not need to be
1595 * the offset included by the retrieved element
1597 * <code>true</code> if working copy should be reconciled
1599 protected IJavaElement getElementAt(int offset, boolean reconcile) {
1600 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1601 .getWorkingCopyManager();
1602 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1606 synchronized (unit) {
1609 return unit.getElementAt(offset);
1610 } else if (unit.isConsistent())
1611 return unit.getElementAt(offset);
1612 } catch (JavaModelException x) {
1613 PHPeclipsePlugin.log(x.getStatus());
1614 // nothing found, be tolerant and go on
1621 * @see JavaEditor#getCorrespondingElement(IJavaElement)
1623 protected IJavaElement getCorrespondingElement(IJavaElement element) {
1625 return EditorUtility.getWorkingCopy(element, true);
1626 } catch (JavaModelException x) {
1627 PHPeclipsePlugin.log(x.getStatus());
1628 // nothing found, be tolerant and go on
1633 public void createPartControl(Composite parent) {
1634 super.createPartControl(parent);
1635 // fPaintManager = new PaintManager(getSourceViewer());
1636 LinePainter linePainter;
1637 linePainter = new LinePainter(getSourceViewer());
1639 .setHighlightColor(new Color(Display.getCurrent(), 225, 235, 224));
1640 // fPaintManager.addPainter(linePainter);
1641 if (isBracketHighlightingEnabled())
1642 startBracketHighlighting();
1643 if (isLineHighlightingEnabled())
1644 startLineHighlighting();
1645 if (isPrintMarginVisible())
1647 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1648 // while (e.hasNext()) {
1649 // AnnotationType type = (AnnotationType) e.next();
1650 // if (isAnnotationIndicationEnabled(type))
1651 // startAnnotationIndication(type);
1653 if (isTabConversionEnabled())
1654 startTabConversion();
1655 // if (isOverviewRulerVisible())
1656 // showOverviewRuler();
1658 // Preferences preferences =
1659 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1660 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1661 IPreferenceStore preferenceStore = getPreferenceStore();
1662 boolean closeBracketsPHP = preferenceStore.getBoolean(CLOSE_BRACKETS_PHP);
1663 boolean closeStringsPHP = preferenceStore.getBoolean(CLOSE_STRINGS_PHP);
1664 boolean closeBracketsHTML = preferenceStore.getBoolean(CLOSE_BRACKETS_HTML);
1665 boolean closeStringsHTML = preferenceStore.getBoolean(CLOSE_STRINGS_HTML);
1666 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1667 fBracketInserter.setCloseStringsPHPEnabled(closeStringsPHP);
1668 fBracketInserter.setCloseBracketsHTMLEnabled(closeBracketsHTML);
1669 fBracketInserter.setCloseStringsHTMLEnabled(closeStringsHTML);
1670 ISourceViewer sourceViewer = getSourceViewer();
1671 if (sourceViewer instanceof ITextViewerExtension)
1672 ((ITextViewerExtension) sourceViewer)
1673 .prependVerifyKeyListener(fBracketInserter);
1676 private static char getPeerCharacter(char character) {
1677 switch (character) {
1689 throw new IllegalArgumentException();
1693 private void startBracketHighlighting() {
1694 if (fBracketPainter == null) {
1695 ISourceViewer sourceViewer = getSourceViewer();
1696 fBracketPainter = new BracketPainter(sourceViewer);
1697 fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1698 // fPaintManager.addPainter(fBracketPainter);
1702 private void stopBracketHighlighting() {
1703 if (fBracketPainter != null) {
1704 // fPaintManager.removePainter(fBracketPainter);
1705 fBracketPainter.deactivate(true);
1706 fBracketPainter.dispose();
1707 fBracketPainter = null;
1711 private boolean isBracketHighlightingEnabled() {
1712 IPreferenceStore store = getPreferenceStore();
1713 return store.getBoolean(MATCHING_BRACKETS);
1716 private void startLineHighlighting() {
1717 if (fLinePainter == null) {
1718 ISourceViewer sourceViewer = getSourceViewer();
1719 fLinePainter = new LinePainter(sourceViewer);
1720 fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1721 // fPaintManager.addPainter(fLinePainter);
1725 private void stopLineHighlighting() {
1726 if (fLinePainter != null) {
1727 // fPaintManager.removePainter(fLinePainter);
1728 fLinePainter.deactivate(true);
1729 fLinePainter.dispose();
1730 fLinePainter = null;
1734 private boolean isLineHighlightingEnabled() {
1735 IPreferenceStore store = getPreferenceStore();
1736 return store.getBoolean(CURRENT_LINE);
1739 private void showPrintMargin() {
1740 if (fPrintMarginPainter == null) {
1741 fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1742 fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1743 fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(
1744 PRINT_MARGIN_COLUMN));
1745 // fPaintManager.addPainter(fPrintMarginPainter);
1749 private void hidePrintMargin() {
1750 if (fPrintMarginPainter != null) {
1751 // fPaintManager.removePainter(fPrintMarginPainter);
1752 fPrintMarginPainter.deactivate(true);
1753 fPrintMarginPainter.dispose();
1754 fPrintMarginPainter = null;
1758 private boolean isPrintMarginVisible() {
1759 IPreferenceStore store = getPreferenceStore();
1760 return store.getBoolean(PRINT_MARGIN);
1763 // private void startAnnotationIndication(AnnotationType annotationType) {
1764 // if (fProblemPainter == null) {
1765 // fProblemPainter = new ProblemPainter(this, getSourceViewer());
1766 //// fPaintManager.addPainter(fProblemPainter);
1768 // fProblemPainter.setColor(annotationType, getColor(annotationType));
1769 // fProblemPainter.paintAnnotations(annotationType, true);
1770 // fProblemPainter.paint(IPainter.CONFIGURATION);
1773 // private void shutdownAnnotationIndication() {
1774 // if (fProblemPainter != null) {
1776 // if (!fProblemPainter.isPaintingAnnotations()) {
1777 //// fPaintManager.removePainter(fProblemPainter);
1778 // fProblemPainter.deactivate(true);
1779 // fProblemPainter.dispose();
1780 // fProblemPainter = null;
1782 // fProblemPainter.paint(IPainter.CONFIGURATION);
1787 // private void stopAnnotationIndication(AnnotationType annotationType) {
1788 // if (fProblemPainter != null) {
1789 // fProblemPainter.paintAnnotations(annotationType, false);
1790 // shutdownAnnotationIndication();
1794 // private boolean isAnnotationIndicationEnabled(AnnotationType
1795 // annotationType) {
1796 // IPreferenceStore store = getPreferenceStore();
1797 // AnnotationInfo info = (AnnotationInfo)
1798 // ANNOTATION_MAP.get(annotationType);
1799 // if (info != null)
1800 // return store.getBoolean(info.fEditorPreference);
1805 // isAnnotationIndicationInOverviewRulerEnabled(AnnotationType
1806 // annotationType) {
1807 // IPreferenceStore store = getPreferenceStore();
1808 // AnnotationInfo info = (AnnotationInfo)
1809 // ANNOTATION_MAP.get(annotationType);
1810 // if (info != null)
1811 // return store.getBoolean(info.fOverviewRulerPreference);
1815 // private void showAnnotationIndicationInOverviewRuler(AnnotationType
1816 // annotationType, boolean show) {
1817 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1818 // OverviewRuler ruler = asv.getOverviewRuler();
1819 // if (ruler != null) {
1820 // ruler.setColor(annotationType, getColor(annotationType));
1821 // ruler.showAnnotation(annotationType, show);
1826 // private void setColorInOverviewRuler(AnnotationType annotationType, Color
1828 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1829 // OverviewRuler ruler = asv.getOverviewRuler();
1830 // if (ruler != null) {
1831 // ruler.setColor(annotationType, color);
1836 private int getTabSize() {
1837 Preferences preferences = PHPeclipsePlugin.getDefault()
1838 .getPluginPreferences();
1839 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1842 private boolean isTabConversionEnabled() {
1843 IPreferenceStore store = getPreferenceStore();
1844 return store.getBoolean(SPACES_FOR_TABS);
1847 // private void showOverviewRuler() {
1848 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1849 // asv.showOverviewRuler();
1851 // OverviewRuler overviewRuler = asv.getOverviewRuler();
1852 // if (overviewRuler != null) {
1853 // for (int i = 0; i < ANNOTATION_LAYERS.length; i++) {
1854 // AnnotationType type = ANNOTATION_LAYERS[i];
1855 // overviewRuler.setLayer(type, i);
1856 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
1857 // showAnnotationIndicationInOverviewRuler(type, true);
1862 // private void hideOverviewRuler() {
1863 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1864 // asv.hideOverviewRuler();
1867 // private boolean isOverviewRulerVisible() {
1868 // IPreferenceStore store = getPreferenceStore();
1869 // return store.getBoolean(OVERVIEW_RULER);
1871 private Color getColor(String key) {
1872 RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1873 return getColor(rgb);
1876 private Color getColor(RGB rgb) {
1877 JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1878 return textTools.getColorManager().getColor(rgb);
1881 // private Color getColor(AnnotationType annotationType) {
1882 // AnnotationInfo info = (AnnotationInfo)
1883 // ANNOTATION_MAP.get(annotationType);
1884 // if (info != null)
1885 // return getColor(info.fColorPreference);
1888 public void dispose() {
1889 ISourceViewer sourceViewer = getSourceViewer();
1890 if (sourceViewer instanceof ITextViewerExtension)
1891 ((ITextViewerExtension) sourceViewer)
1892 .removeVerifyKeyListener(fBracketInserter);
1893 // if (fPropertyChangeListener != null) {
1894 // Preferences preferences =
1895 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1896 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1897 // fPropertyChangeListener = null;
1899 if (fJavaEditorErrorTickUpdater != null) {
1900 fJavaEditorErrorTickUpdater.dispose();
1901 fJavaEditorErrorTickUpdater = null;
1903 // if (fSelectionHistory != null)
1904 // fSelectionHistory.dispose();
1905 // if (fPaintManager != null) {
1906 // fPaintManager.dispose();
1907 // fPaintManager = null;
1909 if (fActionGroups != null) {
1910 fActionGroups.dispose();
1911 fActionGroups = null;
1916 // protected AnnotationType getAnnotationType(String preferenceKey) {
1917 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1918 // while (e.hasNext()) {
1919 // AnnotationType type = (AnnotationType) e.next();
1920 // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1921 // if (info != null) {
1922 // if (preferenceKey.equals(info.fColorPreference)
1923 // || preferenceKey.equals(info.fEditorPreference)
1924 // || preferenceKey.equals(info.fOverviewRulerPreference))
1931 * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1933 protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1935 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1937 String p = event.getProperty();
1938 if (CLOSE_BRACKETS_PHP.equals(p)) {
1939 fBracketInserter.setCloseBracketsPHPEnabled(getPreferenceStore()
1943 if (CLOSE_STRINGS_PHP.equals(p)) {
1944 fBracketInserter.setCloseStringsPHPEnabled(getPreferenceStore()
1948 if (CLOSE_BRACKETS_HTML.equals(p)) {
1949 fBracketInserter.setCloseBracketsHTMLEnabled(getPreferenceStore()
1953 if (CLOSE_STRINGS_HTML.equals(p)) {
1954 fBracketInserter.setCloseStringsHTMLEnabled(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)
1975 .setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1978 if (CURRENT_LINE.equals(p)) {
1979 if (isLineHighlightingEnabled())
1980 startLineHighlighting();
1982 stopLineHighlighting();
1985 if (CURRENT_LINE_COLOR.equals(p)) {
1986 if (fLinePainter != null) {
1987 stopLineHighlighting();
1988 startLineHighlighting();
1992 if (PRINT_MARGIN.equals(p)) {
1993 if (isPrintMarginVisible())
1999 if (PRINT_MARGIN_COLOR.equals(p)) {
2000 if (fPrintMarginPainter != null)
2002 .setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2005 if (PRINT_MARGIN_COLUMN.equals(p)) {
2006 if (fPrintMarginPainter != null)
2007 fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore()
2008 .getInt(PRINT_MARGIN_COLUMN));
2011 // if (OVERVIEW_RULER.equals(p)) {
2012 // if (isOverviewRulerVisible())
2013 // showOverviewRuler();
2015 // hideOverviewRuler();
2018 // AnnotationType type = getAnnotationType(p);
2019 // if (type != null) {
2021 // AnnotationInfo info = (AnnotationInfo)
2022 // ANNOTATION_MAP.get(type);
2023 // if (info.fColorPreference.equals(p)) {
2024 // Color color = getColor(type);
2025 // if (fProblemPainter != null) {
2026 // fProblemPainter.setColor(type, color);
2027 // fProblemPainter.paint(IPainter.CONFIGURATION);
2029 // setColorInOverviewRuler(type, color);
2033 // if (info.fEditorPreference.equals(p)) {
2034 // if (isAnnotationIndicationEnabled(type))
2035 // startAnnotationIndication(type);
2037 // stopAnnotationIndication(type);
2041 // if (info.fOverviewRulerPreference.equals(p)) {
2042 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2043 // showAnnotationIndicationInOverviewRuler(type, true);
2045 // showAnnotationIndicationInOverviewRuler(type, false);
2049 IContentAssistant c = asv.getContentAssistant();
2050 if (c instanceof ContentAssistant)
2051 ContentAssistPreference.changeConfiguration((ContentAssistant) c,
2052 getPreferenceStore(), event);
2055 super.handlePreferenceStoreChanged(event);
2060 * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2062 protected void handlePreferencePropertyChanged(
2063 org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2064 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2066 String p = event.getProperty();
2067 if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2068 asv.updateIndentationPrefixes();
2069 if (fTabConverter != null)
2070 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2073 super.handlePreferencePropertyChanged(event);
2077 * Handles a property change event describing a change of the php core's
2078 * preferences and updates the preference related editor properties.
2081 * the property change event
2084 // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2086 // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2087 // if (asv != null) {
2088 // String p = event.getProperty();
2089 // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2090 // asv.updateIndentationPrefixes();
2091 // if (fTabConverter != null)
2092 // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2097 * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2098 * org.eclipse.jface.text.source.IVerticalRuler,
2099 * org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2101 protected ISourceViewer createJavaSourceViewer(Composite parent,
2102 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2103 boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2104 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2105 isOverviewRulerVisible, styles, store);
2108 // protected ISourceViewer createJavaSourceViewer(Composite parent,
2109 // IVerticalRuler ruler, int styles) {
2110 // return new AdaptedSourceViewer(parent, ruler, styles);
2112 private boolean isValidSelection(int offset, int length) {
2113 IDocumentProvider provider = getDocumentProvider();
2114 if (provider != null) {
2115 IDocument document = provider.getDocument(getEditorInput());
2116 if (document != null) {
2117 int end = offset + length;
2118 int documentLength = document.getLength();
2119 return 0 <= offset && offset <= documentLength && 0 <= end
2120 && end <= documentLength;
2127 * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2129 protected IJavaElement getInputJavaElement() {
2130 return PHPeclipsePlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput());
2133 * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2135 public void editorContextMenuAboutToShow(IMenuManager menu) {
2136 super.editorContextMenuAboutToShow(menu);
2137 ActionContext context = new ActionContext(getSelectionProvider()
2139 fContextMenuGroup.setContext(context);
2140 fContextMenuGroup.fillContextMenu(menu);
2141 fContextMenuGroup.setContext(null);
2145 * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2147 protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2149 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2150 .getWorkingCopyManager();
2151 page.setInput(manager.getWorkingCopy(input));
2157 * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2160 // protected void performSaveOperation(WorkspaceModifyOperation operation,
2161 // IProgressMonitor progressMonitor) {
2162 // IDocumentProvider p = getDocumentProvider();
2163 // if (p instanceof PHPDocumentProvider) {
2164 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2165 // cp.setSavePolicy(fSavePolicy);
2169 // super.performSaveOperation(operation, progressMonitor);
2171 // if (p instanceof PHPDocumentProvider) {
2172 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2173 // cp.setSavePolicy(null);
2178 * @see AbstractTextEditor#doSave(IProgressMonitor)
2180 public void doSave(IProgressMonitor progressMonitor) {
2182 IDocumentProvider p = getDocumentProvider();
2184 // editor has been closed
2188 if (p.isDeleted(getEditorInput())) {
2190 if (isSaveAsAllowed()) {
2193 * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the
2194 * editors. Changed Behavior to make sure that if called inside a
2195 * regular save (because of deletion of input element) there is a way to
2196 * report back to the caller.
2198 performSaveAs(progressMonitor);
2203 * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
2204 * Missing resources.
2206 Shell shell = getSite().getShell();
2211 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2216 setStatusLineErrorMessage(null);
2218 updateState(getEditorInput());
2219 validateState(getEditorInput());
2221 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2222 .getWorkingCopyManager();
2223 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2226 synchronized (unit) {
2227 performSave(false, progressMonitor);
2230 performSave(false, progressMonitor);
2232 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2238 public boolean isSaveAsAllowed() {
2243 * The compilation unit editor implementation of this
2244 * <code>AbstractTextEditor</code> method asks the user for the workspace
2245 * path of a file resource and saves the document there. See
2246 * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2248 * @param progressMonitor
2249 * the progress monitor
2251 protected void performSaveAs(IProgressMonitor progressMonitor) {
2253 Shell shell = getSite().getShell();
2254 IEditorInput input = getEditorInput();
2256 SaveAsDialog dialog = new SaveAsDialog(shell);
2258 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2261 if (original != null)
2262 dialog.setOriginalFile(original);
2266 IDocumentProvider provider = getDocumentProvider();
2267 if (provider == null) {
2268 // editor has been programmatically closed while the dialog was open
2272 if (provider.isDeleted(input) && original != null) {
2273 String message = PHPEditorMessages
2274 .getFormattedString(
2275 "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2276 dialog.setErrorMessage(null);
2277 dialog.setMessage(message, IMessageProvider.WARNING);
2280 if (dialog.open() == Window.CANCEL) {
2281 if (progressMonitor != null)
2282 progressMonitor.setCanceled(true);
2286 IPath filePath = dialog.getResult();
2287 if (filePath == null) {
2288 if (progressMonitor != null)
2289 progressMonitor.setCanceled(true);
2293 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2294 IFile file = workspaceRoot.getFile(filePath);
2295 final IEditorInput newInput = new FileEditorInput(file);
2297 boolean success = false;
2300 provider.aboutToChange(newInput);
2301 getDocumentProvider().saveDocument(progressMonitor, newInput,
2302 getDocumentProvider().getDocument(getEditorInput()), true);
2305 } catch (CoreException x) {
2306 IStatus status = x.getStatus();
2307 if (status == null || status.getSeverity() != IStatus.CANCEL)
2312 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2314 provider.changed(newInput);
2319 if (progressMonitor != null)
2320 progressMonitor.setCanceled(!success);
2324 * @see AbstractTextEditor#doSetInput(IEditorInput)
2326 protected void doSetInput(IEditorInput input) throws CoreException {
2327 super.doSetInput(input);
2328 configureTabConverter();
2329 configureToggleCommentAction();
2334 // org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2337 // protected void installOverrideIndicator(boolean waitForReconcilation) {
2338 // IAnnotationModel model=
2339 // getDocumentProvider().getAnnotationModel(getEditorInput());
2340 // if (!waitForReconcilation)
2341 // super.installOverrideIndicator(false);
2343 // uninstallOverrideIndicator();
2344 // IJavaElement inputElement= getInputJavaElement();
2345 // if (model == null || inputElement == null)
2348 // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2349 // inputElement, null);
2350 // addReconcileListener(fOverrideIndicatorManager);
2356 // org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2359 // protected void uninstallOverrideIndicator() {
2360 // if (fOverrideIndicatorManager != null)
2361 // removeReconcileListener(fOverrideIndicatorManager);
2362 // super.uninstallOverrideIndicator();
2366 * Configures the toggle comment action
2370 private void configureToggleCommentAction() {
2371 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2372 if (action instanceof ToggleCommentAction) {
2373 ISourceViewer sourceViewer = getSourceViewer();
2374 SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2375 ((ToggleCommentAction) action).configure(sourceViewer, configuration);
2379 private void configureTabConverter() {
2380 if (fTabConverter != null) {
2381 IDocumentProvider provider = getDocumentProvider();
2382 if (provider instanceof PHPDocumentProvider) {
2383 PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2384 fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2389 private void startTabConversion() {
2390 if (fTabConverter == null) {
2391 fTabConverter = new TabConverter();
2392 configureTabConverter();
2393 fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2394 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2395 asv.addTextConverter(fTabConverter);
2396 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2397 asv.updateIndentationPrefixes();
2401 private void stopTabConversion() {
2402 if (fTabConverter != null) {
2403 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2404 asv.removeTextConverter(fTabConverter);
2405 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2406 asv.updateIndentationPrefixes();
2407 fTabConverter = null;
2412 * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2413 * org.eclipse.core.runtime.IProgressMonitor)
2415 protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
2416 IDocumentProvider p = getDocumentProvider();
2417 if (p instanceof PHPDocumentProvider) {
2418 PHPDocumentProvider cp = (PHPDocumentProvider) p;
2419 cp.setSavePolicy(fSavePolicy);
2422 super.performSave(overwrite, progressMonitor);
2424 if (p instanceof PHPDocumentProvider) {
2425 PHPDocumentProvider cp = (PHPDocumentProvider) p;
2426 cp.setSavePolicy(null);
2432 * @see AbstractTextEditor#doSaveAs
2434 public void doSaveAs() {
2435 if (askIfNonWorkbenchEncodingIsOk()) {
2441 * Asks the user if it is ok to store in non-workbench encoding.
2443 * @return <true>if the user wants to continue
2445 private boolean askIfNonWorkbenchEncodingIsOk() {
2446 IDocumentProvider provider = getDocumentProvider();
2447 if (provider instanceof IStorageDocumentProvider) {
2448 IEditorInput input = getEditorInput();
2449 IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2450 String encoding = storageProvider.getEncoding(input);
2451 String defaultEncoding = storageProvider.getDefaultEncoding();
2452 if (encoding != null && !encoding.equals(defaultEncoding)) {
2453 Shell shell = getSite().getShell();
2454 String title = PHPEditorMessages
2455 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2461 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2462 new String[] { input.getName(), encoding }); //$NON-NLS-1$
2467 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2468 new String[] { encoding }); //$NON-NLS-1$
2469 return MessageDialog.openQuestion(shell, title, msg);
2476 * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2479 public void aboutToBeReconciled() {
2481 // Notify AST provider
2482 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2485 Object[] listeners = fReconcilingListeners.getListeners();
2486 for (int i = 0, length= listeners.length; i < length; ++i)
2487 ((IJavaReconcilingListener)listeners[i]).aboutToBeReconciled();
2491 * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor)
2494 public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) {
2496 // Always notify AST provider
2497 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast, getInputJavaElement());
2500 // Object[] listeners = fReconcilingListeners.getListeners();
2501 // for (int i = 0, length= listeners.length; i < length; ++i)
2502 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, progressMonitor);
2504 // Update Java Outline page selection
2505 if (!forced && !progressMonitor.isCanceled()) {
2506 Shell shell= getSite().getShell();
2507 if (shell != null && !shell.isDisposed()) {
2508 shell.getDisplay().asyncExec(new Runnable() {
2517 private boolean synchronizeOutlineOnCursorMove() {
2518 return PreferenceConstants.getPreferenceStore().getBoolean(
2519 PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
2523 * Returns the updated java element for the old java element.
2525 private IJavaElement findElement(IJavaElement element) {
2526 if (element == null)
2528 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2529 .getWorkingCopyManager();
2530 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2533 synchronized (unit) {
2536 IJavaElement[] findings = unit.findElements(element);
2537 if (findings != null && findings.length > 0)
2539 } catch (JavaModelException x) {
2540 PHPeclipsePlugin.log(x.getStatus());
2541 // nothing found, be tolerant and go on
2548 * Returns the offset of the given Java element.
2550 private int getOffset(IJavaElement element) {
2551 if (element instanceof ISourceReference) {
2552 ISourceReference sr = (ISourceReference) element;
2554 ISourceRange srcRange = sr.getSourceRange();
2555 if (srcRange != null)
2556 return srcRange.getOffset();
2557 } catch (JavaModelException e) {
2566 * @see AbstractTextEditor#restoreSelection()
2568 // protected void restoreSelection() {
2570 // if (getSourceViewer() == null || fRememberedSelection == null)
2572 // IJavaElement newElement = findElement(fRememberedElement);
2573 // int newOffset = getOffset(newElement);
2574 // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2575 // - fRememberedElementOffset : 0;
2576 // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2577 // fRememberedSelection.getLength()))
2578 // selectAndReveal(delta + fRememberedSelection.getOffset(),
2579 // fRememberedSelection.getLength());
2581 // fRememberedSelection = null;
2582 // fRememberedElement = null;
2583 // fRememberedElementOffset = -1;
2588 * Tells whether this is the active editor in the active page.
2590 * @return <code>true</code> if this is the active editor in the active page
2591 * @see IWorkbenchPage#getActiveEditor();
2593 protected final boolean isActiveEditor() {
2594 IWorkbenchWindow window= getSite().getWorkbenchWindow();
2595 IWorkbenchPage page= window.getActivePage();
2598 IEditorPart activeEditor= page.getActiveEditor();
2599 return activeEditor != null && activeEditor.equals(this);
2603 * Adds the given listener.
2604 * Has no effect if an identical listener was not already registered.
2606 * @param listener The reconcile listener to be added
2609 final void addReconcileListener(IJavaReconcilingListener listener) {
2610 synchronized (fReconcilingListeners) {
2611 fReconcilingListeners.add(listener);
2616 * Removes the given listener.
2617 * Has no effect if an identical listener was not already registered.
2619 * @param listener the reconcile listener to be removed
2622 final void removeReconcileListener(IJavaReconcilingListener listener) {
2623 synchronized (fReconcilingListeners) {
2624 fReconcilingListeners.remove(listener);
2628 protected void updateStateDependentActions() {
2629 super.updateStateDependentActions();
2630 fGenerateActionGroup.editorStateChanged();
2634 * @see AbstractTextEditor#rememberSelection()
2636 protected void rememberSelection() {
2637 fRememberedSelection.remember();
2641 * @see AbstractTextEditor#restoreSelection()
2643 protected void restoreSelection() {
2644 fRememberedSelection.restore();
2648 * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2650 protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
2652 String oldExtension= ""; //$NON-NLS-1$
2653 if (originalElement instanceof IFileEditorInput) {
2654 IFile file= ((IFileEditorInput) originalElement).getFile();
2656 String ext= file.getFileExtension();
2662 String newExtension= ""; //$NON-NLS-1$
2663 if (movedElement instanceof IFileEditorInput) {
2664 IFile file= ((IFileEditorInput) movedElement).getFile();
2666 newExtension= file.getFileExtension();
2669 return oldExtension.equals(newExtension);
2673 * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2675 protected boolean isPrefQuickDiffAlwaysOn() {
2676 // reestablishes the behaviour from AbstractDecoratedTextEditor which was hacked by JavaEditor
2677 // to disable the change bar for the class file (attached source) java editor.
2678 IPreferenceStore store= getPreferenceStore();
2679 return store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2683 * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2685 public Object getAdapter(Class required) {
2686 if (SmartBackspaceManager.class.equals(required)) {
2687 if (getSourceViewer() instanceof JavaSourceViewer) {
2688 return ((JavaSourceViewer) getSourceViewer()).getBackspaceManager();
2692 return super.getAdapter(required);
2695 * Returns the mutex for the reconciler. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898
2696 * for a description of the problem.
2698 * TODO remove once the underlying problem is solved.
2700 * @return the lock reconcilers may use to synchronize on
2702 public Object getReconcilerLock() {
2703 return fReconcilerLock;