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