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