Added patch for #1589521 "3 character function names invalid?"
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPUnitEditor.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
3 import java.text.MessageFormat;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9
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;
44
45 import org.eclipse.core.resources.IFile;
46 import org.eclipse.core.resources.IWorkspaceRoot;
47 import org.eclipse.core.resources.ResourcesPlugin;
48 import org.eclipse.core.runtime.CoreException;
49 import org.eclipse.core.runtime.IPath;
50 import org.eclipse.core.runtime.IProgressMonitor;
51 import org.eclipse.core.runtime.IStatus;
52 import org.eclipse.core.runtime.Preferences;
53 import org.eclipse.jface.action.Action;
54 import org.eclipse.jface.action.IAction;
55 import org.eclipse.jface.action.IMenuManager;
56 import org.eclipse.jface.dialogs.ErrorDialog;
57 import org.eclipse.jface.dialogs.IMessageProvider;
58 import org.eclipse.jface.dialogs.MessageDialog;
59 import org.eclipse.jface.preference.IPreferenceStore;
60 import org.eclipse.jface.preference.PreferenceConverter;
61 import org.eclipse.jface.text.BadLocationException;
62 import org.eclipse.jface.text.DocumentCommand;
63 import org.eclipse.jface.text.IAutoEditStrategy;
64 import org.eclipse.jface.text.IDocument;
65 import org.eclipse.jface.text.ILineTracker;
66 import org.eclipse.jface.text.IRegion;
67 import org.eclipse.jface.text.ITextOperationTarget;
68 import org.eclipse.jface.text.ITextViewerExtension;
69 import org.eclipse.jface.text.ITypedRegion;
70 import org.eclipse.jface.text.IWidgetTokenKeeper;
71 import org.eclipse.jface.text.contentassist.ContentAssistant;
72 import org.eclipse.jface.text.contentassist.IContentAssistant;
73 import org.eclipse.jface.text.formatter.FormattingContextProperties;
74 import org.eclipse.jface.text.formatter.IFormattingContext;
75 import org.eclipse.jface.text.source.IOverviewRuler;
76 import org.eclipse.jface.text.source.ISourceViewer;
77 import org.eclipse.jface.text.source.IVerticalRuler;
78 import org.eclipse.jface.text.source.SourceViewerConfiguration;
79 import org.eclipse.jface.util.ListenerList;
80 import org.eclipse.jface.util.PropertyChangeEvent;
81 import org.eclipse.jface.window.Window;
82 import org.eclipse.swt.SWT;
83 import org.eclipse.swt.custom.VerifyKeyListener;
84 import org.eclipse.swt.events.VerifyEvent;
85 import org.eclipse.swt.graphics.Color;
86 import org.eclipse.swt.graphics.Point;
87 import org.eclipse.swt.graphics.RGB;
88 import org.eclipse.swt.widgets.Composite;
89 import org.eclipse.swt.widgets.Display;
90 import org.eclipse.swt.widgets.Shell;
91 import org.eclipse.ui.IEditorInput;
92 import org.eclipse.ui.IEditorPart;
93 import org.eclipse.ui.IFileEditorInput;
94 import org.eclipse.ui.IWorkbenchPage;
95 import org.eclipse.ui.IWorkbenchWindow;
96 import org.eclipse.ui.PlatformUI;
97 import org.eclipse.ui.actions.ActionContext;
98 import org.eclipse.ui.actions.ActionGroup;
99 import org.eclipse.ui.dialogs.SaveAsDialog;
100 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
101 import org.eclipse.ui.part.FileEditorInput;
102 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
103 import org.eclipse.ui.texteditor.ContentAssistAction;
104 import org.eclipse.ui.texteditor.IDocumentProvider;
105 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
106 import org.eclipse.ui.texteditor.TextOperationAction;
107
108 /*******************************************************************************
109  * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
110  * program and the accompanying materials are made available under the terms of
111  * the Common Public License v1.0 which accompanies this distribution, and is
112  * available at http://www.eclipse.org/legal/cpl-v10.html
113  *
114  * Contributors: IBM Corporation - Initial implementation
115  * www.phpeclipse.de
116  ******************************************************************************/
117 /**
118  * PHP specific text editor.
119  */
120 public class PHPUnitEditor extends PHPEditor { // implements
121         // IJavaReconcilingListener {
122         interface ITextConverter {
123                 void customizeDocumentCommand(IDocument document,
124                                 DocumentCommand command);
125         };
126
127         // class AdaptedSourceViewer extends JavaSourceViewer {
128         // private List fTextConverters;
129         //
130         // private boolean fIgnoreTextConverters = false;
131         //
132         // // private JavaCorrectionAssistant fCorrectionAssistant;
133         // public AdaptedSourceViewer(Composite parent, IVerticalRuler
134         // verticalRuler,
135         // IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
136         // int styles, IPreferenceStore store) {
137         // super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
138         // styles, store);
139         // }
140         //
141         // // public AdaptedSourceViewer(Composite parent,
142         // // IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
143         // // boolean showAnnotationsOverview, int styles) {
144         // // super(parent, verticalRuler, overviewRuler,
145         // // showAnnotationsOverview, styles);
146         // // }
147         // public IContentAssistant getContentAssistant() {
148         // return fContentAssistant;
149         // }
150         //
151         // /*
152         // * @see ITextOperationTarget#doOperation(int)
153         // */
154         // public void doOperation(int operation) {
155         // if (getTextWidget() == null)
156         // return;
157         // switch (operation) {
158         // case CONTENTASSIST_PROPOSALS:
159         // String msg = fContentAssistant.showPossibleCompletions();
160         // setStatusLineErrorMessage(msg);
161         // return;
162         // // case CORRECTIONASSIST_PROPOSALS:
163         // // fCorrectionAssistant.showPossibleCompletions();
164         // // return;
165         // case UNDO:
166         // fIgnoreTextConverters = true;
167         // break;
168         // case REDO:
169         // fIgnoreTextConverters = true;
170         // break;
171         // }
172         // super.doOperation(operation);
173         // }
174         //
175         // /*
176         // * @see ITextOperationTarget#canDoOperation(int)
177         // */
178         // public boolean canDoOperation(int operation) {
179         // // if (operation == CORRECTIONASSIST_PROPOSALS)
180         // // return isEditable();
181         // return super.canDoOperation(operation);
182         // }
183         //
184         // /*
185         // * @see TextViewer#handleDispose()
186         // */
187         // protected void handleDispose() {
188         // // if (fCorrectionAssistant != null) {
189         // // fCorrectionAssistant.uninstall();
190         // // fCorrectionAssistant= null;
191         // // }
192         // super.handleDispose();
193         // }
194         //
195         // public void insertTextConverter(ITextConverter textConverter, int index)
196         // {
197         // throw new UnsupportedOperationException();
198         // }
199         //
200         // public void addTextConverter(ITextConverter textConverter) {
201         // if (fTextConverters == null) {
202         // fTextConverters = new ArrayList(1);
203         // fTextConverters.add(textConverter);
204         // } else if (!fTextConverters.contains(textConverter))
205         // fTextConverters.add(textConverter);
206         // }
207         //
208         // public void removeTextConverter(ITextConverter textConverter) {
209         // if (fTextConverters != null) {
210         // fTextConverters.remove(textConverter);
211         // if (fTextConverters.size() == 0)
212         // fTextConverters = null;
213         // }
214         // }
215         //
216         // /*
217         // * @see TextViewer#customizeDocumentCommand(DocumentCommand)
218         // */
219         // protected void customizeDocumentCommand(DocumentCommand command) {
220         // super.customizeDocumentCommand(command);
221         // if (!fIgnoreTextConverters && fTextConverters != null) {
222         // for (Iterator e = fTextConverters.iterator(); e.hasNext();)
223         // ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
224         // command);
225         // }
226         // fIgnoreTextConverters = false;
227         // }
228         //
229         // // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
230         // public void updateIndentationPrefixes() {
231         // SourceViewerConfiguration configuration = getSourceViewerConfiguration();
232         // String[] types = configuration.getConfiguredContentTypes(this);
233         // for (int i = 0; i < types.length; i++) {
234         // String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
235         // if (prefixes != null && prefixes.length > 0)
236         // setIndentPrefixes(prefixes, types[i]);
237         // }
238         // }
239         //
240         // /*
241         // * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
242         // */
243         // public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
244         // if (WorkbenchHelp.isContextHelpDisplayed())
245         // return false;
246         // return super.requestWidgetToken(requester);
247         // }
248         //
249         // // /*
250         // // * @see
251         // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
252         // // */
253         // // public void configure(SourceViewerConfiguration configuration) {
254         // // super.configure(configuration);
255         // // // fCorrectionAssistant= new
256         // // // JavaCorrectionAssistant(CompilationUnitEditor.this);
257         // // // fCorrectionAssistant.install(this);
258         // // //TODO install SmartBracesAutoEditStrategy
259         // // // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
260         // // // IDocument.DEFAULT_CONTENT_TYPE);
261         // // }
262         // public void configure(SourceViewerConfiguration configuration) {
263         // super.configure(configuration);
264         // // fCorrectionAssistant= new
265         // JavaCorrectionAssistant(CompilationUnitEditor.this);
266         // // fCorrectionAssistant.install(this);
267         // IAutoEditStrategy smartSemi= new
268         // SmartSemicolonAutoEditStrategy(IPHPPartitions.PHP_PARTITIONING);
269         // prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
270         // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
271         // prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
272         // // prependAutoEditStrategy(smartSemi, IPHPPartitions.JAVA_CHARACTER);
273         // }
274         // };
275         class AdaptedSourceViewer extends JavaSourceViewer {
276
277                 private List fTextConverters;
278
279                 private boolean fIgnoreTextConverters = false;
280
281                 // private JavaCorrectionAssistant fCorrectionAssistant;
282
283                 public AdaptedSourceViewer(Composite parent,
284                                 IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
285                                 boolean showAnnotationsOverview, int styles,
286                                 IPreferenceStore store) {
287                         super(parent, verticalRuler, overviewRuler,
288                                         showAnnotationsOverview, styles, store);
289                 }
290
291                 public IContentAssistant getContentAssistant() {
292                         return fContentAssistant;
293                 }
294
295                 /*
296                  * @see ITextOperationTarget#doOperation(int)
297                  */
298                 public void doOperation(int operation) {
299
300                         if (getTextWidget() == null)
301                                 return;
302
303                         switch (operation) {
304                         case CONTENTASSIST_PROPOSALS:
305                                 String msg = fContentAssistant.showPossibleCompletions();
306                                 setStatusLineErrorMessage(msg);
307                                 return;
308                                 // case CORRECTIONASSIST_PROPOSALS:
309                                 // msg = fCorrectionAssistant.showPossibleCompletions();
310                                 // setStatusLineErrorMessage(msg);
311                                 // return;
312                         case UNDO:
313                                 fIgnoreTextConverters = true;
314                                 super.doOperation(operation);
315                                 fIgnoreTextConverters = false;
316                                 return;
317                         case REDO:
318                                 fIgnoreTextConverters = true;
319                                 super.doOperation(operation);
320                                 fIgnoreTextConverters = false;
321                                 return;
322                         }
323
324                         super.doOperation(operation);
325                 }
326
327                 /*
328                  * @see ITextOperationTarget#canDoOperation(int)
329                  */
330                 public boolean canDoOperation(int operation) {
331                         // if (operation == CORRECTIONASSIST_PROPOSALS)
332                         // return isEditable();
333
334                         return super.canDoOperation(operation);
335                 }
336
337                 /*
338                  * @see org.eclipse.jface.text.source.ISourceViewerExtension2#unconfigure()
339                  * @since 3.0
340                  */
341                 public void unconfigure() {
342                         // if (fCorrectionAssistant != null) {
343                         // fCorrectionAssistant.uninstall();
344                         // fCorrectionAssistant = null;
345                         // }
346                         super.unconfigure();
347                 }
348
349                 public void insertTextConverter(ITextConverter textConverter, int index) {
350                         throw new UnsupportedOperationException();
351                 }
352
353                 public void addTextConverter(ITextConverter textConverter) {
354                         if (fTextConverters == null) {
355                                 fTextConverters = new ArrayList(1);
356                                 fTextConverters.add(textConverter);
357                         } else if (!fTextConverters.contains(textConverter))
358                                 fTextConverters.add(textConverter);
359                 }
360
361                 public void removeTextConverter(ITextConverter textConverter) {
362                         if (fTextConverters != null) {
363                                 fTextConverters.remove(textConverter);
364                                 if (fTextConverters.size() == 0)
365                                         fTextConverters = null;
366                         }
367                 }
368
369                 /*
370                  * @see TextViewer#customizeDocumentCommand(DocumentCommand)
371                  */
372                 protected void customizeDocumentCommand(DocumentCommand command) {
373                         super.customizeDocumentCommand(command);
374                         if (!fIgnoreTextConverters && fTextConverters != null) {
375                                 for (Iterator e = fTextConverters.iterator(); e.hasNext();)
376                                         ((ITextConverter) e.next()).customizeDocumentCommand(
377                                                         getDocument(), command);
378                         }
379                 }
380
381                 // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
382                 public void updateIndentationPrefixes() {
383                         SourceViewerConfiguration configuration = getSourceViewerConfiguration();
384                         String[] types = configuration.getConfiguredContentTypes(this);
385                         for (int i = 0; i < types.length; i++) {
386                                 String[] prefixes = configuration.getIndentPrefixes(this,
387                                                 types[i]);
388                                 if (prefixes != null && prefixes.length > 0)
389                                         setIndentPrefixes(prefixes, types[i]);
390                         }
391                 }
392
393                 /*
394                  * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
395                  */
396                 public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
397                         if (PlatformUI.getWorkbench().getHelpSystem()
398                                         .isContextHelpDisplayed())
399                                 return false;
400                         return super.requestWidgetToken(requester);
401                 }
402
403                 /*
404                  * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper,
405                  *      int)
406                  * @since 3.0
407                  */
408                 public boolean requestWidgetToken(IWidgetTokenKeeper requester,
409                                 int priority) {
410                         if (PlatformUI.getWorkbench().getHelpSystem()
411                                         .isContextHelpDisplayed())
412                                 return false;
413                         return super.requestWidgetToken(requester, priority);
414                 }
415
416                 /*
417                  * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
418                  */
419                 public void configure(SourceViewerConfiguration configuration) {
420                         super.configure(configuration);
421                         // fCorrectionAssistant = new
422                         // JavaCorrectionAssistant(CompilationUnitEditor.this);
423                         // fCorrectionAssistant.install(this);
424                         IAutoEditStrategy smartSemi = new SmartSemicolonAutoEditStrategy(
425                                         IPHPPartitions.PHP_PARTITIONING);
426                         prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
427                         prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_DQ);
428                         prependAutoEditStrategy(smartSemi, IPHPPartitions.PHP_STRING_SQ);
429                         prependAutoEditStrategy(smartSemi,
430                                         IPHPPartitions.PHP_STRING_HEREDOC);
431                 }
432
433                 /*
434                  * @see org.eclipse.jface.text.source.SourceViewer#createFormattingContext()
435                  * @since 3.0
436                  */
437                 public IFormattingContext createFormattingContext() {
438                         IFormattingContext context = new CommentFormattingContext();
439
440                         Map preferences;
441                         IJavaElement inputJavaElement = getInputJavaElement();
442                         IJavaProject javaProject = inputJavaElement != null ? inputJavaElement
443                                         .getJavaProject()
444                                         : null;
445                         if (javaProject == null)
446                                 preferences = new HashMap(JavaCore.getOptions());
447                         else
448                                 preferences = new HashMap(javaProject.getOptions(true));
449
450                         context.storeToMap(PreferenceConstants.getPreferenceStore(),
451                                         preferences, false);
452                         context.setProperty(
453                                         FormattingContextProperties.CONTEXT_PREFERENCES,
454                                         preferences);
455
456                         return context;
457                 }
458         }
459
460         /**
461          * Remembers data related to the current selection to be able to restore it
462          * later.
463          * 
464          * @since 3.0
465          */
466         private class RememberedSelection {
467                 /** The remembered selection start. */
468                 private RememberedOffset fStartOffset = new RememberedOffset();
469
470                 /** The remembered selection end. */
471                 private RememberedOffset fEndOffset = new RememberedOffset();
472
473                 /**
474                  * Remember current selection.
475                  */
476                 public void remember() {
477                         /*
478                          * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
479                          * may be called inside an async call posted to the UI thread, so
480                          * protect against intermediate disposal of the editor.
481                          */
482                         ISourceViewer viewer = getSourceViewer();
483                         if (viewer != null) {
484                                 IRegion selection = getSignedSelection(viewer);
485                                 int startOffset = selection.getOffset();
486                                 int endOffset = startOffset + selection.getLength();
487
488                                 fStartOffset.setOffset(startOffset);
489                                 fEndOffset.setOffset(endOffset);
490                         }
491                 }
492
493                 /**
494                  * Restore remembered selection.
495                  */
496                 public void restore() {
497                         /*
498                          * https://bugs.eclipse.org/bugs/show_bug.cgi?id=52257 This method
499                          * may be called inside an async call posted to the UI thread, so
500                          * protect against intermediate disposal of the editor.
501                          */
502                         if (getSourceViewer() == null)
503                                 return;
504
505                         try {
506
507                                 int startOffset, endOffset;
508                                 int revealStartOffset, revealEndOffset;
509                                 if (showsHighlightRangeOnly()) {
510                                         IJavaElement newStartElement = fStartOffset.getElement();
511                                         startOffset = fStartOffset
512                                                         .getRememberedOffset(newStartElement);
513                                         revealStartOffset = fStartOffset.getRevealOffset(
514                                                         newStartElement, startOffset);
515                                         if (revealStartOffset == -1)
516                                                 startOffset = -1;
517
518                                         IJavaElement newEndElement = fEndOffset.getElement();
519                                         endOffset = fEndOffset.getRememberedOffset(newEndElement);
520                                         revealEndOffset = fEndOffset.getRevealOffset(newEndElement,
521                                                         endOffset);
522                                         if (revealEndOffset == -1)
523                                                 endOffset = -1;
524                                 } else {
525                                         startOffset = fStartOffset.getOffset();
526                                         revealStartOffset = startOffset;
527                                         endOffset = fEndOffset.getOffset();
528                                         revealEndOffset = endOffset;
529                                 }
530
531                                 if (startOffset == -1) {
532                                         startOffset = endOffset; // fallback to caret offset
533                                         revealStartOffset = revealEndOffset;
534                                 }
535
536                                 if (endOffset == -1) {
537                                         endOffset = startOffset; // fallback to other offset
538                                         revealEndOffset = revealStartOffset;
539                                 }
540
541                                 IJavaElement element;
542                                 if (endOffset == -1) {
543                                         // fallback to element selection
544                                         element = fEndOffset.getElement();
545                                         if (element == null)
546                                                 element = fStartOffset.getElement();
547                                         if (element != null)
548                                                 setSelection(element);
549                                         return;
550                                 }
551
552                                 if (isValidSelection(revealStartOffset, revealEndOffset
553                                                 - revealStartOffset)
554                                                 && isValidSelection(startOffset, endOffset
555                                                                 - startOffset))
556                                         selectAndReveal(startOffset, endOffset - startOffset,
557                                                         revealStartOffset, revealEndOffset
558                                                                         - revealStartOffset);
559                         } finally {
560                                 fStartOffset.clear();
561                                 fEndOffset.clear();
562                         }
563                 }
564
565                 private boolean isValidSelection(int offset, int length) {
566                         IDocumentProvider provider = getDocumentProvider();
567                         if (provider != null) {
568                                 IDocument document = provider.getDocument(getEditorInput());
569                                 if (document != null) {
570                                         int end = offset + length;
571                                         int documentLength = document.getLength();
572                                         return 0 <= offset && offset <= documentLength && 0 <= end
573                                                         && end <= documentLength;
574                                 }
575                         }
576                         return false;
577                 }
578
579         }
580
581         /**
582          * Remembers additional data for a given offset to be able restore it later.
583          * 
584          * @since 3.0
585          */
586         private class RememberedOffset {
587                 /** Remembered line for the given offset */
588                 private int fLine;
589
590                 /** Remembered column for the given offset */
591                 private int fColumn;
592
593                 /** Remembered Java element for the given offset */
594                 private IJavaElement fElement;
595
596                 /** Remembered Java element line for the given offset */
597                 private int fElementLine;
598
599                 /**
600                  * Store visual properties of the given offset.
601                  * 
602                  * @param offset
603                  *            Offset in the document
604                  */
605                 public void setOffset(int offset) {
606                         try {
607                                 IDocument document = getSourceViewer().getDocument();
608                                 fLine = document.getLineOfOffset(offset);
609                                 fColumn = offset - document.getLineOffset(fLine);
610                                 fElement = getElementAt(offset, true);
611
612                                 fElementLine = -1;
613                                 if (fElement instanceof IMember) {
614                                         ISourceRange range = ((IMember) fElement).getNameRange();
615                                         if (range != null)
616                                                 fElementLine = document.getLineOfOffset(range
617                                                                 .getOffset());
618                                 }
619                                 if (fElementLine == -1)
620                                         fElementLine = document
621                                                         .getLineOfOffset(getOffset(fElement));
622                         } catch (BadLocationException e) {
623                                 // should not happen
624                                 PHPeclipsePlugin.log(e);
625                                 clear();
626                         } catch (JavaModelException e) {
627                                 // should not happen
628                                 PHPeclipsePlugin.log(e.getStatus());
629                                 clear();
630                         }
631                 }
632
633                 /**
634                  * Return offset recomputed from stored visual properties.
635                  * 
636                  * @return Offset in the document
637                  */
638                 public int getOffset() {
639                         IJavaElement newElement = getElement();
640
641                         int offset = getRememberedOffset(newElement);
642
643                         if (offset != -1 && !containsOffset(newElement, offset)
644                                         && (offset == 0 || !containsOffset(newElement, offset - 1)))
645                                 return -1;
646
647                         return offset;
648                 }
649
650                 /**
651                  * Return offset recomputed from stored visual properties.
652                  * 
653                  * @param newElement
654                  *            Enclosing element
655                  * @return Offset in the document
656                  */
657                 public int getRememberedOffset(IJavaElement newElement) {
658                         try {
659                                 if (newElement == null)
660                                         return -1;
661
662                                 IDocument document = getSourceViewer().getDocument();
663                                 int newElementLine = -1;
664                                 if (newElement instanceof IMember) {
665                                         ISourceRange range = ((IMember) newElement).getNameRange();
666                                         if (range != null)
667                                                 newElementLine = document.getLineOfOffset(range
668                                                                 .getOffset());
669                                 }
670                                 if (newElementLine == -1)
671                                         newElementLine = document
672                                                         .getLineOfOffset(getOffset(newElement));
673                                 if (newElementLine == -1)
674                                         return -1;
675
676                                 int newLine = fLine + newElementLine - fElementLine;
677                                 if (newLine < 0 || newLine >= document.getNumberOfLines())
678                                         return -1;
679                                 int maxColumn = document.getLineLength(newLine);
680                                 String lineDelimiter = document.getLineDelimiter(newLine);
681                                 if (lineDelimiter != null)
682                                         maxColumn = maxColumn - lineDelimiter.length();
683                                 int offset;
684                                 if (fColumn > maxColumn)
685                                         offset = document.getLineOffset(newLine) + maxColumn;
686                                 else
687                                         offset = document.getLineOffset(newLine) + fColumn;
688
689                                 return offset;
690                         } catch (BadLocationException e) {
691                                 // should not happen
692                                 PHPeclipsePlugin.log(e);
693                                 return -1;
694                         } catch (JavaModelException e) {
695                                 // should not happen
696                                 PHPeclipsePlugin.log(e.getStatus());
697                                 return -1;
698                         }
699                 }
700
701                 /**
702                  * Returns the offset used to reveal the given element based on the
703                  * given selection offset.
704                  * 
705                  * @param element
706                  *            the element
707                  * @param offset
708                  *            the selection offset
709                  * @return the offset to reveal the given element based on the given
710                  *         selection offset
711                  */
712                 public int getRevealOffset(IJavaElement element, int offset) {
713                         if (element == null || offset == -1)
714                                 return -1;
715
716                         if (containsOffset(element, offset)) {
717                                 if (offset > 0) {
718                                         IJavaElement alternateElement = getElementAt(offset, false);
719                                         if (element.getHandleIdentifier().equals(
720                                                         alternateElement.getParent().getHandleIdentifier()))
721                                                 return offset - 1; // Solves test case 2 from
722                                                                                         // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
723                                 }
724                                 return offset;
725                         } else if (offset > 0 && containsOffset(element, offset - 1))
726                                 return offset - 1; // Solves test case 1 from
727                                                                         // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47727#c3
728
729                         return -1;
730                 }
731
732                 /**
733                  * Return Java element recomputed from stored visual properties.
734                  * 
735                  * @return Java element
736                  */
737                 public IJavaElement getElement() {
738                         if (fElement == null)
739                                 return null;
740
741                         return findElement(fElement);
742                 }
743
744                 /**
745                  * Clears the stored position
746                  */
747                 public void clear() {
748                         fLine = -1;
749                         fColumn = -1;
750                         fElement = null;
751                         fElementLine = -1;
752                 }
753
754                 /**
755                  * Does the given Java element contain the given offset?
756                  * 
757                  * @param element
758                  *            Java element
759                  * @param offset
760                  *            Offset
761                  * @return <code>true</code> iff the Java element contains the offset
762                  */
763                 private boolean containsOffset(IJavaElement element, int offset) {
764                         int elementOffset = getOffset(element);
765                         int elementLength = getLength(element);
766                         return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset
767                                         + elementLength)
768                                         : false;
769                 }
770
771                 /**
772                  * Returns the offset of the given Java element.
773                  * 
774                  * @param element
775                  *            Java element
776                  * @return Offset of the given Java element
777                  */
778                 private int getOffset(IJavaElement element) {
779                         if (element instanceof ISourceReference) {
780                                 ISourceReference sr = (ISourceReference) element;
781                                 try {
782                                         ISourceRange srcRange = sr.getSourceRange();
783                                         if (srcRange != null)
784                                                 return srcRange.getOffset();
785                                 } catch (JavaModelException e) {
786                                 }
787                         }
788                         return -1;
789                 }
790
791                 /**
792                  * Returns the length of the given Java element.
793                  * 
794                  * @param element
795                  *            Java element
796                  * @return Length of the given Java element
797                  */
798                 private int getLength(IJavaElement element) {
799                         if (element instanceof ISourceReference) {
800                                 ISourceReference sr = (ISourceReference) element;
801                                 try {
802                                         ISourceRange srcRange = sr.getSourceRange();
803                                         if (srcRange != null)
804                                                 return srcRange.getLength();
805                                 } catch (JavaModelException e) {
806                                 }
807                         }
808                         return -1;
809                 }
810
811                 /**
812                  * Returns the updated java element for the old java element.
813                  * 
814                  * @param element
815                  *            Old Java element
816                  * @return Updated Java element
817                  */
818                 private IJavaElement findElement(IJavaElement element) {
819
820                         if (element == null)
821                                 return null;
822
823                         IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
824                                         .getWorkingCopyManager();
825                         ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
826
827                         if (unit != null) {
828                                 try {
829
830                                         synchronized (unit) {
831                                                 // unit.reconcile(ICompilationUnit.NO_AST, false, null,
832                                                 // null);
833                                                 unit.reconcile();
834                                         }
835                                         IJavaElement[] findings = unit.findElements(element);
836                                         if (findings != null && findings.length > 0)
837                                                 return findings[0];
838
839                                 } catch (JavaModelException x) {
840                                         PHPeclipsePlugin.log(x.getStatus());
841                                         // nothing found, be tolerant and go on
842                                 }
843                         }
844
845                         return null;
846                 }
847
848         }
849
850         static class TabConverter implements ITextConverter {
851                 private int fTabRatio;
852
853                 private ILineTracker fLineTracker;
854
855                 public TabConverter() {
856                 }
857
858                 public void setNumberOfSpacesPerTab(int ratio) {
859                         fTabRatio = ratio;
860                 }
861
862                 public void setLineTracker(ILineTracker lineTracker) {
863                         fLineTracker = lineTracker;
864                 }
865
866                 private int insertTabString(StringBuffer buffer, int offsetInLine) {
867                         if (fTabRatio == 0)
868                                 return 0;
869                         int remainder = offsetInLine % fTabRatio;
870                         remainder = fTabRatio - remainder;
871                         for (int i = 0; i < remainder; i++)
872                                 buffer.append(' ');
873                         return remainder;
874                 }
875
876                 public void customizeDocumentCommand(IDocument document,
877                                 DocumentCommand command) {
878                         String text = command.text;
879                         if (text == null)
880                                 return;
881                         int index = text.indexOf('\t');
882                         if (index > -1) {
883                                 StringBuffer buffer = new StringBuffer();
884                                 fLineTracker.set(command.text);
885                                 int lines = fLineTracker.getNumberOfLines();
886                                 try {
887                                         for (int i = 0; i < lines; i++) {
888                                                 int offset = fLineTracker.getLineOffset(i);
889                                                 int endOffset = offset + fLineTracker.getLineLength(i);
890                                                 String line = text.substring(offset, endOffset);
891                                                 int position = 0;
892                                                 if (i == 0) {
893                                                         IRegion firstLine = document
894                                                                         .getLineInformationOfOffset(command.offset);
895                                                         position = command.offset - firstLine.getOffset();
896                                                 }
897                                                 int length = line.length();
898                                                 for (int j = 0; j < length; j++) {
899                                                         char c = line.charAt(j);
900                                                         if (c == '\t') {
901                                                                 position += insertTabString(buffer, position);
902                                                         } else {
903                                                                 buffer.append(c);
904                                                                 ++position;
905                                                         }
906                                                 }
907                                         }
908                                         command.text = buffer.toString();
909                                 } catch (BadLocationException x) {
910                                 }
911                         }
912                 }
913         };
914
915         private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
916                 final char fExitCharacter;
917
918                 public ExitPolicy(char exitCharacter) {
919                         fExitCharacter = exitCharacter;
920                 }
921
922                 /*
923                  * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
924                  *      org.eclipse.swt.events.VerifyEvent, int, int)
925                  */
926                 public ExitFlags doExit(LinkedPositionManager manager,
927                                 VerifyEvent event, int offset, int length) {
928                         if (event.character == fExitCharacter) {
929                                 if (manager.anyPositionIncludes(offset, length))
930                                         return new ExitFlags(LinkedPositionUI.COMMIT
931                                                         | LinkedPositionUI.UPDATE_CARET, false);
932                                 else
933                                         return new ExitFlags(LinkedPositionUI.COMMIT, true);
934                         }
935                         switch (event.character) {
936                         case '\b':
937                                 if (manager.getFirstPosition().length == 0)
938                                         return new ExitFlags(0, false);
939                                 else
940                                         return null;
941                         case '\n':
942                         case '\r':
943                                 return new ExitFlags(LinkedPositionUI.COMMIT, true);
944                         default:
945                                 return null;
946                         }
947                 }
948         }
949
950         private static class BracketLevel {
951                 int fOffset;
952
953                 int fLength;
954
955                 LinkedPositionManager fManager;
956
957                 LinkedPositionUI fEditor;
958         };
959
960         private class BracketInserter implements VerifyKeyListener,
961                         LinkedPositionUI.ExitListener {
962                 private boolean fCloseBracketsPHP = true;
963
964                 private boolean fCloseStringsPHPDQ = true;
965
966                 private boolean fCloseStringsPHPSQ = true;
967
968                 private int fOffset;
969
970                 private int fLength;
971
972                 public void setCloseBracketsPHPEnabled(boolean enabled) {
973                         fCloseBracketsPHP = enabled;
974                 }
975
976                 public void setCloseStringsPHPDQEnabled(boolean enabled) {
977                         fCloseStringsPHPDQ = enabled;
978                 }
979
980                 public void setCloseStringsPHPSQEnabled(boolean enabled) {
981                         fCloseStringsPHPSQ = enabled;
982                 }
983
984                 private boolean hasIdentifierToTheRight(IDocument document, int offset) {
985                         try {
986                                 int end = offset;
987                                 IRegion endLine = document.getLineInformationOfOffset(end);
988                                 int maxEnd = endLine.getOffset() + endLine.getLength();
989                                 while (end != maxEnd
990                                                 && Character.isWhitespace(document.getChar(end)))
991                                         ++end;
992                                 return end != maxEnd
993                                                 && Scanner.isPHPIdentifierPart(document.getChar(end));
994                         } catch (BadLocationException e) {
995                                 // be conservative
996                                 return true;
997                         }
998                 }
999
1000                 private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
1001                         try {
1002                                 int start = offset;
1003                                 IRegion startLine = document.getLineInformationOfOffset(start);
1004                                 int minStart = startLine.getOffset();
1005                                 while (start != minStart
1006                                                 && Character.isWhitespace(document.getChar(start - 1)))
1007                                         --start;
1008                                 return start != minStart
1009                                                 && Scanner.isPHPIdentifierPart(document
1010                                                                 .getChar(start - 1));
1011                         } catch (BadLocationException e) {
1012                                 return true;
1013                         }
1014                 }
1015
1016                 private boolean hasCharacterToTheLeft(IDocument document, int offset,
1017                                 char character) {
1018                         try {
1019                                 int start = offset;
1020                                 IRegion startLine = document.getLineInformationOfOffset(start);
1021                                 int minStart = startLine.getOffset();
1022                                 while (start != minStart
1023                                                 && Character.isWhitespace(document.getChar(start - 1)))
1024                                         --start;
1025                                 return start != minStart
1026                                                 && document.getChar(start - 1) == character;
1027                         } catch (BadLocationException e) {
1028                                 return false;
1029                         }
1030                 }
1031
1032                 private boolean hasCharacterToTheRight(IDocument document, int offset,
1033                                 char character) {
1034                         try {
1035                                 int end = offset;
1036                                 IRegion endLine = document.getLineInformationOfOffset(end);
1037                                 int maxEnd = endLine.getOffset() + endLine.getLength();
1038                                 while (end != maxEnd
1039                                                 && Character.isWhitespace(document.getChar(end)))
1040                                         ++end;
1041                                 return end != maxEnd && document.getChar(end) == character;
1042                         } catch (BadLocationException e) {
1043                                 // be conservative
1044                                 return true;
1045                         }
1046                 }
1047
1048                 /*
1049                  * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
1050                  */
1051                 public void verifyKey(VerifyEvent event) {
1052                         if (!event.doit)
1053                                 return;
1054                         final ISourceViewer sourceViewer = getSourceViewer();
1055                         IDocument document = sourceViewer.getDocument();
1056                         final Point selection = sourceViewer.getSelectedRange();
1057                         final int offset = selection.x;
1058                         final int length = selection.y;
1059                         try {
1060                                 ITypedRegion partition = document.getPartition(offset);
1061                                 String type = partition.getType();
1062                                 if (type.equals(IPHPPartitions.PHP_PARTITIONING)
1063                                                 || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
1064                                         // you will get IDocument.DEFAULT_CONTENT_TYPE for both PHP
1065                                         // and HTML area
1066                                         switch (event.character) {
1067                                         case '(':
1068                                                 if (hasCharacterToTheRight(document, offset + length,
1069                                                                 '('))
1070                                                         return;
1071                                                 // fall through
1072                                         case '[':
1073                                                 if (!fCloseBracketsPHP)
1074                                                         return;
1075                                                 if (hasIdentifierToTheRight(document, offset + length))
1076                                                         return;
1077                                                 // fall through
1078                                         case '{':
1079                                                 if (!fCloseBracketsPHP)
1080                                                         return;
1081                                                 if (hasIdentifierToTheRight(document, offset + length))
1082                                                         return;
1083                                                 // fall through
1084                                         case '"':
1085                                                 if (event.character == '"') {
1086                                                         if (!fCloseStringsPHPDQ)
1087                                                                 return;
1088                                                         // changed for statements like echo "" print ""
1089                                                         // if (hasIdentifierToTheLeft(document, offset)
1090                                                         // ||
1091                                                         // hasIdentifierToTheRight(document, offset +
1092                                                         // length))
1093                                                         if (hasIdentifierToTheRight(document, offset
1094                                                                         + length))
1095                                                                 return;
1096                                                 }
1097                                                 // ITypedRegion partition=
1098                                                 // document.getPartition(offset);
1099                                                 // if (!
1100                                                 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1101                                                 // &&
1102                                                 // (partition.getOffset() != offset))
1103                                                 // return;
1104                                                 final char characterDQ = event.character;
1105                                                 final char closingCharacterDQ = getPeerCharacter(characterDQ);
1106                                                 final StringBuffer bufferDQ = new StringBuffer();
1107                                                 bufferDQ.append(characterDQ);
1108                                                 bufferDQ.append(closingCharacterDQ);
1109                                                 document.replace(offset, length, bufferDQ.toString());
1110                                                 LinkedPositionManager managerDQ = new LinkedPositionManager(
1111                                                                 document);
1112                                                 managerDQ.addPosition(offset + 1, 0);
1113                                                 fOffset = offset;
1114                                                 fLength = 2;
1115                                                 LinkedPositionUI editorDQ = new LinkedPositionUI(
1116                                                                 sourceViewer, managerDQ);
1117                                                 editorDQ.setCancelListener(this);
1118                                                 editorDQ.setExitPolicy(new ExitPolicy(
1119                                                                 closingCharacterDQ));
1120                                                 editorDQ.setFinalCaretOffset(offset + 2);
1121                                                 editorDQ.enter();
1122                                                 IRegion newSelectionDQ = editorDQ.getSelectedRegion();
1123                                                 sourceViewer.setSelectedRange(newSelectionDQ
1124                                                                 .getOffset(), newSelectionDQ.getLength());
1125                                                 event.doit = false;
1126                                                 break;
1127                                         case '\'':
1128                                                 if (event.character == '\'') {
1129                                                         if (!fCloseStringsPHPSQ)
1130                                                                 return;
1131                                                         // changed for statements like echo "" print ""
1132                                                         // if (hasIdentifierToTheLeft(document, offset)
1133                                                         // ||
1134                                                         // hasIdentifierToTheRight(document, offset +
1135                                                         // length))
1136                                                         if (hasIdentifierToTheRight(document, offset
1137                                                                         + length))
1138                                                                 return;
1139                                                 }
1140                                                 // ITypedRegion partition=
1141                                                 // document.getPartition(offset);
1142                                                 // if (!
1143                                                 // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())
1144                                                 // &&
1145                                                 // (partition.getOffset() != offset))
1146                                                 // return;
1147                                                 final char characterSQ = event.character;
1148                                                 final char closingCharacterSQ = getPeerCharacter(characterSQ);
1149                                                 final StringBuffer bufferSQ = new StringBuffer();
1150                                                 bufferSQ.append(characterSQ);
1151                                                 bufferSQ.append(closingCharacterSQ);
1152                                                 document.replace(offset, length, bufferSQ.toString());
1153                                                 LinkedPositionManager managerSQ = new LinkedPositionManager(
1154                                                                 document);
1155                                                 managerSQ.addPosition(offset + 1, 0);
1156                                                 fOffset = offset;
1157                                                 fLength = 2;
1158                                                 LinkedPositionUI editorSQ = new LinkedPositionUI(
1159                                                                 sourceViewer, managerSQ);
1160                                                 editorSQ.setCancelListener(this);
1161                                                 editorSQ.setExitPolicy(new ExitPolicy(
1162                                                                 closingCharacterSQ));
1163                                                 editorSQ.setFinalCaretOffset(offset + 2);
1164                                                 editorSQ.enter();
1165                                                 IRegion newSelectionSQ = editorSQ.getSelectedRegion();
1166                                                 sourceViewer.setSelectedRange(newSelectionSQ
1167                                                                 .getOffset(), newSelectionSQ.getLength());
1168                                                 event.doit = false;
1169                                         case '\r': { // insert linebreaks and new closing brace
1170                                                                         // after brace and return
1171                                                 if (!fCloseBracketsPHP) {
1172                                                         return;
1173                                                 }
1174                                                 if (hasCharacterToTheLeft(document, offset, '{')
1175                                                                 && hasCharacterToTheRight(document, offset, '}')) {
1176                                                         String lineDelimiter = StubUtility
1177                                                                         .getLineDelimiterFor(document);
1178                                                         int caretPos = sourceViewer.getTextWidget()
1179                                                                         .getCaretOffset();
1180                                                         final StringBuffer buffer = new StringBuffer(
1181                                                                         lineDelimiter);
1182                                                         // get indentation
1183                                                         IRegion line = document
1184                                                                         .getLineInformationOfOffset(offset);
1185                                                         String currentLine = document.get(line.getOffset(),
1186                                                                         line.getLength());
1187                                                         int index = 0;
1188                                                         int max = currentLine.length();
1189                                                         StringBuffer indent = new StringBuffer();
1190                                                         while (index < max
1191                                                                         && Character.isWhitespace(currentLine
1192                                                                                         .charAt(index))) {
1193                                                                 indent.append(currentLine.charAt(index));
1194                                                                 index++;
1195                                                         }
1196                                                         buffer.append(indent);
1197                                                         JavaHeuristicScanner scanner = new JavaHeuristicScanner(
1198                                                                         document);
1199                                                         JavaIndenter indenter = new JavaIndenter(document,
1200                                                                         scanner);
1201                                                         buffer.append(indenter.createIndent(1));
1202                                                         int cursorPos = buffer.length();
1203                                                         buffer.append(lineDelimiter);
1204                                                         buffer.append(indent);
1205                                                         document.replace(offset, length, buffer.toString());
1206                                                         sourceViewer.getTextWidget().setCaretOffset(
1207                                                                         caretPos + cursorPos);
1208                                                         event.doit = false;
1209                                                 }
1210                                         }
1211                                         }
1212                                 }
1213                         } catch (BadLocationException e) {
1214                         }
1215                 }
1216
1217                 /*
1218                  * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
1219                  */
1220                 public void exit(boolean accept) {
1221                         if (accept)
1222                                 return;
1223                         // remove brackets
1224                         try {
1225                                 final ISourceViewer sourceViewer = getSourceViewer();
1226                                 IDocument document = sourceViewer.getDocument();
1227                                 document.replace(fOffset, fLength, null);
1228                         } catch (BadLocationException e) {
1229                         }
1230                 }
1231         }
1232
1233         /** The editor's save policy */
1234         protected ISavePolicy fSavePolicy;
1235
1236         /**
1237          * Listener to annotation model changes that updates the error tick in the
1238          * tab image
1239          */
1240         private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
1241
1242         /** The editor's paint manager */
1243         // private PaintManager fPaintManager;
1244         /** The editor's bracket painter */
1245         // private BracketPainter fBracketPainter;
1246         /** The editor's bracket matcher */
1247         private PHPPairMatcher fBracketMatcher;
1248
1249         /** The editor's line painter */
1250         // private LinePainter fLinePainter;
1251         /** The editor's print margin ruler painter */
1252         // private PrintMarginPainter fPrintMarginPainter;
1253         /** The editor's problem painter */
1254         // private ProblemPainter fProblemPainter;
1255         /** The editor's tab converter */
1256         private TabConverter fTabConverter;
1257
1258         /** History for structure select action */
1259         // private SelectionHistory fSelectionHistory;
1260         /** The preference property change listener for php core. */
1261         // private IPropertyChangeListener fPropertyChangeListener = new
1262         // PropertyChangeListener();
1263         /** The remembered java element */
1264         private IJavaElement fRememberedElement;
1265
1266         /**
1267          * The remembered selection.
1268          * 
1269          * @since 3.0
1270          */
1271         private RememberedSelection fRememberedSelection = new RememberedSelection();
1272
1273         /** The remembered php element offset */
1274         private int fRememberedElementOffset;
1275
1276         /** The bracket inserter. */
1277         private BracketInserter fBracketInserter = new BracketInserter();
1278
1279         /** The standard action groups added to the menu */
1280         private GenerateActionGroup fGenerateActionGroup;
1281
1282         private CompositeActionGroup fContextMenuGroup;
1283
1284         // private class PropertyChangeListener implements IPropertyChangeListener {
1285         // /*
1286         // * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1287         // */
1288         // public void
1289         // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1290         // event) {
1291         // handlePreferencePropertyChanged(event);
1292         // }
1293         // }
1294         /* Preference key for code formatter tab size */
1295         private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
1296
1297         /** Preference key for matching brackets */
1298         // private final static String MATCHING_BRACKETS =
1299         // PreferenceConstants.EDITOR_MATCHING_BRACKETS;
1300         /** Preference key for matching brackets color */
1301         // private final static String MATCHING_BRACKETS_COLOR =
1302         // PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
1303         /** Preference key for highlighting current line */
1304         // private final static String CURRENT_LINE =
1305         // PreferenceConstants.EDITOR_CURRENT_LINE;
1306         /** Preference key for highlight color of current line */
1307         // private final static String CURRENT_LINE_COLOR =
1308         // PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
1309         /** Preference key for showing print marging ruler */
1310         // private final static String PRINT_MARGIN =
1311         // PreferenceConstants.EDITOR_PRINT_MARGIN;
1312         /** Preference key for print margin ruler color */
1313         // private final static String PRINT_MARGIN_COLOR =
1314         // PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
1315         /** Preference key for print margin ruler column */
1316         // private final static String PRINT_MARGIN_COLUMN =
1317         // PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
1318         /** Preference key for inserting spaces rather than tabs */
1319         private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
1320
1321         /** Preference key for error indication */
1322         // private final static String ERROR_INDICATION =
1323         // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
1324         /** Preference key for error color */
1325         // private final static String ERROR_INDICATION_COLOR =
1326         // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
1327         /** Preference key for warning indication */
1328         // private final static String WARNING_INDICATION =
1329         // PreferenceConstants.EDITOR_WARNING_INDICATION;
1330         /** Preference key for warning color */
1331         // private final static String WARNING_INDICATION_COLOR =
1332         // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
1333         /** Preference key for task indication */
1334         private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
1335
1336         /** Preference key for task color */
1337         private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
1338
1339         /** Preference key for bookmark indication */
1340         private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
1341
1342         /** Preference key for bookmark color */
1343         private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
1344
1345         /** Preference key for search result indication */
1346         private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
1347
1348         /** Preference key for search result color */
1349         private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
1350
1351         /** Preference key for unknown annotation indication */
1352         private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
1353
1354         /** Preference key for unknown annotation color */
1355         private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
1356
1357         /** Preference key for linked position color */
1358         private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
1359
1360         /** Preference key for shwoing the overview ruler */
1361         private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
1362
1363         /** Preference key for error indication in overview ruler */
1364         private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
1365
1366         /** Preference key for warning indication in overview ruler */
1367         private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
1368
1369         /** Preference key for task indication in overview ruler */
1370         private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
1371
1372         /** Preference key for bookmark indication in overview ruler */
1373         private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1374
1375         /** Preference key for search result indication in overview ruler */
1376         private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1377
1378         /** Preference key for unknown annotation indication in overview ruler */
1379         private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1380
1381         /** Preference key for automatically closing double quoted strings */
1382         private final static String CLOSE_STRINGS_DQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_DQ_PHP;
1383
1384         /** Preference key for automatically closing single quoted strings */
1385         private final static String CLOSE_STRINGS_SQ_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_SQ_PHP;
1386
1387         /** Preference key for automatically wrapping Java strings */
1388         // private final static String WRAP_STRINGS =
1389         // PreferenceConstants.EDITOR_WRAP_STRINGS_DQ;
1390         /** Preference key for automatically closing brackets and parenthesis */
1391         private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
1392
1393         /** Preference key for automatically closing phpdocs and comments */
1394         private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
1395
1396         /** Preference key for automatically adding phpdoc tags */
1397         private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
1398
1399         /** Preference key for automatically formatting phpdocs */
1400         // private final static String FORMAT_JAVADOCS =
1401         // PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
1402         /** Preference key for automatically closing strings */
1403         private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
1404
1405         /** Preference key for automatically closing brackets and parenthesis */
1406         private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
1407
1408         /** Preference key for smart paste */
1409         private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
1410
1411         // private final static class AnnotationInfo {
1412         // public String fColorPreference;
1413         // public String fOverviewRulerPreference;
1414         // public String fEditorPreference;
1415         // };
1416         // private final static Map ANNOTATION_MAP;
1417         // static {
1418         //
1419         // AnnotationInfo info;
1420         // ANNOTATION_MAP = new HashMap();
1421         //
1422         // info = new AnnotationInfo();
1423         // info.fColorPreference = TASK_INDICATION_COLOR;
1424         // info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
1425         // info.fEditorPreference = TASK_INDICATION;
1426         // ANNOTATION_MAP.put(AnnotationType.TASK, info);
1427         //
1428         // info = new AnnotationInfo();
1429         // info.fColorPreference = ERROR_INDICATION_COLOR;
1430         // info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
1431         // info.fEditorPreference = ERROR_INDICATION;
1432         // ANNOTATION_MAP.put(AnnotationType.ERROR, info);
1433         //
1434         // info = new AnnotationInfo();
1435         // info.fColorPreference = WARNING_INDICATION_COLOR;
1436         // info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
1437         // info.fEditorPreference = WARNING_INDICATION;
1438         // ANNOTATION_MAP.put(AnnotationType.WARNING, info);
1439         //
1440         // info = new AnnotationInfo();
1441         // info.fColorPreference = BOOKMARK_INDICATION_COLOR;
1442         // info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
1443         // info.fEditorPreference = BOOKMARK_INDICATION;
1444         // ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
1445         //
1446         // info = new AnnotationInfo();
1447         // info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
1448         // info.fOverviewRulerPreference =
1449         // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
1450         // info.fEditorPreference = SEARCH_RESULT_INDICATION;
1451         // ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
1452         //
1453         // info = new AnnotationInfo();
1454         // info.fColorPreference = UNKNOWN_INDICATION_COLOR;
1455         // info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
1456         // info.fEditorPreference = UNKNOWN_INDICATION;
1457         // ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
1458         // };
1459         //
1460         // private final static AnnotationType[] ANNOTATION_LAYERS =
1461         // new AnnotationType[] {
1462         // AnnotationType.UNKNOWN,
1463         // AnnotationType.BOOKMARK,
1464         // AnnotationType.TASK,
1465         // AnnotationType.SEARCH,
1466         // AnnotationType.WARNING,
1467         // AnnotationType.ERROR };
1468         /**
1469          * Creates a new php unit editor.
1470          */
1471
1472         /**
1473          * Reconciling listeners.
1474          * 
1475          * @since 3.0
1476          */
1477         private ListenerList fReconcilingListeners = new ListenerList();
1478
1479         /**
1480          * Mutex for the reconciler. See
1481          * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
1482          * the problem.
1483          * <p>
1484          * TODO remove once the underlying problem is solved.
1485          * </p>
1486          */
1487         private final Object fReconcilerLock = new Object();
1488
1489         public PHPUnitEditor() {
1490                 super();
1491                 setDocumentProvider(PHPeclipsePlugin.getDefault()
1492                                 .getCompilationUnitDocumentProvider());
1493                 setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
1494                 setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
1495                 setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
1496                 // don't set help contextId, we install our own help context
1497                 fSavePolicy = null;
1498                 fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
1499         }
1500
1501         /*
1502          * @see AbstractTextEditor#createActions()
1503          */
1504         protected void createActions() {
1505                 super.createActions();
1506                 Action action;
1507                 // Action action= new
1508                 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1509                 // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
1510                 // //$NON-NLS-1$
1511                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
1512                 // setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
1513                 // markAsStateDependentAction("CorrectionAssistProposal", true);
1514                 // //$NON-NLS-1$
1515                 // // WorkbenchHelp.setHelp(action,
1516                 // IJavaHelpContextIds.QUICK_FIX_ACTION);
1517                 action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(),
1518                                 "ContentAssistProposal.", this); //$NON-NLS-1$
1519                 action
1520                                 .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
1521                 setAction("ContentAssistProposal", action); //$NON-NLS-1$
1522                 markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
1523                 // WorkbenchHelp.setHelp(action,
1524                 // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
1525                 // action = new
1526                 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1527                 // "ContentAssistContextInformation.", this,
1528                 // ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
1529                 // action
1530                 // .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1531                 // setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1532                 // markAsStateDependentAction("ContentAssistContextInformation", true);
1533                 // //$NON-NLS-1$
1534                 // WorkbenchHelp.setHelp(action,
1535                 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1536                 // action= new
1537                 // TextOperationAction(PHPEditorMessages.getResourceBundle(),
1538                 // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1539                 // //$NON-NLS-1$
1540                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1541                 // setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1542                 // markAsStateDependentAction("ContentAssistCompletePrefix", true);
1543                 // //$NON-NLS-1$
1544                 // // WorkbenchHelp.setHelp(action,
1545                 // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1546                 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1547                                 "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1548                 action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1549                 setAction("Comment", action); //$NON-NLS-1$
1550                 markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1551                 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1552                 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1553                                 "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1554                 action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1555                 setAction("Uncomment", action); //$NON-NLS-1$
1556                 markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1557                 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1558
1559                 action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1560                                 "ToggleComment.", this); //$NON-NLS-1$
1561                 action
1562                                 .setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1563                 setAction("ToggleComment", action); //$NON-NLS-1$
1564                 markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1565                 // WorkbenchHelp.setHelp(action,
1566                 // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1567                 configureToggleCommentAction();
1568
1569                 action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1570                                 "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1571                 action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1572                 setAction("Format", action); //$NON-NLS-1$
1573                 markAsStateDependentAction("Format", true); //$NON-NLS-1$
1574                 markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
1575                 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1576
1577                 // action = new
1578                 // AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1579                 // "AddBlockComment.", this); //$NON-NLS-1$
1580                 // action
1581                 // .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1582                 // setAction("AddBlockComment", action); //$NON-NLS-1$
1583                 // markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1584                 // markAsSelectionDependentAction("AddBlockComment", true);
1585                 // //$NON-NLS-1$
1586                 // // WorkbenchHelp.setHelp(action,
1587                 // // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1588                 // action = new RemoveBlockCommentAction(
1589                 // PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this);
1590                 // //$NON-NLS-1$
1591                 // action
1592                 // .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1593                 // setAction("RemoveBlockComment", action); //$NON-NLS-1$
1594                 // markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1595                 // markAsSelectionDependentAction("RemoveBlockComment", true);
1596                 // //$NON-NLS-1$
1597                 // WorkbenchHelp.setHelp(action,
1598                 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1599                 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1600                                 "Indent.", this, false); //$NON-NLS-1$
1601                 action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1602                 setAction("Indent", action); //$NON-NLS-1$
1603                 markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1604                 markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1605                 // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1606                 //
1607                 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1608                 // "Indent.", this, true); //$NON-NLS-1$
1609                 // setAction("IndentOnTab", action); //$NON-NLS-1$
1610                 // markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1611                 // markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1612                 //
1613
1614                 action = new AddBlockCommentAction(PHPEditorMessages
1615                                 .getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$
1616                 action
1617                                 .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1618                 setAction("AddBlockComment", action); //$NON-NLS-1$
1619                 markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1620                 markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$
1621                 // WorkbenchHelp.setHelp(action,
1622                 // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1623
1624                 action = new RemoveBlockCommentAction(PHPEditorMessages
1625                                 .getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1626                 action
1627                                 .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1628                 setAction("RemoveBlockComment", action); //$NON-NLS-1$
1629                 markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1630                 markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1631                 // WorkbenchHelp.setHelp(action,
1632                 // IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION);
1633
1634                 // action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1635                 // "Indent.", this, false); //$NON-NLS-1$
1636                 // action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1637                 // setAction("Indent", action); //$NON-NLS-1$
1638                 // markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1639                 // markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1640                 // // WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1641                 //
1642                 action = new IndentAction(PHPEditorMessages.getResourceBundle(),
1643                                 "Indent.", this, true); //$NON-NLS-1$
1644                 setAction("IndentOnTab", action); //$NON-NLS-1$
1645                 markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1646                 markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1647
1648                 if (getPreferenceStore().getBoolean(
1649                                 PreferenceConstants.EDITOR_SMART_TAB)) {
1650                         // don't replace Shift Right - have to make sure their enablement is
1651                         // mutually exclusive
1652                         // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1653                         setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1654                 }
1655                 fGenerateActionGroup = new GenerateActionGroup(this,
1656                                 ITextEditorActionConstants.GROUP_EDIT);
1657                 // ActionGroup rg= new RefactorActionGroup(this,
1658                 // ITextEditorActionConstants.GROUP_EDIT);
1659
1660                 // fActionGroups.addGroup(rg);
1661                 fActionGroups.addGroup(fGenerateActionGroup);
1662
1663                 // We have to keep the context menu group separate to have better
1664                 // control over positioning
1665                 fContextMenuGroup = new CompositeActionGroup(
1666                                 new ActionGroup[] { fGenerateActionGroup
1667                                 // rg,
1668                                 // new LocalHistoryActionGroup(this,
1669                                 // ITextEditorActionConstants.GROUP_EDIT)
1670                                 });
1671
1672         }
1673
1674         /*
1675          * @see JavaEditor#getElementAt(int)
1676          */
1677         protected IJavaElement getElementAt(int offset) {
1678                 return getElementAt(offset, true);
1679         }
1680
1681         /**
1682          * Returns the most narrow element including the given offset. If
1683          * <code>reconcile</code> is <code>true</code> the editor's input
1684          * element is reconciled in advance. If it is <code>false</code> this
1685          * method only returns a result if the editor's input element does not need
1686          * to be reconciled.
1687          * 
1688          * @param offset
1689          *            the offset included by the retrieved element
1690          * @param reconcile
1691          *            <code>true</code> if working copy should be reconciled
1692          */
1693         protected IJavaElement getElementAt(int offset, boolean reconcile) {
1694                 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1695                                 .getWorkingCopyManager();
1696                 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1697                 if (unit != null) {
1698                         try {
1699                                 if (reconcile) {
1700                                         synchronized (unit) {
1701                                                 unit.reconcile();
1702                                         }
1703                                         return unit.getElementAt(offset);
1704                                 } else if (unit.isConsistent())
1705                                         return unit.getElementAt(offset);
1706                         } catch (JavaModelException x) {
1707                                 PHPeclipsePlugin.log(x.getStatus());
1708                                 // nothing found, be tolerant and go on
1709                         }
1710                 }
1711                 return null;
1712         }
1713
1714         /*
1715          * @see JavaEditor#getCorrespondingElement(IJavaElement)
1716          */
1717         protected IJavaElement getCorrespondingElement(IJavaElement element) {
1718                 try {
1719                         return EditorUtility.getWorkingCopy(element, true);
1720                 } catch (JavaModelException x) {
1721                         PHPeclipsePlugin.log(x.getStatus());
1722                         // nothing found, be tolerant and go on
1723                 }
1724                 return null;
1725         }
1726
1727         public void createPartControl(Composite parent) {
1728                 super.createPartControl(parent);
1729                 // fPaintManager = new PaintManager(getSourceViewer());
1730                 LinePainter linePainter;
1731                 linePainter = new LinePainter(getSourceViewer());
1732                 linePainter.setHighlightColor(new Color(Display.getCurrent(), 225, 235,
1733                                 224));
1734                 // fPaintManager.addPainter(linePainter);
1735                 // if (isBracketHighlightingEnabled())
1736                 // startBracketHighlighting();
1737                 // if (isLineHighlightingEnabled())
1738                 // startLineHighlighting();
1739                 // if (isPrintMarginVisible())
1740                 // showPrintMargin();
1741                 // Iterator e = ANNOTATION_MAP.keySet().iterator();
1742                 // while (e.hasNext()) {
1743                 // AnnotationType type = (AnnotationType) e.next();
1744                 // if (isAnnotationIndicationEnabled(type))
1745                 // startAnnotationIndication(type);
1746                 // }
1747                 if (isTabConversionEnabled())
1748                         startTabConversion();
1749                 // if (isOverviewRulerVisible())
1750                 // showOverviewRuler();
1751                 //
1752                 // Preferences preferences =
1753                 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1754                 // preferences.addPropertyChangeListener(fPropertyChangeListener);
1755                 IPreferenceStore preferenceStore = getPreferenceStore();
1756                 boolean closeBracketsPHP = preferenceStore
1757                                 .getBoolean(CLOSE_BRACKETS_PHP);
1758                 boolean closeStringsPHPDQ = preferenceStore
1759                                 .getBoolean(CLOSE_STRINGS_DQ_PHP);
1760                 boolean closeStringsPHPSQ = preferenceStore
1761                                 .getBoolean(CLOSE_STRINGS_SQ_PHP);
1762                 fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1763                 fBracketInserter.setCloseStringsPHPDQEnabled(closeStringsPHPDQ);
1764                 fBracketInserter.setCloseStringsPHPSQEnabled(closeStringsPHPSQ);
1765                 ISourceViewer sourceViewer = getSourceViewer();
1766                 if (sourceViewer instanceof ITextViewerExtension)
1767                         ((ITextViewerExtension) sourceViewer)
1768                                         .prependVerifyKeyListener(fBracketInserter);
1769         }
1770
1771         private static char getPeerCharacter(char character) {
1772                 switch (character) {
1773                 case '(':
1774                         return ')';
1775                 case ')':
1776                         return '(';
1777                 case '[':
1778                         return ']';
1779                 case ']':
1780                         return '[';
1781                 case '"':
1782                         return character;
1783                 case '\'':
1784                         return character;
1785                 case '{':
1786                         return '}';
1787                 default:
1788                         throw new IllegalArgumentException();
1789                 }
1790         }
1791
1792         // private void startBracketHighlighting() {
1793         // if (fBracketPainter == null) {
1794         // ISourceViewer sourceViewer = getSourceViewer();
1795         // fBracketPainter = new BracketPainter(sourceViewer);
1796         // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1797         // // fPaintManager.addPainter(fBracketPainter);
1798         // }
1799         // }
1800         //
1801         // private void stopBracketHighlighting() {
1802         // if (fBracketPainter != null) {
1803         // // fPaintManager.removePainter(fBracketPainter);
1804         // fBracketPainter.deactivate(true);
1805         // fBracketPainter.dispose();
1806         // fBracketPainter = null;
1807         // }
1808         // }
1809
1810         // private boolean isBracketHighlightingEnabled() {
1811         // IPreferenceStore store = getPreferenceStore();
1812         // return store.getBoolean(MATCHING_BRACKETS);
1813         // }
1814
1815         // private void startLineHighlighting() {
1816         // if (fLinePainter == null) {
1817         // ISourceViewer sourceViewer = getSourceViewer();
1818         // fLinePainter = new LinePainter(sourceViewer);
1819         // fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1820         // // fPaintManager.addPainter(fLinePainter);
1821         // }
1822         // }
1823
1824         // private void stopLineHighlighting() {
1825         // if (fLinePainter != null) {
1826         // // fPaintManager.removePainter(fLinePainter);
1827         // fLinePainter.deactivate(true);
1828         // fLinePainter.dispose();
1829         // fLinePainter = null;
1830         // }
1831         // }
1832
1833         // private boolean isLineHighlightingEnabled() {
1834         // IPreferenceStore store = getPreferenceStore();
1835         // return store.getBoolean(CURRENT_LINE);
1836         // }
1837
1838         // private void showPrintMargin() {
1839         // if (fPrintMarginPainter == null) {
1840         // fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1841         // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1842         // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
1843         // // fPaintManager.addPainter(fPrintMarginPainter);
1844         // }
1845         // }
1846
1847         // private void hidePrintMargin() {
1848         // if (fPrintMarginPainter != null) {
1849         // // fPaintManager.removePainter(fPrintMarginPainter);
1850         // fPrintMarginPainter.deactivate(true);
1851         // fPrintMarginPainter.dispose();
1852         // fPrintMarginPainter = null;
1853         // }
1854         // }
1855
1856         // private boolean isPrintMarginVisible() {
1857         // IPreferenceStore store = getPreferenceStore();
1858         // return store.getBoolean(PRINT_MARGIN);
1859         // }
1860
1861         private int getTabSize() {
1862                 Preferences preferences = PHPeclipsePlugin.getDefault()
1863                                 .getPluginPreferences();
1864                 return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1865         }
1866
1867         private boolean isTabConversionEnabled() {
1868                 IPreferenceStore store = getPreferenceStore();
1869                 return store.getBoolean(SPACES_FOR_TABS);
1870         }
1871
1872         private Color getColor(String key) {
1873                 RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1874                 return getColor(rgb);
1875         }
1876
1877         private Color getColor(RGB rgb) {
1878                 JavaTextTools textTools = PHPeclipsePlugin.getDefault()
1879                                 .getJavaTextTools();
1880                 return textTools.getColorManager().getColor(rgb);
1881         }
1882
1883         // private Color getColor(AnnotationType annotationType) {
1884         // AnnotationInfo info = (AnnotationInfo)
1885         // ANNOTATION_MAP.get(annotationType);
1886         // if (info != null)
1887         // return getColor(info.fColorPreference);
1888         // return null;
1889         // }
1890         public void dispose() {
1891                 ISourceViewer sourceViewer = getSourceViewer();
1892                 if (sourceViewer instanceof ITextViewerExtension)
1893                         ((ITextViewerExtension) sourceViewer)
1894                                         .removeVerifyKeyListener(fBracketInserter);
1895                 // if (fPropertyChangeListener != null) {
1896                 // Preferences preferences =
1897                 // PHPeclipsePlugin.getDefault().getPluginPreferences();
1898                 // preferences.removePropertyChangeListener(fPropertyChangeListener);
1899                 // fPropertyChangeListener = null;
1900                 // }
1901                 if (fJavaEditorErrorTickUpdater != null) {
1902                         fJavaEditorErrorTickUpdater.dispose();
1903                         fJavaEditorErrorTickUpdater = null;
1904                 }
1905                 // if (fSelectionHistory != null)
1906                 // fSelectionHistory.dispose();
1907                 // if (fPaintManager != null) {
1908                 // fPaintManager.dispose();
1909                 // fPaintManager = null;
1910                 // }
1911                 if (fActionGroups != null) {
1912                         fActionGroups.dispose();
1913                         fActionGroups = null;
1914                 }
1915                 super.dispose();
1916         }
1917
1918         // protected AnnotationType getAnnotationType(String preferenceKey) {
1919         // Iterator e = ANNOTATION_MAP.keySet().iterator();
1920         // while (e.hasNext()) {
1921         // AnnotationType type = (AnnotationType) e.next();
1922         // AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1923         // if (info != null) {
1924         // if (preferenceKey.equals(info.fColorPreference)
1925         // || preferenceKey.equals(info.fEditorPreference)
1926         // || preferenceKey.equals(info.fOverviewRulerPreference))
1927         // return type;
1928         // }
1929         // }
1930         // return null;
1931         // }
1932         /*
1933          * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1934          */
1935         protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1936                 try {
1937                         AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1938                         if (asv != null) {
1939                                 String p = event.getProperty();
1940                                 if (CLOSE_BRACKETS_PHP.equals(p)) {
1941                                         fBracketInserter
1942                                                         .setCloseBracketsPHPEnabled(getPreferenceStore()
1943                                                                         .getBoolean(p));
1944                                         return;
1945                                 }
1946                                 if (CLOSE_STRINGS_DQ_PHP.equals(p)) {
1947                                         fBracketInserter
1948                                                         .setCloseStringsPHPDQEnabled(getPreferenceStore()
1949                                                                         .getBoolean(p));
1950                                         return;
1951                                 }
1952                                 if (CLOSE_STRINGS_SQ_PHP.equals(p)) {
1953                                         fBracketInserter
1954                                                         .setCloseStringsPHPSQEnabled(getPreferenceStore()
1955                                                                         .getBoolean(p));
1956                                         return;
1957                                 }
1958                                 if (SPACES_FOR_TABS.equals(p)) {
1959                                         if (isTabConversionEnabled())
1960                                                 startTabConversion();
1961                                         else
1962                                                 stopTabConversion();
1963                                         return;
1964                                 }
1965                                 // if (MATCHING_BRACKETS.equals(p)) {
1966                                 // if (isBracketHighlightingEnabled())
1967                                 // startBracketHighlighting();
1968                                 // else
1969                                 // stopBracketHighlighting();
1970                                 // return;
1971                                 // }
1972                                 // if (MATCHING_BRACKETS_COLOR.equals(p)) {
1973                                 // if (fBracketPainter != null)
1974                                 // fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1975                                 // return;
1976                                 // }
1977                                 // if (CURRENT_LINE.equals(p)) {
1978                                 // if (isLineHighlightingEnabled())
1979                                 // startLineHighlighting();
1980                                 // else
1981                                 // stopLineHighlighting();
1982                                 // return;
1983                                 // }
1984                                 // if (CURRENT_LINE_COLOR.equals(p)) {
1985                                 // if (fLinePainter != null) {
1986                                 // stopLineHighlighting();
1987                                 // startLineHighlighting();
1988                                 // }
1989                                 // return;
1990                                 // }
1991                                 // if (PRINT_MARGIN.equals(p)) {
1992                                 // if (isPrintMarginVisible())
1993                                 // showPrintMargin();
1994                                 // else
1995                                 // hidePrintMargin();
1996                                 // return;
1997                                 // }
1998                                 // if (PRINT_MARGIN_COLOR.equals(p)) {
1999                                 // if (fPrintMarginPainter != null)
2000                                 // fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
2001                                 // return;
2002                                 // }
2003                                 // if (PRINT_MARGIN_COLUMN.equals(p)) {
2004                                 // if (fPrintMarginPainter != null)
2005                                 // fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
2006                                 // return;
2007                                 // }
2008                                 // if (OVERVIEW_RULER.equals(p)) {
2009                                 // if (isOverviewRulerVisible())
2010                                 // showOverviewRuler();
2011                                 // else
2012                                 // hideOverviewRuler();
2013                                 // return;
2014                                 // }
2015                                 // AnnotationType type = getAnnotationType(p);
2016                                 // if (type != null) {
2017                                 //
2018                                 // AnnotationInfo info = (AnnotationInfo)
2019                                 // ANNOTATION_MAP.get(type);
2020                                 // if (info.fColorPreference.equals(p)) {
2021                                 // Color color = getColor(type);
2022                                 // if (fProblemPainter != null) {
2023                                 // fProblemPainter.setColor(type, color);
2024                                 // fProblemPainter.paint(IPainter.CONFIGURATION);
2025                                 // }
2026                                 // setColorInOverviewRuler(type, color);
2027                                 // return;
2028                                 // }
2029                                 //
2030                                 // if (info.fEditorPreference.equals(p)) {
2031                                 // if (isAnnotationIndicationEnabled(type))
2032                                 // startAnnotationIndication(type);
2033                                 // else
2034                                 // stopAnnotationIndication(type);
2035                                 // return;
2036                                 // }
2037                                 //
2038                                 // if (info.fOverviewRulerPreference.equals(p)) {
2039                                 // if (isAnnotationIndicationInOverviewRulerEnabled(type))
2040                                 // showAnnotationIndicationInOverviewRuler(type, true);
2041                                 // else
2042                                 // showAnnotationIndicationInOverviewRuler(type, false);
2043                                 // return;
2044                                 // }
2045                                 // }
2046                                 IContentAssistant c = asv.getContentAssistant();
2047                                 if (c instanceof ContentAssistant)
2048                                         ContentAssistPreference.changeConfiguration(
2049                                                         (ContentAssistant) c, getPreferenceStore(), event);
2050                         }
2051                 } finally {
2052                         super.handlePreferenceStoreChanged(event);
2053                 }
2054         }
2055
2056         /*
2057          * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
2058          */
2059         protected void handlePreferencePropertyChanged(
2060                         org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2061                 AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2062                 if (asv != null) {
2063                         String p = event.getProperty();
2064                         if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2065                                 asv.updateIndentationPrefixes();
2066                                 if (fTabConverter != null)
2067                                         fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2068                         }
2069                 }
2070                 super.handlePreferencePropertyChanged(event);
2071         }
2072
2073         /**
2074          * Handles a property change event describing a change of the php core's
2075          * preferences and updates the preference related editor properties.
2076          * 
2077          * @param event
2078          *            the property change event
2079          */
2080         // protected void
2081         // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
2082         // event) {
2083         // AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2084         // if (asv != null) {
2085         // String p = event.getProperty();
2086         // if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
2087         // asv.updateIndentationPrefixes();
2088         // if (fTabConverter != null)
2089         // fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2090         // }
2091         // }
2092         // }
2093         /*
2094          * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite,
2095          *      org.eclipse.jface.text.source.IVerticalRuler,
2096          *      org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
2097          */
2098         protected ISourceViewer createJavaSourceViewer(Composite parent,
2099                         IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
2100                         boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2101                 return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
2102                                 isOverviewRulerVisible, styles, store);
2103         }
2104
2105         // protected ISourceViewer createJavaSourceViewer(Composite parent,
2106         // IVerticalRuler ruler, int styles) {
2107         // return new AdaptedSourceViewer(parent, ruler, styles);
2108         // }
2109         private boolean isValidSelection(int offset, int length) {
2110                 IDocumentProvider provider = getDocumentProvider();
2111                 if (provider != null) {
2112                         IDocument document = provider.getDocument(getEditorInput());
2113                         if (document != null) {
2114                                 int end = offset + length;
2115                                 int documentLength = document.getLength();
2116                                 return 0 <= offset && offset <= documentLength && 0 <= end
2117                                                 && end <= documentLength;
2118                         }
2119                 }
2120                 return false;
2121         }
2122
2123         /*
2124          * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getInputElement()
2125          */
2126         protected IJavaElement getInputJavaElement() {
2127                 return PHPeclipsePlugin.getDefault().getWorkingCopyManager()
2128                                 .getWorkingCopy(getEditorInput());
2129         }
2130
2131         /*
2132          * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
2133          */
2134         public void editorContextMenuAboutToShow(IMenuManager menu) {
2135                 super.editorContextMenuAboutToShow(menu);
2136                 ActionContext context = new ActionContext(getSelectionProvider()
2137                                 .getSelection());
2138                 fContextMenuGroup.setContext(context);
2139                 fContextMenuGroup.fillContextMenu(menu);
2140                 fContextMenuGroup.setContext(null);
2141         }
2142
2143         /*
2144          * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
2145          */
2146         protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
2147                 if (page != null) {
2148                         IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2149                                         .getWorkingCopyManager();
2150                         page.setInput(manager.getWorkingCopy(input));
2151                 }
2152         }
2153
2154         /*
2155          * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
2156          *      IProgressMonitor)
2157          */
2158         // protected void performSaveOperation(WorkspaceModifyOperation operation,
2159         // IProgressMonitor progressMonitor) {
2160         // IDocumentProvider p = getDocumentProvider();
2161         // if (p instanceof PHPDocumentProvider) {
2162         // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2163         // cp.setSavePolicy(fSavePolicy);
2164         // }
2165         //
2166         // try {
2167         // super.performSaveOperation(operation, progressMonitor);
2168         // } finally {
2169         // if (p instanceof PHPDocumentProvider) {
2170         // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2171         // cp.setSavePolicy(null);
2172         // }
2173         // }
2174         // }
2175         /*
2176          * @see AbstractTextEditor#doSave(IProgressMonitor)
2177          */
2178         public void doSave(IProgressMonitor progressMonitor) {
2179
2180                 IDocumentProvider p = getDocumentProvider();
2181                 if (p == null) {
2182                         // editor has been closed
2183                         return;
2184                 }
2185
2186                 if (p.isDeleted(getEditorInput())) {
2187
2188                         if (isSaveAsAllowed()) {
2189
2190                                 /*
2191                                  * 1GEUSSR: ITPUI:ALL - User should never loose changes made in
2192                                  * the editors. Changed Behavior to make sure that if called
2193                                  * inside a regular save (because of deletion of input element)
2194                                  * there is a way to report back to the caller.
2195                                  */
2196                                 performSaveAs(progressMonitor);
2197
2198                         } else {
2199
2200                                 /*
2201                                  * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still
2202                                  * there Missing resources.
2203                                  */
2204                                 Shell shell = getSite().getShell();
2205                                 MessageDialog
2206                                                 .openError(
2207                                                                 shell,
2208                                                                 PHPEditorMessages
2209                                                                                 .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages.getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
2210                         }
2211
2212                 } else {
2213                         if (getPreferenceStore().getBoolean(
2214                                         PreferenceConstants.EDITOR_P_RTRIM_ON_SAVE)) {
2215                                 RTrimAction trimAction = new RTrimAction();
2216                                 trimAction.setActiveEditor(null, getSite().getPage()
2217                                                 .getActiveEditor());
2218                                 trimAction.run(null);
2219                         }
2220
2221                         setStatusLineErrorMessage(null);
2222
2223                         updateState(getEditorInput());
2224                         validateState(getEditorInput());
2225
2226                         IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2227                                         .getWorkingCopyManager();
2228                         ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2229
2230                         if (unit != null) {
2231                                 synchronized (unit) {
2232                                         performSave(false, progressMonitor);
2233                                 }
2234                         } else
2235                                 performSave(false, progressMonitor);
2236                 }
2237         }
2238
2239         public boolean isSaveAsAllowed() {
2240                 return true;
2241         }
2242
2243         /**
2244          * The compilation unit editor implementation of this
2245          * <code>AbstractTextEditor</code> method asks the user for the workspace
2246          * path of a file resource and saves the document there. See
2247          * http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
2248          * 
2249          * @param progressMonitor
2250          *            the progress monitor
2251          */
2252         protected void performSaveAs(IProgressMonitor progressMonitor) {
2253
2254                 Shell shell = getSite().getShell();
2255                 IEditorInput input = getEditorInput();
2256
2257                 SaveAsDialog dialog = new SaveAsDialog(shell);
2258
2259                 IFile original = (input instanceof IFileEditorInput) ? ((IFileEditorInput) input)
2260                                 .getFile()
2261                                 : null;
2262                 if (original != null)
2263                         dialog.setOriginalFile(original);
2264
2265                 dialog.create();
2266
2267                 IDocumentProvider provider = getDocumentProvider();
2268                 if (provider == null) {
2269                         // editor has been programmatically closed while the dialog was open
2270                         return;
2271                 }
2272
2273                 if (provider.isDeleted(input) && original != null) {
2274                         String message = PHPEditorMessages
2275                                         .getFormattedString(
2276                                                         "CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
2277                         dialog.setErrorMessage(null);
2278                         dialog.setMessage(message, IMessageProvider.WARNING);
2279                 }
2280
2281                 if (dialog.open() == Window.CANCEL) {
2282                         if (progressMonitor != null)
2283                                 progressMonitor.setCanceled(true);
2284                         return;
2285                 }
2286
2287                 IPath filePath = dialog.getResult();
2288                 if (filePath == null) {
2289                         if (progressMonitor != null)
2290                                 progressMonitor.setCanceled(true);
2291                         return;
2292                 }
2293
2294                 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
2295                 IFile file = workspaceRoot.getFile(filePath);
2296                 final IEditorInput newInput = new FileEditorInput(file);
2297
2298                 boolean success = false;
2299                 try {
2300
2301                         provider.aboutToChange(newInput);
2302                         getDocumentProvider().saveDocument(progressMonitor, newInput,
2303                                         getDocumentProvider().getDocument(getEditorInput()), true);
2304                         success = true;
2305
2306                 } catch (CoreException x) {
2307                         IStatus status = x.getStatus();
2308                         if (status == null || status.getSeverity() != IStatus.CANCEL)
2309                                 ErrorDialog
2310                                                 .openError(
2311                                                                 shell,
2312                                                                 PHPEditorMessages
2313                                                                                 .getString("CompilationUnitEditor.error.saving.title2"), PHPEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
2314                 } finally {
2315                         provider.changed(newInput);
2316                         if (success)
2317                                 setInput(newInput);
2318                 }
2319
2320                 if (progressMonitor != null)
2321                         progressMonitor.setCanceled(!success);
2322         }
2323
2324         /*
2325          * @see AbstractTextEditor#doSetInput(IEditorInput)
2326          */
2327         protected void doSetInput(IEditorInput input) throws CoreException {
2328                 super.doSetInput(input);
2329                 configureTabConverter();
2330                 configureToggleCommentAction();
2331         }
2332
2333         // /*
2334         // * @see
2335         // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#installOverrideIndicator(boolean)
2336         // * @since 3.0
2337         // */
2338         // protected void installOverrideIndicator(boolean waitForReconcilation) {
2339         // IAnnotationModel model=
2340         // getDocumentProvider().getAnnotationModel(getEditorInput());
2341         // if (!waitForReconcilation)
2342         // super.installOverrideIndicator(false);
2343         // else {
2344         // uninstallOverrideIndicator();
2345         // IJavaElement inputElement= getInputJavaElement();
2346         // if (model == null || inputElement == null)
2347         // return;
2348         //
2349         // fOverrideIndicatorManager= new OverrideIndicatorManager(model,
2350         // inputElement, null);
2351         // addReconcileListener(fOverrideIndicatorManager);
2352         // }
2353         // }
2354         //
2355         // /*
2356         // * @see
2357         // net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#uninstallOverrideIndicator()
2358         // * @since 3.0
2359         // */
2360         // protected void uninstallOverrideIndicator() {
2361         // if (fOverrideIndicatorManager != null)
2362         // removeReconcileListener(fOverrideIndicatorManager);
2363         // super.uninstallOverrideIndicator();
2364         // }
2365
2366         /**
2367          * Configures the toggle comment action
2368          * 
2369          * @since 3.0
2370          */
2371         private void configureToggleCommentAction() {
2372                 IAction action = getAction("ToggleComment"); //$NON-NLS-1$
2373                 if (action instanceof ToggleCommentAction) {
2374                         ISourceViewer sourceViewer = getSourceViewer();
2375                         SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2376                         ((ToggleCommentAction) action).configure(sourceViewer,
2377                                         configuration);
2378                 }
2379         }
2380
2381         // private void configureTabConverter() {
2382         // if (fTabConverter != null) {
2383         // IDocumentProvider provider = getDocumentProvider();
2384         // if (provider instanceof PHPDocumentProvider) {
2385         // PHPDocumentProvider cup = (PHPDocumentProvider) provider;
2386         // fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
2387         // }
2388         // }
2389         // }
2390         private void configureTabConverter() {
2391                 if (fTabConverter != null) {
2392                         IDocumentProvider provider = getDocumentProvider();
2393                         if (provider instanceof ICompilationUnitDocumentProvider) {
2394                                 ICompilationUnitDocumentProvider cup = (ICompilationUnitDocumentProvider) provider;
2395                                 fTabConverter.setLineTracker(cup
2396                                                 .createLineTracker(getEditorInput()));
2397                         }
2398                 }
2399         }
2400
2401         private void startTabConversion() {
2402                 if (fTabConverter == null) {
2403                         fTabConverter = new TabConverter();
2404                         configureTabConverter();
2405                         fTabConverter.setNumberOfSpacesPerTab(getTabSize());
2406                         AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2407                         asv.addTextConverter(fTabConverter);
2408                         // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2409                         asv.updateIndentationPrefixes();
2410                 }
2411         }
2412
2413         private void stopTabConversion() {
2414                 if (fTabConverter != null) {
2415                         AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
2416                         asv.removeTextConverter(fTabConverter);
2417                         // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
2418                         asv.updateIndentationPrefixes();
2419                         fTabConverter = null;
2420                 }
2421         }
2422
2423         /*
2424          * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
2425          *      org.eclipse.core.runtime.IProgressMonitor)
2426          */
2427         protected void performSave(boolean overwrite,
2428                         IProgressMonitor progressMonitor) {
2429                 // IDocumentProvider p = getDocumentProvider();
2430                 // if (p instanceof PHPDocumentProvider) {
2431                 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2432                 // cp.setSavePolicy(fSavePolicy);
2433                 // }
2434                 // try {
2435                 // super.performSave(overwrite, progressMonitor);
2436                 // } finally {
2437                 // if (p instanceof PHPDocumentProvider) {
2438                 // PHPDocumentProvider cp = (PHPDocumentProvider) p;
2439                 // cp.setSavePolicy(null);
2440                 // }
2441                 // }
2442
2443                 IDocumentProvider p = getDocumentProvider();
2444                 if (p instanceof ICompilationUnitDocumentProvider) {
2445                         ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2446                         cp.setSavePolicy(fSavePolicy);
2447                 }
2448                 try {
2449                         super.performSave(overwrite, progressMonitor);
2450                 } finally {
2451                         if (p instanceof ICompilationUnitDocumentProvider) {
2452                                 ICompilationUnitDocumentProvider cp = (ICompilationUnitDocumentProvider) p;
2453                                 cp.setSavePolicy(null);
2454                         }
2455                 }
2456         }
2457
2458         /*
2459          * @see AbstractTextEditor#doSaveAs
2460          */
2461         public void doSaveAs() {
2462                 if (askIfNonWorkbenchEncodingIsOk()) {
2463                         super.doSaveAs();
2464                 }
2465         }
2466
2467         /**
2468          * Asks the user if it is ok to store in non-workbench encoding.
2469          * 
2470          * @return <true>if the user wants to continue
2471          */
2472         private boolean askIfNonWorkbenchEncodingIsOk() {
2473                 IDocumentProvider provider = getDocumentProvider();
2474                 if (provider instanceof IStorageDocumentProvider) {
2475                         IEditorInput input = getEditorInput();
2476                         IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
2477                         String encoding = storageProvider.getEncoding(input);
2478                         String defaultEncoding = storageProvider.getDefaultEncoding();
2479                         if (encoding != null && !encoding.equals(defaultEncoding)) {
2480                                 Shell shell = getSite().getShell();
2481                                 String title = PHPEditorMessages
2482                                                 .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
2483                                 String msg;
2484                                 if (input != null)
2485                                         msg = MessageFormat
2486                                                         .format(
2487                                                                         PHPEditorMessages
2488                                                                                         .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
2489                                                                         new String[] { input.getName(), encoding }); //$NON-NLS-1$
2490                                 else
2491                                         msg = MessageFormat
2492                                                         .format(
2493                                                                         PHPEditorMessages
2494                                                                                         .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
2495                                                                         new String[] { encoding }); //$NON-NLS-1$
2496                                 return MessageDialog.openQuestion(shell, title, msg);
2497                         }
2498                 }
2499                 return true;
2500         }
2501
2502         /*
2503          * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
2504          * @since 3.0
2505          */
2506         public void aboutToBeReconciled() {
2507
2508                 // Notify AST provider
2509                 // PHPeclipsePlugin.getDefault().getASTProvider().aboutToBeReconciled(getInputJavaElement());
2510
2511                 // Notify listeners
2512                 Object[] listeners = fReconcilingListeners.getListeners();
2513                 for (int i = 0, length = listeners.length; i < length; ++i)
2514                         ((IJavaReconcilingListener) listeners[i]).aboutToBeReconciled();
2515         }
2516
2517         /*
2518          * @see net.sourceforge.phpdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
2519          *      boolean, IProgressMonitor)
2520          * @since 3.0
2521          */
2522         public void reconciled(CompilationUnit ast, boolean forced,
2523                         IProgressMonitor progressMonitor) {
2524
2525                 // Always notify AST provider
2526                 // PHPeclipsePlugin.getDefault().getASTProvider().reconciled(ast,
2527                 // getInputJavaElement());
2528
2529                 // Notify listeners
2530                 // Object[] listeners = fReconcilingListeners.getListeners();
2531                 // for (int i = 0, length= listeners.length; i < length; ++i)
2532                 // ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced,
2533                 // progressMonitor);
2534
2535                 // Update Java Outline page selection
2536                 if (!forced && !progressMonitor.isCanceled()) {
2537                         Shell shell = getSite().getShell();
2538                         if (shell != null && !shell.isDisposed()) {
2539                                 shell.getDisplay().asyncExec(new Runnable() {
2540                                         public void run() {
2541                                                 selectionChanged();
2542                                         }
2543                                 });
2544                         }
2545                 }
2546         }
2547
2548         /**
2549          * Returns the updated java element for the old java element.
2550          */
2551         private IJavaElement findElement(IJavaElement element) {
2552                 if (element == null)
2553                         return null;
2554                 IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
2555                                 .getWorkingCopyManager();
2556                 ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
2557                 if (unit != null) {
2558                         try {
2559                                 synchronized (unit) {
2560                                         unit.reconcile();
2561                                 }
2562                                 IJavaElement[] findings = unit.findElements(element);
2563                                 if (findings != null && findings.length > 0)
2564                                         return findings[0];
2565                         } catch (JavaModelException x) {
2566                                 PHPeclipsePlugin.log(x.getStatus());
2567                                 // nothing found, be tolerant and go on
2568                         }
2569                 }
2570                 return null;
2571         }
2572
2573         /**
2574          * Returns the offset of the given Java element.
2575          */
2576         private int getOffset(IJavaElement element) {
2577                 if (element instanceof ISourceReference) {
2578                         ISourceReference sr = (ISourceReference) element;
2579                         try {
2580                                 ISourceRange srcRange = sr.getSourceRange();
2581                                 if (srcRange != null)
2582                                         return srcRange.getOffset();
2583                         } catch (JavaModelException e) {
2584                         }
2585                 }
2586                 return -1;
2587         }
2588
2589         /*
2590          * @see AbstractTextEditor#restoreSelection()
2591          */
2592         // protected void restoreSelection() {
2593         // try {
2594         // if (getSourceViewer() == null || fRememberedSelection == null)
2595         // return;
2596         // IJavaElement newElement = findElement(fRememberedElement);
2597         // int newOffset = getOffset(newElement);
2598         // int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
2599         // - fRememberedElementOffset : 0;
2600         // if (isValidSelection(delta + fRememberedSelection.getOffset(),
2601         // fRememberedSelection.getLength()))
2602         // selectAndReveal(delta + fRememberedSelection.getOffset(),
2603         // fRememberedSelection.getLength());
2604         // } finally {
2605         // fRememberedSelection = null;
2606         // fRememberedElement = null;
2607         // fRememberedElementOffset = -1;
2608         // }
2609         // }
2610         /**
2611          * Tells whether this is the active editor in the active page.
2612          * 
2613          * @return <code>true</code> if this is the active editor in the active
2614          *         page
2615          * @see IWorkbenchPage#getActiveEditor();
2616          */
2617         protected final boolean isActiveEditor() {
2618                 IWorkbenchWindow window = getSite().getWorkbenchWindow();
2619                 IWorkbenchPage page = window.getActivePage();
2620                 if (page == null)
2621                         return false;
2622                 IEditorPart activeEditor = page.getActiveEditor();
2623                 return activeEditor != null && activeEditor.equals(this);
2624         }
2625
2626         /**
2627          * Adds the given listener. Has no effect if an identical listener was not
2628          * already registered.
2629          * 
2630          * @param listener
2631          *            The reconcile listener to be added
2632          * @since 3.0
2633          */
2634         final void addReconcileListener(IJavaReconcilingListener listener) {
2635                 synchronized (fReconcilingListeners) {
2636                         fReconcilingListeners.add(listener);
2637                 }
2638         }
2639
2640         /**
2641          * Removes the given listener. Has no effect if an identical listener was
2642          * not already registered.
2643          * 
2644          * @param listener
2645          *            the reconcile listener to be removed
2646          * @since 3.0
2647          */
2648         final void removeReconcileListener(IJavaReconcilingListener listener) {
2649                 synchronized (fReconcilingListeners) {
2650                         fReconcilingListeners.remove(listener);
2651                 }
2652         }
2653
2654         protected void updateStateDependentActions() {
2655                 super.updateStateDependentActions();
2656                 fGenerateActionGroup.editorStateChanged();
2657         }
2658
2659         /*
2660          * @see AbstractTextEditor#rememberSelection()
2661          */
2662         protected void rememberSelection() {
2663                 fRememberedSelection.remember();
2664         }
2665
2666         /*
2667          * @see AbstractTextEditor#restoreSelection()
2668          */
2669         protected void restoreSelection() {
2670                 fRememberedSelection.restore();
2671         }
2672
2673         /*
2674          * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
2675          */
2676         protected boolean canHandleMove(IEditorInput originalElement,
2677                         IEditorInput movedElement) {
2678
2679                 String oldExtension = ""; //$NON-NLS-1$
2680                 if (originalElement instanceof IFileEditorInput) {
2681                         IFile file = ((IFileEditorInput) originalElement).getFile();
2682                         if (file != null) {
2683                                 String ext = file.getFileExtension();
2684                                 if (ext != null)
2685                                         oldExtension = ext;
2686                         }
2687                 }
2688
2689                 String newExtension = ""; //$NON-NLS-1$
2690                 if (movedElement instanceof IFileEditorInput) {
2691                         IFile file = ((IFileEditorInput) movedElement).getFile();
2692                         if (file != null)
2693                                 newExtension = file.getFileExtension();
2694                 }
2695
2696                 return oldExtension.equals(newExtension);
2697         }
2698
2699         /*
2700          * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#isPrefQuickDiffAlwaysOn()
2701          */
2702         protected boolean isPrefQuickDiffAlwaysOn() {
2703                 // reestablishes the behaviour from AbstractDecoratedTextEditor which
2704                 // was hacked by JavaEditor
2705                 // to disable the change bar for the class file (attached source) java
2706                 // editor.
2707                 IPreferenceStore store = getPreferenceStore();
2708                 return store
2709                                 .getBoolean(AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON);
2710         }
2711
2712         /*
2713          * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor#getAdapter(java.lang.Class)
2714          */
2715         public Object getAdapter(Class required) {
2716                 if (SmartBackspaceManager.class.equals(required)) {
2717                         if (getSourceViewer() instanceof JavaSourceViewer) {
2718                                 return ((JavaSourceViewer) getSourceViewer())
2719                                                 .getBackspaceManager();
2720                         }
2721                 }
2722
2723                 return super.getAdapter(required);
2724         }
2725
2726         /**
2727          * Returns the mutex for the reconciler. See
2728          * https://bugs.eclipse.org/bugs/show_bug.cgi?id=63898 for a description of
2729          * the problem.
2730          * <p>
2731          * TODO remove once the underlying problem is solved.
2732          * </p>
2733          * 
2734          * @return the lock reconcilers may use to synchronize on
2735          */
2736         public Object getReconcilerLock() {
2737                 return fReconcilerLock;
2738         }
2739
2740         /*
2741          * (non-Javadoc)
2742          * 
2743          * @see org.eclipse.ui.texteditor.AbstractTextEditor#editorSaved()
2744          */
2745         protected void editorSaved() {
2746                 super.editorSaved();
2747                 ShowExternalPreviewAction a = ShowExternalPreviewAction.getInstance();
2748                 if (a != null) {
2749                         a.refresh(ShowExternalPreviewAction.PHP_TYPE);
2750                 }
2751         }
2752 }