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