df0ea7e00b085187d3c67a109521cf291730b10a
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPUnitEditor.java
1 package net.sourceforge.phpeclipse.phpeditor;
2 import java.lang.reflect.InvocationTargetException;
3 import java.text.MessageFormat;
4 import java.util.ArrayList;
5 import java.util.Iterator;
6 import java.util.List;
7
8 import net.sourceforge.phpdt.core.ICompilationUnit;
9 import net.sourceforge.phpdt.core.IJavaElement;
10 import net.sourceforge.phpdt.core.ISourceRange;
11 import net.sourceforge.phpdt.core.ISourceReference;
12 import net.sourceforge.phpdt.core.JavaCore;
13 import net.sourceforge.phpdt.core.JavaModelException;
14 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
15 import net.sourceforge.phpdt.internal.ui.actions.AddBlockCommentAction;
16 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
17 import net.sourceforge.phpdt.internal.ui.actions.RemoveBlockCommentAction;
18 import net.sourceforge.phpdt.internal.ui.text.ContentAssistPreference;
19 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
20 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
21 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionManager;
22 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI;
23 import net.sourceforge.phpdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
24 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
25 import net.sourceforge.phpdt.ui.PreferenceConstants;
26 import net.sourceforge.phpdt.ui.actions.GenerateActionGroup;
27 import net.sourceforge.phpdt.ui.text.JavaTextTools;
28 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
29
30 import org.eclipse.core.resources.IFile;
31 import org.eclipse.core.resources.IWorkspace;
32 import org.eclipse.core.resources.ResourcesPlugin;
33 import org.eclipse.core.runtime.CoreException;
34 import org.eclipse.core.runtime.IPath;
35 import org.eclipse.core.runtime.IProgressMonitor;
36 import org.eclipse.core.runtime.Preferences;
37 import org.eclipse.jface.action.Action;
38 import org.eclipse.jface.action.IMenuManager;
39 import org.eclipse.jface.dialogs.Dialog;
40 import org.eclipse.jface.dialogs.ErrorDialog;
41 import org.eclipse.jface.dialogs.IMessageProvider;
42 import org.eclipse.jface.dialogs.MessageDialog;
43 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
44 import org.eclipse.jface.preference.IPreferenceStore;
45 import org.eclipse.jface.preference.PreferenceConverter;
46 import org.eclipse.jface.text.BadLocationException;
47 import org.eclipse.jface.text.DocumentCommand;
48 import org.eclipse.jface.text.IDocument;
49 import org.eclipse.jface.text.ILineTracker;
50 import org.eclipse.jface.text.IRegion;
51 import org.eclipse.jface.text.ITextOperationTarget;
52 import org.eclipse.jface.text.ITextSelection;
53 import org.eclipse.jface.text.ITextViewerExtension;
54 import org.eclipse.jface.text.ITypedRegion;
55 import org.eclipse.jface.text.IWidgetTokenKeeper;
56 import org.eclipse.jface.text.contentassist.ContentAssistant;
57 import org.eclipse.jface.text.contentassist.IContentAssistant;
58 import org.eclipse.jface.text.source.IOverviewRuler;
59 import org.eclipse.jface.text.source.ISourceViewer;
60 import org.eclipse.jface.text.source.IVerticalRuler;
61 import org.eclipse.jface.text.source.SourceViewerConfiguration;
62 import org.eclipse.jface.util.PropertyChangeEvent;
63 import org.eclipse.jface.viewers.ISelectionProvider;
64 import org.eclipse.swt.SWT;
65 import org.eclipse.swt.custom.VerifyKeyListener;
66 import org.eclipse.swt.events.VerifyEvent;
67 import org.eclipse.swt.graphics.Color;
68 import org.eclipse.swt.graphics.Point;
69 import org.eclipse.swt.graphics.RGB;
70 import org.eclipse.swt.widgets.Composite;
71 import org.eclipse.swt.widgets.Display;
72 import org.eclipse.swt.widgets.Shell;
73 import org.eclipse.ui.IEditorInput;
74 import org.eclipse.ui.IFileEditorInput;
75 import org.eclipse.ui.actions.ActionContext;
76 import org.eclipse.ui.actions.ActionGroup;
77 import org.eclipse.ui.actions.WorkspaceModifyOperation;
78 import org.eclipse.ui.dialogs.SaveAsDialog;
79 import org.eclipse.ui.editors.text.IStorageDocumentProvider;
80 import org.eclipse.ui.help.WorkbenchHelp;
81 import org.eclipse.ui.part.FileEditorInput;
82 import org.eclipse.ui.texteditor.ContentAssistAction;
83 import org.eclipse.ui.texteditor.IDocumentProvider;
84 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
85 import org.eclipse.ui.texteditor.TextOperationAction;
86 /*******************************************************************************
87  * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
88  * program and the accompanying materials are made available under the terms of
89  * the Common Public License v1.0 which accompanies this distribution, and is
90  * available at http://www.eclipse.org/legal/cpl-v10.html
91  * 
92  * Contributors: IBM Corporation - Initial implementation Klaus Hartlage -
93  * www.eclipseproject.de
94  ******************************************************************************/
95 /**
96  * PHP specific text editor.
97  */
98 public class PHPUnitEditor extends PHPEditor {
99   interface ITextConverter {
100     void customizeDocumentCommand(IDocument document, DocumentCommand command);
101   };
102   //  class AdaptedRulerLayout extends Layout {
103   //
104   //    protected int fGap;
105   //    protected AdaptedSourceViewer fAdaptedSourceViewer;
106   //
107   //    protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
108   //      fGap = gap;
109   //      fAdaptedSourceViewer = asv;
110   //    }
111   //
112   //    protected Point computeSize(Composite composite, int wHint, int hHint,
113   // boolean flushCache) {
114   //      Control[] children = composite.getChildren();
115   //      Point s = children[children.length - 1].computeSize(SWT.DEFAULT,
116   // SWT.DEFAULT, flushCache);
117   //      if (fAdaptedSourceViewer.isVerticalRulerVisible())
118   //        s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
119   //      return s;
120   //    }
121   //
122   //    protected void layout(Composite composite, boolean flushCache) {
123   //      Rectangle clArea = composite.getClientArea();
124   //      if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
125   //
126   //        StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
127   //        Rectangle trim = textWidget.computeTrim(0, 0, 0, 0);
128   //        int scrollbarHeight = trim.height;
129   //
130   //        IVerticalRuler vr = fAdaptedSourceViewer.getVerticalRuler();
131   //        int vrWidth = vr.getWidth();
132   //
133   //        int orWidth = 0;
134   //        if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
135   //          OverviewRuler or = fAdaptedSourceViewer.getOverviewRuler();
136   //          orWidth = or.getWidth();
137   //          or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight,
138   // orWidth, clArea.height - 3 * scrollbarHeight);
139   //        }
140   //
141   //        textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth -
142   // 2 * fGap, clArea.height);
143   //        vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight);
144   //
145   //      } else {
146   //        StyledText textWidget = fAdaptedSourceViewer.getTextWidget();
147   //        textWidget.setBounds(0, 0, clArea.width, clArea.height);
148   //      }
149   //    }
150   //  };
151   //
152   //  class AdaptedSourceViewer extends SourceViewer { // extends
153   // JavaCorrectionSourceViewer {
154   //
155   //    private List fTextConverters;
156   //
157   //    private OverviewRuler fOverviewRuler;
158   //    private boolean fIsOverviewRulerVisible;
159   //    /** The viewer's overview ruler hovering controller */
160   //    private AbstractHoverInformationControlManager
161   // fOverviewRulerHoveringController;
162   //
163   //    private boolean fIgnoreTextConverters = false;
164   //
165   //    private IVerticalRuler fCachedVerticalRuler;
166   //    private boolean fCachedIsVerticalRulerVisible;
167   //
168   //    public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int
169   // styles) {
170   //      super(parent, ruler, styles); //, CompilationUnitEditor.this);
171   //
172   //      fCachedVerticalRuler = ruler;
173   //      fCachedIsVerticalRulerVisible = (ruler != null);
174   //      fOverviewRuler = new OverviewRuler(VERTICAL_RULER_WIDTH);
175   //
176   //      delayedCreateControl(parent, styles);
177   //    }
178   //
179   //    /*
180   //     * @see ISourceViewer#showAnnotations(boolean)
181   //     */
182   //    public void showAnnotations(boolean show) {
183   //      fCachedIsVerticalRulerVisible = (show && fCachedVerticalRuler != null);
184   //      // super.showAnnotations(show);
185   //    }
186   //
187   //    public IContentAssistant getContentAssistant() {
188   //      return fContentAssistant;
189   //    }
190   //
191   //    /*
192   //     * @see ITextOperationTarget#doOperation(int)
193   //     */
194   //    public void doOperation(int operation) {
195   //
196   //      if (getTextWidget() == null)
197   //        return;
198   //
199   //      switch (operation) {
200   //        case CONTENTASSIST_PROPOSALS :
201   //          String msg = fContentAssistant.showPossibleCompletions();
202   //          setStatusLineErrorMessage(msg);
203   //          return;
204   //        case UNDO :
205   //          fIgnoreTextConverters = true;
206   //          break;
207   //        case REDO :
208   //          fIgnoreTextConverters = true;
209   //          break;
210   //      }
211   //
212   //      super.doOperation(operation);
213   //    }
214   //
215   //    public void insertTextConverter(ITextConverter textConverter, int index) {
216   //      throw new UnsupportedOperationException();
217   //    }
218   //
219   //    public void addTextConverter(ITextConverter textConverter) {
220   //      if (fTextConverters == null) {
221   //        fTextConverters = new ArrayList(1);
222   //        fTextConverters.add(textConverter);
223   //      } else if (!fTextConverters.contains(textConverter))
224   //        fTextConverters.add(textConverter);
225   //    }
226   //
227   //    public void removeTextConverter(ITextConverter textConverter) {
228   //      if (fTextConverters != null) {
229   //        fTextConverters.remove(textConverter);
230   //        if (fTextConverters.size() == 0)
231   //          fTextConverters = null;
232   //      }
233   //    }
234   //
235   //    /*
236   //     * @see TextViewer#customizeDocumentCommand(DocumentCommand)
237   //     */
238   //    protected void customizeDocumentCommand(DocumentCommand command) {
239   //      super.customizeDocumentCommand(command);
240   //      if (!fIgnoreTextConverters && fTextConverters != null) {
241   //        for (Iterator e = fTextConverters.iterator(); e.hasNext();)
242   //           ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
243   // command);
244   //      }
245   //      fIgnoreTextConverters = false;
246   //    }
247   //
248   //    public IVerticalRuler getVerticalRuler() {
249   //      return fCachedVerticalRuler;
250   //    }
251   //
252   //    public boolean isVerticalRulerVisible() {
253   //      return fCachedIsVerticalRulerVisible;
254   //    }
255   //
256   //    public OverviewRuler getOverviewRuler() {
257   //      return fOverviewRuler;
258   //    }
259   //
260   //    /*
261   //     * @see TextViewer#createControl(Composite, int)
262   //     */
263   //    protected void createControl(Composite parent, int styles) {
264   //      // do nothing here
265   //    }
266   //
267   //    protected void delayedCreateControl(Composite parent, int styles) {
268   //      //create the viewer
269   //      super.createControl(parent, styles);
270   //
271   //      Control control = getControl();
272   //      if (control instanceof Composite) {
273   //        Composite composite = (Composite) control;
274   //        composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
275   //        fOverviewRuler.createControl(composite, this);
276   //      }
277   //    }
278   //    protected void ensureOverviewHoverManagerInstalled() {
279   //      if (fOverviewRulerHoveringController == null && fAnnotationHover != null
280   // && fHoverControlCreator != null) {
281   //        fOverviewRulerHoveringController =
282   //          new OverviewRulerHoverManager(fOverviewRuler, this, fAnnotationHover,
283   // fHoverControlCreator);
284   //        fOverviewRulerHoveringController.install(fOverviewRuler.getControl());
285   //      }
286   //    }
287   //
288   //    public void hideOverviewRuler() {
289   //      fIsOverviewRulerVisible = false;
290   //      Control control = getControl();
291   //      if (control instanceof Composite) {
292   //        Composite composite = (Composite) control;
293   //        composite.layout();
294   //      }
295   //      if (fOverviewRulerHoveringController != null) {
296   //        fOverviewRulerHoveringController.dispose();
297   //        fOverviewRulerHoveringController = null;
298   //      }
299   //    }
300   //
301   //    public void showOverviewRuler() {
302   //      fIsOverviewRulerVisible = true;
303   //      Control control = getControl();
304   //      if (control instanceof Composite) {
305   //        Composite composite = (Composite) control;
306   //        composite.layout();
307   //      }
308   //      ensureOverviewHoverManagerInstalled();
309   //    }
310   //
311   //    public boolean isOverviewRulerVisible() {
312   //      return fIsOverviewRulerVisible;
313   //    }
314   //
315   //    /*
316   //     * @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
317   //     */
318   //    public void setDocument(
319   //      IDocument document,
320   //      IAnnotationModel annotationModel,
321   //      int visibleRegionOffset,
322   //      int visibleRegionLength) {
323   //      super.setDocument(document, annotationModel, visibleRegionOffset,
324   // visibleRegionLength);
325   //      fOverviewRuler.setModel(annotationModel);
326   //    }
327   //
328   //    // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
329   //    public void updateIndentationPrefixes() {
330   //      SourceViewerConfiguration configuration = getSourceViewerConfiguration();
331   //      String[] types = configuration.getConfiguredContentTypes(this);
332   //      for (int i = 0; i < types.length; i++) {
333   //        String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
334   //        if (prefixes != null && prefixes.length > 0)
335   //          setIndentPrefixes(prefixes, types[i]);
336   //      }
337   //    }
338   //
339   //    /*
340   //     * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
341   //     */
342   //    public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
343   //      if (WorkbenchHelp.isContextHelpDisplayed())
344   //        return false;
345   //      return super.requestWidgetToken(requester);
346   //    }
347   //
348   //    /*
349   //     * @see
350   // org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
351   //     */
352   //    public void configure(SourceViewerConfiguration configuration) {
353   //      super.configure(configuration);
354   //      // prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
355   // IDocument.DEFAULT_CONTENT_TYPE);
356   //    }
357   //
358   //    protected void handleDispose() {
359   //      fOverviewRuler = null;
360   //
361   //      if (fOverviewRulerHoveringController != null) {
362   //        fOverviewRulerHoveringController.dispose();
363   //        fOverviewRulerHoveringController = null;
364   //      }
365   //
366   //      super.handleDispose();
367   //    }
368   //
369   //  };
370   class AdaptedSourceViewer extends JavaSourceViewer {
371     private List fTextConverters;
372     private boolean fIgnoreTextConverters = false;
373     //                  private JavaCorrectionAssistant fCorrectionAssistant;
374     public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler,
375         IOverviewRuler overviewRuler, boolean showAnnotationsOverview,
376         int styles) {
377       super(parent, verticalRuler, overviewRuler, showAnnotationsOverview,
378           styles);
379     }
380     public IContentAssistant getContentAssistant() {
381       return fContentAssistant;
382     }
383     /*
384      * @see ITextOperationTarget#doOperation(int)
385      */
386     public void doOperation(int operation) {
387       if (getTextWidget() == null)
388         return;
389       switch (operation) {
390         case CONTENTASSIST_PROPOSALS :
391           String msg = fContentAssistant.showPossibleCompletions();
392           setStatusLineErrorMessage(msg);
393           return;
394         //                                      case CORRECTIONASSIST_PROPOSALS:
395         //                                              fCorrectionAssistant.showPossibleCompletions();
396         //                                              return;
397         case UNDO :
398           fIgnoreTextConverters = true;
399           break;
400         case REDO :
401           fIgnoreTextConverters = true;
402           break;
403       }
404       super.doOperation(operation);
405     }
406     /*
407      * @see ITextOperationTarget#canDoOperation(int)
408      */
409     public boolean canDoOperation(int operation) {
410       //                                if (operation == CORRECTIONASSIST_PROPOSALS)
411       //                                        return isEditable();
412       return super.canDoOperation(operation);
413     }
414     /*
415      * @see TextViewer#handleDispose()
416      */
417     protected void handleDispose() {
418       //                                if (fCorrectionAssistant != null) {
419       //                                        fCorrectionAssistant.uninstall();
420       //                                        fCorrectionAssistant= null;
421       //                                }
422       super.handleDispose();
423     }
424     public void insertTextConverter(ITextConverter textConverter, int index) {
425       throw new UnsupportedOperationException();
426     }
427     public void addTextConverter(ITextConverter textConverter) {
428       if (fTextConverters == null) {
429         fTextConverters = new ArrayList(1);
430         fTextConverters.add(textConverter);
431       } else if (!fTextConverters.contains(textConverter))
432         fTextConverters.add(textConverter);
433     }
434     public void removeTextConverter(ITextConverter textConverter) {
435       if (fTextConverters != null) {
436         fTextConverters.remove(textConverter);
437         if (fTextConverters.size() == 0)
438           fTextConverters = null;
439       }
440     }
441     /*
442      * @see TextViewer#customizeDocumentCommand(DocumentCommand)
443      */
444     protected void customizeDocumentCommand(DocumentCommand command) {
445       super.customizeDocumentCommand(command);
446       if (!fIgnoreTextConverters && fTextConverters != null) {
447         for (Iterator e = fTextConverters.iterator(); e.hasNext();)
448           ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(),
449               command);
450       }
451       fIgnoreTextConverters = false;
452     }
453     // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
454     public void updateIndentationPrefixes() {
455       SourceViewerConfiguration configuration = getSourceViewerConfiguration();
456       String[] types = configuration.getConfiguredContentTypes(this);
457       for (int i = 0; i < types.length; i++) {
458         String[] prefixes = configuration.getIndentPrefixes(this, types[i]);
459         if (prefixes != null && prefixes.length > 0)
460           setIndentPrefixes(prefixes, types[i]);
461       }
462     }
463     /*
464      * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
465      */
466     public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
467       if (WorkbenchHelp.isContextHelpDisplayed())
468         return false;
469       return super.requestWidgetToken(requester);
470     }
471     /*
472      * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
473      */
474     public void configure(SourceViewerConfiguration configuration) {
475       super.configure(configuration);
476       //                                fCorrectionAssistant= new
477       // JavaCorrectionAssistant(CompilationUnitEditor.this);
478       //                                fCorrectionAssistant.install(this);
479       //TODO install SmartBracesAutoEditStrategy
480       //                                prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this),
481       // IDocument.DEFAULT_CONTENT_TYPE);
482     }
483   };
484   static class TabConverter implements ITextConverter {
485     private int fTabRatio;
486     private ILineTracker fLineTracker;
487     public TabConverter() {
488     }
489     public void setNumberOfSpacesPerTab(int ratio) {
490       fTabRatio = ratio;
491     }
492     public void setLineTracker(ILineTracker lineTracker) {
493       fLineTracker = lineTracker;
494     }
495     private int insertTabString(StringBuffer buffer, int offsetInLine) {
496       if (fTabRatio == 0)
497         return 0;
498       int remainder = offsetInLine % fTabRatio;
499       remainder = fTabRatio - remainder;
500       for (int i = 0; i < remainder; i++)
501         buffer.append(' ');
502       return remainder;
503     }
504     public void customizeDocumentCommand(IDocument document,
505         DocumentCommand command) {
506       String text = command.text;
507       if (text == null)
508         return;
509       int index = text.indexOf('\t');
510       if (index > -1) {
511         StringBuffer buffer = new StringBuffer();
512         fLineTracker.set(command.text);
513         int lines = fLineTracker.getNumberOfLines();
514         try {
515           for (int i = 0; i < lines; i++) {
516             int offset = fLineTracker.getLineOffset(i);
517             int endOffset = offset + fLineTracker.getLineLength(i);
518             String line = text.substring(offset, endOffset);
519             int position = 0;
520             if (i == 0) {
521               IRegion firstLine = document
522                   .getLineInformationOfOffset(command.offset);
523               position = command.offset - firstLine.getOffset();
524             }
525             int length = line.length();
526             for (int j = 0; j < length; j++) {
527               char c = line.charAt(j);
528               if (c == '\t') {
529                 position += insertTabString(buffer, position);
530               } else {
531                 buffer.append(c);
532                 ++position;
533               }
534             }
535           }
536           command.text = buffer.toString();
537         } catch (BadLocationException x) {
538         }
539       }
540     }
541   };
542   private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
543     final char fExitCharacter;
544     public ExitPolicy(char exitCharacter) {
545       fExitCharacter = exitCharacter;
546     }
547     /*
548      * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionManager,
549      *      org.eclipse.swt.events.VerifyEvent, int, int)
550      */
551     public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event,
552         int offset, int length) {
553       if (event.character == fExitCharacter) {
554         if (manager.anyPositionIncludes(offset, length))
555           return new ExitFlags(LinkedPositionUI.COMMIT
556               | LinkedPositionUI.UPDATE_CARET, false);
557         else
558           return new ExitFlags(LinkedPositionUI.COMMIT, true);
559       }
560       switch (event.character) {
561         case '\b' :
562           if (manager.getFirstPosition().length == 0)
563             return new ExitFlags(0, false);
564           else
565             return null;
566         case '\n' :
567         case '\r' :
568           return new ExitFlags(LinkedPositionUI.COMMIT, true);
569         default :
570           return null;
571       }
572     }
573   }
574   private static class BracketLevel {
575     int fOffset;
576     int fLength;
577     LinkedPositionManager fManager;
578     LinkedPositionUI fEditor;
579   };
580   private class BracketInserter
581       implements
582         VerifyKeyListener,
583         LinkedPositionUI.ExitListener {
584     private boolean fCloseBracketsPHP = true;
585     private boolean fCloseStringsPHP = true;
586     private boolean fCloseBracketsHTML = true;
587     private boolean fCloseStringsHTML = true;
588     private int fOffset;
589     private int fLength;
590     public void setCloseBracketsPHPEnabled(boolean enabled) {
591       fCloseBracketsPHP = enabled;
592     }
593     public void setCloseStringsPHPEnabled(boolean enabled) {
594       fCloseStringsPHP = enabled;
595     }
596     public void setCloseBracketsHTMLEnabled(boolean enabled) {
597       fCloseBracketsHTML = enabled;
598     }
599     public void setCloseStringsHTMLEnabled(boolean enabled) {
600       fCloseStringsHTML = enabled;
601     }
602     private boolean hasIdentifierToTheRight(IDocument document, int offset) {
603       try {
604         int end = offset;
605         IRegion endLine = document.getLineInformationOfOffset(end);
606         int maxEnd = endLine.getOffset() + endLine.getLength();
607         while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
608           ++end;
609         return end != maxEnd
610             && Scanner.isPHPIdentifierPart(document.getChar(end));
611       } catch (BadLocationException e) {
612         // be conservative
613         return true;
614       }
615     }
616     private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
617       try {
618         int start = offset;
619         IRegion startLine = document.getLineInformationOfOffset(start);
620         int minStart = startLine.getOffset();
621         while (start != minStart
622             && Character.isWhitespace(document.getChar(start - 1)))
623           --start;
624         return start != minStart
625             && Scanner.isPHPIdentifierPart(document.getChar(start - 1));
626       } catch (BadLocationException e) {
627         return true;
628       }
629     }
630     private boolean hasCharacterToTheRight(IDocument document, int offset,
631         char character) {
632       try {
633         int end = offset;
634         IRegion endLine = document.getLineInformationOfOffset(end);
635         int maxEnd = endLine.getOffset() + endLine.getLength();
636         while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
637           ++end;
638         return end != maxEnd && document.getChar(end) == character;
639       } catch (BadLocationException e) {
640         // be conservative
641         return true;
642       }
643     }
644     /*
645      * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
646      */
647     public void verifyKey(VerifyEvent event) {
648       if (!event.doit)
649         return;
650       final ISourceViewer sourceViewer = getSourceViewer();
651       IDocument document = sourceViewer.getDocument();
652       final Point selection = sourceViewer.getSelectedRange();
653       final int offset = selection.x;
654       final int length = selection.y;
655       try {
656         ITypedRegion partition = document.getPartition(offset);
657         String type = partition.getType();
658         if (type.equals(IPHPPartitions.PHP_PARTITIONING)) {
659           switch (event.character) {
660             case '(' :
661               if (hasCharacterToTheRight(document, offset + length, '('))
662                 return;
663             // fall through
664             case '[' :
665               if (!fCloseBracketsPHP)
666                 return;
667               if (hasIdentifierToTheRight(document, offset + length))
668                 return;
669             // fall through
670             case '"' :
671               if (event.character == '"') {
672                 if (!fCloseStringsPHP)
673                   return;
674                 // changed for statements like echo "" print ""
675                 //    if (hasIdentifierToTheLeft(document, offset) ||
676                 // hasIdentifierToTheRight(document, offset + length))
677                 if (hasIdentifierToTheRight(document, offset + length))
678                   return;
679               }
680               //     ITypedRegion partition= document.getPartition(offset);
681               //       if (!
682               // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) &&
683               // (partition.getOffset() != offset))
684               //         return;
685               final char character = event.character;
686               final char closingCharacter = getPeerCharacter(character);
687               final StringBuffer buffer = new StringBuffer();
688               buffer.append(character);
689               buffer.append(closingCharacter);
690               document.replace(offset, length, buffer.toString());
691               LinkedPositionManager manager = new LinkedPositionManager(
692                   document);
693               manager.addPosition(offset + 1, 0);
694               fOffset = offset;
695               fLength = 2;
696               LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
697                   manager);
698               editor.setCancelListener(this);
699               editor.setExitPolicy(new ExitPolicy(closingCharacter));
700               editor.setFinalCaretOffset(offset + 2);
701               editor.enter();
702               IRegion newSelection = editor.getSelectedRegion();
703               sourceViewer.setSelectedRange(newSelection.getOffset(),
704                   newSelection.getLength());
705               event.doit = false;
706           }
707         } else if (type.equals(IPHPPartitions.HTML)
708             || type.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
709           switch (event.character) {
710             case '(' :
711               if (hasCharacterToTheRight(document, offset + length, '('))
712                 return;
713             // fall through
714             case '[' :
715               if (!fCloseBracketsHTML)
716                 return;
717               if (hasIdentifierToTheRight(document, offset + length))
718                 return;
719             // fall through
720             case '"' :
721               if (event.character == '"') {
722                 if (!fCloseStringsHTML)
723                   return;
724                 if (hasIdentifierToTheLeft(document, offset)
725                     || hasIdentifierToTheRight(document, offset + length))
726                   return;
727               }
728               //     ITypedRegion partition= document.getPartition(offset);
729               //       if (!
730               // IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) &&
731               // (partition.getOffset() != offset))
732               //         return;
733               final char character = event.character;
734               final char closingCharacter = getPeerCharacter(character);
735               final StringBuffer buffer = new StringBuffer();
736               buffer.append(character);
737               buffer.append(closingCharacter);
738               document.replace(offset, length, buffer.toString());
739               LinkedPositionManager manager = new LinkedPositionManager(
740                   document);
741               manager.addPosition(offset + 1, 0);
742               fOffset = offset;
743               fLength = 2;
744               LinkedPositionUI editor = new LinkedPositionUI(sourceViewer,
745                   manager);
746               editor.setCancelListener(this);
747               editor.setExitPolicy(new ExitPolicy(closingCharacter));
748               editor.setFinalCaretOffset(offset + 2);
749               editor.enter();
750               IRegion newSelection = editor.getSelectedRegion();
751               sourceViewer.setSelectedRange(newSelection.getOffset(),
752                   newSelection.getLength());
753               event.doit = false;
754           }
755         }
756       } catch (BadLocationException e) {
757       }
758     }
759     /*
760      * @see org.phpeclipse.phpdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
761      */
762     public void exit(boolean accept) {
763       if (accept)
764         return;
765       // remove brackets
766       try {
767         final ISourceViewer sourceViewer = getSourceViewer();
768         IDocument document = sourceViewer.getDocument();
769         document.replace(fOffset, fLength, null);
770       } catch (BadLocationException e) {
771       }
772     }
773   }
774   /** The editor's save policy */
775   protected ISavePolicy fSavePolicy;
776   /**
777    * Listener to annotation model changes that updates the error tick in the
778    * tab image
779    */
780   private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
781   /** The editor's paint manager */
782   //  private PaintManager fPaintManager;
783   /** The editor's bracket painter */
784   private BracketPainter fBracketPainter;
785   /** The editor's bracket matcher */
786   private PHPPairMatcher fBracketMatcher;
787   /** The editor's line painter */
788   private LinePainter fLinePainter;
789   /** The editor's print margin ruler painter */
790   private PrintMarginPainter fPrintMarginPainter;
791   /** The editor's problem painter */
792   //  private ProblemPainter fProblemPainter;
793   /** The editor's tab converter */
794   private TabConverter fTabConverter;
795   /** History for structure select action */
796   //private SelectionHistory fSelectionHistory;
797   /** The preference property change listener for php core. */
798   //  private IPropertyChangeListener fPropertyChangeListener = new
799   // PropertyChangeListener();
800   /** The remembered java element */
801   private IJavaElement fRememberedElement;
802   /** The remembered selection */
803   private ITextSelection fRememberedSelection;
804   /** The remembered php element offset */
805   private int fRememberedElementOffset;
806   /** The bracket inserter. */
807   private BracketInserter fBracketInserter = new BracketInserter();
808   
809   /** The standard action groups added to the menu */
810   private GenerateActionGroup fGenerateActionGroup;
811   private CompositeActionGroup fContextMenuGroup;
812   //  private class PropertyChangeListener implements IPropertyChangeListener {
813   //    /*
814   //     * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
815   //     */
816   //    public void
817   // propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
818   // event) {
819   //      handlePreferencePropertyChanged(event);
820   //    }
821   //  }
822   /* Preference key for code formatter tab size */
823   private final static String CODE_FORMATTER_TAB_SIZE = JavaCore.FORMATTER_TAB_SIZE;
824   /** Preference key for matching brackets */
825   private final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
826   /** Preference key for matching brackets color */
827   private final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
828   /** Preference key for highlighting current line */
829   private final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
830   /** Preference key for highlight color of current line */
831   private final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
832   /** Preference key for showing print marging ruler */
833   private final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
834   /** Preference key for print margin ruler color */
835   private final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
836   /** Preference key for print margin ruler column */
837   private final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
838   /** Preference key for inserting spaces rather than tabs */
839   private final static String SPACES_FOR_TABS = PreferenceConstants.EDITOR_SPACES_FOR_TABS;
840   /** Preference key for error indication */
841   //  private final static String ERROR_INDICATION =
842   // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
843   /** Preference key for error color */
844   //  private final static String ERROR_INDICATION_COLOR =
845   // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
846   /** Preference key for warning indication */
847   //  private final static String WARNING_INDICATION =
848   // PreferenceConstants.EDITOR_WARNING_INDICATION;
849   /** Preference key for warning color */
850   //  private final static String WARNING_INDICATION_COLOR =
851   // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
852   /** Preference key for task indication */
853   private final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
854   /** Preference key for task color */
855   private final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
856   /** Preference key for bookmark indication */
857   private final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
858   /** Preference key for bookmark color */
859   private final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
860   /** Preference key for search result indication */
861   private final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
862   /** Preference key for search result color */
863   private final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
864   /** Preference key for unknown annotation indication */
865   private final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
866   /** Preference key for unknown annotation color */
867   private final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
868   /** Preference key for linked position color */
869   private final static String LINKED_POSITION_COLOR = PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
870   /** Preference key for shwoing the overview ruler */
871   private final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
872   /** Preference key for error indication in overview ruler */
873   private final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
874   /** Preference key for warning indication in overview ruler */
875   private final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
876   /** Preference key for task indication in overview ruler */
877   private final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
878   /** Preference key for bookmark indication in overview ruler */
879   private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
880   /** Preference key for search result indication in overview ruler */
881   private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
882   /** Preference key for unknown annotation indication in overview ruler */
883   private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
884   /** Preference key for automatically closing strings */
885   private final static String CLOSE_STRINGS_PHP = PreferenceConstants.EDITOR_CLOSE_STRINGS_PHP;
886   /** Preference key for automatically wrapping Java strings */
887   private final static String WRAP_STRINGS = PreferenceConstants.EDITOR_WRAP_STRINGS;
888   /** Preference key for automatically closing brackets and parenthesis */
889   private final static String CLOSE_BRACKETS_PHP = PreferenceConstants.EDITOR_CLOSE_BRACKETS_PHP;
890   /** Preference key for automatically closing phpdocs and comments */
891   private final static String CLOSE_JAVADOCS = PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
892   /** Preference key for automatically adding phpdoc tags */
893   private final static String ADD_JAVADOC_TAGS = PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
894   /** Preference key for automatically formatting phpdocs */
895   private final static String FORMAT_JAVADOCS = PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
896   /** Preference key for automatically closing strings */
897   private final static String CLOSE_STRINGS_HTML = PreferenceConstants.EDITOR_CLOSE_STRINGS_HTML;
898   /** Preference key for automatically closing brackets and parenthesis */
899   private final static String CLOSE_BRACKETS_HTML = PreferenceConstants.EDITOR_CLOSE_BRACKETS_HTML;
900   /** Preference key for smart paste */
901   private final static String SMART_PASTE = PreferenceConstants.EDITOR_SMART_PASTE;
902   //  private final static class AnnotationInfo {
903   //    public String fColorPreference;
904   //    public String fOverviewRulerPreference;
905   //    public String fEditorPreference;
906   //  };
907   //  private final static Map ANNOTATION_MAP;
908   //  static {
909   //
910   //    AnnotationInfo info;
911   //    ANNOTATION_MAP = new HashMap();
912   //
913   //    info = new AnnotationInfo();
914   //    info.fColorPreference = TASK_INDICATION_COLOR;
915   //    info.fOverviewRulerPreference = TASK_INDICATION_IN_OVERVIEW_RULER;
916   //    info.fEditorPreference = TASK_INDICATION;
917   //    ANNOTATION_MAP.put(AnnotationType.TASK, info);
918   //
919   //    info = new AnnotationInfo();
920   //    info.fColorPreference = ERROR_INDICATION_COLOR;
921   //    info.fOverviewRulerPreference = ERROR_INDICATION_IN_OVERVIEW_RULER;
922   //    info.fEditorPreference = ERROR_INDICATION;
923   //    ANNOTATION_MAP.put(AnnotationType.ERROR, info);
924   //
925   //    info = new AnnotationInfo();
926   //    info.fColorPreference = WARNING_INDICATION_COLOR;
927   //    info.fOverviewRulerPreference = WARNING_INDICATION_IN_OVERVIEW_RULER;
928   //    info.fEditorPreference = WARNING_INDICATION;
929   //    ANNOTATION_MAP.put(AnnotationType.WARNING, info);
930   //
931   //    info = new AnnotationInfo();
932   //    info.fColorPreference = BOOKMARK_INDICATION_COLOR;
933   //    info.fOverviewRulerPreference = BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
934   //    info.fEditorPreference = BOOKMARK_INDICATION;
935   //    ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
936   //
937   //    info = new AnnotationInfo();
938   //    info.fColorPreference = SEARCH_RESULT_INDICATION_COLOR;
939   //    info.fOverviewRulerPreference =
940   // SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
941   //    info.fEditorPreference = SEARCH_RESULT_INDICATION;
942   //    ANNOTATION_MAP.put(AnnotationType.SEARCH, info);
943   //
944   //    info = new AnnotationInfo();
945   //    info.fColorPreference = UNKNOWN_INDICATION_COLOR;
946   //    info.fOverviewRulerPreference = UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
947   //    info.fEditorPreference = UNKNOWN_INDICATION;
948   //    ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
949   //  };
950   //
951   //  private final static AnnotationType[] ANNOTATION_LAYERS =
952   //    new AnnotationType[] {
953   //      AnnotationType.UNKNOWN,
954   //      AnnotationType.BOOKMARK,
955   //      AnnotationType.TASK,
956   //      AnnotationType.SEARCH,
957   //      AnnotationType.WARNING,
958   //      AnnotationType.ERROR };
959   /**
960    * Creates a new php unit editor.
961    */
962   public PHPUnitEditor() {
963     super();
964     setDocumentProvider(PHPeclipsePlugin.getDefault()
965         .getCompilationUnitDocumentProvider());
966     setEditorContextMenuId("#PHPEditorContext"); //$NON-NLS-1$
967     setRulerContextMenuId("#PHPRulerContext"); //$NON-NLS-1$
968     setOutlinerContextMenuId("#PHPOutlinerContext"); //$NON-NLS-1$
969     // don't set help contextId, we install our own help context
970     fSavePolicy = null;
971     fJavaEditorErrorTickUpdater = new JavaEditorErrorTickUpdater(this);
972   }
973   /*
974    * @see AbstractTextEditor#createActions()
975    */
976   protected void createActions() {
977     super.createActions();
978     Action action;
979     //          Action action= new
980     // TextOperationAction(PHPEditorMessages.getResourceBundle(),
981     // "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS);
982     // //$NON-NLS-1$
983     //          action.setActionDefinitionId(PHPEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
984     //          setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
985     //          markAsStateDependentAction("CorrectionAssistProposal", true);
986     // //$NON-NLS-1$
987     //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION);
988     action = new ContentAssistAction(PHPEditorMessages.getResourceBundle(), 
989         "ContentAssistProposal.", this); //$NON-NLS-1$
990     action
991         .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
992     setAction("ContentAssistProposal", action); //$NON-NLS-1$
993     markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
994     //          WorkbenchHelp.setHelp(action,
995     // IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
996     action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
997         "ContentAssistContextInformation.", this,
998         ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
999     action
1000         .setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
1001     setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
1002     markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
1003     //          WorkbenchHelp.setHelp(action,
1004     // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1005     //          action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1006     // "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX);
1007     // //$NON-NLS-1$
1008     //          action.setActionDefinitionId(PHPEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
1009     //          setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
1010     //          markAsStateDependentAction("ContentAssistCompletePrefix", true);
1011     // //$NON-NLS-1$
1012     //// WorkbenchHelp.setHelp(action,
1013     // IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
1014     action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1015         "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
1016     action.setActionDefinitionId(PHPEditorActionDefinitionIds.COMMENT);
1017     setAction("Comment", action); //$NON-NLS-1$
1018     markAsStateDependentAction("Comment", true); //$NON-NLS-1$
1019     //          WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
1020     action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1021         "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
1022     action.setActionDefinitionId(PHPEditorActionDefinitionIds.UNCOMMENT);
1023     setAction("Uncomment", action); //$NON-NLS-1$
1024     markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
1025     //          WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
1026     action = new ToggleCommentAction(PHPEditorMessages.getResourceBundle(),
1027         "ToggleComment.", this, getSourceViewerConfiguration()
1028             .getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$ //$NON-NLS-2$
1029     action.setActionDefinitionId(PHPEditorActionDefinitionIds.TOGGLE_COMMENT);
1030     setAction("ToggleComment", action); //$NON-NLS-1$
1031     markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$
1032     //          WorkbenchHelp.setHelp(action,
1033     // IJavaHelpContextIds.TOGGLE_COMMENT_ACTION);
1034     action = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
1035         "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
1036     action.setActionDefinitionId(PHPEditorActionDefinitionIds.FORMAT);
1037     setAction("Format", action); //$NON-NLS-1$
1038     markAsStateDependentAction("Format", true); //$NON-NLS-1$
1039     markAsSelectionDependentAction("Format", true); //$NON-NLS-1$               
1040     //          WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
1041     action = new AddBlockCommentAction(PHPEditorMessages.getResourceBundle(),
1042         "AddBlockComment.", this); //$NON-NLS-1$
1043     action
1044         .setActionDefinitionId(PHPEditorActionDefinitionIds.ADD_BLOCK_COMMENT);
1045     setAction("AddBlockComment", action); //$NON-NLS-1$
1046     markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$
1047     markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$              
1048     //          WorkbenchHelp.setHelp(action,
1049     // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1050     action = new RemoveBlockCommentAction(
1051         PHPEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$
1052     action
1053         .setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT);
1054     setAction("RemoveBlockComment", action); //$NON-NLS-1$
1055     markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$
1056     markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$           
1057     //          WorkbenchHelp.setHelp(action,
1058     // IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION);
1059     //          action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1060     // "Indent.", this, false); //$NON-NLS-1$
1061     //          action.setActionDefinitionId(PHPEditorActionDefinitionIds.INDENT);
1062     //          setAction("Indent", action); //$NON-NLS-1$
1063     //          markAsStateDependentAction("Indent", true); //$NON-NLS-1$
1064     //          markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$
1065     //// WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION);
1066     //          
1067     //          action= new IndentAction(PHPEditorMessages.getResourceBundle(),
1068     // "Indent.", this, true); //$NON-NLS-1$
1069     //          setAction("IndentOnTab", action); //$NON-NLS-1$
1070     //          markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$
1071     //          markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$
1072     //          
1073     if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) {
1074       // don't replace Shift Right - have to make sure their enablement is
1075       // mutually exclusive
1076       //                        removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT);
1077       setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$
1078     }
1079     fGenerateActionGroup = new GenerateActionGroup(this,
1080         ITextEditorActionConstants.GROUP_EDIT);
1081     fActionGroups = new CompositeActionGroup(
1082         new ActionGroup[]{fGenerateActionGroup});
1083     //    We have to keep the context menu group separate to have better control
1084     // over positioning
1085     fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup });
1086     //      rg, 
1087     //      new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
1088     
1089   }
1090   /*
1091    * @see JavaEditor#getElementAt(int)
1092    */
1093   protected IJavaElement getElementAt(int offset) {
1094     return getElementAt(offset, true);
1095   }
1096   /**
1097    * Returns the most narrow element including the given offset. If <code>reconcile</code>
1098    * is <code>true</code> the editor's input element is reconciled in
1099    * advance. If it is <code>false</code> this method only returns a result
1100    * if the editor's input element does not need to be reconciled.
1101    * 
1102    * @param offset
1103    *            the offset included by the retrieved element
1104    * @param reconcile
1105    *            <code>true</code> if working copy should be reconciled
1106    */
1107   protected IJavaElement getElementAt(int offset, boolean reconcile) {
1108     IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1109         .getWorkingCopyManager();
1110     ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1111     if (unit != null) {
1112       try {
1113         if (reconcile) {
1114           synchronized (unit) {
1115             unit.reconcile();
1116           }
1117           return unit.getElementAt(offset);
1118         } else if (unit.isConsistent())
1119           return unit.getElementAt(offset);
1120       } catch (JavaModelException x) {
1121         PHPeclipsePlugin.log(x.getStatus());
1122         // nothing found, be tolerant and go on
1123       }
1124     }
1125     return null;
1126   }
1127   /*
1128    * @see JavaEditor#getCorrespondingElement(IJavaElement)
1129    */
1130   protected IJavaElement getCorrespondingElement(IJavaElement element) {
1131     try {
1132       return EditorUtility.getWorkingCopy(element, true);
1133     } catch (JavaModelException x) {
1134       PHPeclipsePlugin.log(x.getStatus());
1135       // nothing found, be tolerant and go on
1136     }
1137     return null;
1138   }
1139   public void createPartControl(Composite parent) {
1140     super.createPartControl(parent);
1141     //    fPaintManager = new PaintManager(getSourceViewer());
1142     LinePainter linePainter;
1143     linePainter = new LinePainter(getSourceViewer());
1144     linePainter
1145         .setHighlightColor(new Color(Display.getCurrent(), 225, 235, 224));
1146     //    fPaintManager.addPainter(linePainter);
1147     if (isBracketHighlightingEnabled())
1148       startBracketHighlighting();
1149     if (isLineHighlightingEnabled())
1150       startLineHighlighting();
1151     if (isPrintMarginVisible())
1152       showPrintMargin();
1153     //    Iterator e = ANNOTATION_MAP.keySet().iterator();
1154     //    while (e.hasNext()) {
1155     //      AnnotationType type = (AnnotationType) e.next();
1156     //      if (isAnnotationIndicationEnabled(type))
1157     //        startAnnotationIndication(type);
1158     //    }
1159     if (isTabConversionEnabled())
1160       startTabConversion();
1161     //    if (isOverviewRulerVisible())
1162     //      showOverviewRuler();
1163     //
1164     //    Preferences preferences =
1165     // PHPeclipsePlugin.getDefault().getPluginPreferences();
1166     //    preferences.addPropertyChangeListener(fPropertyChangeListener);
1167     IPreferenceStore preferenceStore = getPreferenceStore();
1168     boolean closeBracketsPHP = preferenceStore.getBoolean(CLOSE_BRACKETS_PHP);
1169     boolean closeStringsPHP = preferenceStore.getBoolean(CLOSE_STRINGS_PHP);
1170     boolean closeBracketsHTML = preferenceStore.getBoolean(CLOSE_BRACKETS_HTML);
1171     boolean closeStringsHTML = preferenceStore.getBoolean(CLOSE_STRINGS_HTML);
1172     fBracketInserter.setCloseBracketsPHPEnabled(closeBracketsPHP);
1173     fBracketInserter.setCloseStringsPHPEnabled(closeStringsPHP);
1174     fBracketInserter.setCloseBracketsHTMLEnabled(closeBracketsHTML);
1175     fBracketInserter.setCloseStringsHTMLEnabled(closeStringsHTML);
1176     ISourceViewer sourceViewer = getSourceViewer();
1177     if (sourceViewer instanceof ITextViewerExtension)
1178       ((ITextViewerExtension) sourceViewer)
1179           .prependVerifyKeyListener(fBracketInserter);
1180   }
1181   private static char getPeerCharacter(char character) {
1182     switch (character) {
1183       case '(' :
1184         return ')';
1185       case ')' :
1186         return '(';
1187       case '[' :
1188         return ']';
1189       case ']' :
1190         return '[';
1191       case '"' :
1192         return character;
1193       default :
1194         throw new IllegalArgumentException();
1195     }
1196   }
1197   /**
1198    * The compilation unit editor implementation of this <code>AbstractTextEditor</code>
1199    * method asks the user for the workspace path of a file resource and saves
1200    * the document there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
1201    */
1202   protected void performSaveAs(IProgressMonitor progressMonitor) {
1203     Shell shell = getSite().getShell();
1204     IEditorInput input = getEditorInput();
1205     SaveAsDialog dialog = new SaveAsDialog(shell);
1206     IFile original = (input instanceof IFileEditorInput)
1207         ? ((IFileEditorInput) input).getFile()
1208         : null;
1209     if (original != null)
1210       dialog.setOriginalFile(original);
1211     dialog.create();
1212     IDocumentProvider provider = getDocumentProvider();
1213     if (provider == null) {
1214       // editor has been programmatically closed while the dialog was open
1215       return;
1216     }
1217     if (provider.isDeleted(input) && original != null) {
1218       String message = PHPEditorMessages.getFormattedString(
1219           "CompilationUnitEditor.warning.save.delete", new Object[]{original
1220               .getName()}); //$NON-NLS-1$
1221       dialog.setErrorMessage(null);
1222       dialog.setMessage(message, IMessageProvider.WARNING);
1223     }
1224     if (dialog.open() == Dialog.CANCEL) {
1225       if (progressMonitor != null)
1226         progressMonitor.setCanceled(true);
1227       return;
1228     }
1229     IPath filePath = dialog.getResult();
1230     if (filePath == null) {
1231       if (progressMonitor != null)
1232         progressMonitor.setCanceled(true);
1233       return;
1234     }
1235     IWorkspace workspace = ResourcesPlugin.getWorkspace();
1236     IFile file = workspace.getRoot().getFile(filePath);
1237     final IEditorInput newInput = new FileEditorInput(file);
1238     WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
1239       public void execute(final IProgressMonitor monitor) throws CoreException {
1240         getDocumentProvider().saveDocument(monitor, newInput,
1241             getDocumentProvider().getDocument(getEditorInput()), true);
1242       }
1243     };
1244     boolean success = false;
1245     try {
1246       provider.aboutToChange(newInput);
1247       new ProgressMonitorDialog(shell).run(false, true, op);
1248       success = true;
1249     } catch (InterruptedException x) {
1250     } catch (InvocationTargetException x) {
1251       Throwable t = x.getTargetException();
1252       if (t instanceof CoreException) {
1253         CoreException cx = (CoreException) t;
1254         ErrorDialog.openError(shell, PHPEditorMessages
1255             .getString("CompilationUnitEditor.error.saving.title2"),
1256             PHPEditorMessages
1257                 .getString("CompilationUnitEditor.error.saving.message2"), cx
1258                 .getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
1259       } else {
1260         MessageDialog.openError(shell, PHPEditorMessages
1261             .getString("CompilationUnitEditor.error.saving.title3"),
1262             PHPEditorMessages
1263                 .getString("CompilationUnitEditor.error.saving.message3")
1264                 + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
1265       }
1266     } finally {
1267       provider.changed(newInput);
1268       if (success)
1269         setInput(newInput);
1270     }
1271     if (progressMonitor != null)
1272       progressMonitor.setCanceled(!success);
1273   }
1274   /*
1275    * @see AbstractTextEditor#doSetInput(IEditorInput)
1276    */
1277   protected void doSetInput(IEditorInput input) throws CoreException {
1278     super.doSetInput(input);
1279     configureTabConverter();
1280   }
1281   private void startBracketHighlighting() {
1282     if (fBracketPainter == null) {
1283       ISourceViewer sourceViewer = getSourceViewer();
1284       fBracketPainter = new BracketPainter(sourceViewer);
1285       fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1286       //      fPaintManager.addPainter(fBracketPainter);
1287     }
1288   }
1289   private void stopBracketHighlighting() {
1290     if (fBracketPainter != null) {
1291       //      fPaintManager.removePainter(fBracketPainter);
1292       fBracketPainter.deactivate(true);
1293       fBracketPainter.dispose();
1294       fBracketPainter = null;
1295     }
1296   }
1297   private boolean isBracketHighlightingEnabled() {
1298     IPreferenceStore store = getPreferenceStore();
1299     return store.getBoolean(MATCHING_BRACKETS);
1300   }
1301   private void startLineHighlighting() {
1302     if (fLinePainter == null) {
1303       ISourceViewer sourceViewer = getSourceViewer();
1304       fLinePainter = new LinePainter(sourceViewer);
1305       fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
1306       //      fPaintManager.addPainter(fLinePainter);
1307     }
1308   }
1309   private void stopLineHighlighting() {
1310     if (fLinePainter != null) {
1311       //      fPaintManager.removePainter(fLinePainter);
1312       fLinePainter.deactivate(true);
1313       fLinePainter.dispose();
1314       fLinePainter = null;
1315     }
1316   }
1317   private boolean isLineHighlightingEnabled() {
1318     IPreferenceStore store = getPreferenceStore();
1319     return store.getBoolean(CURRENT_LINE);
1320   }
1321   private void showPrintMargin() {
1322     if (fPrintMarginPainter == null) {
1323       fPrintMarginPainter = new PrintMarginPainter(getSourceViewer());
1324       fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1325       fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(
1326           PRINT_MARGIN_COLUMN));
1327       //      fPaintManager.addPainter(fPrintMarginPainter);
1328     }
1329   }
1330   private void hidePrintMargin() {
1331     if (fPrintMarginPainter != null) {
1332       //      fPaintManager.removePainter(fPrintMarginPainter);
1333       fPrintMarginPainter.deactivate(true);
1334       fPrintMarginPainter.dispose();
1335       fPrintMarginPainter = null;
1336     }
1337   }
1338   private boolean isPrintMarginVisible() {
1339     IPreferenceStore store = getPreferenceStore();
1340     return store.getBoolean(PRINT_MARGIN);
1341   }
1342   //  private void startAnnotationIndication(AnnotationType annotationType) {
1343   //    if (fProblemPainter == null) {
1344   //      fProblemPainter = new ProblemPainter(this, getSourceViewer());
1345   //// fPaintManager.addPainter(fProblemPainter);
1346   //    }
1347   //    fProblemPainter.setColor(annotationType, getColor(annotationType));
1348   //    fProblemPainter.paintAnnotations(annotationType, true);
1349   //    fProblemPainter.paint(IPainter.CONFIGURATION);
1350   //  }
1351   //
1352   //  private void shutdownAnnotationIndication() {
1353   //    if (fProblemPainter != null) {
1354   //
1355   //      if (!fProblemPainter.isPaintingAnnotations()) {
1356   //// fPaintManager.removePainter(fProblemPainter);
1357   //        fProblemPainter.deactivate(true);
1358   //        fProblemPainter.dispose();
1359   //        fProblemPainter = null;
1360   //      } else {
1361   //        fProblemPainter.paint(IPainter.CONFIGURATION);
1362   //      }
1363   //    }
1364   //  }
1365   //
1366   //  private void stopAnnotationIndication(AnnotationType annotationType) {
1367   //    if (fProblemPainter != null) {
1368   //      fProblemPainter.paintAnnotations(annotationType, false);
1369   //      shutdownAnnotationIndication();
1370   //    }
1371   //  }
1372   //
1373   //  private boolean isAnnotationIndicationEnabled(AnnotationType
1374   // annotationType) {
1375   //    IPreferenceStore store = getPreferenceStore();
1376   //    AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
1377   //    if (info != null)
1378   //      return store.getBoolean(info.fEditorPreference);
1379   //    return false;
1380   //  }
1381   //
1382   //  private boolean
1383   // isAnnotationIndicationInOverviewRulerEnabled(AnnotationType
1384   // annotationType) {
1385   //    IPreferenceStore store = getPreferenceStore();
1386   //    AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
1387   //    if (info != null)
1388   //      return store.getBoolean(info.fOverviewRulerPreference);
1389   //    return false;
1390   //  }
1391   //
1392   //  private void showAnnotationIndicationInOverviewRuler(AnnotationType
1393   // annotationType, boolean show) {
1394   //    AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1395   //    OverviewRuler ruler = asv.getOverviewRuler();
1396   //    if (ruler != null) {
1397   //      ruler.setColor(annotationType, getColor(annotationType));
1398   //      ruler.showAnnotation(annotationType, show);
1399   //      ruler.update();
1400   //    }
1401   //  }
1402   //
1403   //  private void setColorInOverviewRuler(AnnotationType annotationType, Color
1404   // color) {
1405   //    AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1406   //    OverviewRuler ruler = asv.getOverviewRuler();
1407   //    if (ruler != null) {
1408   //      ruler.setColor(annotationType, color);
1409   //      ruler.update();
1410   //    }
1411   //  }
1412   private void configureTabConverter() {
1413     if (fTabConverter != null) {
1414       IDocumentProvider provider = getDocumentProvider();
1415       if (provider instanceof PHPDocumentProvider) {
1416         PHPDocumentProvider cup = (PHPDocumentProvider) provider;
1417         fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
1418       }
1419     }
1420   }
1421   private int getTabSize() {
1422     Preferences preferences = PHPeclipsePlugin.getDefault()
1423         .getPluginPreferences();
1424     return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
1425   }
1426   private void startTabConversion() {
1427     if (fTabConverter == null) {
1428       fTabConverter = new TabConverter();
1429       configureTabConverter();
1430       fTabConverter.setNumberOfSpacesPerTab(getTabSize());
1431       AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1432       asv.addTextConverter(fTabConverter);
1433       // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
1434       asv.updateIndentationPrefixes();
1435     }
1436   }
1437   private void stopTabConversion() {
1438     if (fTabConverter != null) {
1439       AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1440       asv.removeTextConverter(fTabConverter);
1441       // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
1442       asv.updateIndentationPrefixes();
1443       fTabConverter = null;
1444     }
1445   }
1446   private boolean isTabConversionEnabled() {
1447     IPreferenceStore store = getPreferenceStore();
1448     return store.getBoolean(SPACES_FOR_TABS);
1449   }
1450   //  private void showOverviewRuler() {
1451   //    AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1452   //    asv.showOverviewRuler();
1453   //
1454   //    OverviewRuler overviewRuler = asv.getOverviewRuler();
1455   //    if (overviewRuler != null) {
1456   //      for (int i = 0; i < ANNOTATION_LAYERS.length; i++) {
1457   //        AnnotationType type = ANNOTATION_LAYERS[i];
1458   //        overviewRuler.setLayer(type, i);
1459   //        if (isAnnotationIndicationInOverviewRulerEnabled(type))
1460   //          showAnnotationIndicationInOverviewRuler(type, true);
1461   //      }
1462   //    }
1463   //  }
1464   //
1465   //  private void hideOverviewRuler() {
1466   //    AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1467   //    asv.hideOverviewRuler();
1468   //  }
1469   //
1470   //  private boolean isOverviewRulerVisible() {
1471   //    IPreferenceStore store = getPreferenceStore();
1472   //    return store.getBoolean(OVERVIEW_RULER);
1473   //  }
1474   private Color getColor(String key) {
1475     RGB rgb = PreferenceConverter.getColor(getPreferenceStore(), key);
1476     return getColor(rgb);
1477   }
1478   private Color getColor(RGB rgb) {
1479     JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1480     return textTools.getColorManager().getColor(rgb);
1481   }
1482   //  private Color getColor(AnnotationType annotationType) {
1483   //    AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
1484   //    if (info != null)
1485   //      return getColor(info.fColorPreference);
1486   //    return null;
1487   //  }
1488   public void dispose() {
1489     ISourceViewer sourceViewer = getSourceViewer();
1490     if (sourceViewer instanceof ITextViewerExtension)
1491       ((ITextViewerExtension) sourceViewer)
1492           .removeVerifyKeyListener(fBracketInserter);
1493     //    if (fPropertyChangeListener != null) {
1494     //      Preferences preferences =
1495     // PHPeclipsePlugin.getDefault().getPluginPreferences();
1496     //      preferences.removePropertyChangeListener(fPropertyChangeListener);
1497     //      fPropertyChangeListener = null;
1498     //    }
1499     if (fJavaEditorErrorTickUpdater != null) {
1500       fJavaEditorErrorTickUpdater.dispose();
1501       fJavaEditorErrorTickUpdater = null;
1502     }
1503     //    if (fSelectionHistory != null)
1504     //      fSelectionHistory.dispose();
1505     //    if (fPaintManager != null) {
1506     //      fPaintManager.dispose();
1507     //      fPaintManager = null;
1508     //    }
1509     if (fActionGroups != null) {
1510       fActionGroups.dispose();
1511       fActionGroups = null;
1512     }
1513     super.dispose();
1514   }
1515   //  protected AnnotationType getAnnotationType(String preferenceKey) {
1516   //    Iterator e = ANNOTATION_MAP.keySet().iterator();
1517   //    while (e.hasNext()) {
1518   //      AnnotationType type = (AnnotationType) e.next();
1519   //      AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1520   //      if (info != null) {
1521   //        if (preferenceKey.equals(info.fColorPreference)
1522   //          || preferenceKey.equals(info.fEditorPreference)
1523   //          || preferenceKey.equals(info.fOverviewRulerPreference))
1524   //          return type;
1525   //      }
1526   //    }
1527   //    return null;
1528   //  }
1529   /*
1530    * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1531    */
1532   protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1533     try {
1534       AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1535       if (asv != null) {
1536         String p = event.getProperty();
1537         if (CLOSE_BRACKETS_PHP.equals(p)) {
1538           fBracketInserter.setCloseBracketsPHPEnabled(getPreferenceStore()
1539               .getBoolean(p));
1540           return;
1541         }
1542         if (CLOSE_STRINGS_PHP.equals(p)) {
1543           fBracketInserter.setCloseStringsPHPEnabled(getPreferenceStore()
1544               .getBoolean(p));
1545           return;
1546         }
1547         if (CLOSE_BRACKETS_HTML.equals(p)) {
1548           fBracketInserter.setCloseBracketsHTMLEnabled(getPreferenceStore()
1549               .getBoolean(p));
1550           return;
1551         }
1552         if (CLOSE_STRINGS_HTML.equals(p)) {
1553           fBracketInserter.setCloseStringsHTMLEnabled(getPreferenceStore()
1554               .getBoolean(p));
1555           return;
1556         }
1557         if (SPACES_FOR_TABS.equals(p)) {
1558           if (isTabConversionEnabled())
1559             startTabConversion();
1560           else
1561             stopTabConversion();
1562           return;
1563         }
1564         if (MATCHING_BRACKETS.equals(p)) {
1565           if (isBracketHighlightingEnabled())
1566             startBracketHighlighting();
1567           else
1568             stopBracketHighlighting();
1569           return;
1570         }
1571         if (MATCHING_BRACKETS_COLOR.equals(p)) {
1572           if (fBracketPainter != null)
1573             fBracketPainter
1574                 .setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
1575           return;
1576         }
1577         if (CURRENT_LINE.equals(p)) {
1578           if (isLineHighlightingEnabled())
1579             startLineHighlighting();
1580           else
1581             stopLineHighlighting();
1582           return;
1583         }
1584         if (CURRENT_LINE_COLOR.equals(p)) {
1585           if (fLinePainter != null) {
1586             stopLineHighlighting();
1587             startLineHighlighting();
1588           }
1589           return;
1590         }
1591         if (PRINT_MARGIN.equals(p)) {
1592           if (isPrintMarginVisible())
1593             showPrintMargin();
1594           else
1595             hidePrintMargin();
1596           return;
1597         }
1598         if (PRINT_MARGIN_COLOR.equals(p)) {
1599           if (fPrintMarginPainter != null)
1600             fPrintMarginPainter
1601                 .setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
1602           return;
1603         }
1604         if (PRINT_MARGIN_COLUMN.equals(p)) {
1605           if (fPrintMarginPainter != null)
1606             fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore()
1607                 .getInt(PRINT_MARGIN_COLUMN));
1608           return;
1609         }
1610         //        if (OVERVIEW_RULER.equals(p)) {
1611         //          if (isOverviewRulerVisible())
1612         //            showOverviewRuler();
1613         //          else
1614         //            hideOverviewRuler();
1615         //          return;
1616         //        }
1617         //        AnnotationType type = getAnnotationType(p);
1618         //        if (type != null) {
1619         //
1620         //          AnnotationInfo info = (AnnotationInfo) ANNOTATION_MAP.get(type);
1621         //          if (info.fColorPreference.equals(p)) {
1622         //            Color color = getColor(type);
1623         //            if (fProblemPainter != null) {
1624         //              fProblemPainter.setColor(type, color);
1625         //              fProblemPainter.paint(IPainter.CONFIGURATION);
1626         //            }
1627         //            setColorInOverviewRuler(type, color);
1628         //            return;
1629         //          }
1630         //
1631         //          if (info.fEditorPreference.equals(p)) {
1632         //            if (isAnnotationIndicationEnabled(type))
1633         //              startAnnotationIndication(type);
1634         //            else
1635         //              stopAnnotationIndication(type);
1636         //            return;
1637         //          }
1638         //
1639         //          if (info.fOverviewRulerPreference.equals(p)) {
1640         //            if (isAnnotationIndicationInOverviewRulerEnabled(type))
1641         //              showAnnotationIndicationInOverviewRuler(type, true);
1642         //            else
1643         //              showAnnotationIndicationInOverviewRuler(type, false);
1644         //            return;
1645         //          }
1646         //        }
1647         IContentAssistant c = asv.getContentAssistant();
1648         if (c instanceof ContentAssistant)
1649           ContentAssistPreference.changeConfiguration((ContentAssistant) c,
1650               getPreferenceStore(), event);
1651       }
1652     } finally {
1653       super.handlePreferenceStoreChanged(event);
1654     }
1655   }
1656   /*
1657    * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
1658    */
1659   protected void handlePreferencePropertyChanged(
1660       org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
1661     AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1662     if (asv != null) {
1663       String p = event.getProperty();
1664       if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
1665         asv.updateIndentationPrefixes();
1666         if (fTabConverter != null)
1667           fTabConverter.setNumberOfSpacesPerTab(getTabSize());
1668       }
1669     }
1670     super.handlePreferencePropertyChanged(event);
1671   }
1672   /**
1673    * Handles a property change event describing a change of the php core's
1674    * preferences and updates the preference related editor properties.
1675    * 
1676    * @param event
1677    *            the property change event
1678    */
1679   //  protected void
1680   // handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent
1681   // event) {
1682   //    AdaptedSourceViewer asv = (AdaptedSourceViewer) getSourceViewer();
1683   //    if (asv != null) {
1684   //      String p = event.getProperty();
1685   //      if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
1686   //        asv.updateIndentationPrefixes();
1687   //        if (fTabConverter != null)
1688   //          fTabConverter.setNumberOfSpacesPerTab(getTabSize());
1689   //      }
1690   //    }
1691   //  }
1692   /*
1693    * @see PHPEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
1694    */
1695   protected ISourceViewer createJavaSourceViewer(Composite parent,
1696       IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
1697       boolean isOverviewRulerVisible, int styles) {
1698     return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler,
1699         isOverviewRulerVisible, styles);
1700   }
1701   //  protected ISourceViewer createJavaSourceViewer(Composite parent,
1702   // IVerticalRuler ruler, int styles) {
1703   //    return new AdaptedSourceViewer(parent, ruler, styles);
1704   //  }
1705   private boolean isValidSelection(int offset, int length) {
1706     IDocumentProvider provider = getDocumentProvider();
1707     if (provider != null) {
1708       IDocument document = provider.getDocument(getEditorInput());
1709       if (document != null) {
1710         int end = offset + length;
1711         int documentLength = document.getLength();
1712         return 0 <= offset && offset <= documentLength && 0 <= end
1713             && end <= documentLength;
1714       }
1715     }
1716     return false;
1717   }
1718   /*
1719    * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
1720    */
1721   protected boolean canHandleMove(IEditorInput originalElement,
1722       IEditorInput movedElement) {
1723     String oldExtension = ""; //$NON-NLS-1$
1724     if (originalElement instanceof IFileEditorInput) {
1725       IFile file = ((IFileEditorInput) originalElement).getFile();
1726       if (file != null) {
1727         String ext = file.getFileExtension();
1728         if (ext != null)
1729           oldExtension = ext;
1730       }
1731     }
1732     String newExtension = ""; //$NON-NLS-1$
1733     if (movedElement instanceof IFileEditorInput) {
1734       IFile file = ((IFileEditorInput) movedElement).getFile();
1735       if (file != null)
1736         newExtension = file.getFileExtension();
1737     }
1738     return oldExtension.equals(newExtension);
1739   }
1740   /*
1741    * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
1742    */
1743   public void editorContextMenuAboutToShow(IMenuManager menu) {
1744     super.editorContextMenuAboutToShow(menu);
1745     ActionContext context = new ActionContext(getSelectionProvider()
1746         .getSelection());
1747     fContextMenuGroup.setContext(context);
1748     fContextMenuGroup.fillContextMenu(menu);
1749     fContextMenuGroup.setContext(null);
1750   }
1751   /*
1752    * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
1753    */
1754   protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
1755     if (page != null) {
1756       IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1757           .getWorkingCopyManager();
1758       page.setInput(manager.getWorkingCopy(input));
1759     }
1760   }
1761   /*
1762    * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation,
1763    *      IProgressMonitor)
1764    */
1765   //  protected void performSaveOperation(WorkspaceModifyOperation operation,
1766   // IProgressMonitor progressMonitor) {
1767   //    IDocumentProvider p = getDocumentProvider();
1768   //    if (p instanceof PHPDocumentProvider) {
1769   //      PHPDocumentProvider cp = (PHPDocumentProvider) p;
1770   //      cp.setSavePolicy(fSavePolicy);
1771   //    }
1772   //
1773   //    try {
1774   //      super.performSaveOperation(operation, progressMonitor);
1775   //    } finally {
1776   //      if (p instanceof PHPDocumentProvider) {
1777   //        PHPDocumentProvider cp = (PHPDocumentProvider) p;
1778   //        cp.setSavePolicy(null);
1779   //      }
1780   //    }
1781   //  }
1782   /*
1783    * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean,
1784    *      org.eclipse.core.runtime.IProgressMonitor)
1785    */
1786   protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
1787     IDocumentProvider p = getDocumentProvider();
1788     if (p instanceof PHPDocumentProvider) {
1789       PHPDocumentProvider cp = (PHPDocumentProvider) p;
1790       cp.setSavePolicy(fSavePolicy);
1791     }
1792     try {
1793       super.performSave(overwrite, progressMonitor);
1794     } finally {
1795       if (p instanceof PHPDocumentProvider) {
1796         PHPDocumentProvider cp = (PHPDocumentProvider) p;
1797         cp.setSavePolicy(null);
1798       }
1799     }
1800   }
1801   /*
1802    * @see AbstractTextEditor#doSaveAs
1803    */
1804   public void doSaveAs() {
1805     if (askIfNonWorkbenchEncodingIsOk()) {
1806       super.doSaveAs();
1807     }
1808   }
1809   /*
1810    * @see AbstractTextEditor#doSave(IProgressMonitor)
1811    */
1812   public void doSave(IProgressMonitor progressMonitor) {
1813     IDocumentProvider p = getDocumentProvider();
1814     if (p == null) {
1815       // editor has been closed
1816       return;
1817     }
1818     if (!askIfNonWorkbenchEncodingIsOk()) {
1819       progressMonitor.setCanceled(true);
1820       return;
1821     }
1822     if (p.isDeleted(getEditorInput())) {
1823       if (isSaveAsAllowed()) {
1824         /*
1825          * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the
1826          * editors. Changed Behavior to make sure that if called inside a
1827          * regular save (because of deletion of input element) there is a way
1828          * to report back to the caller.
1829          */
1830         //                                       performSaveAs(progressMonitor);
1831         super.doSave(progressMonitor);
1832       } else {
1833         /*
1834          * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
1835          * Missing resources.
1836          */
1837         Shell shell = getSite().getShell();
1838         MessageDialog.openError(shell, PHPEditorMessages
1839             .getString("PHPUnitEditor.error.saving.title1"), PHPEditorMessages
1840             .getString("PHPUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
1841       }
1842     } else {
1843       setStatusLineErrorMessage(null);
1844       super.doSave(progressMonitor);
1845       //                                IWorkingCopyManager manager=
1846       // JavaPlugin.getDefault().getWorkingCopyManager();
1847       //                                ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
1848       //                        
1849       //                                if (unit != null) {
1850       //                                        synchronized (unit) {
1851       //                                                performSaveOperation(createSaveOperation(false), progressMonitor);
1852       //                                        }
1853       //                                } else
1854       //                                        performSaveOperation(createSaveOperation(false), progressMonitor);
1855     }
1856   }
1857   /**
1858    * Asks the user if it is ok to store in non-workbench encoding.
1859    * 
1860    * @return <true>if the user wants to continue
1861    */
1862   private boolean askIfNonWorkbenchEncodingIsOk() {
1863     IDocumentProvider provider = getDocumentProvider();
1864     if (provider instanceof IStorageDocumentProvider) {
1865       IEditorInput input = getEditorInput();
1866       IStorageDocumentProvider storageProvider = (IStorageDocumentProvider) provider;
1867       String encoding = storageProvider.getEncoding(input);
1868       String defaultEncoding = storageProvider.getDefaultEncoding();
1869       if (encoding != null && !encoding.equals(defaultEncoding)) {
1870         Shell shell = getSite().getShell();
1871         String title = PHPEditorMessages
1872             .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
1873         String msg;
1874         if (input != null)
1875           msg = MessageFormat
1876               .format(
1877                   PHPEditorMessages
1878                       .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message1"),
1879                   new String[]{input.getName(), encoding}); //$NON-NLS-1$
1880         else
1881           msg = MessageFormat
1882               .format(
1883                   PHPEditorMessages
1884                       .getString("PHPUnitEditor.warning.save.nonWorkbenchEncoding.message2"),
1885                   new String[]{encoding}); //$NON-NLS-1$
1886         return MessageDialog.openQuestion(shell, title, msg);
1887       }
1888     }
1889     return true;
1890   }
1891   /*
1892    * @see IReconcilingParticipant#reconciled()
1893    */
1894   public void reconciled() {
1895     if (synchronizeOutlineOnCursorMove()) {
1896       Shell shell = getSite().getShell();
1897       if (shell != null && !shell.isDisposed()) {
1898         shell.getDisplay().asyncExec(new Runnable() {
1899           public void run() {
1900             synchronizeOutlinePageSelection();
1901           }
1902         });
1903       }
1904     }
1905   }
1906   
1907   protected void updateStateDependentActions() {
1908     super.updateStateDependentActions();
1909     fGenerateActionGroup.editorStateChanged();
1910   }
1911   
1912   private boolean synchronizeOutlineOnCursorMove() {
1913     return PreferenceConstants.getPreferenceStore().getBoolean(
1914         PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
1915   }
1916
1917   /**
1918    * Returns the updated java element for the old java element.
1919    */
1920   private IJavaElement findElement(IJavaElement element) {
1921     if (element == null)
1922       return null;
1923     IWorkingCopyManager manager = PHPeclipsePlugin.getDefault()
1924         .getWorkingCopyManager();
1925     ICompilationUnit unit = manager.getWorkingCopy(getEditorInput());
1926     if (unit != null) {
1927       try {
1928         synchronized (unit) {
1929           unit.reconcile();
1930         }
1931         IJavaElement[] findings = unit.findElements(element);
1932         if (findings != null && findings.length > 0)
1933           return findings[0];
1934       } catch (JavaModelException x) {
1935         PHPeclipsePlugin.log(x.getStatus());
1936         // nothing found, be tolerant and go on
1937       }
1938     }
1939     return null;
1940   }
1941   /**
1942    * Returns the offset of the given Java element.
1943    */
1944   private int getOffset(IJavaElement element) {
1945     if (element instanceof ISourceReference) {
1946       ISourceReference sr = (ISourceReference) element;
1947       try {
1948         ISourceRange srcRange = sr.getSourceRange();
1949         if (srcRange != null)
1950           return srcRange.getOffset();
1951       } catch (JavaModelException e) {
1952       }
1953     }
1954     return -1;
1955   }
1956   /*
1957    * @see AbstractTextEditor#rememberSelection()
1958    */
1959   protected void rememberSelection() {
1960     ISelectionProvider sp = getSelectionProvider();
1961     fRememberedSelection = (sp == null ? null : (ITextSelection) sp
1962         .getSelection());
1963     if (fRememberedSelection != null) {
1964       fRememberedElement = getElementAt(fRememberedSelection.getOffset(), true);
1965       fRememberedElementOffset = getOffset(fRememberedElement);
1966     }
1967   }
1968   /*
1969    * @see AbstractTextEditor#restoreSelection()
1970    */
1971   protected void restoreSelection() {
1972     try {
1973       if (getSourceViewer() == null || fRememberedSelection == null)
1974         return;
1975       IJavaElement newElement = findElement(fRememberedElement);
1976       int newOffset = getOffset(newElement);
1977       int delta = (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset
1978           - fRememberedElementOffset : 0;
1979       if (isValidSelection(delta + fRememberedSelection.getOffset(),
1980           fRememberedSelection.getLength()))
1981         selectAndReveal(delta + fRememberedSelection.getOffset(),
1982             fRememberedSelection.getLength());
1983     } finally {
1984       fRememberedSelection = null;
1985       fRememberedElement = null;
1986       fRememberedElementOffset = -1;
1987     }
1988   }
1989 }