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