Avoid message in 31M6:
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / phpeditor / PHPEditor.java
1 package net.sourceforge.phpeclipse.phpeditor;
2
3 /**********************************************************************
4  Copyright (c) 2000, 2002 IBM Corp. and others.
5  All rights reserved. This program and the accompanying materials
6  are made available under the terms of the Common Public License v1.0
7  which accompanies this distribution, and is available at
8  http://www.eclipse.org/legal/cpl-v10.html
9
10  Contributors:
11  IBM Corporation - Initial implementation
12  www.phpeclipse.de
13  **********************************************************************/
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.text.BreakIterator;
17 import java.text.CharacterIterator;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.ResourceBundle;
24 import java.util.StringTokenizer;
25
26 import net.sourceforge.phpdt.core.ICompilationUnit;
27 import net.sourceforge.phpdt.core.IImportContainer;
28 import net.sourceforge.phpdt.core.IImportDeclaration;
29 import net.sourceforge.phpdt.core.IJavaElement;
30 import net.sourceforge.phpdt.core.IJavaProject;
31 import net.sourceforge.phpdt.core.IMember;
32 import net.sourceforge.phpdt.core.ISourceRange;
33 import net.sourceforge.phpdt.core.ISourceReference;
34 import net.sourceforge.phpdt.core.JavaCore;
35 import net.sourceforge.phpdt.core.JavaModelException;
36 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
37 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
38 import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
39 import net.sourceforge.phpdt.internal.ui.actions.SelectionConverter;
40 import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
41 import net.sourceforge.phpdt.internal.ui.text.DocumentCharacterIterator;
42 import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
43 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
44 import net.sourceforge.phpdt.internal.ui.text.JavaWordIterator;
45 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
46 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
47 import net.sourceforge.phpdt.internal.ui.text.java.JavaExpandHover;
48 import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider;
49 import net.sourceforge.phpdt.ui.IContextMenuConstants;
50 import net.sourceforge.phpdt.ui.JavaUI;
51 import net.sourceforge.phpdt.ui.PreferenceConstants;
52 import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
53 import net.sourceforge.phpdt.ui.actions.OpenEditorActionGroup;
54 import net.sourceforge.phpdt.ui.text.JavaTextTools;
55 import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration;
56 import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
57 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
58
59 import org.eclipse.core.resources.IMarker;
60 import org.eclipse.core.resources.IResource;
61 import org.eclipse.core.runtime.CoreException;
62 import org.eclipse.core.runtime.IProgressMonitor;
63 import org.eclipse.core.runtime.IStatus;
64 import org.eclipse.core.runtime.Preferences;
65 import org.eclipse.core.runtime.Status;
66 import org.eclipse.core.runtime.jobs.Job;
67 import org.eclipse.jface.action.Action;
68 import org.eclipse.jface.action.GroupMarker;
69 import org.eclipse.jface.action.IAction;
70 import org.eclipse.jface.action.MenuManager;
71 import org.eclipse.jface.action.Separator;
72 import org.eclipse.jface.preference.IPreferenceStore;
73 import org.eclipse.jface.preference.PreferenceConverter;
74 import org.eclipse.jface.text.BadLocationException;
75 import org.eclipse.jface.text.DefaultInformationControl;
76 import org.eclipse.jface.text.DocumentEvent;
77 import org.eclipse.jface.text.IDocument;
78 import org.eclipse.jface.text.IDocumentListener;
79 import org.eclipse.jface.text.IInformationControl;
80 import org.eclipse.jface.text.IInformationControlCreator;
81 import org.eclipse.jface.text.IRegion;
82 import org.eclipse.jface.text.ISynchronizable;
83 import org.eclipse.jface.text.ITextHover;
84 import org.eclipse.jface.text.ITextInputListener;
85 import org.eclipse.jface.text.ITextPresentationListener;
86 import org.eclipse.jface.text.ITextSelection;
87 import org.eclipse.jface.text.ITextViewer;
88 import org.eclipse.jface.text.ITextViewerExtension2;
89 import org.eclipse.jface.text.ITextViewerExtension3;
90 import org.eclipse.jface.text.ITextViewerExtension4;
91 import org.eclipse.jface.text.ITextViewerExtension5;
92 import org.eclipse.jface.text.ITypedRegion;
93 import org.eclipse.jface.text.Position;
94 import org.eclipse.jface.text.Region;
95 import org.eclipse.jface.text.TextPresentation;
96 import org.eclipse.jface.text.TextSelection;
97 import org.eclipse.jface.text.TextUtilities;
98 import org.eclipse.jface.text.information.IInformationProvider;
99 import org.eclipse.jface.text.information.InformationPresenter;
100 import org.eclipse.jface.text.reconciler.IReconciler;
101 import org.eclipse.jface.text.source.Annotation;
102 import org.eclipse.jface.text.source.AnnotationRulerColumn;
103 import org.eclipse.jface.text.source.CompositeRuler;
104 import org.eclipse.jface.text.source.IAnnotationModel;
105 import org.eclipse.jface.text.source.IAnnotationModelExtension;
106 import org.eclipse.jface.text.source.IOverviewRuler;
107 import org.eclipse.jface.text.source.ISourceViewer;
108 import org.eclipse.jface.text.source.ISourceViewerExtension2;
109 import org.eclipse.jface.text.source.IVerticalRuler;
110 import org.eclipse.jface.text.source.OverviewRuler;
111 import org.eclipse.jface.text.source.SourceViewerConfiguration;
112 import org.eclipse.jface.text.source.projection.ProjectionSupport;
113 import org.eclipse.jface.text.source.projection.ProjectionViewer;
114 import org.eclipse.jface.util.IPropertyChangeListener;
115 import org.eclipse.jface.util.ListenerList;
116 import org.eclipse.jface.util.PropertyChangeEvent;
117 import org.eclipse.jface.viewers.DoubleClickEvent;
118 import org.eclipse.jface.viewers.IDoubleClickListener;
119 import org.eclipse.jface.viewers.IPostSelectionProvider;
120 import org.eclipse.jface.viewers.ISelection;
121 import org.eclipse.jface.viewers.ISelectionChangedListener;
122 import org.eclipse.jface.viewers.ISelectionProvider;
123 import org.eclipse.jface.viewers.IStructuredSelection;
124 import org.eclipse.jface.viewers.SelectionChangedEvent;
125 import org.eclipse.jface.viewers.StructuredSelection;
126 import org.eclipse.swt.SWT;
127 import org.eclipse.swt.custom.BidiSegmentEvent;
128 import org.eclipse.swt.custom.BidiSegmentListener;
129 import org.eclipse.swt.custom.ST;
130 import org.eclipse.swt.custom.StyleRange;
131 import org.eclipse.swt.custom.StyledText;
132 import org.eclipse.swt.events.FocusEvent;
133 import org.eclipse.swt.events.FocusListener;
134 import org.eclipse.swt.events.KeyEvent;
135 import org.eclipse.swt.events.KeyListener;
136 import org.eclipse.swt.events.MouseEvent;
137 import org.eclipse.swt.events.MouseListener;
138 import org.eclipse.swt.events.MouseMoveListener;
139 import org.eclipse.swt.events.PaintEvent;
140 import org.eclipse.swt.events.PaintListener;
141 import org.eclipse.swt.graphics.Color;
142 import org.eclipse.swt.graphics.Cursor;
143 import org.eclipse.swt.graphics.GC;
144 import org.eclipse.swt.graphics.Image;
145 import org.eclipse.swt.graphics.Point;
146 import org.eclipse.swt.graphics.RGB;
147 import org.eclipse.swt.widgets.Composite;
148 import org.eclipse.swt.widgets.Control;
149 import org.eclipse.swt.widgets.Display;
150 import org.eclipse.swt.widgets.Shell;
151 import org.eclipse.ui.IEditorInput;
152 import org.eclipse.ui.IPageLayout;
153 import org.eclipse.ui.IPartService;
154 import org.eclipse.ui.ISelectionListener;
155 import org.eclipse.ui.IViewPart;
156 import org.eclipse.ui.IWorkbenchPage;
157 import org.eclipse.ui.IWorkbenchPart;
158 import org.eclipse.ui.IWorkbenchWindow;
159 import org.eclipse.ui.actions.ActionContext;
160 import org.eclipse.ui.actions.ActionGroup;
161 import org.eclipse.ui.editors.text.DefaultEncodingSupport;
162 import org.eclipse.ui.editors.text.EditorsUI;
163 import org.eclipse.ui.editors.text.IEncodingSupport;
164 import org.eclipse.ui.part.IShowInTargetList;
165 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
166 import org.eclipse.ui.texteditor.AnnotationPreference;
167 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
168 import org.eclipse.ui.texteditor.IDocumentProvider;
169 import org.eclipse.ui.texteditor.IEditorStatusLine;
170 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
171 import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
172 import org.eclipse.ui.texteditor.IUpdate;
173 import org.eclipse.ui.texteditor.MarkerAnnotation;
174 import org.eclipse.ui.texteditor.ResourceAction;
175 import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
176 import org.eclipse.ui.texteditor.TextEditorAction;
177 import org.eclipse.ui.texteditor.TextNavigationAction;
178 import org.eclipse.ui.texteditor.TextOperationAction;
179 import org.eclipse.ui.views.contentoutline.ContentOutline;
180 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
181 import org.eclipse.ui.views.tasklist.TaskList;
182
183 /**
184  * PHP specific text editor.
185  */
186 public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
187   //extends StatusTextEditor implements IViewPartInputProvider { // extends
188   // TextEditor {
189
190   /**
191    * Internal implementation class for a change listener.
192    * 
193    * @since 3.0
194    */
195   protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
196
197     /**
198      * Installs this selection changed listener with the given selection provider. If the selection provider is a post selection
199      * provider, post selection changed events are the preferred choice, otherwise normal selection changed events are requested.
200      * 
201      * @param selectionProvider
202      */
203     public void install(ISelectionProvider selectionProvider) {
204       if (selectionProvider == null)
205         return;
206
207       if (selectionProvider instanceof IPostSelectionProvider) {
208         IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
209         provider.addPostSelectionChangedListener(this);
210       } else {
211         selectionProvider.addSelectionChangedListener(this);
212       }
213     }
214
215     /**
216      * Removes this selection changed listener from the given selection provider.
217      * 
218      * @param selectionProvider
219      *          the selection provider
220      */
221     public void uninstall(ISelectionProvider selectionProvider) {
222       if (selectionProvider == null)
223         return;
224
225       if (selectionProvider instanceof IPostSelectionProvider) {
226         IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
227         provider.removePostSelectionChangedListener(this);
228       } else {
229         selectionProvider.removeSelectionChangedListener(this);
230       }
231     }
232   }
233
234   /**
235    * Updates the Java outline page selection and this editor's range indicator.
236    * 
237    * @since 3.0
238    */
239   private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
240
241     /*
242      * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
243      */
244     public void selectionChanged(SelectionChangedEvent event) {
245       // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
246       PHPEditor.this.selectionChanged();
247     }
248   }
249
250   /**
251    * "Smart" runnable for updating the outline page's selection.
252    */
253   //  class OutlinePageSelectionUpdater implements Runnable {
254   //
255   //    /** Has the runnable already been posted? */
256   //    private boolean fPosted = false;
257   //
258   //    public OutlinePageSelectionUpdater() {
259   //    }
260   //
261   //    /*
262   //     * @see Runnable#run()
263   //     */
264   //    public void run() {
265   //      synchronizeOutlinePageSelection();
266   //      fPosted = false;
267   //    }
268   //
269   //    /**
270   //     * Posts this runnable into the event queue.
271   //     */
272   //    public void post() {
273   //      if (fPosted)
274   //        return;
275   //
276   //      Shell shell = getSite().getShell();
277   //      if (shell != null & !shell.isDisposed()) {
278   //        fPosted = true;
279   //        shell.getDisplay().asyncExec(this);
280   //      }
281   //    }
282   //  };
283   class SelectionChangedListener implements ISelectionChangedListener {
284     public void selectionChanged(SelectionChangedEvent event) {
285       doSelectionChanged(event);
286     }
287   };
288
289   /**
290    * Adapts an options {@link java.util.Map}to {@link org.eclipse.jface.preference.IPreferenceStore}.
291    * <p>
292    * This preference store is read-only i.e. write access throws an {@link java.lang.UnsupportedOperationException}.
293    * </p>
294    * 
295    * @since 3.0
296    */
297   private static class OptionsAdapter implements IPreferenceStore {
298
299     /**
300      * A property change event filter.
301      */
302     public interface IPropertyChangeEventFilter {
303
304       /**
305        * Should the given event be filtered?
306        * 
307        * @param event
308        *          The property change event.
309        * @return <code>true</code> iff the given event should be filtered.
310        */
311       public boolean isFiltered(PropertyChangeEvent event);
312
313     }
314
315     /**
316      * Property change listener. Listens for events in the options Map and fires a
317      * {@link org.eclipse.jface.util.PropertyChangeEvent}on this adapter with arguments from the received event.
318      */
319     private class PropertyChangeListener implements IPropertyChangeListener {
320
321       /**
322        * {@inheritDoc}
323        */
324       public void propertyChange(PropertyChangeEvent event) {
325         if (getFilter().isFiltered(event))
326           return;
327
328         if (event.getNewValue() == null)
329           fOptions.remove(event.getProperty());
330         else
331           fOptions.put(event.getProperty(), event.getNewValue());
332
333         firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
334       }
335     }
336
337     /** Listeners on this adapter */
338     private ListenerList fListeners = new ListenerList();
339
340     /** Listener on the adapted options Map */
341     private IPropertyChangeListener fListener = new PropertyChangeListener();
342
343     /** Adapted options Map */
344     private Map fOptions;
345
346     /** Preference store through which events are received. */
347     private IPreferenceStore fMockupPreferenceStore;
348
349     /** Property event filter. */
350     private IPropertyChangeEventFilter fFilter;
351
352     /**
353      * Initialize with the given options.
354      * 
355      * @param options
356      *          The options to wrap
357      * @param mockupPreferenceStore
358      *          the mock-up preference store
359      * @param filter
360      *          the property change filter
361      */
362     public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
363       fMockupPreferenceStore = mockupPreferenceStore;
364       fOptions = options;
365       setFilter(filter);
366     }
367
368     /**
369      * {@inheritDoc}
370      */
371     public void addPropertyChangeListener(IPropertyChangeListener listener) {
372       if (fListeners.size() == 0)
373         fMockupPreferenceStore.addPropertyChangeListener(fListener);
374       fListeners.add(listener);
375     }
376
377     /**
378      * {@inheritDoc}
379      */
380     public void removePropertyChangeListener(IPropertyChangeListener listener) {
381       fListeners.remove(listener);
382       if (fListeners.size() == 0)
383         fMockupPreferenceStore.removePropertyChangeListener(fListener);
384     }
385
386     /**
387      * {@inheritDoc}
388      */
389     public boolean contains(String name) {
390       return fOptions.containsKey(name);
391     }
392
393     /**
394      * {@inheritDoc}
395      */
396     public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
397       PropertyChangeEvent event = new PropertyChangeEvent(this, name, oldValue, newValue);
398       Object[] listeners = fListeners.getListeners();
399       for (int i = 0; i < listeners.length; i++)
400         ((IPropertyChangeListener) listeners[i]).propertyChange(event);
401     }
402
403     /**
404      * {@inheritDoc}
405      */
406     public boolean getBoolean(String name) {
407       boolean value = BOOLEAN_DEFAULT_DEFAULT;
408       String s = (String) fOptions.get(name);
409       if (s != null)
410         value = s.equals(TRUE);
411       return value;
412     }
413
414     /**
415      * {@inheritDoc}
416      */
417     public boolean getDefaultBoolean(String name) {
418       return BOOLEAN_DEFAULT_DEFAULT;
419     }
420
421     /**
422      * {@inheritDoc}
423      */
424     public double getDefaultDouble(String name) {
425       return DOUBLE_DEFAULT_DEFAULT;
426     }
427
428     /**
429      * {@inheritDoc}
430      */
431     public float getDefaultFloat(String name) {
432       return FLOAT_DEFAULT_DEFAULT;
433     }
434
435     /**
436      * {@inheritDoc}
437      */
438     public int getDefaultInt(String name) {
439       return INT_DEFAULT_DEFAULT;
440     }
441
442     /**
443      * {@inheritDoc}
444      */
445     public long getDefaultLong(String name) {
446       return LONG_DEFAULT_DEFAULT;
447     }
448
449     /**
450      * {@inheritDoc}
451      */
452     public String getDefaultString(String name) {
453       return STRING_DEFAULT_DEFAULT;
454     }
455
456     /**
457      * {@inheritDoc}
458      */
459     public double getDouble(String name) {
460       double value = DOUBLE_DEFAULT_DEFAULT;
461       String s = (String) fOptions.get(name);
462       if (s != null) {
463         try {
464           value = new Double(s).doubleValue();
465         } catch (NumberFormatException e) {
466         }
467       }
468       return value;
469     }
470
471     /**
472      * {@inheritDoc}
473      */
474     public float getFloat(String name) {
475       float value = FLOAT_DEFAULT_DEFAULT;
476       String s = (String) fOptions.get(name);
477       if (s != null) {
478         try {
479           value = new Float(s).floatValue();
480         } catch (NumberFormatException e) {
481         }
482       }
483       return value;
484     }
485
486     /**
487      * {@inheritDoc}
488      */
489     public int getInt(String name) {
490       int value = INT_DEFAULT_DEFAULT;
491       String s = (String) fOptions.get(name);
492       if (s != null) {
493         try {
494           value = new Integer(s).intValue();
495         } catch (NumberFormatException e) {
496         }
497       }
498       return value;
499     }
500
501     /**
502      * {@inheritDoc}
503      */
504     public long getLong(String name) {
505       long value = LONG_DEFAULT_DEFAULT;
506       String s = (String) fOptions.get(name);
507       if (s != null) {
508         try {
509           value = new Long(s).longValue();
510         } catch (NumberFormatException e) {
511         }
512       }
513       return value;
514     }
515
516     /**
517      * {@inheritDoc}
518      */
519     public String getString(String name) {
520       String value = (String) fOptions.get(name);
521       if (value == null)
522         value = STRING_DEFAULT_DEFAULT;
523       return value;
524     }
525
526     /**
527      * {@inheritDoc}
528      */
529     public boolean isDefault(String name) {
530       return false;
531     }
532
533     /**
534      * {@inheritDoc}
535      */
536     public boolean needsSaving() {
537       return !fOptions.isEmpty();
538     }
539
540     /**
541      * {@inheritDoc}
542      */
543     public void putValue(String name, String value) {
544       throw new UnsupportedOperationException();
545     }
546
547     /**
548      * {@inheritDoc}
549      */
550     public void setDefault(String name, double value) {
551       throw new UnsupportedOperationException();
552     }
553
554     /**
555      * {@inheritDoc}
556      */
557     public void setDefault(String name, float value) {
558       throw new UnsupportedOperationException();
559     }
560
561     /**
562      * {@inheritDoc}
563      */
564     public void setDefault(String name, int value) {
565       throw new UnsupportedOperationException();
566     }
567
568     /**
569      * {@inheritDoc}
570      */
571     public void setDefault(String name, long value) {
572       throw new UnsupportedOperationException();
573     }
574
575     /**
576      * {@inheritDoc}
577      */
578     public void setDefault(String name, String defaultObject) {
579       throw new UnsupportedOperationException();
580     }
581
582     /**
583      * {@inheritDoc}
584      */
585     public void setDefault(String name, boolean value) {
586       throw new UnsupportedOperationException();
587     }
588
589     /**
590      * {@inheritDoc}
591      */
592     public void setToDefault(String name) {
593       throw new UnsupportedOperationException();
594     }
595
596     /**
597      * {@inheritDoc}
598      */
599     public void setValue(String name, double value) {
600       throw new UnsupportedOperationException();
601     }
602
603     /**
604      * {@inheritDoc}
605      */
606     public void setValue(String name, float value) {
607       throw new UnsupportedOperationException();
608     }
609
610     /**
611      * {@inheritDoc}
612      */
613     public void setValue(String name, int value) {
614       throw new UnsupportedOperationException();
615     }
616
617     /**
618      * {@inheritDoc}
619      */
620     public void setValue(String name, long value) {
621       throw new UnsupportedOperationException();
622     }
623
624     /**
625      * {@inheritDoc}
626      */
627     public void setValue(String name, String value) {
628       throw new UnsupportedOperationException();
629     }
630
631     /**
632      * {@inheritDoc}
633      */
634     public void setValue(String name, boolean value) {
635       throw new UnsupportedOperationException();
636     }
637
638     /**
639      * Returns the adapted options Map.
640      * 
641      * @return Returns the adapted options Map.
642      */
643     public Map getOptions() {
644       return fOptions;
645     }
646
647     /**
648      * Returns the mock-up preference store, events are received through this preference store.
649      * 
650      * @return Returns the mock-up preference store.
651      */
652     public IPreferenceStore getMockupPreferenceStore() {
653       return fMockupPreferenceStore;
654     }
655
656     /**
657      * Set the event filter to the given filter.
658      * 
659      * @param filter
660      *          The new filter.
661      */
662     public void setFilter(IPropertyChangeEventFilter filter) {
663       fFilter = filter;
664     }
665
666     /**
667      * Returns the event filter.
668      * 
669      * @return The event filter.
670      */
671     public IPropertyChangeEventFilter getFilter() {
672       return fFilter;
673     }
674   }
675
676   /*
677    * Link mode.
678    */
679   //  class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener,
680   //      IPropertyChangeListener, IDocumentListener, ITextInputListener {
681   //
682   //    /** The session is active. */
683   //    private boolean fActive;
684   //
685   //    /** The currently active style range. */
686   //    private IRegion fActiveRegion;
687   //
688   //    /** The currently active style range as position. */
689   //    private Position fRememberedPosition;
690   //
691   //    /** The hand cursor. */
692   //    private Cursor fCursor;
693   //
694   //    /** The link color. */
695   //    private Color fColor;
696   //
697   //    /** The key modifier mask. */
698   //    private int fKeyModifierMask;
699   //
700   //    public void deactivate() {
701   //      deactivate(false);
702   //    }
703   //
704   //    public void deactivate(boolean redrawAll) {
705   //      if (!fActive)
706   //        return;
707   //
708   //      repairRepresentation(redrawAll);
709   //      fActive = false;
710   //    }
711   //
712   //    public void install() {
713   //
714   //      ISourceViewer sourceViewer = getSourceViewer();
715   //      if (sourceViewer == null)
716   //        return;
717   //
718   //      StyledText text = sourceViewer.getTextWidget();
719   //      if (text == null || text.isDisposed())
720   //        return;
721   //
722   //      updateColor(sourceViewer);
723   //
724   //      sourceViewer.addTextInputListener(this);
725   //
726   //      IDocument document = sourceViewer.getDocument();
727   //      if (document != null)
728   //        document.addDocumentListener(this);
729   //
730   //      text.addKeyListener(this);
731   //      text.addMouseListener(this);
732   //      text.addMouseMoveListener(this);
733   //      text.addFocusListener(this);
734   //      text.addPaintListener(this);
735   //
736   //      updateKeyModifierMask();
737   //
738   //      IPreferenceStore preferenceStore = getPreferenceStore();
739   //      preferenceStore.addPropertyChangeListener(this);
740   //    }
741   //
742   //    private void updateKeyModifierMask() {
743   //      String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
744   //      fKeyModifierMask = computeStateMask(modifiers);
745   //      if (fKeyModifierMask == -1) {
746   //        // Fallback to stored state mask
747   //        fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
748   //      }
749   //      ;
750   //    }
751   //
752   //    private int computeStateMask(String modifiers) {
753   //      if (modifiers == null)
754   //        return -1;
755   //
756   //      if (modifiers.length() == 0)
757   //        return SWT.NONE;
758   //
759   //      int stateMask = 0;
760   //      StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
761   //      while (modifierTokenizer.hasMoreTokens()) {
762   //        int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
763   //        if (modifier == 0 || (stateMask & modifier) == modifier)
764   //          return -1;
765   //        stateMask = stateMask | modifier;
766   //      }
767   //      return stateMask;
768   //    }
769   //
770   //    public void uninstall() {
771   //
772   //      if (fColor != null) {
773   //        fColor.dispose();
774   //        fColor = null;
775   //      }
776   //
777   //      if (fCursor != null) {
778   //        fCursor.dispose();
779   //        fCursor = null;
780   //      }
781   //
782   //      ISourceViewer sourceViewer = getSourceViewer();
783   //      if (sourceViewer == null)
784   //        return;
785   //
786   //      sourceViewer.removeTextInputListener(this);
787   //
788   //      IDocument document = sourceViewer.getDocument();
789   //      if (document != null)
790   //        document.removeDocumentListener(this);
791   //
792   //      IPreferenceStore preferenceStore = getPreferenceStore();
793   //      if (preferenceStore != null)
794   //        preferenceStore.removePropertyChangeListener(this);
795   //
796   //      StyledText text = sourceViewer.getTextWidget();
797   //      if (text == null || text.isDisposed())
798   //        return;
799   //
800   //      text.removeKeyListener(this);
801   //      text.removeMouseListener(this);
802   //      text.removeMouseMoveListener(this);
803   //      text.removeFocusListener(this);
804   //      text.removePaintListener(this);
805   //    }
806   //
807   //    /*
808   //     * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
809   //     */
810   //    public void propertyChange(PropertyChangeEvent event) {
811   //      if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
812   //        ISourceViewer viewer = getSourceViewer();
813   //        if (viewer != null)
814   //          updateColor(viewer);
815   //      } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
816   //        updateKeyModifierMask();
817   //      }
818   //    }
819   //
820   //    private void updateColor(ISourceViewer viewer) {
821   //      if (fColor != null)
822   //        fColor.dispose();
823   //
824   //      StyledText text = viewer.getTextWidget();
825   //      if (text == null || text.isDisposed())
826   //        return;
827   //
828   //      Display display = text.getDisplay();
829   //      fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
830   //    }
831   //
832   //    /**
833   //     * Creates a color from the information stored in the given preference store. Returns <code>null</code> if there is no such
834   //     * information available.
835   //     */
836   //    private Color createColor(IPreferenceStore store, String key, Display display) {
837   //
838   //      RGB rgb = null;
839   //
840   //      if (store.contains(key)) {
841   //
842   //        if (store.isDefault(key))
843   //          rgb = PreferenceConverter.getDefaultColor(store, key);
844   //        else
845   //          rgb = PreferenceConverter.getColor(store, key);
846   //
847   //        if (rgb != null)
848   //          return new Color(display, rgb);
849   //      }
850   //
851   //      return null;
852   //    }
853   //
854   //    private void repairRepresentation() {
855   //      repairRepresentation(false);
856   //    }
857   //
858   //    private void repairRepresentation(boolean redrawAll) {
859   //
860   //      if (fActiveRegion == null)
861   //        return;
862   //
863   //      ISourceViewer viewer = getSourceViewer();
864   //      if (viewer != null) {
865   //        resetCursor(viewer);
866   //
867   //        int offset = fActiveRegion.getOffset();
868   //        int length = fActiveRegion.getLength();
869   //
870   //        // remove style
871   //        if (!redrawAll && viewer instanceof ITextViewerExtension2)
872   //          ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
873   //        else
874   //          viewer.invalidateTextPresentation();
875   //
876   //        // remove underline
877   //        if (viewer instanceof ITextViewerExtension3) {
878   //          ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
879   //          offset = extension.modelOffset2WidgetOffset(offset);
880   //        } else {
881   //          offset -= viewer.getVisibleRegion().getOffset();
882   //        }
883   //
884   //        StyledText text = viewer.getTextWidget();
885   //        try {
886   //          text.redrawRange(offset, length, true);
887   //        } catch (IllegalArgumentException x) {
888   //          PHPeclipsePlugin.log(x);
889   //        }
890   //      }
891   //
892   //      fActiveRegion = null;
893   //    }
894   //
895   //    // will eventually be replaced by a method provided by jdt.core
896   //    private IRegion selectWord(IDocument document, int anchor) {
897   //
898   //      try {
899   //        int offset = anchor;
900   //        char c;
901   //
902   //        while (offset >= 0) {
903   //          c = document.getChar(offset);
904   //          if (!Scanner.isPHPIdentifierPart(c))
905   //            break;
906   //          --offset;
907   //        }
908   //
909   //        int start = offset;
910   //
911   //        offset = anchor;
912   //        int length = document.getLength();
913   //
914   //        while (offset < length) {
915   //          c = document.getChar(offset);
916   //          if (!Scanner.isPHPIdentifierPart(c))
917   //            break;
918   //          ++offset;
919   //        }
920   //
921   //        int end = offset;
922   //
923   //        if (start == end)
924   //          return new Region(start, 0);
925   //        else
926   //          return new Region(start + 1, end - start - 1);
927   //
928   //      } catch (BadLocationException x) {
929   //        return null;
930   //      }
931   //    }
932   //
933   //    IRegion getCurrentTextRegion(ISourceViewer viewer) {
934   //
935   //      int offset = getCurrentTextOffset(viewer);
936   //      if (offset == -1)
937   //        return null;
938   //
939   //      return null;
940   //      // IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
941   //      // if (input == null)
942   //      // return null;
943   //      //
944   //      // try {
945   //      //
946   //      // IJavaElement[] elements= null;
947   //      // synchronized (input) {
948   //      // elements= ((ICodeAssist) input).codeSelect(offset, 0);
949   //      // }
950   //      //
951   //      // if (elements == null || elements.length == 0)
952   //      // return null;
953   //      //
954   //      // return selectWord(viewer.getDocument(), offset);
955   //      //
956   //      // } catch (JavaModelException e) {
957   //      // return null;
958   //      // }
959   //    }
960   //
961   //    private int getCurrentTextOffset(ISourceViewer viewer) {
962   //
963   //      try {
964   //        StyledText text = viewer.getTextWidget();
965   //        if (text == null || text.isDisposed())
966   //          return -1;
967   //
968   //        Display display = text.getDisplay();
969   //        Point absolutePosition = display.getCursorLocation();
970   //        Point relativePosition = text.toControl(absolutePosition);
971   //
972   //        int widgetOffset = text.getOffsetAtLocation(relativePosition);
973   //        if (viewer instanceof ITextViewerExtension3) {
974   //          ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
975   //          return extension.widgetOffset2ModelOffset(widgetOffset);
976   //        } else {
977   //          return widgetOffset + viewer.getVisibleRegion().getOffset();
978   //        }
979   //
980   //      } catch (IllegalArgumentException e) {
981   //        return -1;
982   //      }
983   //    }
984   //
985   //    private void highlightRegion(ISourceViewer viewer, IRegion region) {
986   //
987   //      if (region.equals(fActiveRegion))
988   //        return;
989   //
990   //      repairRepresentation();
991   //
992   //      StyledText text = viewer.getTextWidget();
993   //      if (text == null || text.isDisposed())
994   //        return;
995   //
996   //      // highlight region
997   //      int offset = 0;
998   //      int length = 0;
999   //
1000   //      if (viewer instanceof ITextViewerExtension3) {
1001   //        ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1002   //        IRegion widgetRange = extension.modelRange2WidgetRange(region);
1003   //        if (widgetRange == null)
1004   //          return;
1005   //
1006   //        offset = widgetRange.getOffset();
1007   //        length = widgetRange.getLength();
1008   //
1009   //      } else {
1010   //        offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1011   //        length = region.getLength();
1012   //      }
1013   //
1014   //      StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset);
1015   //      Color foregroundColor = fColor;
1016   //      Color backgroundColor = oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
1017   //      StyleRange styleRange = new StyleRange(offset, length, foregroundColor, backgroundColor);
1018   //      text.setStyleRange(styleRange);
1019   //
1020   //      // underline
1021   //      text.redrawRange(offset, length, true);
1022   //
1023   //      fActiveRegion = region;
1024   //    }
1025   //
1026   //    private void activateCursor(ISourceViewer viewer) {
1027   //      StyledText text = viewer.getTextWidget();
1028   //      if (text == null || text.isDisposed())
1029   //        return;
1030   //      Display display = text.getDisplay();
1031   //      if (fCursor == null)
1032   //        fCursor = new Cursor(display, SWT.CURSOR_HAND);
1033   //      text.setCursor(fCursor);
1034   //    }
1035   //
1036   //    private void resetCursor(ISourceViewer viewer) {
1037   //      StyledText text = viewer.getTextWidget();
1038   //      if (text != null && !text.isDisposed())
1039   //        text.setCursor(null);
1040   //
1041   //      if (fCursor != null) {
1042   //        fCursor.dispose();
1043   //        fCursor = null;
1044   //      }
1045   //    }
1046   //
1047   //    /*
1048   //     * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1049   //     */
1050   //    public void keyPressed(KeyEvent event) {
1051   //
1052   //      if (fActive) {
1053   //        deactivate();
1054   //        return;
1055   //      }
1056   //
1057   //      if (event.keyCode != fKeyModifierMask) {
1058   //        deactivate();
1059   //        return;
1060   //      }
1061   //
1062   //      fActive = true;
1063   //
1064   //      // removed for #25871
1065   //      //
1066   //      // ISourceViewer viewer= getSourceViewer();
1067   //      // if (viewer == null)
1068   //      // return;
1069   //      //
1070   //      // IRegion region= getCurrentTextRegion(viewer);
1071   //      // if (region == null)
1072   //      // return;
1073   //      //
1074   //      // highlightRegion(viewer, region);
1075   //      // activateCursor(viewer);
1076   //    }
1077   //
1078   //    /*
1079   //     * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1080   //     */
1081   //    public void keyReleased(KeyEvent event) {
1082   //
1083   //      if (!fActive)
1084   //        return;
1085   //
1086   //      deactivate();
1087   //    }
1088   //
1089   //    /*
1090   //     * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1091   //     */
1092   //    public void mouseDoubleClick(MouseEvent e) {
1093   //    }
1094   //
1095   //    /*
1096   //     * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1097   //     */
1098   //    public void mouseDown(MouseEvent event) {
1099   //
1100   //      if (!fActive)
1101   //        return;
1102   //
1103   //      if (event.stateMask != fKeyModifierMask) {
1104   //        deactivate();
1105   //        return;
1106   //      }
1107   //
1108   //      if (event.button != 1) {
1109   //        deactivate();
1110   //        return;
1111   //      }
1112   //    }
1113   //
1114   //    /*
1115   //     * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1116   //     */
1117   //    public void mouseUp(MouseEvent e) {
1118   //
1119   //      if (!fActive)
1120   //        return;
1121   //
1122   //      if (e.button != 1) {
1123   //        deactivate();
1124   //        return;
1125   //      }
1126   //
1127   //      boolean wasActive = fCursor != null;
1128   //
1129   //      deactivate();
1130   //
1131   //      if (wasActive) {
1132   //        IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1133   //        if (action != null)
1134   //          action.run();
1135   //      }
1136   //    }
1137   //
1138   //    /*
1139   //     * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1140   //     */
1141   //    public void mouseMove(MouseEvent event) {
1142   //
1143   //      if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
1144   //        deactivate();
1145   //        return;
1146   //      }
1147   //
1148   //      if (!fActive) {
1149   //        if (event.stateMask != fKeyModifierMask)
1150   //          return;
1151   //        // modifier was already pressed
1152   //        fActive = true;
1153   //      }
1154   //
1155   //      ISourceViewer viewer = getSourceViewer();
1156   //      if (viewer == null) {
1157   //        deactivate();
1158   //        return;
1159   //      }
1160   //
1161   //      StyledText text = viewer.getTextWidget();
1162   //      if (text == null || text.isDisposed()) {
1163   //        deactivate();
1164   //        return;
1165   //      }
1166   //
1167   //      if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
1168   //        deactivate();
1169   //        return;
1170   //      }
1171   //
1172   //      IRegion region = getCurrentTextRegion(viewer);
1173   //      if (region == null || region.getLength() == 0) {
1174   //        repairRepresentation();
1175   //        return;
1176   //      }
1177   //
1178   //      highlightRegion(viewer, region);
1179   //      activateCursor(viewer);
1180   //    }
1181   //
1182   //    /*
1183   //     * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1184   //     */
1185   //    public void focusGained(FocusEvent e) {
1186   //    }
1187   //
1188   //    /*
1189   //     * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1190   //     */
1191   //    public void focusLost(FocusEvent event) {
1192   //      deactivate();
1193   //    }
1194   //
1195   //    /*
1196   //     * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1197   //     */
1198   //    public void documentAboutToBeChanged(DocumentEvent event) {
1199   //      if (fActive && fActiveRegion != null) {
1200   //        fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
1201   //        try {
1202   //          event.getDocument().addPosition(fRememberedPosition);
1203   //        } catch (BadLocationException x) {
1204   //          fRememberedPosition = null;
1205   //        }
1206   //      }
1207   //    }
1208   //
1209   //    /*
1210   //     * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1211   //     */
1212   //    public void documentChanged(DocumentEvent event) {
1213   //      if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
1214   //        event.getDocument().removePosition(fRememberedPosition);
1215   //        fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
1216   //      }
1217   //      fRememberedPosition = null;
1218   //
1219   //      ISourceViewer viewer = getSourceViewer();
1220   //      if (viewer != null) {
1221   //        StyledText widget = viewer.getTextWidget();
1222   //        if (widget != null && !widget.isDisposed()) {
1223   //          widget.getDisplay().asyncExec(new Runnable() {
1224   //            public void run() {
1225   //              deactivate();
1226   //            }
1227   //          });
1228   //        }
1229   //      }
1230   //    }
1231   //
1232   //    /*
1233   //     * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1234   //     * org.eclipse.jface.text.IDocument)
1235   //     */
1236   //    public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
1237   //      if (oldInput == null)
1238   //        return;
1239   //      deactivate();
1240   //      oldInput.removeDocumentListener(this);
1241   //    }
1242   //
1243   //    /*
1244   //     * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1245   //     * org.eclipse.jface.text.IDocument)
1246   //     */
1247   //    public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
1248   //      if (newInput == null)
1249   //        return;
1250   //      newInput.addDocumentListener(this);
1251   //    }
1252   //
1253   //    /*
1254   //     * @see PaintListener#paintControl(PaintEvent)
1255   //     */
1256   //    public void paintControl(PaintEvent event) {
1257   //      if (fActiveRegion == null)
1258   //        return;
1259   //
1260   //      ISourceViewer viewer = getSourceViewer();
1261   //      if (viewer == null)
1262   //        return;
1263   //
1264   //      StyledText text = viewer.getTextWidget();
1265   //      if (text == null || text.isDisposed())
1266   //        return;
1267   //
1268   //      int offset = 0;
1269   //      int length = 0;
1270   //
1271   //      if (viewer instanceof ITextViewerExtension3) {
1272   //
1273   //        ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1274   //        IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset, length));
1275   //        if (widgetRange == null)
1276   //          return;
1277   //
1278   //        offset = widgetRange.getOffset();
1279   //        length = widgetRange.getLength();
1280   //
1281   //      } else {
1282   //
1283   //        IRegion region = viewer.getVisibleRegion();
1284   //        if (!includes(region, fActiveRegion))
1285   //          return;
1286   //
1287   //        offset = fActiveRegion.getOffset() - region.getOffset();
1288   //        length = fActiveRegion.getLength();
1289   //      }
1290   //
1291   //      // support for bidi
1292   //      Point minLocation = getMinimumLocation(text, offset, length);
1293   //      Point maxLocation = getMaximumLocation(text, offset, length);
1294   //
1295   //      int x1 = minLocation.x;
1296   //      int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1297   //      int y = minLocation.y + text.getLineHeight() - 1;
1298   //
1299   //      GC gc = event.gc;
1300   //      if (fColor != null && !fColor.isDisposed())
1301   //        gc.setForeground(fColor);
1302   //      gc.drawLine(x1, y, x2, y);
1303   //    }
1304   //
1305   //    private boolean includes(IRegion region, IRegion position) {
1306   //      return position.getOffset() >= region.getOffset()
1307   //          && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
1308   //    }
1309   //
1310   //    private Point getMinimumLocation(StyledText text, int offset, int length) {
1311   //      Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
1312   //
1313   //      for (int i = 0; i <= length; i++) {
1314   //        Point location = text.getLocationAtOffset(offset + i);
1315   //
1316   //        if (location.x < minLocation.x)
1317   //          minLocation.x = location.x;
1318   //        if (location.y < minLocation.y)
1319   //          minLocation.y = location.y;
1320   //      }
1321   //
1322   //      return minLocation;
1323   //    }
1324   //
1325   //    private Point getMaximumLocation(StyledText text, int offset, int length) {
1326   //      Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
1327   //
1328   //      for (int i = 0; i <= length; i++) {
1329   //        Point location = text.getLocationAtOffset(offset + i);
1330   //
1331   //        if (location.x > maxLocation.x)
1332   //          maxLocation.x = location.x;
1333   //        if (location.y > maxLocation.y)
1334   //          maxLocation.y = location.y;
1335   //      }
1336   //
1337   //      return maxLocation;
1338   //    }
1339   //  };
1340   /*
1341    * Link mode.
1342    */
1343   class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener,
1344       IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
1345
1346     /** The session is active. */
1347     private boolean fActive;
1348
1349     /** The currently active style range. */
1350     private IRegion fActiveRegion;
1351
1352     /** The currently active style range as position. */
1353     private Position fRememberedPosition;
1354
1355     /** The hand cursor. */
1356     private Cursor fCursor;
1357
1358     /** The link color. */
1359     private Color fColor;
1360
1361     /** The key modifier mask. */
1362     private int fKeyModifierMask;
1363
1364     public void deactivate() {
1365       deactivate(false);
1366     }
1367
1368     public void deactivate(boolean redrawAll) {
1369       if (!fActive)
1370         return;
1371
1372       repairRepresentation(redrawAll);
1373       fActive = false;
1374     }
1375
1376     public void install() {
1377       ISourceViewer sourceViewer = getSourceViewer();
1378       if (sourceViewer == null)
1379         return;
1380
1381       StyledText text = sourceViewer.getTextWidget();
1382       if (text == null || text.isDisposed())
1383         return;
1384
1385       updateColor(sourceViewer);
1386
1387       sourceViewer.addTextInputListener(this);
1388
1389       IDocument document = sourceViewer.getDocument();
1390       if (document != null)
1391         document.addDocumentListener(this);
1392
1393       text.addKeyListener(this);
1394       text.addMouseListener(this);
1395       text.addMouseMoveListener(this);
1396       text.addFocusListener(this);
1397       text.addPaintListener(this);
1398
1399       ((ITextViewerExtension4) sourceViewer).addTextPresentationListener(this);
1400
1401       updateKeyModifierMask();
1402
1403       IPreferenceStore preferenceStore = getPreferenceStore();
1404       preferenceStore.addPropertyChangeListener(this);
1405     }
1406
1407     private void updateKeyModifierMask() {
1408       String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
1409       fKeyModifierMask = computeStateMask(modifiers);
1410       if (fKeyModifierMask == -1) {
1411         // Fall back to stored state mask
1412         fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
1413       }
1414     }
1415
1416     private int computeStateMask(String modifiers) {
1417       if (modifiers == null)
1418         return -1;
1419
1420       if (modifiers.length() == 0)
1421         return SWT.NONE;
1422
1423       int stateMask = 0;
1424       StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
1425       while (modifierTokenizer.hasMoreTokens()) {
1426         int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
1427         if (modifier == 0 || (stateMask & modifier) == modifier)
1428           return -1;
1429         stateMask = stateMask | modifier;
1430       }
1431       return stateMask;
1432     }
1433
1434     public void uninstall() {
1435
1436       if (fColor != null) {
1437         fColor.dispose();
1438         fColor = null;
1439       }
1440
1441       if (fCursor != null) {
1442         fCursor.dispose();
1443         fCursor = null;
1444       }
1445
1446       ISourceViewer sourceViewer = getSourceViewer();
1447       if (sourceViewer != null)
1448         sourceViewer.removeTextInputListener(this);
1449
1450       IDocumentProvider documentProvider = getDocumentProvider();
1451       if (documentProvider != null) {
1452         IDocument document = documentProvider.getDocument(getEditorInput());
1453         if (document != null)
1454           document.removeDocumentListener(this);
1455       }
1456
1457       IPreferenceStore preferenceStore = getPreferenceStore();
1458       if (preferenceStore != null)
1459         preferenceStore.removePropertyChangeListener(this);
1460
1461       if (sourceViewer == null)
1462         return;
1463
1464       StyledText text = sourceViewer.getTextWidget();
1465       if (text == null || text.isDisposed())
1466         return;
1467
1468       text.removeKeyListener(this);
1469       text.removeMouseListener(this);
1470       text.removeMouseMoveListener(this);
1471       text.removeFocusListener(this);
1472       text.removePaintListener(this);
1473
1474       ((ITextViewerExtension4) sourceViewer).removeTextPresentationListener(this);
1475     }
1476
1477     /*
1478      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1479      */
1480     public void propertyChange(PropertyChangeEvent event) {
1481       if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
1482         ISourceViewer viewer = getSourceViewer();
1483         if (viewer != null)
1484           updateColor(viewer);
1485       } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
1486         updateKeyModifierMask();
1487       }
1488     }
1489
1490     private void updateColor(ISourceViewer viewer) {
1491       if (fColor != null)
1492         fColor.dispose();
1493
1494       StyledText text = viewer.getTextWidget();
1495       if (text == null || text.isDisposed())
1496         return;
1497
1498       Display display = text.getDisplay();
1499       fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
1500     }
1501
1502     /**
1503      * Creates a color from the information stored in the given preference store.
1504      * 
1505      * @param store
1506      *          the preference store
1507      * @param key
1508      *          the key
1509      * @param display
1510      *          the display
1511      * @return the color or <code>null</code> if there is no such information available
1512      */
1513     private Color createColor(IPreferenceStore store, String key, Display display) {
1514
1515       RGB rgb = null;
1516
1517       if (store.contains(key)) {
1518
1519         if (store.isDefault(key))
1520           rgb = PreferenceConverter.getDefaultColor(store, key);
1521         else
1522           rgb = PreferenceConverter.getColor(store, key);
1523
1524         if (rgb != null)
1525           return new Color(display, rgb);
1526       }
1527
1528       return null;
1529     }
1530
1531     private void repairRepresentation() {
1532       repairRepresentation(false);
1533     }
1534
1535     private void repairRepresentation(boolean redrawAll) {
1536
1537       if (fActiveRegion == null)
1538         return;
1539
1540       int offset = fActiveRegion.getOffset();
1541       int length = fActiveRegion.getLength();
1542       fActiveRegion = null;
1543
1544       ISourceViewer viewer = getSourceViewer();
1545       if (viewer != null) {
1546
1547         resetCursor(viewer);
1548
1549         // Invalidate ==> remove applied text presentation
1550         if (!redrawAll && viewer instanceof ITextViewerExtension2)
1551           ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
1552         else
1553           viewer.invalidateTextPresentation();
1554
1555         // Remove underline
1556         if (viewer instanceof ITextViewerExtension5) {
1557           ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1558           offset = extension.modelOffset2WidgetOffset(offset);
1559         } else {
1560           offset -= viewer.getVisibleRegion().getOffset();
1561         }
1562         try {
1563           StyledText text = viewer.getTextWidget();
1564
1565           text.redrawRange(offset, length, false);
1566         } catch (IllegalArgumentException x) {
1567           //                                    JavaPlugin.log(x);
1568         }
1569       }
1570     }
1571
1572     // will eventually be replaced by a method provided by jdt.core
1573     private IRegion selectWord(IDocument document, int anchor) {
1574
1575       try {
1576         int offset = anchor;
1577         char c;
1578
1579         while (offset >= 0) {
1580           c = document.getChar(offset);
1581           if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1582             break;
1583           --offset;
1584         }
1585
1586         int start = offset;
1587
1588         offset = anchor;
1589         int length = document.getLength();
1590
1591         while (offset < length) {
1592           c = document.getChar(offset);
1593           if (!Scanner.isPHPIdentifierPart(c) && c != '$')
1594             break;
1595           ++offset;
1596         }
1597
1598         int end = offset;
1599
1600         if (start == end)
1601           return new Region(start, 0);
1602         else
1603           return new Region(start + 1, end - start - 1);
1604
1605       } catch (BadLocationException x) {
1606         return null;
1607       }
1608     }
1609
1610     IRegion getCurrentTextRegion(ISourceViewer viewer) {
1611
1612       int offset = getCurrentTextOffset(viewer);
1613       if (offset == -1)
1614         return null;
1615
1616       IJavaElement input = SelectionConverter.getInput(PHPEditor.this);
1617       if (input == null)
1618         return null;
1619
1620       //                        try {
1621
1622       //                                IJavaElement[] elements= null;
1623       //                                synchronized (input) {
1624       //                                        elements= ((ICodeAssist) input).codeSelect(offset, 0);
1625       //                                }
1626       //                                
1627       //                                if (elements == null || elements.length == 0)
1628       //                                        return null;
1629
1630       return selectWord(viewer.getDocument(), offset);
1631
1632       //                        } catch (JavaModelException e) {
1633       //                                return null;
1634       //                        }
1635     }
1636
1637     private int getCurrentTextOffset(ISourceViewer viewer) {
1638
1639       try {
1640         StyledText text = viewer.getTextWidget();
1641         if (text == null || text.isDisposed())
1642           return -1;
1643
1644         Display display = text.getDisplay();
1645         Point absolutePosition = display.getCursorLocation();
1646         Point relativePosition = text.toControl(absolutePosition);
1647
1648         int widgetOffset = text.getOffsetAtLocation(relativePosition);
1649         if (viewer instanceof ITextViewerExtension5) {
1650           ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1651           return extension.widgetOffset2ModelOffset(widgetOffset);
1652         } else {
1653           return widgetOffset + viewer.getVisibleRegion().getOffset();
1654         }
1655
1656       } catch (IllegalArgumentException e) {
1657         return -1;
1658       }
1659     }
1660
1661     public void applyTextPresentation(TextPresentation textPresentation) {
1662       if (fActiveRegion == null)
1663         return;
1664       IRegion region = textPresentation.getExtent();
1665       if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset()
1666           && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
1667         textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
1668     }
1669
1670     private void highlightRegion(ISourceViewer viewer, IRegion region) {
1671
1672       if (region.equals(fActiveRegion))
1673         return;
1674
1675       repairRepresentation();
1676
1677       StyledText text = viewer.getTextWidget();
1678       if (text == null || text.isDisposed())
1679         return;
1680
1681       // Underline
1682       int offset = 0;
1683       int length = 0;
1684       if (viewer instanceof ITextViewerExtension5) {
1685         ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1686         IRegion widgetRange = extension.modelRange2WidgetRange(region);
1687         if (widgetRange == null)
1688           return;
1689
1690         offset = widgetRange.getOffset();
1691         length = widgetRange.getLength();
1692
1693       } else {
1694         offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
1695         length = region.getLength();
1696       }
1697       text.redrawRange(offset, length, false);
1698
1699       // Invalidate region ==> apply text presentation
1700       fActiveRegion = region;
1701       if (viewer instanceof ITextViewerExtension2)
1702         ((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
1703       else
1704         viewer.invalidateTextPresentation();
1705     }
1706
1707     private void activateCursor(ISourceViewer viewer) {
1708       StyledText text = viewer.getTextWidget();
1709       if (text == null || text.isDisposed())
1710         return;
1711       Display display = text.getDisplay();
1712       if (fCursor == null)
1713         fCursor = new Cursor(display, SWT.CURSOR_HAND);
1714       text.setCursor(fCursor);
1715     }
1716
1717     private void resetCursor(ISourceViewer viewer) {
1718       StyledText text = viewer.getTextWidget();
1719       if (text != null && !text.isDisposed())
1720         text.setCursor(null);
1721
1722       if (fCursor != null) {
1723         fCursor.dispose();
1724         fCursor = null;
1725       }
1726     }
1727
1728     /*
1729      * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1730      */
1731     public void keyPressed(KeyEvent event) {
1732
1733       if (fActive) {
1734         deactivate();
1735         return;
1736       }
1737
1738       if (event.keyCode != fKeyModifierMask) {
1739         deactivate();
1740         return;
1741       }
1742
1743       fActive = true;
1744
1745       //                        removed for #25871
1746       //
1747       //                        ISourceViewer viewer= getSourceViewer();
1748       //                        if (viewer == null)
1749       //                                return;
1750       //                        
1751       //                        IRegion region= getCurrentTextRegion(viewer);
1752       //                        if (region == null)
1753       //                                return;
1754       //                        
1755       //                        highlightRegion(viewer, region);
1756       //                        activateCursor(viewer);
1757     }
1758
1759     /*
1760      * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1761      */
1762     public void keyReleased(KeyEvent event) {
1763
1764       if (!fActive)
1765         return;
1766
1767       deactivate();
1768     }
1769
1770     /*
1771      * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1772      */
1773     public void mouseDoubleClick(MouseEvent e) {
1774     }
1775
1776     /*
1777      * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1778      */
1779     public void mouseDown(MouseEvent event) {
1780
1781       if (!fActive)
1782         return;
1783
1784       if (event.stateMask != fKeyModifierMask) {
1785         deactivate();
1786         return;
1787       }
1788
1789       if (event.button != 1) {
1790         deactivate();
1791         return;
1792       }
1793     }
1794
1795     /*
1796      * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1797      */
1798     public void mouseUp(MouseEvent e) {
1799
1800       if (!fActive)
1801         return;
1802
1803       if (e.button != 1) {
1804         deactivate();
1805         return;
1806       }
1807
1808       boolean wasActive = fCursor != null;
1809
1810       deactivate();
1811
1812       if (wasActive) {
1813         IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1814         if (action != null)
1815           action.run();
1816       }
1817     }
1818
1819     /*
1820      * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1821      */
1822     public void mouseMove(MouseEvent event) {
1823
1824       if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
1825         deactivate();
1826         return;
1827       }
1828
1829       if (!fActive) {
1830         if (event.stateMask != fKeyModifierMask)
1831           return;
1832         // modifier was already pressed
1833         fActive = true;
1834       }
1835
1836       ISourceViewer viewer = getSourceViewer();
1837       if (viewer == null) {
1838         deactivate();
1839         return;
1840       }
1841
1842       StyledText text = viewer.getTextWidget();
1843       if (text == null || text.isDisposed()) {
1844         deactivate();
1845         return;
1846       }
1847
1848       if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
1849         deactivate();
1850         return;
1851       }
1852
1853       IRegion region = getCurrentTextRegion(viewer);
1854       if (region == null || region.getLength() == 0) {
1855         repairRepresentation();
1856         return;
1857       }
1858
1859       highlightRegion(viewer, region);
1860       activateCursor(viewer);
1861     }
1862
1863     /*
1864      * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1865      */
1866     public void focusGained(FocusEvent e) {
1867     }
1868
1869     /*
1870      * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1871      */
1872     public void focusLost(FocusEvent event) {
1873       deactivate();
1874     }
1875
1876     /*
1877      * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1878      */
1879     public void documentAboutToBeChanged(DocumentEvent event) {
1880       if (fActive && fActiveRegion != null) {
1881         fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
1882         try {
1883           event.getDocument().addPosition(fRememberedPosition);
1884         } catch (BadLocationException x) {
1885           fRememberedPosition = null;
1886         }
1887       }
1888     }
1889
1890     /*
1891      * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1892      */
1893     public void documentChanged(DocumentEvent event) {
1894       if (fRememberedPosition != null) {
1895         if (!fRememberedPosition.isDeleted()) {
1896
1897           event.getDocument().removePosition(fRememberedPosition);
1898           fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
1899           fRememberedPosition = null;
1900
1901           ISourceViewer viewer = getSourceViewer();
1902           if (viewer != null) {
1903             StyledText widget = viewer.getTextWidget();
1904             if (widget != null && !widget.isDisposed()) {
1905               widget.getDisplay().asyncExec(new Runnable() {
1906                 public void run() {
1907                   deactivate();
1908                 }
1909               });
1910             }
1911           }
1912
1913         } else {
1914           fActiveRegion = null;
1915           fRememberedPosition = null;
1916           deactivate();
1917         }
1918       }
1919     }
1920
1921     /*
1922      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1923      *      org.eclipse.jface.text.IDocument)
1924      */
1925     public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
1926       if (oldInput == null)
1927         return;
1928       deactivate();
1929       oldInput.removeDocumentListener(this);
1930     }
1931
1932     /*
1933      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1934      *      org.eclipse.jface.text.IDocument)
1935      */
1936     public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
1937       if (newInput == null)
1938         return;
1939       newInput.addDocumentListener(this);
1940     }
1941
1942     /*
1943      * @see PaintListener#paintControl(PaintEvent)
1944      */
1945     public void paintControl(PaintEvent event) {
1946       if (fActiveRegion == null)
1947         return;
1948
1949       ISourceViewer viewer = getSourceViewer();
1950       if (viewer == null)
1951         return;
1952
1953       StyledText text = viewer.getTextWidget();
1954       if (text == null || text.isDisposed())
1955         return;
1956
1957       int offset = 0;
1958       int length = 0;
1959
1960       if (viewer instanceof ITextViewerExtension5) {
1961
1962         ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
1963         IRegion widgetRange = extension.modelRange2WidgetRange(fActiveRegion);
1964         if (widgetRange == null)
1965           return;
1966
1967         offset = widgetRange.getOffset();
1968         length = widgetRange.getLength();
1969
1970       } else {
1971
1972         IRegion region = viewer.getVisibleRegion();
1973         if (!includes(region, fActiveRegion))
1974           return;
1975
1976         offset = fActiveRegion.getOffset() - region.getOffset();
1977         length = fActiveRegion.getLength();
1978       }
1979
1980       // support for bidi
1981       Point minLocation = getMinimumLocation(text, offset, length);
1982       Point maxLocation = getMaximumLocation(text, offset, length);
1983
1984       int x1 = minLocation.x;
1985       int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1986       int y = minLocation.y + text.getLineHeight() - 1;
1987
1988       GC gc = event.gc;
1989       if (fColor != null && !fColor.isDisposed())
1990         gc.setForeground(fColor);
1991       gc.drawLine(x1, y, x2, y);
1992     }
1993
1994     private boolean includes(IRegion region, IRegion position) {
1995       return position.getOffset() >= region.getOffset()
1996           && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
1997     }
1998
1999     private Point getMinimumLocation(StyledText text, int offset, int length) {
2000       Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
2001
2002       for (int i = 0; i <= length; i++) {
2003         Point location = text.getLocationAtOffset(offset + i);
2004
2005         if (location.x < minLocation.x)
2006           minLocation.x = location.x;
2007         if (location.y < minLocation.y)
2008           minLocation.y = location.y;
2009       }
2010
2011       return minLocation;
2012     }
2013
2014     private Point getMaximumLocation(StyledText text, int offset, int length) {
2015       Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
2016
2017       for (int i = 0; i <= length; i++) {
2018         Point location = text.getLocationAtOffset(offset + i);
2019
2020         if (location.x > maxLocation.x)
2021           maxLocation.x = location.x;
2022         if (location.y > maxLocation.y)
2023           maxLocation.y = location.y;
2024       }
2025
2026       return maxLocation;
2027     }
2028   }
2029
2030   /**
2031    * This action dispatches into two behaviours: If there is no current text hover, the javadoc is displayed using information
2032    * presenter. If there is a current text hover, it is converted into a information presenter in order to make it sticky.
2033    */
2034   class InformationDispatchAction extends TextEditorAction {
2035
2036     /** The wrapped text operation action. */
2037     private final TextOperationAction fTextOperationAction;
2038
2039     /**
2040      * Creates a dispatch action.
2041      */
2042     public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
2043       super(resourceBundle, prefix, PHPEditor.this);
2044       if (textOperationAction == null)
2045         throw new IllegalArgumentException();
2046       fTextOperationAction = textOperationAction;
2047     }
2048
2049     /*
2050      * @see org.eclipse.jface.action.IAction#run()
2051      */
2052     public void run() {
2053
2054       ISourceViewer sourceViewer = getSourceViewer();
2055       if (sourceViewer == null) {
2056         fTextOperationAction.run();
2057         return;
2058       }
2059
2060       if (!(sourceViewer instanceof ITextViewerExtension2)) {
2061         fTextOperationAction.run();
2062         return;
2063       }
2064
2065       ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
2066
2067       // does a text hover exist?
2068       ITextHover textHover = textViewerExtension2.getCurrentTextHover();
2069       if (textHover == null) {
2070         fTextOperationAction.run();
2071         return;
2072       }
2073
2074       Point hoverEventLocation = textViewerExtension2.getHoverEventLocation();
2075       int offset = computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
2076       if (offset == -1) {
2077         fTextOperationAction.run();
2078         return;
2079       }
2080
2081       try {
2082         // get the text hover content
2083         IDocument document = sourceViewer.getDocument();
2084         String contentType = document.getContentType(offset);
2085
2086         final IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset);
2087         if (hoverRegion == null)
2088           return;
2089
2090         final String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion);
2091
2092         // with information provider
2093         IInformationProvider informationProvider = new IInformationProvider() {
2094           /*
2095            * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
2096            */
2097           public IRegion getSubject(ITextViewer textViewer, int offset) {
2098             return hoverRegion;
2099           }
2100
2101           /*
2102            * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer,
2103            *      org.eclipse.jface.text.IRegion)
2104            */
2105           public String getInformation(ITextViewer textViewer, IRegion subject) {
2106             return hoverInfo;
2107           }
2108         };
2109
2110         fInformationPresenter.setOffset(offset);
2111         fInformationPresenter.setInformationProvider(informationProvider, contentType);
2112         fInformationPresenter.showInformation();
2113
2114       } catch (BadLocationException e) {
2115       }
2116     }
2117
2118     // modified version from TextViewer
2119     private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
2120
2121       StyledText styledText = textViewer.getTextWidget();
2122       IDocument document = textViewer.getDocument();
2123
2124       if (document == null)
2125         return -1;
2126
2127       try {
2128         int widgetLocation = styledText.getOffsetAtLocation(new Point(x, y));
2129         if (textViewer instanceof ITextViewerExtension3) {
2130           ITextViewerExtension3 extension = (ITextViewerExtension3) textViewer;
2131           return extension.widgetOffset2ModelOffset(widgetLocation);
2132         } else {
2133           IRegion visibleRegion = textViewer.getVisibleRegion();
2134           return widgetLocation + visibleRegion.getOffset();
2135         }
2136       } catch (IllegalArgumentException e) {
2137         return -1;
2138       }
2139
2140     }
2141   };
2142
2143   /**
2144    * This action implements smart home.
2145    * 
2146    * Instead of going to the start of a line it does the following:
2147    *  - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before
2148    * it, taking JavaDoc and multi-line comments into account. - if the caret is before the line's first non-whitespace the caret is
2149    * moved to the beginning of the line - if the caret is at the beginning of the line see first case.
2150    * 
2151    * @since 3.0
2152    */
2153   protected class SmartLineStartAction extends LineStartAction {
2154
2155     /**
2156      * Creates a new smart line start action
2157      * 
2158      * @param textWidget
2159      *          the styled text widget
2160      * @param doSelect
2161      *          a boolean flag which tells if the text up to the beginning of the line should be selected
2162      */
2163     public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
2164       super(textWidget, doSelect);
2165     }
2166
2167     /*
2168      * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int,
2169      *      java.lang.String)
2170      */
2171     protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
2172
2173       String type = IDocument.DEFAULT_CONTENT_TYPE;
2174       try {
2175         type = TextUtilities.getContentType(document, IPHPPartitions.PHP_PARTITIONING, offset, true);
2176       } catch (BadLocationException exception) {
2177         // Should not happen
2178       }
2179
2180       int index = super.getLineStartPosition(document, line, length, offset);
2181       if (type.equals(IPHPPartitions.PHP_PHPDOC_COMMENT) || type.equals(IPHPPartitions.PHP_MULTILINE_COMMENT)) {
2182         if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
2183           do {
2184             ++index;
2185           } while (index < length && Character.isWhitespace(line.charAt(index)));
2186         }
2187       } else {
2188         if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
2189           index++;
2190           do {
2191             ++index;
2192           } while (index < length && Character.isWhitespace(line.charAt(index)));
2193         }
2194       }
2195       return index;
2196     }
2197   }
2198
2199   /**
2200    * Text navigation action to navigate to the next sub-word.
2201    * 
2202    * @since 3.0
2203    */
2204   protected abstract class NextSubWordAction extends TextNavigationAction {
2205
2206     protected JavaWordIterator fIterator = new JavaWordIterator();
2207
2208     /**
2209      * Creates a new next sub-word action.
2210      * 
2211      * @param code
2212      *          Action code for the default operation. Must be an action code from
2213      * @see org.eclipse.swt.custom.ST.
2214      */
2215     protected NextSubWordAction(int code) {
2216       super(getSourceViewer().getTextWidget(), code);
2217     }
2218
2219     /*
2220      * @see org.eclipse.jface.action.IAction#run()
2221      */
2222     public void run() {
2223       // Check whether we are in a java code partition and the preference is enabled
2224       final IPreferenceStore store = getPreferenceStore();
2225       if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2226         super.run();
2227         return;
2228       }
2229
2230       final ISourceViewer viewer = getSourceViewer();
2231       final IDocument document = viewer.getDocument();
2232       fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
2233       int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2234       if (position == -1)
2235         return;
2236
2237       int next = findNextPosition(position);
2238       if (next != BreakIterator.DONE) {
2239         setCaretPosition(next);
2240         getTextWidget().showSelection();
2241         fireSelectionChanged();
2242       }
2243
2244     }
2245
2246     /**
2247      * Finds the next position after the given position.
2248      * 
2249      * @param position
2250      *          the current position
2251      * @return the next position
2252      */
2253     protected int findNextPosition(int position) {
2254       ISourceViewer viewer = getSourceViewer();
2255       int widget = -1;
2256       while (position != BreakIterator.DONE && widget == -1) { // TODO: optimize
2257         position = fIterator.following(position);
2258         if (position != BreakIterator.DONE)
2259           widget = modelOffset2WidgetOffset(viewer, position);
2260       }
2261       return position;
2262     }
2263
2264     /**
2265      * Sets the caret position to the sub-word boundary given with <code>position</code>.
2266      * 
2267      * @param position
2268      *          Position where the action should move the caret
2269      */
2270     protected abstract void setCaretPosition(int position);
2271   }
2272
2273   /**
2274    * Text navigation action to navigate to the next sub-word.
2275    * 
2276    * @since 3.0
2277    */
2278   protected class NavigateNextSubWordAction extends NextSubWordAction {
2279
2280     /**
2281      * Creates a new navigate next sub-word action.
2282      */
2283     public NavigateNextSubWordAction() {
2284       super(ST.WORD_NEXT);
2285     }
2286
2287     /*
2288      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2289      */
2290     protected void setCaretPosition(final int position) {
2291       getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
2292     }
2293   }
2294
2295   /**
2296    * Text operation action to delete the next sub-word.
2297    * 
2298    * @since 3.0
2299    */
2300   protected class DeleteNextSubWordAction extends NextSubWordAction implements IUpdate {
2301
2302     /**
2303      * Creates a new delete next sub-word action.
2304      */
2305     public DeleteNextSubWordAction() {
2306       super(ST.DELETE_WORD_NEXT);
2307     }
2308
2309     /*
2310      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2311      */
2312     protected void setCaretPosition(final int position) {
2313       if (!validateEditorInputState())
2314         return;
2315
2316       final ISourceViewer viewer = getSourceViewer();
2317       final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2318
2319       try {
2320         viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
2321       } catch (BadLocationException exception) {
2322         // Should not happen
2323       }
2324     }
2325
2326     /*
2327      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#findNextPosition(int)
2328      */
2329     protected int findNextPosition(int position) {
2330       return fIterator.following(position);
2331     }
2332
2333     /*
2334      * @see org.eclipse.ui.texteditor.IUpdate#update()
2335      */
2336     public void update() {
2337       setEnabled(isEditorInputModifiable());
2338     }
2339   }
2340
2341   /**
2342    * Text operation action to select the next sub-word.
2343    * 
2344    * @since 3.0
2345    */
2346   protected class SelectNextSubWordAction extends NextSubWordAction {
2347
2348     /**
2349      * Creates a new select next sub-word action.
2350      */
2351     public SelectNextSubWordAction() {
2352       super(ST.SELECT_WORD_NEXT);
2353     }
2354
2355     /*
2356      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
2357      */
2358     protected void setCaretPosition(final int position) {
2359       final ISourceViewer viewer = getSourceViewer();
2360
2361       final StyledText text = viewer.getTextWidget();
2362       if (text != null && !text.isDisposed()) {
2363
2364         final Point selection = text.getSelection();
2365         final int caret = text.getCaretOffset();
2366         final int offset = modelOffset2WidgetOffset(viewer, position);
2367
2368         if (caret == selection.x)
2369           text.setSelectionRange(selection.y, offset - selection.y);
2370         else
2371           text.setSelectionRange(selection.x, offset - selection.x);
2372       }
2373     }
2374   }
2375
2376   /**
2377    * Text navigation action to navigate to the previous sub-word.
2378    * 
2379    * @since 3.0
2380    */
2381   protected abstract class PreviousSubWordAction extends TextNavigationAction {
2382
2383     protected JavaWordIterator fIterator = new JavaWordIterator();
2384
2385     /**
2386      * Creates a new previous sub-word action.
2387      * 
2388      * @param code
2389      *          Action code for the default operation. Must be an action code from
2390      * @see org.eclipse.swt.custom.ST.
2391      */
2392     protected PreviousSubWordAction(final int code) {
2393       super(getSourceViewer().getTextWidget(), code);
2394     }
2395
2396     /*
2397      * @see org.eclipse.jface.action.IAction#run()
2398      */
2399     public void run() {
2400       // Check whether we are in a java code partition and the preference is enabled
2401       final IPreferenceStore store = getPreferenceStore();
2402       if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
2403         super.run();
2404         return;
2405       }
2406
2407       final ISourceViewer viewer = getSourceViewer();
2408       final IDocument document = viewer.getDocument();
2409       fIterator.setText((CharacterIterator) new DocumentCharacterIterator(document));
2410       int position = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2411       if (position == -1)
2412         return;
2413
2414       int previous = findPreviousPosition(position);
2415       if (previous != BreakIterator.DONE) {
2416         setCaretPosition(previous);
2417         getTextWidget().showSelection();
2418         fireSelectionChanged();
2419       }
2420
2421     }
2422
2423     /**
2424      * Finds the previous position before the given position.
2425      * 
2426      * @param position
2427      *          the current position
2428      * @return the previous position
2429      */
2430     protected int findPreviousPosition(int position) {
2431       ISourceViewer viewer = getSourceViewer();
2432       int widget = -1;
2433       while (position != BreakIterator.DONE && widget == -1) { // TODO: optimize
2434         position = fIterator.preceding(position);
2435         if (position != BreakIterator.DONE)
2436           widget = modelOffset2WidgetOffset(viewer, position);
2437       }
2438       return position;
2439     }
2440
2441     /**
2442      * Sets the caret position to the sub-word boundary given with <code>position</code>.
2443      * 
2444      * @param position
2445      *          Position where the action should move the caret
2446      */
2447     protected abstract void setCaretPosition(int position);
2448   }
2449
2450   /**
2451    * Text navigation action to navigate to the previous sub-word.
2452    * 
2453    * @since 3.0
2454    */
2455   protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
2456
2457     /**
2458      * Creates a new navigate previous sub-word action.
2459      */
2460     public NavigatePreviousSubWordAction() {
2461       super(ST.WORD_PREVIOUS);
2462     }
2463
2464     /*
2465      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2466      */
2467     protected void setCaretPosition(final int position) {
2468       getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
2469     }
2470   }
2471
2472   /**
2473    * Text operation action to delete the previous sub-word.
2474    * 
2475    * @since 3.0
2476    */
2477   protected class DeletePreviousSubWordAction extends PreviousSubWordAction implements IUpdate {
2478
2479     /**
2480      * Creates a new delete previous sub-word action.
2481      */
2482     public DeletePreviousSubWordAction() {
2483       super(ST.DELETE_WORD_PREVIOUS);
2484     }
2485
2486     /*
2487      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2488      */
2489     protected void setCaretPosition(final int position) {
2490       if (!validateEditorInputState())
2491         return;
2492
2493       final ISourceViewer viewer = getSourceViewer();
2494       final int caret = widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
2495
2496       try {
2497         viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
2498       } catch (BadLocationException exception) {
2499         // Should not happen
2500       }
2501     }
2502
2503     /*
2504      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#findPreviousPosition(int)
2505      */
2506     protected int findPreviousPosition(int position) {
2507       return fIterator.preceding(position);
2508     }
2509
2510     /*
2511      * @see org.eclipse.ui.texteditor.IUpdate#update()
2512      */
2513     public void update() {
2514       setEnabled(isEditorInputModifiable());
2515     }
2516   }
2517
2518   /**
2519    * Text operation action to select the previous sub-word.
2520    * 
2521    * @since 3.0
2522    */
2523   protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
2524
2525     /**
2526      * Creates a new select previous sub-word action.
2527      */
2528     public SelectPreviousSubWordAction() {
2529       super(ST.SELECT_WORD_PREVIOUS);
2530     }
2531
2532     /*
2533      * @see net.sourceforge.phpdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
2534      */
2535     protected void setCaretPosition(final int position) {
2536       final ISourceViewer viewer = getSourceViewer();
2537
2538       final StyledText text = viewer.getTextWidget();
2539       if (text != null && !text.isDisposed()) {
2540
2541         final Point selection = text.getSelection();
2542         final int caret = text.getCaretOffset();
2543         final int offset = modelOffset2WidgetOffset(viewer, position);
2544
2545         if (caret == selection.x)
2546           text.setSelectionRange(selection.y, offset - selection.y);
2547         else
2548           text.setSelectionRange(selection.x, offset - selection.x);
2549       }
2550     }
2551   }
2552
2553   //  static protected class AnnotationAccess implements IAnnotationAccess {
2554   //    /*
2555   //     * @see
2556   // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
2557   //     */
2558   //    public Object getType(Annotation annotation) {
2559   //      if (annotation instanceof IJavaAnnotation) {
2560   //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2561   //   // if (javaAnnotation.isRelevant())
2562   //   // return javaAnnotation.getAnnotationType();
2563   //      }
2564   //      return null;
2565   //    }
2566   //
2567   //    /*
2568   //     * @see
2569   // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
2570   //     */
2571   //    public boolean isMultiLine(Annotation annotation) {
2572   //      return true;
2573   //    }
2574   //
2575   //    /*
2576   //     * @see
2577   // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
2578   //     */
2579   //    public boolean isTemporary(Annotation annotation) {
2580   //      if (annotation instanceof IJavaAnnotation) {
2581   //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
2582   //        if (javaAnnotation.isRelevant())
2583   //          return javaAnnotation.isTemporary();
2584   //      }
2585   //      return false;
2586   //    }
2587   //  };
2588
2589   private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
2590     /*
2591      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
2592      */
2593     public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2594       handlePreferencePropertyChanged(event);
2595     }
2596   };
2597
2598   /**
2599    * Finds and marks occurrence annotations.
2600    * 
2601    * @since 3.0
2602    */
2603   class OccurrencesFinderJob extends Job implements IDocumentListener {
2604
2605     private IDocument fDocument;
2606
2607     private boolean fCancelled = false;
2608
2609     private IProgressMonitor fProgressMonitor;
2610
2611     private Position[] fPositions;
2612
2613     public OccurrencesFinderJob(IDocument document, Position[] positions) {
2614       super("Occurrences Marker"); //$NON-NLS-1$
2615       fDocument = document;
2616       fPositions = positions;
2617       fDocument.addDocumentListener(this);
2618     }
2619
2620     private boolean isCancelled() {
2621       return fCancelled || fProgressMonitor.isCanceled();
2622     }
2623
2624     /*
2625      * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
2626      */
2627     public IStatus run(IProgressMonitor progressMonitor) {
2628
2629       fProgressMonitor = progressMonitor;
2630
2631       try {
2632
2633         if (isCancelled())
2634           return Status.CANCEL_STATUS;
2635
2636         ITextViewer textViewer = getViewer();
2637         if (textViewer == null)
2638           return Status.CANCEL_STATUS;
2639
2640         IDocument document = textViewer.getDocument();
2641         if (document == null)
2642           return Status.CANCEL_STATUS;
2643
2644         IDocumentProvider documentProvider = getDocumentProvider();
2645         if (documentProvider == null)
2646           return Status.CANCEL_STATUS;
2647
2648         IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
2649         if (annotationModel == null)
2650           return Status.CANCEL_STATUS;
2651
2652         // Add occurrence annotations
2653         int length = fPositions.length;
2654         Map annotationMap = new HashMap(length);
2655         for (int i = 0; i < length; i++) {
2656
2657           if (isCancelled())
2658             return Status.CANCEL_STATUS;
2659
2660           String message;
2661           Position position = fPositions[i];
2662
2663           // Create & add annotation
2664           try {
2665             message = document.get(position.offset, position.length);
2666           } catch (BadLocationException ex) {
2667             // Skip this match
2668             continue;
2669           }
2670           annotationMap.put(new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
2671               position);
2672         }
2673
2674         if (isCancelled())
2675           return Status.CANCEL_STATUS;
2676
2677         synchronized (annotationModel) {
2678           if (annotationModel instanceof IAnnotationModelExtension) {
2679             ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
2680           } else {
2681             removeOccurrenceAnnotations();
2682             Iterator iter = annotationMap.entrySet().iterator();
2683             while (iter.hasNext()) {
2684               Map.Entry mapEntry = (Map.Entry) iter.next();
2685               annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue());
2686             }
2687           }
2688           fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
2689         }
2690       } finally {
2691         fDocument.removeDocumentListener(this);
2692       }
2693       return Status.OK_STATUS;
2694     }
2695
2696     /*
2697      * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
2698      */
2699     public void documentAboutToBeChanged(DocumentEvent event) {
2700       fCancelled = true;
2701     }
2702
2703     /*
2704      * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
2705      */
2706     public void documentChanged(DocumentEvent event) {
2707     }
2708   }
2709
2710   /**
2711    * Updates the selection in the editor's widget with the selection of the outline page.
2712    */
2713   class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
2714     public void selectionChanged(SelectionChangedEvent event) {
2715       doSelectionChanged(event);
2716     }
2717   }
2718
2719   /**
2720    * Holds the current occurrence annotations.
2721    * 
2722    * @since 3.0
2723    */
2724   private Annotation[] fOccurrenceAnnotations = null;
2725
2726   private Job fOccurrencesFinderJob;
2727
2728   /** Preference key for showing the line number ruler */
2729   //  private final static String LINE_NUMBER_RULER =
2730   // PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
2731   /** Preference key for the foreground color of the line numbers */
2732   // private final static String LINE_NUMBER_COLOR =
2733   // PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
2734   /** Preference key for the link color */
2735   private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR;
2736
2737   /** Preference key for compiler task tags */
2738   private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
2739
2740   // protected PHPActionGroup fActionGroups;
2741   //  /** The outline page */
2742   //  private AbstractContentOutlinePage fOutlinePage;
2743   /** The outline page */
2744   protected JavaOutlinePage fOutlinePage;
2745
2746   /** Outliner context menu Id */
2747   protected String fOutlinerContextMenuId;
2748
2749   /**
2750    * Indicates whether this editor should react on outline page selection changes
2751    */
2752   private int fIgnoreOutlinePageSelection;
2753
2754   /** The outline page selection updater */
2755   //  private OutlinePageSelectionUpdater fUpdater;
2756   //  protected PHPSyntaxParserThread fValidationThread = null;
2757   // private IPreferenceStore fPHPPrefStore;
2758   /** The selection changed listener */
2759   //  protected ISelectionChangedListener fSelectionChangedListener = new
2760   // SelectionChangedListener();
2761   /**
2762    * The editor selection changed listener.
2763    * 
2764    * @since 3.0
2765    */
2766   private EditorSelectionChangedListener fEditorSelectionChangedListener;
2767
2768   /** The selection changed listener */
2769   protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener();
2770
2771   /** The editor's bracket matcher */
2772   private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
2773
2774   /** The line number ruler column */
2775   //  private LineNumberRulerColumn fLineNumberRulerColumn;
2776   /** This editor's encoding support */
2777   private DefaultEncodingSupport fEncodingSupport;
2778
2779   /** The mouse listener */
2780   private MouseClickListener fMouseListener;
2781
2782   /**
2783    * Indicates whether this editor is about to update any annotation views.
2784    * 
2785    * @since 3.0
2786    */
2787   private boolean fIsUpdatingAnnotationViews = false;
2788
2789   /**
2790    * The marker that served as last target for a goto marker request.
2791    * 
2792    * @since 3.0
2793    */
2794   private IMarker fLastMarkerTarget = null;
2795
2796   protected CompositeActionGroup fActionGroups;
2797
2798   protected CompositeActionGroup fContextMenuGroup;
2799
2800   /**
2801    * This editor's projection support
2802    * 
2803    * @since 3.0
2804    */
2805   private ProjectionSupport fProjectionSupport;
2806
2807   /**
2808    * This editor's projection model updater
2809    * 
2810    * @since 3.0
2811    */
2812   private IJavaFoldingStructureProvider fProjectionModelUpdater;
2813
2814   /**
2815    * The override and implements indicator manager for this editor.
2816    * 
2817    * @since 3.0
2818    */
2819   //    protected OverrideIndicatorManager fOverrideIndicatorManager;
2820   /**
2821    * The action group for folding.
2822    * 
2823    * @since 3.0
2824    */
2825   private FoldingActionGroup fFoldingGroup;
2826
2827   /** The information presenter. */
2828   private InformationPresenter fInformationPresenter;
2829
2830   /** The annotation access */
2831   //  protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
2832   /** The overview ruler */
2833   protected OverviewRuler isOverviewRulerVisible;
2834
2835   /** The source viewer decoration support */
2836   //protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
2837   /** The overview ruler */
2838   //protected OverviewRuler fOverviewRuler;
2839   /** The preference property change listener for java core. */
2840   private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener();
2841
2842   /**
2843    * Returns the most narrow java element including the given offset
2844    * 
2845    * @param offset
2846    *          the offset inside of the requested element
2847    */
2848   abstract protected IJavaElement getElementAt(int offset);
2849
2850   /**
2851    * Returns the java element of this editor's input corresponding to the given IJavaElement
2852    */
2853   abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
2854
2855   /**
2856    * Sets the input of the editor's outline page.
2857    */
2858   abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
2859
2860   /**
2861    * Default constructor.
2862    */
2863   public PHPEditor() {
2864     super();
2865   }
2866
2867   /*
2868    * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
2869    */
2870   protected void initializeKeyBindingScopes() {
2871     setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$
2872   }
2873
2874   /*
2875    * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
2876    */
2877   protected void initializeEditor() {
2878     //jsurfer old code
2879     //    JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
2880     //    setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, this, IPHPPartitions.PHP_PARTITIONING)); //,
2881     // IJavaPartitions.JAVA_PARTITIONING));
2882     IPreferenceStore store = createCombinedPreferenceStore(null);
2883     setPreferenceStore(store);
2884     JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
2885     setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
2886         IPHPPartitions.PHP_PARTITIONING));
2887     // TODO changed in 3.x ?
2888     //    setRangeIndicator(new DefaultRangeIndicator());
2889     //    if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
2890     //      fUpdater = new OutlinePageSelectionUpdater();
2891     // jsurfer end
2892
2893     //          IPreferenceStore store= createCombinedPreferenceStore(null);
2894     //          setPreferenceStore(store);
2895     //          JavaTextTools textTools=
2896     // PHPeclipsePlugin.getDefault().getJavaTextTools();
2897     //          setSourceViewerConfiguration(new
2898     // JavaSourceViewerConfiguration(textTools.getColorManager(), store,
2899     // this, IJavaPartitions.JAVA_PARTITIONING));
2900     //          fMarkOccurrenceAnnotations=
2901     // store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
2902     //          fStickyOccurrenceAnnotations=
2903     // store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
2904     //          fMarkTypeOccurrences=
2905     // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
2906     //          fMarkMethodOccurrences=
2907     // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
2908     //          fMarkConstantOccurrences=
2909     // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
2910     //          fMarkFieldOccurrences=
2911     // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
2912     //          fMarkLocalVariableypeOccurrences=
2913     // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
2914     //          fMarkExceptionOccurrences=
2915     // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
2916     //          fMarkMethodExitPoints=
2917     // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
2918   }
2919
2920   /*
2921    * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
2922    */
2923   protected void updatePropertyDependentActions() {
2924     super.updatePropertyDependentActions();
2925     if (fEncodingSupport != null)
2926       fEncodingSupport.reset();
2927   }
2928
2929   /*
2930    * Update the hovering behavior depending on the preferences.
2931    */
2932   private void updateHoverBehavior() {
2933     SourceViewerConfiguration configuration = getSourceViewerConfiguration();
2934     String[] types = configuration.getConfiguredContentTypes(getSourceViewer());
2935
2936     for (int i = 0; i < types.length; i++) {
2937
2938       String t = types[i];
2939
2940       int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
2941
2942       ISourceViewer sourceViewer = getSourceViewer();
2943       if (sourceViewer instanceof ITextViewerExtension2) {
2944         if (stateMasks != null) {
2945           for (int j = 0; j < stateMasks.length; j++) {
2946             int stateMask = stateMasks[j];
2947             ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask);
2948             ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask);
2949           }
2950         } else {
2951           ITextHover textHover = configuration.getTextHover(sourceViewer, t);
2952           ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
2953         }
2954       } else
2955         sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
2956     }
2957   }
2958
2959   public void updatedTitleImage(Image image) {
2960     setTitleImage(image);
2961   }
2962
2963   /*
2964    * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
2965    */
2966   public Object getViewPartInput() {
2967     return getEditorInput().getAdapter(IResource.class);
2968   }
2969
2970   /*
2971    * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
2972    */
2973   protected void doSetSelection(ISelection selection) {
2974     super.doSetSelection(selection);
2975     synchronizeOutlinePageSelection();
2976   }
2977
2978   boolean isFoldingEnabled() {
2979     return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
2980   }
2981
2982   /*
2983    * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. widgets.Composite)
2984    */
2985   public void createPartControl(Composite parent) {
2986     super.createPartControl(parent);
2987
2988     //fSourceViewerDecorationSupport.install(getPreferenceStore());
2989
2990     ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
2991
2992     fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
2993     fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
2994     fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
2995     fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
2996       public IInformationControl createInformationControl(Shell shell) {
2997         return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
2998       }
2999     });
3000     fProjectionSupport.install();
3001
3002     fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
3003     if (fProjectionModelUpdater != null)
3004       fProjectionModelUpdater.install(this, projectionViewer);
3005
3006     if (isFoldingEnabled())
3007       projectionViewer.doOperation(ProjectionViewer.TOGGLE);
3008     Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
3009     preferences.addPropertyChangeListener(fPropertyChangeListener);
3010
3011     IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
3012       public IInformationControl createInformationControl(Shell parent) {
3013         boolean cutDown = false;
3014         int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
3015         return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
3016       }
3017     };
3018
3019     fInformationPresenter = new InformationPresenter(informationControlCreator);
3020     fInformationPresenter.setSizeConstraints(60, 10, true, true);
3021     fInformationPresenter.install(getSourceViewer());
3022
3023     fEditorSelectionChangedListener = new EditorSelectionChangedListener();
3024     fEditorSelectionChangedListener.install(getSelectionProvider());
3025
3026     if (isBrowserLikeLinks())
3027       enableBrowserLikeLinks();
3028
3029     if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
3030       enableOverwriteMode(false);
3031
3032     setWordWrap();
3033     //    getEditorSite().getShell().addShellListener(fActivationListener);
3034   }
3035
3036   private void setWordWrap() {
3037     if (getSourceViewer() != null) {
3038       getSourceViewer().getTextWidget().setWordWrap(
3039           PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS));
3040     }
3041   }
3042
3043   protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
3044
3045     support.setCharacterPairMatcher(fBracketMatcher);
3046     support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
3047
3048     super.configureSourceViewerDecorationSupport(support);
3049   }
3050
3051   /*
3052    * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
3053    */
3054   public void gotoMarker(IMarker marker) {
3055     fLastMarkerTarget = marker;
3056     if (!fIsUpdatingAnnotationViews) {
3057       super.gotoMarker(marker);
3058     }
3059   }
3060
3061   /**
3062    * Jumps to the next enabled annotation according to the given direction. An annotation type is enabled if it is configured to be
3063    * in the Next/Previous tool bar drop down menu and if it is checked.
3064    * 
3065    * @param forward
3066    *          <code>true</code> if search direction is forward, <code>false</code> if backward
3067    */
3068   public void gotoAnnotation(boolean forward) {
3069     ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
3070     Position position = new Position(0, 0);
3071     if (false /* delayed - see bug 18316 */) {
3072       getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
3073       selectAndReveal(position.getOffset(), position.getLength());
3074     } else /* no delay - see bug 18316 */{
3075       Annotation annotation = getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
3076       setStatusLineErrorMessage(null);
3077       setStatusLineMessage(null);
3078       if (annotation != null) {
3079         updateAnnotationViews(annotation);
3080         selectAndReveal(position.getOffset(), position.getLength());
3081         setStatusLineMessage(annotation.getText());
3082       }
3083     }
3084   }
3085
3086   /**
3087    * Returns the lock object for the given annotation model.
3088    * 
3089    * @param annotationModel
3090    *          the annotation model
3091    * @return the annotation model's lock object
3092    * @since 3.0
3093    */
3094   private Object getLockObject(IAnnotationModel annotationModel) {
3095     if (annotationModel instanceof ISynchronizable)
3096       return ((ISynchronizable) annotationModel).getLockObject();
3097     else
3098       return annotationModel;
3099   }
3100
3101   /**
3102    * Updates the annotation views that show the given annotation.
3103    * 
3104    * @param annotation
3105    *          the annotation
3106    */
3107   private void updateAnnotationViews(Annotation annotation) {
3108     IMarker marker = null;
3109     if (annotation instanceof MarkerAnnotation)
3110       marker = ((MarkerAnnotation) annotation).getMarker();
3111     else if (annotation instanceof IJavaAnnotation) {
3112       Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator();
3113       if (e != null) {
3114         while (e.hasNext()) {
3115           Object o = e.next();
3116           if (o instanceof MarkerAnnotation) {
3117             marker = ((MarkerAnnotation) o).getMarker();
3118             break;
3119           }
3120         }
3121       }
3122     }
3123
3124     if (marker != null && !marker.equals(fLastMarkerTarget)) {
3125       try {
3126         boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM);
3127         IWorkbenchPage page = getSite().getPage();
3128         IViewPart view = page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$  //$NON-NLS-2$
3129         if (view != null) {
3130           Method method = view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
3131           method.invoke(view, new Object[] { new StructuredSelection(marker), Boolean.TRUE });
3132         }
3133       } catch (CoreException x) {
3134       } catch (NoSuchMethodException x) {
3135       } catch (IllegalAccessException x) {
3136       } catch (InvocationTargetException x) {
3137       }
3138       // ignore exceptions, don't update any of the lists, just set status line
3139     }
3140   }
3141
3142   /**
3143    * Returns this document's complete text.
3144    * 
3145    * @return the document's complete text
3146    */
3147   public String get() {
3148     IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
3149     return doc.get();
3150   }
3151
3152   /**
3153    * Sets the outliner's context menu ID.
3154    */
3155   protected void setOutlinerContextMenuId(String menuId) {
3156     fOutlinerContextMenuId = menuId;
3157   }
3158
3159   /**
3160    * Returns the standard action group of this editor.
3161    */
3162   protected ActionGroup getActionGroup() {
3163     return fActionGroups;
3164   }
3165
3166   //  public JavaOutlinePage getfOutlinePage() {
3167   //    return fOutlinePage;
3168   //  }
3169
3170   /**
3171    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method extend the actions to add those
3172    * specific to the receiver
3173    */
3174   protected void createActions() {
3175     super.createActions();
3176
3177     ActionGroup oeg, ovg, jsg, sg;
3178     fActionGroups = new CompositeActionGroup(new ActionGroup[] { oeg = new OpenEditorActionGroup(this),
3179     //          sg= new ShowActionGroup(this),
3180         //              ovg= new OpenViewActionGroup(this),
3181         //              jsg= new JavaSearchActionGroup(this)
3182         });
3183     fContextMenuGroup = new CompositeActionGroup(new ActionGroup[] { oeg });
3184     //, ovg, sg, jsg});
3185
3186     fFoldingGroup = new FoldingActionGroup(this, getViewer());
3187
3188 //    ResourceAction resAction = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
3189 //        "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
3190 //    resAction = new InformationDispatchAction(PHPEditorMessages.getResourceBundle(),
3191 //        "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
3192 //    resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC);
3193 //    setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
3194     
3195     //  WorkbenchHelp.setHelp(resAction,
3196     // IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
3197
3198     Action action = new GotoMatchingBracketAction(this);
3199     action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
3200     setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
3201
3202     //  action= new
3203     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.",
3204     // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
3205     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE);
3206     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action);
3207     //// WorkbenchHelp.setHelp(action,
3208     // IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
3209     //
3210     //  action= new
3211     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.",
3212     // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
3213     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE);
3214     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE,
3215     // action);
3216     //// WorkbenchHelp.setHelp(action,
3217     // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
3218     //  
3219     //  action= new
3220     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.",
3221     // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
3222     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY);
3223     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY,
3224     // action);
3225     //// WorkbenchHelp.setHelp(action,
3226     // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
3227
3228     fEncodingSupport = new DefaultEncodingSupport();
3229     fEncodingSupport.initialize(this);
3230
3231     //  fSelectionHistory= new SelectionHistory(this);
3232     //
3233     //  action= new StructureSelectEnclosingAction(this, fSelectionHistory);
3234     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);
3235     //  setAction(StructureSelectionAction.ENCLOSING, action);
3236     //
3237     //  action= new StructureSelectNextAction(this, fSelectionHistory);
3238     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
3239     //  setAction(StructureSelectionAction.NEXT, action);
3240     //
3241     //  action= new StructureSelectPreviousAction(this, fSelectionHistory);
3242     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
3243     //  setAction(StructureSelectionAction.PREVIOUS, action);
3244     //
3245     //  StructureSelectHistoryAction historyAction= new
3246     // StructureSelectHistoryAction(this, fSelectionHistory);
3247     //  historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);
3248     //  setAction(StructureSelectionAction.HISTORY, historyAction);
3249     //  fSelectionHistory.setHistoryAction(historyAction);
3250     //                  
3251     //  action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
3252     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
3253     //  setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
3254     //
3255     //  action=
3256     // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
3257     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
3258     //  setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
3259     //  
3260     //  action= new QuickFormatAction();
3261     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
3262     //  setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
3263     //
3264     //  action= new RemoveOccurrenceAnnotations(this);
3265     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
3266     //  setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
3267
3268     // add annotation actions
3269     action = new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
3270     setAction("AnnotationAction", action); //$NON-NLS-1$
3271   }
3272
3273   private void internalDoSetInput(IEditorInput input) throws CoreException {
3274     super.doSetInput(input);
3275
3276     if (getSourceViewer() instanceof JavaSourceViewer) {
3277       JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer();
3278       if (viewer.getReconciler() == null) {
3279         IReconciler reconciler = getSourceViewerConfiguration().getReconciler(viewer);
3280         if (reconciler != null) {
3281           reconciler.install(viewer);
3282           viewer.setReconciler(reconciler);
3283         }
3284       }
3285     }
3286
3287     if (fEncodingSupport != null)
3288       fEncodingSupport.reset();
3289
3290     setOutlinePageInput(fOutlinePage, input);
3291
3292     if (fProjectionModelUpdater != null)
3293       fProjectionModelUpdater.initialize();
3294
3295     //        if (isShowingOverrideIndicators())
3296     //                  installOverrideIndicator(false);
3297   }
3298
3299   /*
3300    * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
3301    * @since 3.0
3302    */
3303   protected void setPreferenceStore(IPreferenceStore store) {
3304     super.setPreferenceStore(store);
3305     if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
3306       JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
3307       setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
3308           IPHPPartitions.PHP_PARTITIONING));
3309     }
3310     if (getSourceViewer() instanceof JavaSourceViewer)
3311       ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
3312   }
3313
3314   /**
3315    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra disposal
3316    * actions required by the php editor.
3317    */
3318   public void dispose() {
3319     if (fProjectionModelUpdater != null) {
3320       fProjectionModelUpdater.uninstall();
3321       fProjectionModelUpdater = null;
3322     }
3323
3324     if (fProjectionSupport != null) {
3325       fProjectionSupport.dispose();
3326       fProjectionSupport = null;
3327     }
3328     //   PHPEditorEnvironment.disconnect(this);
3329     if (fOutlinePage != null)
3330       fOutlinePage.setInput(null);
3331
3332     if (fActionGroups != null)
3333       fActionGroups.dispose();
3334
3335     if (isBrowserLikeLinks())
3336       disableBrowserLikeLinks();
3337
3338     if (fEncodingSupport != null) {
3339       fEncodingSupport.dispose();
3340       fEncodingSupport = null;
3341     }
3342
3343     if (fPropertyChangeListener != null) {
3344       Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
3345       preferences.removePropertyChangeListener(fPropertyChangeListener);
3346       fPropertyChangeListener = null;
3347     }
3348
3349     //    if (fSourceViewerDecorationSupport != null) {
3350     //      fSourceViewerDecorationSupport.dispose();
3351     //      fSourceViewerDecorationSupport = null;
3352     //    }
3353
3354     if (fBracketMatcher != null) {
3355       fBracketMatcher.dispose();
3356       fBracketMatcher = null;
3357     }
3358
3359     if (fEditorSelectionChangedListener != null) {
3360       fEditorSelectionChangedListener.uninstall(getSelectionProvider());
3361       fEditorSelectionChangedListener = null;
3362     }
3363
3364     super.dispose();
3365   }
3366
3367   /**
3368    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra revert behavior
3369    * required by the php editor.
3370    */
3371   //  public void doRevertToSaved() {
3372   //    super.doRevertToSaved();
3373   //    if (fOutlinePage != null)
3374   //      fOutlinePage.update();
3375   //  }
3376   /**
3377    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra save behavior
3378    * required by the php editor.
3379    */
3380   //  public void doSave(IProgressMonitor monitor) {
3381   //    super.doSave(monitor);
3382   // compile or not, according to the user preferences
3383   // IPreferenceStore store = getPreferenceStore();
3384   // the parse on save was changed to the eclipse "builders" concept
3385   //    if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) {
3386   //      IAction a = PHPParserAction.getInstance();
3387   //      if (a != null)
3388   //        a.run();
3389   //    }
3390   //    if (SWT.getPlatform().equals("win32")) {
3391   //      IAction a = ShowExternalPreviewAction.getInstance();
3392   //      if (a != null)
3393   //        a.run();
3394   //    }
3395   //    if (fOutlinePage != null)
3396   //      fOutlinePage.update();
3397   //  }
3398   /**
3399    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra save as
3400    * behavior required by the php editor.
3401    */
3402   //  public void doSaveAs() {
3403   //    super.doSaveAs();
3404   //    if (fOutlinePage != null)
3405   //      fOutlinePage.update();
3406   //  }
3407   /*
3408    * @see StatusTextEditor#getStatusHeader(IStatus)
3409    */
3410   protected String getStatusHeader(IStatus status) {
3411     if (fEncodingSupport != null) {
3412       String message = fEncodingSupport.getStatusHeader(status);
3413       if (message != null)
3414         return message;
3415     }
3416     return super.getStatusHeader(status);
3417   }
3418
3419   /*
3420    * @see StatusTextEditor#getStatusBanner(IStatus)
3421    */
3422   protected String getStatusBanner(IStatus status) {
3423     if (fEncodingSupport != null) {
3424       String message = fEncodingSupport.getStatusBanner(status);
3425       if (message != null)
3426         return message;
3427     }
3428     return super.getStatusBanner(status);
3429   }
3430
3431   /*
3432    * @see StatusTextEditor#getStatusMessage(IStatus)
3433    */
3434   protected String getStatusMessage(IStatus status) {
3435     if (fEncodingSupport != null) {
3436       String message = fEncodingSupport.getStatusMessage(status);
3437       if (message != null)
3438         return message;
3439     }
3440     return super.getStatusMessage(status);
3441   }
3442
3443   /**
3444    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs sets the input of the
3445    * outline page after AbstractTextEditor has set input.
3446    */
3447   //  protected void doSetInput(IEditorInput input) throws CoreException {
3448   //    super.doSetInput(input);
3449   //    if (fEncodingSupport != null)
3450   //      fEncodingSupport.reset();
3451   //    setOutlinePageInput(fOutlinePage, input);
3452   //  }
3453   /*
3454    * @see AbstractTextEditor#doSetInput
3455    */
3456   protected void doSetInput(IEditorInput input) throws CoreException {
3457     ISourceViewer sourceViewer = getSourceViewer();
3458     if (!(sourceViewer instanceof ISourceViewerExtension2)) {
3459       setPreferenceStore(createCombinedPreferenceStore(input));
3460       internalDoSetInput(input);
3461       return;
3462     }
3463
3464     // uninstall & unregister preference store listener
3465     if (isBrowserLikeLinks())
3466       disableBrowserLikeLinks();
3467     getSourceViewerDecorationSupport(sourceViewer).uninstall();
3468     ((ISourceViewerExtension2) sourceViewer).unconfigure();
3469
3470     setPreferenceStore(createCombinedPreferenceStore(input));
3471
3472     // install & register preference store listener
3473     sourceViewer.configure(getSourceViewerConfiguration());
3474     getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
3475     if (isBrowserLikeLinks())
3476       enableBrowserLikeLinks();
3477
3478     internalDoSetInput(input);
3479   }
3480
3481   /*
3482    * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
3483    */
3484   //  public Object getViewPartInput() {
3485   //    return getEditorInput().getAdapter(IFile.class);
3486   //  }
3487   /**
3488    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method adds any PHPEditor specific
3489    * entries.
3490    */
3491   public void editorContextMenuAboutToShow(MenuManager menu) {
3492     super.editorContextMenuAboutToShow(menu);
3493     menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
3494     menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
3495
3496     ActionContext context = new ActionContext(getSelectionProvider().getSelection());
3497     fContextMenuGroup.setContext(context);
3498     fContextMenuGroup.fillContextMenu(menu);
3499     fContextMenuGroup.setContext(null);
3500     //    addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format");
3501     // //$NON-NLS-1$
3502     //
3503     //    ActionContext context =
3504     //      new ActionContext(getSelectionProvider().getSelection());
3505     //    fContextMenuGroup.setContext(context);
3506     //    fContextMenuGroup.fillContextMenu(menu);
3507     //    fContextMenuGroup.setContext(null);
3508   }
3509
3510   /**
3511    * Creates the outline page used with this editor.
3512    */
3513   protected JavaOutlinePage createOutlinePage() {
3514     JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
3515     fOutlineSelectionChangedListener.install(page);
3516     setOutlinePageInput(page, getEditorInput());
3517     return page;
3518   }
3519
3520   /**
3521    * Informs the editor that its outliner has been closed.
3522    */
3523   public void outlinePageClosed() {
3524     if (fOutlinePage != null) {
3525       fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3526       fOutlinePage = null;
3527       resetHighlightRange();
3528     }
3529   }
3530
3531   /**
3532    * Synchronizes the outliner selection with the given element position in the editor.
3533    * 
3534    * @param element
3535    *          the java element to select
3536    */
3537   protected void synchronizeOutlinePage(ISourceReference element) {
3538     synchronizeOutlinePage(element, true);
3539   }
3540
3541   /**
3542    * Synchronizes the outliner selection with the given element position in the editor.
3543    * 
3544    * @param element
3545    *          the java element to select
3546    * @param checkIfOutlinePageActive
3547    *          <code>true</code> if check for active outline page needs to be done
3548    */
3549   protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
3550     if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
3551       fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3552       fOutlinePage.select(element);
3553       fOutlineSelectionChangedListener.install(fOutlinePage);
3554     }
3555   }
3556
3557   /**
3558    * Synchronizes the outliner selection with the actual cursor position in the editor.
3559    */
3560   public void synchronizeOutlinePageSelection() {
3561     synchronizeOutlinePage(computeHighlightRangeSourceReference());
3562
3563     //    ISourceViewer sourceViewer = getSourceViewer();
3564     //    if (sourceViewer == null || fOutlinePage == null)
3565     //      return;
3566     //
3567     //    StyledText styledText = sourceViewer.getTextWidget();
3568     //    if (styledText == null)
3569     //      return;
3570     //
3571     //    int caret = 0;
3572     //    if (sourceViewer instanceof ITextViewerExtension3) {
3573     //      ITextViewerExtension3 extension = (ITextViewerExtension3)
3574     // sourceViewer;
3575     //      caret =
3576     // extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3577     //    } else {
3578     //      int offset = sourceViewer.getVisibleRegion().getOffset();
3579     //      caret = offset + styledText.getCaretOffset();
3580     //    }
3581     //
3582     //    IJavaElement element = getElementAt(caret);
3583     //    if (element instanceof ISourceReference) {
3584     //      fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
3585     //      fOutlinePage.select((ISourceReference) element);
3586     //      fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
3587     //    }
3588   }
3589
3590   protected void setSelection(ISourceReference reference, boolean moveCursor) {
3591
3592     ISelection selection = getSelectionProvider().getSelection();
3593     if (selection instanceof TextSelection) {
3594       TextSelection textSelection = (TextSelection) selection;
3595       if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
3596         markInNavigationHistory();
3597     }
3598
3599     if (reference != null) {
3600
3601       StyledText textWidget = null;
3602
3603       ISourceViewer sourceViewer = getSourceViewer();
3604       if (sourceViewer != null)
3605         textWidget = sourceViewer.getTextWidget();
3606
3607       if (textWidget == null)
3608         return;
3609
3610       try {
3611
3612         ISourceRange range = reference.getSourceRange();
3613         if (range == null)
3614           return;
3615
3616         int offset = range.getOffset();
3617         int length = range.getLength();
3618
3619         if (offset < 0 || length < 0)
3620           return;
3621
3622         textWidget.setRedraw(false);
3623
3624         setHighlightRange(offset, length, moveCursor);
3625
3626         if (!moveCursor)
3627           return;
3628
3629         offset = -1;
3630         length = -1;
3631
3632         if (reference instanceof IMember) {
3633           range = ((IMember) reference).getNameRange();
3634           if (range != null) {
3635             offset = range.getOffset();
3636             length = range.getLength();
3637           }
3638         }
3639         //                                      else if (reference instanceof IImportDeclaration) {
3640         //                                              String name= ((IImportDeclaration)
3641         // reference).getElementName();
3642         //                                              if (name != null && name.length() > 0) {
3643         //                                                      String content= reference.getSource();
3644         //                                                      if (content != null) {
3645         //                                                              offset= range.getOffset() + content.indexOf(name);
3646         //                                                              length= name.length();
3647         //                                                      }
3648         //                                              }
3649         //                                      } else if (reference instanceof IPackageDeclaration) {
3650         //                                              String name= ((IPackageDeclaration)
3651         // reference).getElementName();
3652         //                                              if (name != null && name.length() > 0) {
3653         //                                                      String content= reference.getSource();
3654         //                                                      if (content != null) {
3655         //                                                              offset= range.getOffset() + content.indexOf(name);
3656         //                                                              length= name.length();
3657         //                                                      }
3658         //                                              }
3659         //                                      }
3660
3661         if (offset > -1 && length > 0) {
3662           sourceViewer.revealRange(offset, length);
3663           sourceViewer.setSelectedRange(offset, length);
3664         }
3665
3666       } catch (JavaModelException x) {
3667       } catch (IllegalArgumentException x) {
3668       } finally {
3669         if (textWidget != null)
3670           textWidget.setRedraw(true);
3671       }
3672
3673     } else if (moveCursor) {
3674       resetHighlightRange();
3675     }
3676
3677     markInNavigationHistory();
3678   }
3679
3680   public void setSelection(IJavaElement element) {
3681     if (element == null || element instanceof ICompilationUnit) { // ||
3682       // element
3683       // instanceof
3684       // IClassFile)
3685       // {
3686       /*
3687        * If the element is an ICompilationUnit this unit is either the input of this editor or not being displayed. In both cases,
3688        * nothing should happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
3689        */
3690       return;
3691     }
3692
3693     IJavaElement corresponding = getCorrespondingElement(element);
3694     if (corresponding instanceof ISourceReference) {
3695       ISourceReference reference = (ISourceReference) corresponding;
3696       // set highlight range
3697       setSelection(reference, true);
3698       // set outliner selection
3699       if (fOutlinePage != null) {
3700         fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3701         fOutlinePage.select(reference);
3702         fOutlineSelectionChangedListener.install(fOutlinePage);
3703       }
3704     }
3705   }
3706
3707   public synchronized void editingScriptStarted() {
3708     ++fIgnoreOutlinePageSelection;
3709   }
3710
3711   public synchronized void editingScriptEnded() {
3712     --fIgnoreOutlinePageSelection;
3713   }
3714
3715   public synchronized boolean isEditingScriptRunning() {
3716     return (fIgnoreOutlinePageSelection > 0);
3717   }
3718
3719   /**
3720    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs gets the java content
3721    * outline page if request is for a an outline page.
3722    */
3723   public Object getAdapter(Class required) {
3724
3725     if (IContentOutlinePage.class.equals(required)) {
3726       if (fOutlinePage == null)
3727         fOutlinePage = createOutlinePage();
3728       return fOutlinePage;
3729     }
3730
3731     if (IEncodingSupport.class.equals(required))
3732       return fEncodingSupport;
3733
3734     if (required == IShowInTargetList.class) {
3735       return new IShowInTargetList() {
3736         public String[] getShowInTargetIds() {
3737           return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
3738         }
3739
3740       };
3741     }
3742     if (fProjectionSupport != null) {
3743       Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required);
3744       if (adapter != null)
3745         return adapter;
3746     }
3747
3748     return super.getAdapter(required);
3749   }
3750
3751   //  public Object getAdapter(Class required) {
3752   //    if (IContentOutlinePage.class.equals(required)) {
3753   //      if (fOutlinePage == null) {
3754   //        fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this);
3755   //        if (getEditorInput() != null)
3756   //          fOutlinePage.setInput(getEditorInput());
3757   //      }
3758   //      return fOutlinePage;
3759   //    }
3760   //
3761   //    if (IEncodingSupport.class.equals(required))
3762   //      return fEncodingSupport;
3763   //
3764   //    return super.getAdapter(required);
3765   //  }
3766
3767   protected void doSelectionChanged(SelectionChangedEvent event) {
3768     ISourceReference reference = null;
3769
3770     ISelection selection = event.getSelection();
3771     Iterator iter = ((IStructuredSelection) selection).iterator();
3772     while (iter.hasNext()) {
3773       Object o = iter.next();
3774       if (o instanceof ISourceReference) {
3775         reference = (ISourceReference) o;
3776         break;
3777       }
3778     }
3779
3780     if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
3781       PHPeclipsePlugin.getActivePage().bringToTop(this);
3782
3783     try {
3784       editingScriptStarted();
3785       setSelection(reference, !isActivePart());
3786     } finally {
3787       editingScriptEnded();
3788     }
3789   }
3790
3791   /*
3792    * @see AbstractTextEditor#adjustHighlightRange(int, int)
3793    */
3794   protected void adjustHighlightRange(int offset, int length) {
3795
3796     try {
3797
3798       IJavaElement element = getElementAt(offset);
3799       while (element instanceof ISourceReference) {
3800         ISourceRange range = ((ISourceReference) element).getSourceRange();
3801         if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
3802
3803           ISourceViewer viewer = getSourceViewer();
3804           if (viewer instanceof ITextViewerExtension5) {
3805             ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
3806             extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
3807           }
3808
3809           setHighlightRange(range.getOffset(), range.getLength(), true);
3810           if (fOutlinePage != null) {
3811             fOutlineSelectionChangedListener.uninstall(fOutlinePage);
3812             fOutlinePage.select((ISourceReference) element);
3813             fOutlineSelectionChangedListener.install(fOutlinePage);
3814           }
3815
3816           return;
3817         }
3818         element = element.getParent();
3819       }
3820
3821     } catch (JavaModelException x) {
3822       PHPeclipsePlugin.log(x.getStatus());
3823     }
3824
3825     ISourceViewer viewer = getSourceViewer();
3826     if (viewer instanceof ITextViewerExtension5) {
3827       ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
3828       extension.exposeModelRange(new Region(offset, length));
3829     } else {
3830       resetHighlightRange();
3831     }
3832
3833   }
3834
3835   protected boolean isActivePart() {
3836     IWorkbenchWindow window = getSite().getWorkbenchWindow();
3837     IPartService service = window.getPartService();
3838     IWorkbenchPart part = service.getActivePart();
3839     return part != null && part.equals(this);
3840   }
3841
3842   //  public void openContextHelp() {
3843   //    IDocument doc =
3844   // this.getDocumentProvider().getDocument(this.getEditorInput());
3845   //    ITextSelection selection = (ITextSelection)
3846   // this.getSelectionProvider().getSelection();
3847   //    int pos = selection.getOffset();
3848   //    String word = getFunctionName(doc, pos);
3849   //    openContextHelp(word);
3850   //  }
3851   //
3852   //  private void openContextHelp(String word) {
3853   //    open(word);
3854   //  }
3855   //
3856   //  public static void open(String word) {
3857   //    IHelp help = WorkbenchHelp.getHelpSupport();
3858   //    if (help != null) {
3859   //      IHelpResource helpResource = new PHPFunctionHelpResource(word);
3860   //      WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource);
3861   //    } else {
3862   //      // showMessage(shell, dialogTitle, ActionMessages.getString("Open help
3863   // not available"), false); //$NON-NLS-1$
3864   //    }
3865   //  }
3866
3867   //    private String getFunctionName(IDocument doc, int pos) {
3868   //            Point word = PHPWordExtractor.findWord(doc, pos);
3869   //            if (word != null) {
3870   //                    try {
3871   //                            return doc.get(word.x, word.y).replace('_', '-');
3872   //                    } catch (BadLocationException e) {
3873   //                    }
3874   //            }
3875   //            return "";
3876   //    }
3877
3878   /*
3879    * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
3880    */
3881   protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
3882
3883     try {
3884
3885       ISourceViewer sourceViewer = getSourceViewer();
3886       if (sourceViewer == null)
3887         return;
3888
3889       String property = event.getProperty();
3890
3891       if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
3892         Object value = event.getNewValue();
3893         if (value instanceof Integer) {
3894           sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
3895         } else if (value instanceof String) {
3896           try {
3897             sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
3898           } catch (NumberFormatException e) {
3899             // bug #1038071 - set default tab:
3900             sourceViewer.getTextWidget().setTabs(80);
3901           }
3902         }
3903         return;
3904       }
3905
3906       //      if (OVERVIEW_RULER.equals(property)) {
3907       //        if (isOverviewRulerVisible())
3908       //          showOverviewRuler();
3909       //        else
3910       //          hideOverviewRuler();
3911       //        return;
3912       //      }
3913
3914       //      if (LINE_NUMBER_RULER.equals(property)) {
3915       //        if (isLineNumberRulerVisible())
3916       //          showLineNumberRuler();
3917       //        else
3918       //          hideLineNumberRuler();
3919       //        return;
3920       //      }
3921
3922       //      if (fLineNumberRulerColumn != null
3923       //        && (LINE_NUMBER_COLOR.equals(property) ||
3924       // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
3925       // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
3926       //
3927       //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
3928       //      }
3929
3930       if (isJavaEditorHoverProperty(property))
3931         updateHoverBehavior();
3932
3933       if (BROWSER_LIKE_LINKS.equals(property)) {
3934         if (isBrowserLikeLinks())
3935           enableBrowserLikeLinks();
3936         else
3937           disableBrowserLikeLinks();
3938         return;
3939       }
3940
3941       if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
3942         if ((event.getNewValue() instanceof Boolean) && ((Boolean) event.getNewValue()).booleanValue())
3943           selectionChanged();
3944         return;
3945       }
3946
3947       if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
3948         if (event.getNewValue() instanceof Boolean) {
3949           Boolean disable = (Boolean) event.getNewValue();
3950           enableOverwriteMode(!disable.booleanValue());
3951         }
3952         return;
3953       }
3954
3955       //        if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property))
3956       // {
3957       //                if (event.getNewValue() instanceof Boolean) {
3958       //                        boolean markOccurrenceAnnotations=
3959       // ((Boolean)event.getNewValue()).booleanValue();
3960       //                        if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
3961       //                                fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
3962       //                                if (!fMarkOccurrenceAnnotations)
3963       //                                        uninstallOccurrencesFinder();
3964       //                                else
3965       //                                        installOccurrencesFinder();
3966       //                        }
3967       //                }
3968       //        }
3969       //        if
3970       // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
3971       // {
3972       //                if (event.getNewValue() instanceof Boolean) {
3973       //                        boolean stickyOccurrenceAnnotations=
3974       // ((Boolean)event.getNewValue()).booleanValue();
3975       //                        if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
3976       // {
3977       //                                fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations;
3978       //// if (!fMarkOccurrenceAnnotations)
3979       //// uninstallOccurrencesFinder();
3980       //// else
3981       //// installOccurrencesFinder();
3982       //                        }
3983       //                }
3984       //        }
3985
3986       ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
3987
3988       //                if (affectsOverrideIndicatorAnnotations(event)) {
3989       //                        if (isShowingOverrideIndicators()) {
3990       //                                if (fOverrideIndicatorManager == null)
3991       //                                        installOverrideIndicator(true);
3992       //                        } else {
3993       //                                if (fOverrideIndicatorManager != null)
3994       //                                        uninstallOverrideIndicator();
3995       //                        }
3996       //                        return;
3997       //                }
3998
3999       if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
4000         if (sourceViewer instanceof ProjectionViewer) {
4001           ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer;
4002           if (fProjectionModelUpdater != null)
4003             fProjectionModelUpdater.uninstall();
4004           // either freshly enabled or provider changed
4005           fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
4006           if (fProjectionModelUpdater != null) {
4007             fProjectionModelUpdater.install(this, projectionViewer);
4008           }
4009         }
4010         return;
4011       }
4012     } finally {
4013       super.handlePreferenceStoreChanged(event);
4014     }
4015   }
4016
4017   //  /*
4018   //     * @see
4019   // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
4020   //     */
4021   //  protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
4022   //
4023   //    try {
4024   //
4025   //      ISourceViewer sourceViewer = getSourceViewer();
4026   //      if (sourceViewer == null)
4027   //        return;
4028   //
4029   //      String property = event.getProperty();
4030   //
4031   //      // if
4032   // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
4033   //      // Object value= event.getNewValue();
4034   //      // if (value instanceof Integer) {
4035   //      // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
4036   //      // } else if (value instanceof String) {
4037   //      // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String)
4038   // value));
4039   //      // }
4040   //      // return;
4041   //      // }
4042   //
4043   //      if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
4044   //        if (isLineNumberRulerVisible())
4045   //          showLineNumberRuler();
4046   //        else
4047   //          hideLineNumberRuler();
4048   //        return;
4049   //      }
4050   //
4051   //      if (fLineNumberRulerColumn != null
4052   //        && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
4053   //          || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
4054   //          || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
4055   //
4056   //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4057   //      }
4058   //
4059   //    } finally {
4060   //      super.handlePreferenceStoreChanged(event);
4061   //    }
4062   //  }
4063
4064   //  private boolean isJavaEditorHoverProperty(String property) {
4065   //    return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
4066   //      || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
4067   //      || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
4068   //      || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
4069   //      || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
4070   //      || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
4071   //      || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
4072   //      || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
4073   //  }
4074
4075   /**
4076    * Shows the line number ruler column.
4077    */
4078   //  private void showLineNumberRuler() {
4079   //    IVerticalRuler v = getVerticalRuler();
4080   //    if (v instanceof CompositeRuler) {
4081   //      CompositeRuler c = (CompositeRuler) v;
4082   //      c.addDecorator(1, createLineNumberRulerColumn());
4083   //    }
4084   //  }
4085   private boolean isJavaEditorHoverProperty(String property) {
4086     return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
4087   }
4088
4089   /**
4090    * Return whether the browser like links should be enabled according to the preference store settings.
4091    * 
4092    * @return <code>true</code> if the browser like links should be enabled
4093    */
4094   private boolean isBrowserLikeLinks() {
4095     IPreferenceStore store = getPreferenceStore();
4096     return store.getBoolean(BROWSER_LIKE_LINKS);
4097   }
4098
4099   /**
4100    * Enables browser like links.
4101    */
4102   private void enableBrowserLikeLinks() {
4103     if (fMouseListener == null) {
4104       fMouseListener = new MouseClickListener();
4105       fMouseListener.install();
4106     }
4107   }
4108
4109   /**
4110    * Disables browser like links.
4111    */
4112   private void disableBrowserLikeLinks() {
4113     if (fMouseListener != null) {
4114       fMouseListener.uninstall();
4115       fMouseListener = null;
4116     }
4117   }
4118
4119   /**
4120    * Handles a property change event describing a change of the java core's preferences and updates the preference related editor
4121    * properties.
4122    * 
4123    * @param event
4124    *          the property change event
4125    */
4126   protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
4127     if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
4128       ISourceViewer sourceViewer = getSourceViewer();
4129       if (sourceViewer != null
4130           && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event
4131               .getNewValue())))
4132         sourceViewer.invalidateTextPresentation();
4133     }
4134     if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
4135       setWordWrap();
4136     }
4137   }
4138
4139   /**
4140    * Return whether the line number ruler column should be visible according to the preference store settings.
4141    * 
4142    * @return <code>true</code> if the line numbers should be visible
4143    */
4144   //  protected boolean isLineNumberRulerVisible() {
4145   //    IPreferenceStore store = getPreferenceStore();
4146   //    return store.getBoolean(LINE_NUMBER_RULER);
4147   //  }
4148   /**
4149    * Hides the line number ruler column.
4150    */
4151   //  private void hideLineNumberRuler() {
4152   //    IVerticalRuler v = getVerticalRuler();
4153   //    if (v instanceof CompositeRuler) {
4154   //      CompositeRuler c = (CompositeRuler) v;
4155   //      try {
4156   //        c.removeDecorator(1);
4157   //      } catch (Throwable e) {
4158   //      }
4159   //    }
4160   //  }
4161   /*
4162    * @see AbstractTextEditor#handleCursorPositionChanged()
4163    */
4164   //  protected void handleCursorPositionChanged() {
4165   //    super.handleCursorPositionChanged();
4166   //    if (!isEditingScriptRunning() && fUpdater != null)
4167   //      fUpdater.post();
4168   //  }
4169   /*
4170    * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
4171    */
4172   protected void handleElementContentReplaced() {
4173     super.handleElementContentReplaced();
4174     if (fProjectionModelUpdater != null)
4175       fProjectionModelUpdater.initialize();
4176   }
4177
4178   /**
4179    * Initializes the given line number ruler column from the preference store.
4180    * 
4181    * @param rulerColumn
4182    *          the ruler column to be initialized
4183    */
4184   //  protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
4185   // rulerColumn) {
4186   //    JavaTextTools textTools =
4187   // PHPeclipsePlugin.getDefault().getJavaTextTools();
4188   //    IColorManager manager = textTools.getColorManager();
4189   //
4190   //    IPreferenceStore store = getPreferenceStore();
4191   //    if (store != null) {
4192   //
4193   //      RGB rgb = null;
4194   //      // foreground color
4195   //      if (store.contains(LINE_NUMBER_COLOR)) {
4196   //        if (store.isDefault(LINE_NUMBER_COLOR))
4197   //          rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
4198   //        else
4199   //          rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
4200   //      }
4201   //      rulerColumn.setForeground(manager.getColor(rgb));
4202   //
4203   //      rgb = null;
4204   //      // background color
4205   //      if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
4206   //        if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
4207   //          if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
4208   //            rgb = PreferenceConverter.getDefaultColor(store,
4209   // PREFERENCE_COLOR_BACKGROUND);
4210   //          else
4211   //            rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
4212   //        }
4213   //      }
4214   //      rulerColumn.setBackground(manager.getColor(rgb));
4215   //    }
4216   //  }
4217   /**
4218    * Creates a new line number ruler column that is appropriately initialized.
4219    */
4220   //  protected IVerticalRulerColumn createLineNumberRulerColumn() {
4221   //    fLineNumberRulerColumn = new LineNumberRulerColumn();
4222   //    initializeLineNumberRulerColumn(fLineNumberRulerColumn);
4223   //    return fLineNumberRulerColumn;
4224   //  }
4225   /*
4226    * @see AbstractTextEditor#createVerticalRuler()
4227    */
4228   //  protected IVerticalRuler createVerticalRuler() {
4229   //    CompositeRuler ruler = new CompositeRuler();
4230   //    ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
4231   //    if (isLineNumberRulerVisible())
4232   //      ruler.addDecorator(1, createLineNumberRulerColumn());
4233   //    return ruler;
4234   //  }
4235   //  private static IRegion getSignedSelection(ITextViewer viewer) {
4236   //
4237   //    StyledText text = viewer.getTextWidget();
4238   //    int caretOffset = text.getCaretOffset();
4239   //    Point selection = text.getSelection();
4240   //
4241   //    // caret left
4242   //    int offset, length;
4243   //    if (caretOffset == selection.x) {
4244   //      offset = selection.y;
4245   //      length = selection.x - selection.y;
4246   //
4247   //      // caret right
4248   //    } else {
4249   //      offset = selection.x;
4250   //      length = selection.y - selection.x;
4251   //    }
4252   //
4253   //    return new Region(offset, length);
4254   //  }
4255   protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
4256     StyledText text = sourceViewer.getTextWidget();
4257     Point selection = text.getSelectionRange();
4258
4259     if (text.getCaretOffset() == selection.x) {
4260       selection.x = selection.x + selection.y;
4261       selection.y = -selection.y;
4262     }
4263
4264     selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
4265
4266     return new Region(selection.x, selection.y);
4267   }
4268
4269   /** Preference key for matching brackets */
4270   protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
4271
4272   /** Preference key for matching brackets color */
4273   protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
4274
4275   /** Preference key for highlighting current line */
4276   //  protected final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
4277   /** Preference key for highlight color of current line */
4278   //  protected final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
4279   /** Preference key for showing print marging ruler */
4280   //  protected final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
4281   /** Preference key for print margin ruler color */
4282   //  protected final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
4283   /** Preference key for print margin ruler column */
4284   //  protected final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
4285   /** Preference key for error indication */
4286   //  protected final static String ERROR_INDICATION =
4287   // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
4288   /** Preference key for error color */
4289   //  protected final static String ERROR_INDICATION_COLOR =
4290   // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
4291   /** Preference key for warning indication */
4292   //  protected final static String WARNING_INDICATION =
4293   // PreferenceConstants.EDITOR_WARNING_INDICATION;
4294   /** Preference key for warning color */
4295   //  protected final static String WARNING_INDICATION_COLOR =
4296   // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
4297   /** Preference key for task indication */
4298   protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
4299
4300   /** Preference key for task color */
4301   protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
4302
4303   /** Preference key for bookmark indication */
4304   protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
4305
4306   /** Preference key for bookmark color */
4307   protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
4308
4309   /** Preference key for search result indication */
4310   protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
4311
4312   /** Preference key for search result color */
4313   protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
4314
4315   /** Preference key for unknown annotation indication */
4316   protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
4317
4318   /** Preference key for unknown annotation color */
4319   protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
4320
4321   /** Preference key for shwoing the overview ruler */
4322   protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
4323
4324   /** Preference key for error indication in overview ruler */
4325   protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
4326
4327   /** Preference key for warning indication in overview ruler */
4328   protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
4329
4330   /** Preference key for task indication in overview ruler */
4331   protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
4332
4333   /** Preference key for bookmark indication in overview ruler */
4334   protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
4335
4336   /** Preference key for search result indication in overview ruler */
4337   protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
4338
4339   /** Preference key for unknown annotation indication in overview ruler */
4340   protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
4341
4342   //            /** Preference key for compiler task tags */
4343   //            private final static String COMPILER_TASK_TAGS=
4344   // JavaCore.COMPILER_TASK_TAGS;
4345   /** Preference key for browser like links */
4346   private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
4347
4348   /** Preference key for key modifier of browser like links */
4349   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
4350
4351   /**
4352    * Preference key for key modifier mask of browser like links. The value is only used if the value of
4353    * <code>EDITOR_BROWSER_LIKE_LINKS</code> cannot be resolved to valid SWT modifier bits.
4354    * 
4355    * @since 2.1.1
4356    */
4357   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
4358
4359   private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
4360
4361   private static boolean isBracket(char character) {
4362     for (int i = 0; i != BRACKETS.length; ++i)
4363       if (character == BRACKETS[i])
4364         return true;
4365     return false;
4366   }
4367
4368   private static boolean isSurroundedByBrackets(IDocument document, int offset) {
4369     if (offset == 0 || offset == document.getLength())
4370       return false;
4371
4372     try {
4373       return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
4374
4375     } catch (BadLocationException e) {
4376       return false;
4377     }
4378   }
4379
4380   //  protected void configureSourceViewerDecorationSupport() {
4381   //
4382   //    fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
4383   //
4384   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4385   //      AnnotationType.UNKNOWN,
4386   //      UNKNOWN_INDICATION_COLOR,
4387   //      UNKNOWN_INDICATION,
4388   //      UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
4389   //      0);
4390   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4391   //      AnnotationType.BOOKMARK,
4392   //      BOOKMARK_INDICATION_COLOR,
4393   //      BOOKMARK_INDICATION,
4394   //      BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
4395   //      1);
4396   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4397   //      AnnotationType.TASK,
4398   //      TASK_INDICATION_COLOR,
4399   //      TASK_INDICATION,
4400   //      TASK_INDICATION_IN_OVERVIEW_RULER,
4401   //      2);
4402   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4403   //      AnnotationType.SEARCH,
4404   //      SEARCH_RESULT_INDICATION_COLOR,
4405   //      SEARCH_RESULT_INDICATION,
4406   //      SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
4407   //      3);
4408   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4409   //      AnnotationType.WARNING,
4410   //      WARNING_INDICATION_COLOR,
4411   //      WARNING_INDICATION,
4412   //      WARNING_INDICATION_IN_OVERVIEW_RULER,
4413   //      4);
4414   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
4415   //      AnnotationType.ERROR,
4416   //      ERROR_INDICATION_COLOR,
4417   //      ERROR_INDICATION,
4418   //      ERROR_INDICATION_IN_OVERVIEW_RULER,
4419   //      5);
4420   //
4421   //    fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE,
4422   // CURRENT_LINE_COLOR);
4423   //    fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN,
4424   // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
4425   //    fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
4426   // MATCHING_BRACKETS_COLOR);
4427   //
4428   //    fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
4429   //
4430   //  }
4431   /**
4432    * Returns the Java element wrapped by this editors input.
4433    * 
4434    * @return the Java element wrapped by this editors input.
4435    * @since 3.0
4436    */
4437   abstract protected IJavaElement getInputJavaElement();
4438
4439   protected void updateStatusLine() {
4440     ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
4441     Annotation annotation = getAnnotation(selection.getOffset(), selection.getLength());
4442     setStatusLineErrorMessage(null);
4443     setStatusLineMessage(null);
4444     if (annotation != null) {
4445       try {
4446         fIsUpdatingAnnotationViews = true;
4447         updateAnnotationViews(annotation);
4448       } finally {
4449         fIsUpdatingAnnotationViews = false;
4450       }
4451       if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
4452         setStatusLineMessage(annotation.getText());
4453     }
4454   }
4455
4456   /**
4457    * Jumps to the matching bracket.
4458    */
4459   public void gotoMatchingBracket() {
4460
4461     ISourceViewer sourceViewer = getSourceViewer();
4462     IDocument document = sourceViewer.getDocument();
4463     if (document == null)
4464       return;
4465
4466     IRegion selection = getSignedSelection(sourceViewer);
4467
4468     int selectionLength = Math.abs(selection.getLength());
4469     if (selectionLength > 1) {
4470       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$               
4471       sourceViewer.getTextWidget().getDisplay().beep();
4472       return;
4473     }
4474
4475     // #26314
4476     int sourceCaretOffset = selection.getOffset() + selection.getLength();
4477     if (isSurroundedByBrackets(document, sourceCaretOffset))
4478       sourceCaretOffset -= selection.getLength();
4479
4480     IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
4481     if (region == null) {
4482       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$              
4483       sourceViewer.getTextWidget().getDisplay().beep();
4484       return;
4485     }
4486
4487     int offset = region.getOffset();
4488     int length = region.getLength();
4489
4490     if (length < 1)
4491       return;
4492
4493     int anchor = fBracketMatcher.getAnchor();
4494     int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
4495
4496     boolean visible = false;
4497     if (sourceViewer instanceof ITextViewerExtension3) {
4498       ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
4499       visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
4500     } else {
4501       IRegion visibleRegion = sourceViewer.getVisibleRegion();
4502       visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
4503     }
4504
4505     if (!visible) {
4506       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$          
4507       sourceViewer.getTextWidget().getDisplay().beep();
4508       return;
4509     }
4510
4511     if (selection.getLength() < 0)
4512       targetOffset -= selection.getLength();
4513
4514     sourceViewer.setSelectedRange(targetOffset, selection.getLength());
4515     sourceViewer.revealRange(targetOffset, selection.getLength());
4516   }
4517
4518   /**
4519    * Ses the given message as error message to this editor's status line.
4520    * 
4521    * @param msg
4522    *          message to be set
4523    */
4524   protected void setStatusLineErrorMessage(String msg) {
4525     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4526     if (statusLine != null)
4527       statusLine.setMessage(true, msg, null);
4528   }
4529
4530   /**
4531    * Sets the given message as message to this editor's status line.
4532    * 
4533    * @param msg
4534    *          message to be set
4535    * @since 3.0
4536    */
4537   protected void setStatusLineMessage(String msg) {
4538     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
4539     if (statusLine != null)
4540       statusLine.setMessage(false, msg, null);
4541   }
4542
4543   /**
4544    * Returns the annotation closest to the given range respecting the given direction. If an annotation is found, the annotations
4545    * current position is copied into the provided annotation position.
4546    * 
4547    * @param offset
4548    *          the region offset
4549    * @param length
4550    *          the region length
4551    * @param forward
4552    *          <code>true</code> for forwards, <code>false</code> for backward
4553    * @param annotationPosition
4554    *          the position of the found annotation
4555    * @return the found annotation
4556    */
4557   private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
4558
4559     Annotation nextAnnotation = null;
4560     Position nextAnnotationPosition = null;
4561     Annotation containingAnnotation = null;
4562     Position containingAnnotationPosition = null;
4563     boolean currentAnnotation = false;
4564
4565     IDocument document = getDocumentProvider().getDocument(getEditorInput());
4566     int endOfDocument = document.getLength();
4567     int distance = Integer.MAX_VALUE;
4568
4569     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
4570     Iterator e = new JavaAnnotationIterator(model, true, true);
4571     while (e.hasNext()) {
4572       Annotation a = (Annotation) e.next();
4573       if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a))
4574         continue;
4575
4576       Position p = model.getPosition(a);
4577       if (p == null)
4578         continue;
4579
4580       if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
4581         if (containingAnnotation == null
4582             || (forward && p.length >= containingAnnotationPosition.length || !forward
4583                 && p.length >= containingAnnotationPosition.length)) {
4584           containingAnnotation = a;
4585           containingAnnotationPosition = p;
4586           currentAnnotation = p.length == length;
4587         }
4588       } else {
4589         int currentDistance = 0;
4590
4591         if (forward) {
4592           currentDistance = p.getOffset() - offset;
4593           if (currentDistance < 0)
4594             currentDistance = endOfDocument + currentDistance;
4595
4596           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
4597             distance = currentDistance;
4598             nextAnnotation = a;
4599             nextAnnotationPosition = p;
4600           }
4601         } else {
4602           currentDistance = offset + length - (p.getOffset() + p.length);
4603           if (currentDistance < 0)
4604             currentDistance = endOfDocument + currentDistance;
4605
4606           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
4607             distance = currentDistance;
4608             nextAnnotation = a;
4609             nextAnnotationPosition = p;
4610           }
4611         }
4612       }
4613     }
4614     if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
4615       annotationPosition.setOffset(containingAnnotationPosition.getOffset());
4616       annotationPosition.setLength(containingAnnotationPosition.getLength());
4617       return containingAnnotation;
4618     }
4619     if (nextAnnotationPosition != null) {
4620       annotationPosition.setOffset(nextAnnotationPosition.getOffset());
4621       annotationPosition.setLength(nextAnnotationPosition.getLength());
4622     }
4623
4624     return nextAnnotation;
4625   }
4626
4627   /**
4628    * Returns the annotation overlapping with the given range or <code>null</code>.
4629    * 
4630    * @param offset
4631    *          the region offset
4632    * @param length
4633    *          the region length
4634    * @return the found annotation or <code>null</code>
4635    * @since 3.0
4636    */
4637   private Annotation getAnnotation(int offset, int length) {
4638     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
4639     Iterator e = new JavaAnnotationIterator(model, true, true);
4640     while (e.hasNext()) {
4641       Annotation a = (Annotation) e.next();
4642       if (!isNavigationTarget(a))
4643         continue;
4644
4645       Position p = model.getPosition(a);
4646       if (p != null && p.overlapsWith(offset, length))
4647         return a;
4648     }
4649
4650     return null;
4651   }
4652
4653   /**
4654    * Returns whether the given annotation is configured as a target for the "Go to Next/Previous Annotation" actions
4655    * 
4656    * @param annotation
4657    *          the annotation
4658    * @return <code>true</code> if this is a target, <code>false</code> otherwise
4659    * @since 3.0
4660    */
4661   private boolean isNavigationTarget(Annotation annotation) {
4662     Preferences preferences = EditorsUI.getPluginPreferences();
4663     AnnotationPreference preference = getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
4664     //          See bug 41689
4665     //          String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
4666     String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
4667     return (key != null && preferences.getBoolean(key));
4668   }
4669
4670   /**
4671    * Returns a segmentation of the line of the given document appropriate for bidi rendering. The default implementation returns
4672    * only the string literals of a php code line as segments.
4673    * 
4674    * @param document
4675    *          the document
4676    * @param lineOffset
4677    *          the offset of the line
4678    * @return the line's bidi segmentation
4679    * @throws BadLocationException
4680    *           in case lineOffset is not valid in document
4681    */
4682   public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
4683
4684     IRegion line = document.getLineInformationOfOffset(lineOffset);
4685     ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());
4686
4687     List segmentation = new ArrayList();
4688     for (int i = 0; i < linePartitioning.length; i++) {
4689       if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType()))
4690         segmentation.add(linePartitioning[i]);
4691     }
4692
4693     if (segmentation.size() == 0)
4694       return null;
4695
4696     int size = segmentation.size();
4697     int[] segments = new int[size * 2 + 1];
4698
4699     int j = 0;
4700     for (int i = 0; i < size; i++) {
4701       ITypedRegion segment = (ITypedRegion) segmentation.get(i);
4702
4703       if (i == 0)
4704         segments[j++] = 0;
4705
4706       int offset = segment.getOffset() - lineOffset;
4707       if (offset > segments[j - 1])
4708         segments[j++] = offset;
4709
4710       if (offset + segment.getLength() >= line.getLength())
4711         break;
4712
4713       segments[j++] = offset + segment.getLength();
4714     }
4715
4716     if (j < segments.length) {
4717       int[] result = new int[j];
4718       System.arraycopy(segments, 0, result, 0, j);
4719       segments = result;
4720     }
4721
4722     return segments;
4723   }
4724
4725   /**
4726    * Returns a segmentation of the given line appropriate for bidi rendering. The default implementation returns only the string
4727    * literals of a php code line as segments.
4728    * 
4729    * @param lineOffset
4730    *          the offset of the line
4731    * @param line
4732    *          the content of the line
4733    * @return the line's bidi segmentation
4734    */
4735   protected int[] getBidiLineSegments(int lineOffset, String line) {
4736     IDocumentProvider provider = getDocumentProvider();
4737     if (provider != null && line != null && line.length() > 0) {
4738       IDocument document = provider.getDocument(getEditorInput());
4739       if (document != null)
4740         try {
4741           return getBidiLineSegments(document, lineOffset);
4742         } catch (BadLocationException x) {
4743           // ignore
4744         }
4745     }
4746     return null;
4747   }
4748
4749   /*
4750    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
4751    */
4752   //  protected final ISourceViewer createSourceViewer(
4753   //    Composite parent,
4754   //    IVerticalRuler ruler,
4755   //    int styles) {
4756   //    ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
4757   //    StyledText text = viewer.getTextWidget();
4758   //    text.addBidiSegmentListener(new BidiSegmentListener() {
4759   //      public void lineGetSegments(BidiSegmentEvent event) {
4760   //        event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
4761   //      }
4762   //    });
4763   //    // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
4764   //    return viewer;
4765   //  }
4766   public final ISourceViewer getViewer() {
4767     return getSourceViewer();
4768   }
4769
4770   //  protected void showOverviewRuler() {
4771   //    if (fOverviewRuler != null) {
4772   //      if (getSourceViewer() instanceof ISourceViewerExtension) {
4773   //        ((ISourceViewerExtension)
4774   // getSourceViewer()).showAnnotationsOverview(true);
4775   //        fSourceViewerDecorationSupport.updateOverviewDecorations();
4776   //      }
4777   //    }
4778   //  }
4779   //
4780   //  protected void hideOverviewRuler() {
4781   //    if (getSourceViewer() instanceof ISourceViewerExtension) {
4782   //      fSourceViewerDecorationSupport.hideAnnotationOverview();
4783   //      ((ISourceViewerExtension)
4784   // getSourceViewer()).showAnnotationsOverview(false);
4785   //    }
4786   //  }
4787
4788   //  protected boolean isOverviewRulerVisible() {
4789   //    IPreferenceStore store = getPreferenceStore();
4790   //    return store.getBoolean(OVERVIEW_RULER);
4791   //  }
4792   /*
4793    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
4794    */
4795   //  protected ISourceViewer createJavaSourceViewer(
4796   //    Composite parent,
4797   //    IVerticalRuler ruler,
4798   //    IOverviewRuler overviewRuler,
4799   //    boolean isOverviewRulerVisible,
4800   //    int styles) {
4801   //    return new SourceViewer(parent, ruler, overviewRuler,
4802   // isOverviewRulerVisible(), styles);
4803   //  }
4804   /*
4805    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
4806    */
4807   protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
4808       boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
4809     return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
4810   }
4811
4812   /*
4813    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
4814    */
4815   protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
4816
4817     ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles,
4818         getPreferenceStore());
4819
4820     StyledText text = viewer.getTextWidget();
4821     text.addBidiSegmentListener(new BidiSegmentListener() {
4822       public void lineGetSegments(BidiSegmentEvent event) {
4823         event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
4824       }
4825     });
4826
4827     //          JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
4828
4829     // ensure source viewer decoration support has been created and
4830     // configured
4831     getSourceViewerDecorationSupport(viewer);
4832
4833     return viewer;
4834   }
4835
4836   /*
4837    * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
4838    */
4839   protected boolean affectsTextPresentation(PropertyChangeEvent event) {
4840     return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event)
4841         || super.affectsTextPresentation(event);
4842   }
4843
4844   //
4845   //      protected boolean affectsTextPresentation(PropertyChangeEvent event) {
4846   //        JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
4847   //        return textTools.affectsBehavior(event);
4848   //      }
4849   /**
4850    * Creates and returns the preference store for this Java editor with the given input.
4851    * 
4852    * @param input
4853    *          The editor input for which to create the preference store
4854    * @return the preference store for this editor
4855    * 
4856    * @since 3.0
4857    */
4858   private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
4859     List stores = new ArrayList(3);
4860
4861     IJavaProject project = EditorUtility.getJavaProject(input);
4862     if (project != null)
4863       stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(),
4864           new OptionsAdapter.IPropertyChangeEventFilter() {
4865
4866             public boolean isFiltered(PropertyChangeEvent event) {
4867               IJavaElement inputJavaElement = getInputJavaElement();
4868               IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
4869               if (javaProject == null)
4870                 return true;
4871
4872               return !javaProject.getProject().equals(event.getSource());
4873             }
4874
4875           }));
4876
4877     stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
4878     stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
4879     stores.add(EditorsUI.getPreferenceStore());
4880
4881     return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
4882   }
4883
4884   /**
4885    * Jumps to the error next according to the given direction.
4886    */
4887   public void gotoError(boolean forward) {
4888
4889     ISelectionProvider provider = getSelectionProvider();
4890
4891     ITextSelection s = (ITextSelection) provider.getSelection();
4892     Position errorPosition = new Position(0, 0);
4893     IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition);
4894
4895     if (nextError != null) {
4896
4897       IMarker marker = null;
4898       if (nextError instanceof MarkerAnnotation)
4899         marker = ((MarkerAnnotation) nextError).getMarker();
4900       else {
4901         Iterator e = nextError.getOverlaidIterator();
4902         if (e != null) {
4903           while (e.hasNext()) {
4904             Object o = e.next();
4905             if (o instanceof MarkerAnnotation) {
4906               marker = ((MarkerAnnotation) o).getMarker();
4907               break;
4908             }
4909           }
4910         }
4911       }
4912
4913       if (marker != null) {
4914         IWorkbenchPage page = getSite().getPage();
4915         IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
4916         if (view instanceof TaskList) {
4917           StructuredSelection ss = new StructuredSelection(marker);
4918           ((TaskList) view).setSelection(ss, true);
4919         }
4920       }
4921
4922       selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
4923       //      setStatusLineErrorMessage(nextError.getMessage());
4924
4925     } else {
4926
4927       setStatusLineErrorMessage(null);
4928
4929     }
4930   }
4931
4932   private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
4933
4934     IJavaAnnotation nextError = null;
4935     Position nextErrorPosition = null;
4936
4937     IDocument document = getDocumentProvider().getDocument(getEditorInput());
4938     int endOfDocument = document.getLength();
4939     int distance = 0;
4940
4941     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
4942     Iterator e = new JavaAnnotationIterator(model, false);
4943     while (e.hasNext()) {
4944
4945       IJavaAnnotation a = (IJavaAnnotation) e.next();
4946       if (a.hasOverlay() || !a.isProblem())
4947         continue;
4948
4949       Position p = model.getPosition((Annotation) a);
4950       if (!p.includes(offset)) {
4951
4952         int currentDistance = 0;
4953
4954         if (forward) {
4955           currentDistance = p.getOffset() - offset;
4956           if (currentDistance < 0)
4957             currentDistance = endOfDocument - offset + p.getOffset();
4958         } else {
4959           currentDistance = offset - p.getOffset();
4960           if (currentDistance < 0)
4961             currentDistance = offset + endOfDocument - p.getOffset();
4962         }
4963
4964         if (nextError == null || currentDistance < distance) {
4965           distance = currentDistance;
4966           nextError = a;
4967           nextErrorPosition = p;
4968         }
4969       }
4970     }
4971
4972     if (nextErrorPosition != null) {
4973       errorPosition.setOffset(nextErrorPosition.getOffset());
4974       errorPosition.setLength(nextErrorPosition.getLength());
4975     }
4976
4977     return nextError;
4978   }
4979
4980   void removeOccurrenceAnnotations() {
4981     IDocumentProvider documentProvider = getDocumentProvider();
4982     if (documentProvider == null)
4983       return;
4984
4985     IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
4986     if (annotationModel == null || fOccurrenceAnnotations == null)
4987       return;
4988
4989     synchronized (annotationModel) {
4990       if (annotationModel instanceof IAnnotationModelExtension) {
4991         ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
4992       } else {
4993         for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
4994           annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
4995       }
4996       fOccurrenceAnnotations = null;
4997     }
4998   }
4999
5000   protected void uninstallOverrideIndicator() {
5001     //          if (fOverrideIndicatorManager != null) {
5002     //                  fOverrideIndicatorManager.removeAnnotations();
5003     //                  fOverrideIndicatorManager= null;
5004     //          }
5005   }
5006
5007   protected void installOverrideIndicator(boolean waitForReconcilation) {
5008     uninstallOverrideIndicator();
5009     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
5010     final IJavaElement inputElement = getInputJavaElement();
5011
5012     if (model == null || inputElement == null)
5013       return;
5014
5015     //  fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
5016     //  
5017     //  if (provideAST) {
5018     //          Job job= new Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) { //$NON-NLS-1$
5019     //                  /*
5020     //                   * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
5021     //                   * @since 3.0
5022     //                   */
5023     //                  protected IStatus run(IProgressMonitor monitor) {
5024     //                          CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
5025     //                          if (fOverrideIndicatorManager != null) // editor might have been closed in the meanwhile
5026     //                                  fOverrideIndicatorManager.reconciled(ast, true, monitor);
5027     //                          return Status.OK_STATUS;
5028     //                  }
5029     //          };
5030     //          job.setPriority(Job.DECORATE);
5031     //          job.setSystem(true);
5032     //          job.schedule();
5033     //  }
5034   }
5035
5036   /**
5037    * Tells whether override indicators are shown.
5038    * 
5039    * @return <code>true</code> if the override indicators are shown
5040    * @since 3.0
5041    */
5042   //    protected boolean isShowingOverrideIndicators() {
5043   //            AnnotationPreference preference=
5044   // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
5045   //            IPreferenceStore store= getPreferenceStore();
5046   //            return getBoolean(store, preference.getHighlightPreferenceKey())
5047   //                    || getBoolean(store, preference.getVerticalRulerPreferenceKey())
5048   //                    || getBoolean(store, preference.getOverviewRulerPreferenceKey())
5049   //                    || getBoolean(store, preference.getTextPreferenceKey());
5050   //    }
5051   /**
5052    * Returns the boolean preference for the given key.
5053    * 
5054    * @param store
5055    *          the preference store
5056    * @param key
5057    *          the preference key
5058    * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
5059    * @since 3.0
5060    */
5061   private boolean getBoolean(IPreferenceStore store, String key) {
5062     return key != null && store.getBoolean(key);
5063   }
5064
5065   protected boolean isPrefQuickDiffAlwaysOn() {
5066     return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like PHPUnitEditor
5067   }
5068
5069   /*
5070    * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
5071    */
5072   protected void createNavigationActions() {
5073     super.createNavigationActions();
5074
5075     final StyledText textWidget = getSourceViewer().getTextWidget();
5076
5077     IAction action = new SmartLineStartAction(textWidget, false);
5078     action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
5079     setAction(ITextEditorActionDefinitionIds.LINE_START, action);
5080
5081     action = new SmartLineStartAction(textWidget, true);
5082     action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
5083     setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
5084
5085     action = new NavigatePreviousSubWordAction();
5086     action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
5087     setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
5088     textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
5089
5090     action = new NavigateNextSubWordAction();
5091     action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
5092     setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
5093     textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
5094
5095     action = new SelectPreviousSubWordAction();
5096     action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
5097     setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
5098     textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
5099
5100     action = new SelectNextSubWordAction();
5101     action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
5102     setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
5103     textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
5104   }
5105
5106   /*
5107    * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
5108    */
5109   protected CompositeRuler createCompositeRuler() {
5110     if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
5111       return super.createCompositeRuler();
5112
5113     CompositeRuler ruler = new CompositeRuler();
5114     AnnotationRulerColumn column = new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
5115     column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
5116
5117       public void doubleClick(DoubleClickEvent event) {
5118         // for now: just invoke ruler double click action
5119         triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
5120       }
5121
5122       private void triggerAction(String actionID) {
5123         IAction action = getAction(actionID);
5124         if (action != null) {
5125           if (action instanceof IUpdate)
5126             ((IUpdate) action).update();
5127           // hack to propagate line change
5128           if (action instanceof ISelectionListener) {
5129             ((ISelectionListener) action).selectionChanged(null, null);
5130           }
5131           if (action.isEnabled())
5132             action.run();
5133         }
5134       }
5135
5136     }));
5137     ruler.addDecorator(0, column);
5138
5139     if (isLineNumberRulerVisible())
5140       ruler.addDecorator(1, createLineNumberRulerColumn());
5141     else if (isPrefQuickDiffAlwaysOn())
5142       ruler.addDecorator(1, createChangeRulerColumn());
5143
5144     return ruler;
5145   }
5146
5147   /**
5148    * Returns the folding action group, or <code>null</code> if there is none.
5149    * 
5150    * @return the folding action group, or <code>null</code> if there is none
5151    * @since 3.0
5152    */
5153   protected FoldingActionGroup getFoldingActionGroup() {
5154     return fFoldingGroup;
5155   }
5156
5157   /*
5158    * @see org.eclipse.ui.texteditor.AbstractTextEditor#performRevert()
5159    */
5160   protected void performRevert() {
5161     ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
5162     projectionViewer.setRedraw(false);
5163     try {
5164
5165       boolean projectionMode = projectionViewer.isProjectionMode();
5166       if (projectionMode) {
5167         projectionViewer.disableProjection();
5168         if (fProjectionModelUpdater != null)
5169           fProjectionModelUpdater.uninstall();
5170       }
5171
5172       super.performRevert();
5173
5174       if (projectionMode) {
5175         if (fProjectionModelUpdater != null)
5176           fProjectionModelUpdater.install(this, projectionViewer);
5177         projectionViewer.enableProjection();
5178       }
5179
5180     } finally {
5181       projectionViewer.setRedraw(true);
5182     }
5183   }
5184
5185   /**
5186    * React to changed selection.
5187    * 
5188    * @since 3.0
5189    */
5190   protected void selectionChanged() {
5191     if (getSelectionProvider() == null)
5192       return;
5193     ISourceReference element = computeHighlightRangeSourceReference();
5194     if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
5195       synchronizeOutlinePage(element);
5196     setSelection(element, false);
5197     updateStatusLine();
5198   }
5199
5200   private boolean isJavaOutlinePageActive() {
5201     IWorkbenchPart part = getActivePart();
5202     return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
5203   }
5204
5205   private IWorkbenchPart getActivePart() {
5206     IWorkbenchWindow window = getSite().getWorkbenchWindow();
5207     IPartService service = window.getPartService();
5208     IWorkbenchPart part = service.getActivePart();
5209     return part;
5210   }
5211
5212   /**
5213    * Computes and returns the source reference that includes the caret and serves as provider for the outline page selection and the
5214    * editor range indication.
5215    * 
5216    * @return the computed source reference
5217    * @since 3.0
5218    */
5219   protected ISourceReference computeHighlightRangeSourceReference() {
5220     ISourceViewer sourceViewer = getSourceViewer();
5221     if (sourceViewer == null)
5222       return null;
5223
5224     StyledText styledText = sourceViewer.getTextWidget();
5225     if (styledText == null)
5226       return null;
5227
5228     int caret = 0;
5229     if (sourceViewer instanceof ITextViewerExtension5) {
5230       ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
5231       caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
5232     } else {
5233       int offset = sourceViewer.getVisibleRegion().getOffset();
5234       caret = offset + styledText.getCaretOffset();
5235     }
5236
5237     IJavaElement element = getElementAt(caret, false);
5238
5239     if (!(element instanceof ISourceReference))
5240       return null;
5241
5242     if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
5243
5244       IImportDeclaration declaration = (IImportDeclaration) element;
5245       IImportContainer container = (IImportContainer) declaration.getParent();
5246       ISourceRange srcRange = null;
5247
5248       try {
5249         srcRange = container.getSourceRange();
5250       } catch (JavaModelException e) {
5251       }
5252
5253       if (srcRange != null && srcRange.getOffset() == caret)
5254         return container;
5255     }
5256
5257     return (ISourceReference) element;
5258   }
5259
5260   /**
5261    * Returns the most narrow java element including the given offset.
5262    * 
5263    * @param offset
5264    *          the offset inside of the requested element
5265    * @param reconcile
5266    *          <code>true</code> if editor input should be reconciled in advance
5267    * @return the most narrow java element
5268    * @since 3.0
5269    */
5270   protected IJavaElement getElementAt(int offset, boolean reconcile) {
5271     return getElementAt(offset);
5272   }
5273 }