Added word wrap option (problem: conflicts with folding)
[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  Klaus Hartlage - www.eclipseproject.de
13  **********************************************************************/
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.ResourceBundle;
22 import java.util.StringTokenizer;
23
24 import net.sourceforge.phpdt.core.ICompilationUnit;
25 import net.sourceforge.phpdt.core.IImportContainer;
26 import net.sourceforge.phpdt.core.IImportDeclaration;
27 import net.sourceforge.phpdt.core.IJavaElement;
28 import net.sourceforge.phpdt.core.IJavaProject;
29 import net.sourceforge.phpdt.core.IMember;
30 import net.sourceforge.phpdt.core.ISourceRange;
31 import net.sourceforge.phpdt.core.ISourceReference;
32 import net.sourceforge.phpdt.core.JavaCore;
33 import net.sourceforge.phpdt.core.JavaModelException;
34 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
35 import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
36 import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
37 import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
38 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
39 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
40 import net.sourceforge.phpdt.internal.ui.text.PreferencesAdapter;
41 import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider;
42 import net.sourceforge.phpdt.ui.IContextMenuConstants;
43 import net.sourceforge.phpdt.ui.JavaUI;
44 import net.sourceforge.phpdt.ui.PreferenceConstants;
45 import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
46 import net.sourceforge.phpdt.ui.text.JavaTextTools;
47 import net.sourceforge.phpdt.ui.text.PHPSourceViewerConfiguration;
48 import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
49 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
50
51 import org.eclipse.core.resources.IMarker;
52 import org.eclipse.core.resources.IResource;
53 import org.eclipse.core.runtime.CoreException;
54 import org.eclipse.core.runtime.IProgressMonitor;
55 import org.eclipse.core.runtime.IStatus;
56 import org.eclipse.core.runtime.Preferences;
57 import org.eclipse.core.runtime.Status;
58 import org.eclipse.core.runtime.jobs.Job;
59 import org.eclipse.jface.action.Action;
60 import org.eclipse.jface.action.GroupMarker;
61 import org.eclipse.jface.action.IAction;
62 import org.eclipse.jface.action.MenuManager;
63 import org.eclipse.jface.action.Separator;
64 import org.eclipse.jface.preference.IPreferenceStore;
65 import org.eclipse.jface.preference.PreferenceConverter;
66 import org.eclipse.jface.text.BadLocationException;
67 import org.eclipse.jface.text.DefaultInformationControl;
68 import org.eclipse.jface.text.DocumentEvent;
69 import org.eclipse.jface.text.IDocument;
70 import org.eclipse.jface.text.IDocumentListener;
71 import org.eclipse.jface.text.IInformationControl;
72 import org.eclipse.jface.text.IInformationControlCreator;
73 import org.eclipse.jface.text.IRegion;
74 import org.eclipse.jface.text.ISynchronizable;
75 import org.eclipse.jface.text.ITextHover;
76 import org.eclipse.jface.text.ITextInputListener;
77 import org.eclipse.jface.text.ITextSelection;
78 import org.eclipse.jface.text.ITextViewer;
79 import org.eclipse.jface.text.ITextViewerExtension2;
80 import org.eclipse.jface.text.ITextViewerExtension3;
81 import org.eclipse.jface.text.ITextViewerExtension5;
82 import org.eclipse.jface.text.ITypedRegion;
83 import org.eclipse.jface.text.Position;
84 import org.eclipse.jface.text.Region;
85 import org.eclipse.jface.text.TextSelection;
86 import org.eclipse.jface.text.information.IInformationProvider;
87 import org.eclipse.jface.text.information.InformationPresenter;
88 import org.eclipse.jface.text.reconciler.IReconciler;
89 import org.eclipse.jface.text.source.Annotation;
90 import org.eclipse.jface.text.source.IAnnotationModel;
91 import org.eclipse.jface.text.source.IAnnotationModelExtension;
92 import org.eclipse.jface.text.source.IOverviewRuler;
93 import org.eclipse.jface.text.source.ISourceViewer;
94 import org.eclipse.jface.text.source.IVerticalRuler;
95 import org.eclipse.jface.text.source.OverviewRuler;
96 import org.eclipse.jface.text.source.SourceViewerConfiguration;
97 import org.eclipse.jface.text.source.projection.ProjectionSupport;
98 import org.eclipse.jface.text.source.projection.ProjectionViewer;
99 import org.eclipse.jface.util.IPropertyChangeListener;
100 import org.eclipse.jface.util.ListenerList;
101 import org.eclipse.jface.util.PropertyChangeEvent;
102 import org.eclipse.jface.viewers.IPostSelectionProvider;
103 import org.eclipse.jface.viewers.ISelection;
104 import org.eclipse.jface.viewers.ISelectionChangedListener;
105 import org.eclipse.jface.viewers.ISelectionProvider;
106 import org.eclipse.jface.viewers.IStructuredSelection;
107 import org.eclipse.jface.viewers.SelectionChangedEvent;
108 import org.eclipse.jface.viewers.StructuredSelection;
109 import org.eclipse.swt.SWT;
110 import org.eclipse.swt.custom.BidiSegmentEvent;
111 import org.eclipse.swt.custom.BidiSegmentListener;
112 import org.eclipse.swt.custom.StyleRange;
113 import org.eclipse.swt.custom.StyledText;
114 import org.eclipse.swt.events.FocusEvent;
115 import org.eclipse.swt.events.FocusListener;
116 import org.eclipse.swt.events.KeyEvent;
117 import org.eclipse.swt.events.KeyListener;
118 import org.eclipse.swt.events.MouseEvent;
119 import org.eclipse.swt.events.MouseListener;
120 import org.eclipse.swt.events.MouseMoveListener;
121 import org.eclipse.swt.events.PaintEvent;
122 import org.eclipse.swt.events.PaintListener;
123 import org.eclipse.swt.graphics.Color;
124 import org.eclipse.swt.graphics.Cursor;
125 import org.eclipse.swt.graphics.GC;
126 import org.eclipse.swt.graphics.Image;
127 import org.eclipse.swt.graphics.Point;
128 import org.eclipse.swt.graphics.RGB;
129 import org.eclipse.swt.widgets.Composite;
130 import org.eclipse.swt.widgets.Control;
131 import org.eclipse.swt.widgets.Display;
132 import org.eclipse.swt.widgets.Shell;
133 import org.eclipse.ui.IEditorInput;
134 import org.eclipse.ui.IPageLayout;
135 import org.eclipse.ui.IPartService;
136 import org.eclipse.ui.IViewPart;
137 import org.eclipse.ui.IWorkbenchPage;
138 import org.eclipse.ui.IWorkbenchPart;
139 import org.eclipse.ui.IWorkbenchWindow;
140 import org.eclipse.ui.actions.ActionContext;
141 import org.eclipse.ui.actions.ActionGroup;
142 import org.eclipse.ui.editors.text.DefaultEncodingSupport;
143 import org.eclipse.ui.editors.text.EditorsUI;
144 import org.eclipse.ui.editors.text.IEncodingSupport;
145 import org.eclipse.ui.part.IShowInTargetList;
146 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
147 import org.eclipse.ui.texteditor.AnnotationPreference;
148 import org.eclipse.ui.texteditor.ChainedPreferenceStore;
149 import org.eclipse.ui.texteditor.IDocumentProvider;
150 import org.eclipse.ui.texteditor.IEditorStatusLine;
151 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
152 import org.eclipse.ui.texteditor.MarkerAnnotation;
153 import org.eclipse.ui.texteditor.ResourceAction;
154 import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
155 import org.eclipse.ui.texteditor.TextEditorAction;
156 import org.eclipse.ui.texteditor.TextOperationAction;
157 import org.eclipse.ui.views.contentoutline.ContentOutline;
158 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
159 import org.eclipse.ui.views.tasklist.TaskList;
160
161
162 /**
163  * PHP specific text editor.
164  */
165 public abstract class PHPEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
166   //extends StatusTextEditor implements IViewPartInputProvider { // extends
167   // TextEditor {
168
169   /**
170    * Internal implementation class for a change listener.
171    * 
172    * @since 3.0
173    */
174   protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
175
176     /**
177      * Installs this selection changed listener with the given selection provider. If the selection provider is a post selection
178      * provider, post selection changed events are the preferred choice, otherwise normal selection changed events are requested.
179      * 
180      * @param selectionProvider
181      */
182     public void install(ISelectionProvider selectionProvider) {
183       if (selectionProvider == null)
184         return;
185
186       if (selectionProvider instanceof IPostSelectionProvider) {
187         IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
188         provider.addPostSelectionChangedListener(this);
189       } else {
190         selectionProvider.addSelectionChangedListener(this);
191       }
192     }
193
194     /**
195      * Removes this selection changed listener from the given selection provider.
196      * 
197      * @param selectionProvider
198      *          the selection provider
199      */
200     public void uninstall(ISelectionProvider selectionProvider) {
201       if (selectionProvider == null)
202         return;
203
204       if (selectionProvider instanceof IPostSelectionProvider) {
205         IPostSelectionProvider provider = (IPostSelectionProvider) selectionProvider;
206         provider.removePostSelectionChangedListener(this);
207       } else {
208         selectionProvider.removeSelectionChangedListener(this);
209       }
210     }
211   }
212
213   /**
214    * Updates the Java outline page selection and this editor's range indicator.
215    * 
216    * @since 3.0
217    */
218   private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
219
220     /*
221      * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
222      */
223     public void selectionChanged(SelectionChangedEvent event) {
224       // XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
225       PHPEditor.this.selectionChanged();
226     }
227   }
228
229   /**
230    * "Smart" runnable for updating the outline page's selection.
231    */
232   class OutlinePageSelectionUpdater implements Runnable {
233
234     /** Has the runnable already been posted? */
235     private boolean fPosted = false;
236
237     public OutlinePageSelectionUpdater() {
238     }
239
240     /*
241      * @see Runnable#run()
242      */
243     public void run() {
244       synchronizeOutlinePageSelection();
245       fPosted = false;
246     }
247
248     /**
249      * Posts this runnable into the event queue.
250      */
251     public void post() {
252       if (fPosted)
253         return;
254
255       Shell shell = getSite().getShell();
256       if (shell != null & !shell.isDisposed()) {
257         fPosted = true;
258         shell.getDisplay().asyncExec(this);
259       }
260     }
261   };
262
263   class SelectionChangedListener implements ISelectionChangedListener {
264     public void selectionChanged(SelectionChangedEvent event) {
265       doSelectionChanged(event);
266     }
267   };
268
269   /**
270    * Adapts an options {@link java.util.Map}to {@link org.eclipse.jface.preference.IPreferenceStore}.
271    * <p>
272    * This preference store is read-only i.e. write access throws an {@link java.lang.UnsupportedOperationException}.
273    * </p>
274    * 
275    * @since 3.0
276    */
277   private static class OptionsAdapter implements IPreferenceStore {
278
279     /**
280      * A property change event filter.
281      */
282     public interface IPropertyChangeEventFilter {
283
284       /**
285        * Should the given event be filtered?
286        * 
287        * @param event
288        *          The property change event.
289        * @return <code>true</code> iff the given event should be filtered.
290        */
291       public boolean isFiltered(PropertyChangeEvent event);
292
293     }
294
295     /**
296      * Property change listener. Listens for events in the options Map and fires a
297      * {@link org.eclipse.jface.util.PropertyChangeEvent}on this adapter with arguments from the received event.
298      */
299     private class PropertyChangeListener implements IPropertyChangeListener {
300
301       /**
302        * {@inheritDoc}
303        */
304       public void propertyChange(PropertyChangeEvent event) {
305         if (getFilter().isFiltered(event))
306           return;
307
308         if (event.getNewValue() == null)
309           fOptions.remove(event.getProperty());
310         else
311           fOptions.put(event.getProperty(), event.getNewValue());
312
313         firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
314       }
315     }
316
317     /** Listeners on this adapter */
318     private ListenerList fListeners = new ListenerList();
319
320     /** Listener on the adapted options Map */
321     private IPropertyChangeListener fListener = new PropertyChangeListener();
322
323     /** Adapted options Map */
324     private Map fOptions;
325
326     /** Preference store through which events are received. */
327     private IPreferenceStore fMockupPreferenceStore;
328
329     /** Property event filter. */
330     private IPropertyChangeEventFilter fFilter;
331
332     /**
333      * Initialize with the given options.
334      * 
335      * @param options
336      *          The options to wrap
337      * @param mockupPreferenceStore
338      *          the mock-up preference store
339      * @param filter
340      *          the property change filter
341      */
342     public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
343       fMockupPreferenceStore = mockupPreferenceStore;
344       fOptions = options;
345       setFilter(filter);
346     }
347
348     /**
349      * {@inheritDoc}
350      */
351     public void addPropertyChangeListener(IPropertyChangeListener listener) {
352       if (fListeners.size() == 0)
353         fMockupPreferenceStore.addPropertyChangeListener(fListener);
354       fListeners.add(listener);
355     }
356
357     /**
358      * {@inheritDoc}
359      */
360     public void removePropertyChangeListener(IPropertyChangeListener listener) {
361       fListeners.remove(listener);
362       if (fListeners.size() == 0)
363         fMockupPreferenceStore.removePropertyChangeListener(fListener);
364     }
365
366     /**
367      * {@inheritDoc}
368      */
369     public boolean contains(String name) {
370       return fOptions.containsKey(name);
371     }
372
373     /**
374      * {@inheritDoc}
375      */
376     public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
377       PropertyChangeEvent event = new PropertyChangeEvent(this, name, oldValue, newValue);
378       Object[] listeners = fListeners.getListeners();
379       for (int i = 0; i < listeners.length; i++)
380         ((IPropertyChangeListener) listeners[i]).propertyChange(event);
381     }
382
383     /**
384      * {@inheritDoc}
385      */
386     public boolean getBoolean(String name) {
387       boolean value = BOOLEAN_DEFAULT_DEFAULT;
388       String s = (String) fOptions.get(name);
389       if (s != null)
390         value = s.equals(TRUE);
391       return value;
392     }
393
394     /**
395      * {@inheritDoc}
396      */
397     public boolean getDefaultBoolean(String name) {
398       return BOOLEAN_DEFAULT_DEFAULT;
399     }
400
401     /**
402      * {@inheritDoc}
403      */
404     public double getDefaultDouble(String name) {
405       return DOUBLE_DEFAULT_DEFAULT;
406     }
407
408     /**
409      * {@inheritDoc}
410      */
411     public float getDefaultFloat(String name) {
412       return FLOAT_DEFAULT_DEFAULT;
413     }
414
415     /**
416      * {@inheritDoc}
417      */
418     public int getDefaultInt(String name) {
419       return INT_DEFAULT_DEFAULT;
420     }
421
422     /**
423      * {@inheritDoc}
424      */
425     public long getDefaultLong(String name) {
426       return LONG_DEFAULT_DEFAULT;
427     }
428
429     /**
430      * {@inheritDoc}
431      */
432     public String getDefaultString(String name) {
433       return STRING_DEFAULT_DEFAULT;
434     }
435
436     /**
437      * {@inheritDoc}
438      */
439     public double getDouble(String name) {
440       double value = DOUBLE_DEFAULT_DEFAULT;
441       String s = (String) fOptions.get(name);
442       if (s != null) {
443         try {
444           value = new Double(s).doubleValue();
445         } catch (NumberFormatException e) {
446         }
447       }
448       return value;
449     }
450
451     /**
452      * {@inheritDoc}
453      */
454     public float getFloat(String name) {
455       float value = FLOAT_DEFAULT_DEFAULT;
456       String s = (String) fOptions.get(name);
457       if (s != null) {
458         try {
459           value = new Float(s).floatValue();
460         } catch (NumberFormatException e) {
461         }
462       }
463       return value;
464     }
465
466     /**
467      * {@inheritDoc}
468      */
469     public int getInt(String name) {
470       int value = INT_DEFAULT_DEFAULT;
471       String s = (String) fOptions.get(name);
472       if (s != null) {
473         try {
474           value = new Integer(s).intValue();
475         } catch (NumberFormatException e) {
476         }
477       }
478       return value;
479     }
480
481     /**
482      * {@inheritDoc}
483      */
484     public long getLong(String name) {
485       long value = LONG_DEFAULT_DEFAULT;
486       String s = (String) fOptions.get(name);
487       if (s != null) {
488         try {
489           value = new Long(s).longValue();
490         } catch (NumberFormatException e) {
491         }
492       }
493       return value;
494     }
495
496     /**
497      * {@inheritDoc}
498      */
499     public String getString(String name) {
500       String value = (String) fOptions.get(name);
501       if (value == null)
502         value = STRING_DEFAULT_DEFAULT;
503       return value;
504     }
505
506     /**
507      * {@inheritDoc}
508      */
509     public boolean isDefault(String name) {
510       return false;
511     }
512
513     /**
514      * {@inheritDoc}
515      */
516     public boolean needsSaving() {
517       return !fOptions.isEmpty();
518     }
519
520     /**
521      * {@inheritDoc}
522      */
523     public void putValue(String name, String value) {
524       throw new UnsupportedOperationException();
525     }
526
527     /**
528      * {@inheritDoc}
529      */
530     public void setDefault(String name, double value) {
531       throw new UnsupportedOperationException();
532     }
533
534     /**
535      * {@inheritDoc}
536      */
537     public void setDefault(String name, float value) {
538       throw new UnsupportedOperationException();
539     }
540
541     /**
542      * {@inheritDoc}
543      */
544     public void setDefault(String name, int value) {
545       throw new UnsupportedOperationException();
546     }
547
548     /**
549      * {@inheritDoc}
550      */
551     public void setDefault(String name, long value) {
552       throw new UnsupportedOperationException();
553     }
554
555     /**
556      * {@inheritDoc}
557      */
558     public void setDefault(String name, String defaultObject) {
559       throw new UnsupportedOperationException();
560     }
561
562     /**
563      * {@inheritDoc}
564      */
565     public void setDefault(String name, boolean value) {
566       throw new UnsupportedOperationException();
567     }
568
569     /**
570      * {@inheritDoc}
571      */
572     public void setToDefault(String name) {
573       throw new UnsupportedOperationException();
574     }
575
576     /**
577      * {@inheritDoc}
578      */
579     public void setValue(String name, double value) {
580       throw new UnsupportedOperationException();
581     }
582
583     /**
584      * {@inheritDoc}
585      */
586     public void setValue(String name, float value) {
587       throw new UnsupportedOperationException();
588     }
589
590     /**
591      * {@inheritDoc}
592      */
593     public void setValue(String name, int value) {
594       throw new UnsupportedOperationException();
595     }
596
597     /**
598      * {@inheritDoc}
599      */
600     public void setValue(String name, long value) {
601       throw new UnsupportedOperationException();
602     }
603
604     /**
605      * {@inheritDoc}
606      */
607     public void setValue(String name, String value) {
608       throw new UnsupportedOperationException();
609     }
610
611     /**
612      * {@inheritDoc}
613      */
614     public void setValue(String name, boolean value) {
615       throw new UnsupportedOperationException();
616     }
617
618     /**
619      * Returns the adapted options Map.
620      * 
621      * @return Returns the adapted options Map.
622      */
623     public Map getOptions() {
624       return fOptions;
625     }
626
627     /**
628      * Returns the mock-up preference store, events are received through this preference store.
629      * 
630      * @return Returns the mock-up preference store.
631      */
632     public IPreferenceStore getMockupPreferenceStore() {
633       return fMockupPreferenceStore;
634     }
635
636     /**
637      * Set the event filter to the given filter.
638      * 
639      * @param filter
640      *          The new filter.
641      */
642     public void setFilter(IPropertyChangeEventFilter filter) {
643       fFilter = filter;
644     }
645
646     /**
647      * Returns the event filter.
648      * 
649      * @return The event filter.
650      */
651     public IPropertyChangeEventFilter getFilter() {
652       return fFilter;
653     }
654   }
655
656   /*
657    * Link mode.
658    */
659   class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener,
660       IPropertyChangeListener, IDocumentListener, ITextInputListener {
661
662     /** The session is active. */
663     private boolean fActive;
664
665     /** The currently active style range. */
666     private IRegion fActiveRegion;
667
668     /** The currently active style range as position. */
669     private Position fRememberedPosition;
670
671     /** The hand cursor. */
672     private Cursor fCursor;
673
674     /** The link color. */
675     private Color fColor;
676
677     /** The key modifier mask. */
678     private int fKeyModifierMask;
679
680     public void deactivate() {
681       deactivate(false);
682     }
683
684     public void deactivate(boolean redrawAll) {
685       if (!fActive)
686         return;
687
688       repairRepresentation(redrawAll);
689       fActive = false;
690     }
691
692     public void install() {
693
694       ISourceViewer sourceViewer = getSourceViewer();
695       if (sourceViewer == null)
696         return;
697
698       StyledText text = sourceViewer.getTextWidget();
699       if (text == null || text.isDisposed())
700         return;
701
702       updateColor(sourceViewer);
703
704       sourceViewer.addTextInputListener(this);
705
706       IDocument document = sourceViewer.getDocument();
707       if (document != null)
708         document.addDocumentListener(this);
709
710       text.addKeyListener(this);
711       text.addMouseListener(this);
712       text.addMouseMoveListener(this);
713       text.addFocusListener(this);
714       text.addPaintListener(this);
715
716       updateKeyModifierMask();
717
718       IPreferenceStore preferenceStore = getPreferenceStore();
719       preferenceStore.addPropertyChangeListener(this);
720     }
721
722     private void updateKeyModifierMask() {
723       String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
724       fKeyModifierMask = computeStateMask(modifiers);
725       if (fKeyModifierMask == -1) {
726         // Fallback to stored state mask
727         fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
728       }
729       ;
730     }
731
732     private int computeStateMask(String modifiers) {
733       if (modifiers == null)
734         return -1;
735
736       if (modifiers.length() == 0)
737         return SWT.NONE;
738
739       int stateMask = 0;
740       StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
741       while (modifierTokenizer.hasMoreTokens()) {
742         int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
743         if (modifier == 0 || (stateMask & modifier) == modifier)
744           return -1;
745         stateMask = stateMask | modifier;
746       }
747       return stateMask;
748     }
749
750     public void uninstall() {
751
752       if (fColor != null) {
753         fColor.dispose();
754         fColor = null;
755       }
756
757       if (fCursor != null) {
758         fCursor.dispose();
759         fCursor = null;
760       }
761
762       ISourceViewer sourceViewer = getSourceViewer();
763       if (sourceViewer == null)
764         return;
765
766       sourceViewer.removeTextInputListener(this);
767
768       IDocument document = sourceViewer.getDocument();
769       if (document != null)
770         document.removeDocumentListener(this);
771
772       IPreferenceStore preferenceStore = getPreferenceStore();
773       if (preferenceStore != null)
774         preferenceStore.removePropertyChangeListener(this);
775
776       StyledText text = sourceViewer.getTextWidget();
777       if (text == null || text.isDisposed())
778         return;
779
780       text.removeKeyListener(this);
781       text.removeMouseListener(this);
782       text.removeMouseMoveListener(this);
783       text.removeFocusListener(this);
784       text.removePaintListener(this);
785     }
786
787     /*
788      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
789      */
790     public void propertyChange(PropertyChangeEvent event) {
791       if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
792         ISourceViewer viewer = getSourceViewer();
793         if (viewer != null)
794           updateColor(viewer);
795       } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
796         updateKeyModifierMask();
797       }
798     }
799
800     private void updateColor(ISourceViewer viewer) {
801       if (fColor != null)
802         fColor.dispose();
803
804       StyledText text = viewer.getTextWidget();
805       if (text == null || text.isDisposed())
806         return;
807
808       Display display = text.getDisplay();
809       fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
810     }
811
812     /**
813      * Creates a color from the information stored in the given preference store. Returns <code>null</code> if there is no such
814      * information available.
815      */
816     private Color createColor(IPreferenceStore store, String key, Display display) {
817
818       RGB rgb = null;
819
820       if (store.contains(key)) {
821
822         if (store.isDefault(key))
823           rgb = PreferenceConverter.getDefaultColor(store, key);
824         else
825           rgb = PreferenceConverter.getColor(store, key);
826
827         if (rgb != null)
828           return new Color(display, rgb);
829       }
830
831       return null;
832     }
833
834     private void repairRepresentation() {
835       repairRepresentation(false);
836     }
837
838     private void repairRepresentation(boolean redrawAll) {
839
840       if (fActiveRegion == null)
841         return;
842
843       ISourceViewer viewer = getSourceViewer();
844       if (viewer != null) {
845         resetCursor(viewer);
846
847         int offset = fActiveRegion.getOffset();
848         int length = fActiveRegion.getLength();
849
850         // remove style
851         if (!redrawAll && viewer instanceof ITextViewerExtension2)
852           ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
853         else
854           viewer.invalidateTextPresentation();
855
856         // remove underline
857         if (viewer instanceof ITextViewerExtension3) {
858           ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
859           offset = extension.modelOffset2WidgetOffset(offset);
860         } else {
861           offset -= viewer.getVisibleRegion().getOffset();
862         }
863
864         StyledText text = viewer.getTextWidget();
865         try {
866           text.redrawRange(offset, length, true);
867         } catch (IllegalArgumentException x) {
868           PHPeclipsePlugin.log(x);
869         }
870       }
871
872       fActiveRegion = null;
873     }
874
875     // will eventually be replaced by a method provided by jdt.core
876     private IRegion selectWord(IDocument document, int anchor) {
877
878       try {
879         int offset = anchor;
880         char c;
881
882         while (offset >= 0) {
883           c = document.getChar(offset);
884           if (!Character.isJavaIdentifierPart(c))
885             break;
886           --offset;
887         }
888
889         int start = offset;
890
891         offset = anchor;
892         int length = document.getLength();
893
894         while (offset < length) {
895           c = document.getChar(offset);
896           if (!Character.isJavaIdentifierPart(c))
897             break;
898           ++offset;
899         }
900
901         int end = offset;
902
903         if (start == end)
904           return new Region(start, 0);
905         else
906           return new Region(start + 1, end - start - 1);
907
908       } catch (BadLocationException x) {
909         return null;
910       }
911     }
912
913     IRegion getCurrentTextRegion(ISourceViewer viewer) {
914
915       int offset = getCurrentTextOffset(viewer);
916       if (offset == -1)
917         return null;
918
919       return null;
920       //                                IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
921       //                                if (input == null)
922       //                                        return null;
923       //      
924       //                                try {
925       //                                
926       //                                        IJavaElement[] elements= null;
927       //                                        synchronized (input) {
928       //                                                elements= ((ICodeAssist) input).codeSelect(offset, 0);
929       //                                        }
930       //                                
931       //                                        if (elements == null || elements.length == 0)
932       //                                                return null;
933       //                                        
934       //                                        return selectWord(viewer.getDocument(), offset);
935       //                                        
936       //                                } catch (JavaModelException e) {
937       //                                        return null;
938       //                                }
939     }
940
941     private int getCurrentTextOffset(ISourceViewer viewer) {
942
943       try {
944         StyledText text = viewer.getTextWidget();
945         if (text == null || text.isDisposed())
946           return -1;
947
948         Display display = text.getDisplay();
949         Point absolutePosition = display.getCursorLocation();
950         Point relativePosition = text.toControl(absolutePosition);
951
952         int widgetOffset = text.getOffsetAtLocation(relativePosition);
953         if (viewer instanceof ITextViewerExtension3) {
954           ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
955           return extension.widgetOffset2ModelOffset(widgetOffset);
956         } else {
957           return widgetOffset + viewer.getVisibleRegion().getOffset();
958         }
959
960       } catch (IllegalArgumentException e) {
961         return -1;
962       }
963     }
964
965     private void highlightRegion(ISourceViewer viewer, IRegion region) {
966
967       if (region.equals(fActiveRegion))
968         return;
969
970       repairRepresentation();
971
972       StyledText text = viewer.getTextWidget();
973       if (text == null || text.isDisposed())
974         return;
975
976       // highlight region
977       int offset = 0;
978       int length = 0;
979
980       if (viewer instanceof ITextViewerExtension3) {
981         ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
982         IRegion widgetRange = extension.modelRange2WidgetRange(region);
983         if (widgetRange == null)
984           return;
985
986         offset = widgetRange.getOffset();
987         length = widgetRange.getLength();
988
989       } else {
990         offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
991         length = region.getLength();
992       }
993
994       StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset);
995       Color foregroundColor = fColor;
996       Color backgroundColor = oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
997       StyleRange styleRange = new StyleRange(offset, length, foregroundColor, backgroundColor);
998       text.setStyleRange(styleRange);
999
1000       // underline
1001       text.redrawRange(offset, length, true);
1002
1003       fActiveRegion = region;
1004     }
1005
1006     private void activateCursor(ISourceViewer viewer) {
1007       StyledText text = viewer.getTextWidget();
1008       if (text == null || text.isDisposed())
1009         return;
1010       Display display = text.getDisplay();
1011       if (fCursor == null)
1012         fCursor = new Cursor(display, SWT.CURSOR_HAND);
1013       text.setCursor(fCursor);
1014     }
1015
1016     private void resetCursor(ISourceViewer viewer) {
1017       StyledText text = viewer.getTextWidget();
1018       if (text != null && !text.isDisposed())
1019         text.setCursor(null);
1020
1021       if (fCursor != null) {
1022         fCursor.dispose();
1023         fCursor = null;
1024       }
1025     }
1026
1027     /*
1028      * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
1029      */
1030     public void keyPressed(KeyEvent event) {
1031
1032       if (fActive) {
1033         deactivate();
1034         return;
1035       }
1036
1037       if (event.keyCode != fKeyModifierMask) {
1038         deactivate();
1039         return;
1040       }
1041
1042       fActive = true;
1043
1044       //                                removed for #25871
1045       //
1046       //                                ISourceViewer viewer= getSourceViewer();
1047       //                                if (viewer == null)
1048       //                                        return;
1049       //                        
1050       //                                IRegion region= getCurrentTextRegion(viewer);
1051       //                                if (region == null)
1052       //                                        return;
1053       //                        
1054       //                                highlightRegion(viewer, region);
1055       //                                activateCursor(viewer);
1056     }
1057
1058     /*
1059      * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
1060      */
1061     public void keyReleased(KeyEvent event) {
1062
1063       if (!fActive)
1064         return;
1065
1066       deactivate();
1067     }
1068
1069     /*
1070      * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
1071      */
1072     public void mouseDoubleClick(MouseEvent e) {
1073     }
1074
1075     /*
1076      * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
1077      */
1078     public void mouseDown(MouseEvent event) {
1079
1080       if (!fActive)
1081         return;
1082
1083       if (event.stateMask != fKeyModifierMask) {
1084         deactivate();
1085         return;
1086       }
1087
1088       if (event.button != 1) {
1089         deactivate();
1090         return;
1091       }
1092     }
1093
1094     /*
1095      * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
1096      */
1097     public void mouseUp(MouseEvent e) {
1098
1099       if (!fActive)
1100         return;
1101
1102       if (e.button != 1) {
1103         deactivate();
1104         return;
1105       }
1106
1107       boolean wasActive = fCursor != null;
1108
1109       deactivate();
1110
1111       if (wasActive) {
1112         IAction action = getAction("OpenEditor"); //$NON-NLS-1$
1113         if (action != null)
1114           action.run();
1115       }
1116     }
1117
1118     /*
1119      * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
1120      */
1121     public void mouseMove(MouseEvent event) {
1122
1123       if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
1124         deactivate();
1125         return;
1126       }
1127
1128       if (!fActive) {
1129         if (event.stateMask != fKeyModifierMask)
1130           return;
1131         // modifier was already pressed
1132         fActive = true;
1133       }
1134
1135       ISourceViewer viewer = getSourceViewer();
1136       if (viewer == null) {
1137         deactivate();
1138         return;
1139       }
1140
1141       StyledText text = viewer.getTextWidget();
1142       if (text == null || text.isDisposed()) {
1143         deactivate();
1144         return;
1145       }
1146
1147       if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
1148         deactivate();
1149         return;
1150       }
1151
1152       IRegion region = getCurrentTextRegion(viewer);
1153       if (region == null || region.getLength() == 0) {
1154         repairRepresentation();
1155         return;
1156       }
1157
1158       highlightRegion(viewer, region);
1159       activateCursor(viewer);
1160     }
1161
1162     /*
1163      * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
1164      */
1165     public void focusGained(FocusEvent e) {
1166     }
1167
1168     /*
1169      * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
1170      */
1171     public void focusLost(FocusEvent event) {
1172       deactivate();
1173     }
1174
1175     /*
1176      * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1177      */
1178     public void documentAboutToBeChanged(DocumentEvent event) {
1179       if (fActive && fActiveRegion != null) {
1180         fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
1181         try {
1182           event.getDocument().addPosition(fRememberedPosition);
1183         } catch (BadLocationException x) {
1184           fRememberedPosition = null;
1185         }
1186       }
1187     }
1188
1189     /*
1190      * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1191      */
1192     public void documentChanged(DocumentEvent event) {
1193       if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
1194         event.getDocument().removePosition(fRememberedPosition);
1195         fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
1196       }
1197       fRememberedPosition = null;
1198
1199       ISourceViewer viewer = getSourceViewer();
1200       if (viewer != null) {
1201         StyledText widget = viewer.getTextWidget();
1202         if (widget != null && !widget.isDisposed()) {
1203           widget.getDisplay().asyncExec(new Runnable() {
1204             public void run() {
1205               deactivate();
1206             }
1207           });
1208         }
1209       }
1210     }
1211
1212     /*
1213      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument,
1214      *      org.eclipse.jface.text.IDocument)
1215      */
1216     public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
1217       if (oldInput == null)
1218         return;
1219       deactivate();
1220       oldInput.removeDocumentListener(this);
1221     }
1222
1223     /*
1224      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument,
1225      *      org.eclipse.jface.text.IDocument)
1226      */
1227     public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
1228       if (newInput == null)
1229         return;
1230       newInput.addDocumentListener(this);
1231     }
1232
1233     /*
1234      * @see PaintListener#paintControl(PaintEvent)
1235      */
1236     public void paintControl(PaintEvent event) {
1237       if (fActiveRegion == null)
1238         return;
1239
1240       ISourceViewer viewer = getSourceViewer();
1241       if (viewer == null)
1242         return;
1243
1244       StyledText text = viewer.getTextWidget();
1245       if (text == null || text.isDisposed())
1246         return;
1247
1248       int offset = 0;
1249       int length = 0;
1250
1251       if (viewer instanceof ITextViewerExtension3) {
1252
1253         ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
1254         IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset, length));
1255         if (widgetRange == null)
1256           return;
1257
1258         offset = widgetRange.getOffset();
1259         length = widgetRange.getLength();
1260
1261       } else {
1262
1263         IRegion region = viewer.getVisibleRegion();
1264         if (!includes(region, fActiveRegion))
1265           return;
1266
1267         offset = fActiveRegion.getOffset() - region.getOffset();
1268         length = fActiveRegion.getLength();
1269       }
1270
1271       // support for bidi
1272       Point minLocation = getMinimumLocation(text, offset, length);
1273       Point maxLocation = getMaximumLocation(text, offset, length);
1274
1275       int x1 = minLocation.x;
1276       int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
1277       int y = minLocation.y + text.getLineHeight() - 1;
1278
1279       GC gc = event.gc;
1280       if (fColor != null && !fColor.isDisposed())
1281         gc.setForeground(fColor);
1282       gc.drawLine(x1, y, x2, y);
1283     }
1284
1285     private boolean includes(IRegion region, IRegion position) {
1286       return position.getOffset() >= region.getOffset()
1287           && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
1288     }
1289
1290     private Point getMinimumLocation(StyledText text, int offset, int length) {
1291       Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
1292
1293       for (int i = 0; i <= length; i++) {
1294         Point location = text.getLocationAtOffset(offset + i);
1295
1296         if (location.x < minLocation.x)
1297           minLocation.x = location.x;
1298         if (location.y < minLocation.y)
1299           minLocation.y = location.y;
1300       }
1301
1302       return minLocation;
1303     }
1304
1305     private Point getMaximumLocation(StyledText text, int offset, int length) {
1306       Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
1307
1308       for (int i = 0; i <= length; i++) {
1309         Point location = text.getLocationAtOffset(offset + i);
1310
1311         if (location.x > maxLocation.x)
1312           maxLocation.x = location.x;
1313         if (location.y > maxLocation.y)
1314           maxLocation.y = location.y;
1315       }
1316
1317       return maxLocation;
1318     }
1319   };
1320
1321   /**
1322    * This action dispatches into two behaviours: If there is no current text hover, the javadoc is displayed using information
1323    * presenter. If there is a current text hover, it is converted into a information presenter in order to make it sticky.
1324    */
1325   class InformationDispatchAction extends TextEditorAction {
1326
1327     /** The wrapped text operation action. */
1328     private final TextOperationAction fTextOperationAction;
1329
1330     /**
1331      * Creates a dispatch action.
1332      */
1333     public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
1334       super(resourceBundle, prefix, PHPEditor.this);
1335       if (textOperationAction == null)
1336         throw new IllegalArgumentException();
1337       fTextOperationAction = textOperationAction;
1338     }
1339
1340     /*
1341      * @see org.eclipse.jface.action.IAction#run()
1342      */
1343     public void run() {
1344
1345       ISourceViewer sourceViewer = getSourceViewer();
1346       if (sourceViewer == null) {
1347         fTextOperationAction.run();
1348         return;
1349       }
1350
1351       if (!(sourceViewer instanceof ITextViewerExtension2)) {
1352         fTextOperationAction.run();
1353         return;
1354       }
1355
1356       ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
1357
1358       // does a text hover exist?
1359       ITextHover textHover = textViewerExtension2.getCurrentTextHover();
1360       if (textHover == null) {
1361         fTextOperationAction.run();
1362         return;
1363       }
1364
1365       Point hoverEventLocation = textViewerExtension2.getHoverEventLocation();
1366       int offset = computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
1367       if (offset == -1) {
1368         fTextOperationAction.run();
1369         return;
1370       }
1371
1372       try {
1373         // get the text hover content
1374         IDocument document = sourceViewer.getDocument();
1375         String contentType = document.getContentType(offset);
1376
1377         final IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset);
1378         if (hoverRegion == null)
1379           return;
1380
1381         final String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion);
1382
1383         // with information provider
1384         IInformationProvider informationProvider = new IInformationProvider() {
1385           /*
1386            * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
1387            */
1388           public IRegion getSubject(ITextViewer textViewer, int offset) {
1389             return hoverRegion;
1390           }
1391
1392           /*
1393            * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer,
1394            *      org.eclipse.jface.text.IRegion)
1395            */
1396           public String getInformation(ITextViewer textViewer, IRegion subject) {
1397             return hoverInfo;
1398           }
1399         };
1400
1401         fInformationPresenter.setOffset(offset);
1402         fInformationPresenter.setInformationProvider(informationProvider, contentType);
1403         fInformationPresenter.showInformation();
1404
1405       } catch (BadLocationException e) {
1406       }
1407     }
1408
1409     // modified version from TextViewer
1410     private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
1411
1412       StyledText styledText = textViewer.getTextWidget();
1413       IDocument document = textViewer.getDocument();
1414
1415       if (document == null)
1416         return -1;
1417
1418       try {
1419         int widgetLocation = styledText.getOffsetAtLocation(new Point(x, y));
1420         if (textViewer instanceof ITextViewerExtension3) {
1421           ITextViewerExtension3 extension = (ITextViewerExtension3) textViewer;
1422           return extension.widgetOffset2ModelOffset(widgetLocation);
1423         } else {
1424           IRegion visibleRegion = textViewer.getVisibleRegion();
1425           return widgetLocation + visibleRegion.getOffset();
1426         }
1427       } catch (IllegalArgumentException e) {
1428         return -1;
1429       }
1430
1431     }
1432   };
1433
1434   //  static protected class AnnotationAccess implements IAnnotationAccess {
1435   //    /*
1436   //     * @see
1437   // org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
1438   //     */
1439   //    public Object getType(Annotation annotation) {
1440   //      if (annotation instanceof IJavaAnnotation) {
1441   //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
1442   //   // if (javaAnnotation.isRelevant())
1443   //   // return javaAnnotation.getAnnotationType();
1444   //      }
1445   //      return null;
1446   //    }
1447   //
1448   //    /*
1449   //     * @see
1450   // org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
1451   //     */
1452   //    public boolean isMultiLine(Annotation annotation) {
1453   //      return true;
1454   //    }
1455   //
1456   //    /*
1457   //     * @see
1458   // org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
1459   //     */
1460   //    public boolean isTemporary(Annotation annotation) {
1461   //      if (annotation instanceof IJavaAnnotation) {
1462   //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
1463   //        if (javaAnnotation.isRelevant())
1464   //          return javaAnnotation.isTemporary();
1465   //      }
1466   //      return false;
1467   //    }
1468   //  };
1469
1470   private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
1471     /*
1472      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
1473      */
1474     public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
1475       handlePreferencePropertyChanged(event);
1476     }
1477   };
1478
1479   /**
1480    * Finds and marks occurrence annotations.
1481    * 
1482    * @since 3.0
1483    */
1484   class OccurrencesFinderJob extends Job implements IDocumentListener {
1485
1486     private IDocument fDocument;
1487
1488     private boolean fCancelled = false;
1489
1490     private IProgressMonitor fProgressMonitor;
1491
1492     private Position[] fPositions;
1493
1494     public OccurrencesFinderJob(IDocument document, Position[] positions) {
1495       super("Occurrences Marker"); //$NON-NLS-1$
1496       fDocument = document;
1497       fPositions = positions;
1498       fDocument.addDocumentListener(this);
1499     }
1500
1501     private boolean isCancelled() {
1502       return fCancelled || fProgressMonitor.isCanceled();
1503     }
1504
1505     /*
1506      * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
1507      */
1508     public IStatus run(IProgressMonitor progressMonitor) {
1509
1510       fProgressMonitor = progressMonitor;
1511
1512       try {
1513
1514         if (isCancelled())
1515           return Status.CANCEL_STATUS;
1516
1517         ITextViewer textViewer = getViewer();
1518         if (textViewer == null)
1519           return Status.CANCEL_STATUS;
1520
1521         IDocument document = textViewer.getDocument();
1522         if (document == null)
1523           return Status.CANCEL_STATUS;
1524
1525         IDocumentProvider documentProvider = getDocumentProvider();
1526         if (documentProvider == null)
1527           return Status.CANCEL_STATUS;
1528
1529         IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
1530         if (annotationModel == null)
1531           return Status.CANCEL_STATUS;
1532
1533         // Add occurrence annotations
1534         int length = fPositions.length;
1535         Map annotationMap = new HashMap(length);
1536         for (int i = 0; i < length; i++) {
1537
1538           if (isCancelled())
1539             return Status.CANCEL_STATUS;
1540
1541           String message;
1542           Position position = fPositions[i];
1543
1544           // Create & add annotation
1545           try {
1546             message = document.get(position.offset, position.length);
1547           } catch (BadLocationException ex) {
1548             // Skip this match
1549             continue;
1550           }
1551           annotationMap.put(new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
1552               position);
1553         }
1554
1555         if (isCancelled())
1556           return Status.CANCEL_STATUS;
1557
1558         synchronized (annotationModel) {
1559           if (annotationModel instanceof IAnnotationModelExtension) {
1560             ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
1561           } else {
1562             removeOccurrenceAnnotations();
1563             Iterator iter = annotationMap.entrySet().iterator();
1564             while (iter.hasNext()) {
1565               Map.Entry mapEntry = (Map.Entry) iter.next();
1566               annotationModel.addAnnotation((Annotation) mapEntry.getKey(), (Position) mapEntry.getValue());
1567             }
1568           }
1569           fOccurrenceAnnotations = (Annotation[]) annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
1570         }
1571       } finally {
1572         fDocument.removeDocumentListener(this);
1573       }
1574       return Status.OK_STATUS;
1575     }
1576
1577     /*
1578      * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1579      */
1580     public void documentAboutToBeChanged(DocumentEvent event) {
1581       fCancelled = true;
1582     }
1583
1584     /*
1585      * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1586      */
1587     public void documentChanged(DocumentEvent event) {
1588     }
1589   }
1590
1591   /**
1592    * Updates the selection in the editor's widget with the selection of the outline page.
1593    */
1594   class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
1595     public void selectionChanged(SelectionChangedEvent event) {
1596       doSelectionChanged(event);
1597     }
1598   }
1599
1600   /**
1601    * Holds the current occurrence annotations.
1602    * 
1603    * @since 3.0
1604    */
1605   private Annotation[] fOccurrenceAnnotations = null;
1606
1607   private Job fOccurrencesFinderJob;
1608
1609   /** Preference key for showing the line number ruler */
1610   //  private final static String LINE_NUMBER_RULER =
1611   // PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
1612   /** Preference key for the foreground color of the line numbers */
1613   // private final static String LINE_NUMBER_COLOR =
1614   // PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
1615   /** Preference key for the link color */
1616   private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR;
1617
1618   /** Preference key for compiler task tags */
1619   private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
1620
1621   // protected PHPActionGroup fActionGroups;
1622   //  /** The outline page */
1623   //  private AbstractContentOutlinePage fOutlinePage;
1624   /** The outline page */
1625   protected JavaOutlinePage fOutlinePage;
1626
1627   /** Outliner context menu Id */
1628   protected String fOutlinerContextMenuId;
1629
1630   /**
1631    * Indicates whether this editor should react on outline page selection changes
1632    */
1633   private int fIgnoreOutlinePageSelection;
1634
1635   /** The outline page selection updater */
1636   private OutlinePageSelectionUpdater fUpdater;
1637
1638   //  protected PHPSyntaxParserThread fValidationThread = null;
1639
1640   // private IPreferenceStore fPHPPrefStore;
1641   /** The selection changed listener */
1642   //  protected ISelectionChangedListener fSelectionChangedListener = new
1643   // SelectionChangedListener();
1644   /**
1645    * The editor selection changed listener.
1646    * 
1647    * @since 3.0
1648    */
1649   private EditorSelectionChangedListener fEditorSelectionChangedListener;
1650
1651   /** The selection changed listener */
1652   protected AbstractSelectionChangedListener fOutlineSelectionChangedListener = new OutlineSelectionChangedListener();
1653
1654   /** The editor's bracket matcher */
1655   private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
1656
1657   /** The line number ruler column */
1658   //  private LineNumberRulerColumn fLineNumberRulerColumn;
1659   /** This editor's encoding support */
1660   private DefaultEncodingSupport fEncodingSupport;
1661
1662   /** The mouse listener */
1663   private MouseClickListener fMouseListener;
1664
1665   /**
1666    * Indicates whether this editor is about to update any annotation views.
1667    * 
1668    * @since 3.0
1669    */
1670   private boolean fIsUpdatingAnnotationViews = false;
1671
1672   /**
1673    * The marker that served as last target for a goto marker request.
1674    * 
1675    * @since 3.0
1676    */
1677   private IMarker fLastMarkerTarget = null;
1678
1679   protected CompositeActionGroup fActionGroups;
1680
1681   protected CompositeActionGroup fContextMenuGroup;
1682
1683   /**
1684    * This editor's projection support
1685    * 
1686    * @since 3.0
1687    */
1688   private ProjectionSupport fProjectionSupport;
1689
1690   /**
1691    * This editor's projection model updater
1692    * 
1693    * @since 3.0
1694    */
1695   private IJavaFoldingStructureProvider fProjectionModelUpdater;
1696
1697   /**
1698    * The override and implements indicator manager for this editor.
1699    * 
1700    * @since 3.0
1701    */
1702   //    protected OverrideIndicatorManager fOverrideIndicatorManager;
1703   /**
1704    * The action group for folding.
1705    * 
1706    * @since 3.0
1707    */
1708   private FoldingActionGroup fFoldingGroup;
1709
1710   /** The information presenter. */
1711   private InformationPresenter fInformationPresenter;
1712
1713   /** The annotation access */
1714   //  protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
1715   /** The overview ruler */
1716   protected OverviewRuler isOverviewRulerVisible;
1717
1718   /** The source viewer decoration support */
1719   //protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
1720   /** The overview ruler */
1721   //protected OverviewRuler fOverviewRuler;
1722   /** The preference property change listener for java core. */
1723   private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener();
1724
1725   /**
1726    * Returns the most narrow java element including the given offset
1727    * 
1728    * @param offset
1729    *          the offset inside of the requested element
1730    */
1731   abstract protected IJavaElement getElementAt(int offset);
1732
1733   /**
1734    * Returns the java element of this editor's input corresponding to the given IJavaElement
1735    */
1736   abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
1737
1738   /**
1739    * Sets the input of the editor's outline page.
1740    */
1741   abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
1742
1743   /**
1744    * Default constructor.
1745    */
1746   public PHPEditor() {
1747     super();
1748   }
1749
1750   /*
1751    * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
1752    */
1753   protected void initializeKeyBindingScopes() {
1754     setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" }); //$NON-NLS-1$
1755   }
1756
1757   /*
1758    * @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
1759    */
1760   protected void initializeEditor() {
1761     //jsurfer old code
1762     //    JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1763     //    setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, this, IPHPPartitions.PHP_PARTITIONING)); //,
1764     // IJavaPartitions.JAVA_PARTITIONING));
1765     IPreferenceStore store = createCombinedPreferenceStore(null);
1766     setPreferenceStore(store);
1767     JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
1768     setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
1769         IPHPPartitions.PHP_PARTITIONING));
1770     // TODO changed in 3.x ?
1771     //    setRangeIndicator(new DefaultRangeIndicator());
1772     //    if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
1773     //      fUpdater = new OutlinePageSelectionUpdater();
1774     // jsurfer end
1775
1776     //          IPreferenceStore store= createCombinedPreferenceStore(null);
1777     //          setPreferenceStore(store);
1778     //          JavaTextTools textTools=
1779     // PHPeclipsePlugin.getDefault().getJavaTextTools();
1780     //          setSourceViewerConfiguration(new
1781     // JavaSourceViewerConfiguration(textTools.getColorManager(), store,
1782     // this, IJavaPartitions.JAVA_PARTITIONING));
1783     //          fMarkOccurrenceAnnotations=
1784     // store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
1785     //          fStickyOccurrenceAnnotations=
1786     // store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
1787     //          fMarkTypeOccurrences=
1788     // store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
1789     //          fMarkMethodOccurrences=
1790     // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
1791     //          fMarkConstantOccurrences=
1792     // store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
1793     //          fMarkFieldOccurrences=
1794     // store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
1795     //          fMarkLocalVariableypeOccurrences=
1796     // store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
1797     //          fMarkExceptionOccurrences=
1798     // store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
1799     //          fMarkMethodExitPoints=
1800     // store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
1801   }
1802
1803   /*
1804    * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
1805    */
1806   protected void updatePropertyDependentActions() {
1807     super.updatePropertyDependentActions();
1808     if (fEncodingSupport != null)
1809       fEncodingSupport.reset();
1810   }
1811
1812   /*
1813    * Update the hovering behavior depending on the preferences.
1814    */
1815   private void updateHoverBehavior() {
1816     SourceViewerConfiguration configuration = getSourceViewerConfiguration();
1817     String[] types = configuration.getConfiguredContentTypes(getSourceViewer());
1818
1819     for (int i = 0; i < types.length; i++) {
1820
1821       String t = types[i];
1822
1823       int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
1824
1825       ISourceViewer sourceViewer = getSourceViewer();
1826       if (sourceViewer instanceof ITextViewerExtension2) {
1827         if (stateMasks != null) {
1828           for (int j = 0; j < stateMasks.length; j++) {
1829             int stateMask = stateMasks[j];
1830             ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask);
1831             ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask);
1832           }
1833         } else {
1834           ITextHover textHover = configuration.getTextHover(sourceViewer, t);
1835           ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
1836         }
1837       } else
1838         sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
1839     }
1840   }
1841
1842   public void updatedTitleImage(Image image) {
1843     setTitleImage(image);
1844   }
1845
1846   /*
1847    * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
1848    */
1849   public Object getViewPartInput() {
1850     return getEditorInput().getAdapter(IResource.class);
1851   }
1852
1853   /*
1854    * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
1855    */
1856   protected void doSetSelection(ISelection selection) {
1857     super.doSetSelection(selection);
1858     synchronizeOutlinePageSelection();
1859   }
1860
1861   boolean isFoldingEnabled() {
1862     return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
1863   }
1864
1865   /*
1866    * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt. widgets.Composite)
1867    */
1868   public void createPartControl(Composite parent) {
1869     super.createPartControl(parent);
1870
1871     //fSourceViewerDecorationSupport.install(getPreferenceStore());
1872
1873     ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer();
1874
1875     fProjectionSupport = new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
1876     fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
1877     fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
1878     fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
1879       public IInformationControl createInformationControl(Shell shell) {
1880         return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
1881       }
1882     });
1883     fProjectionSupport.install();
1884
1885     fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
1886     if (fProjectionModelUpdater != null)
1887       fProjectionModelUpdater.install(this, projectionViewer);
1888
1889     if (isFoldingEnabled())
1890       projectionViewer.doOperation(ProjectionViewer.TOGGLE);
1891     Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
1892     preferences.addPropertyChangeListener(fPropertyChangeListener);
1893
1894     IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
1895       public IInformationControl createInformationControl(Shell parent) {
1896         boolean cutDown = false;
1897         int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
1898         return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
1899       }
1900     };
1901
1902     fInformationPresenter = new InformationPresenter(informationControlCreator);
1903     fInformationPresenter.setSizeConstraints(60, 10, true, true);
1904     fInformationPresenter.install(getSourceViewer());
1905
1906     fEditorSelectionChangedListener = new EditorSelectionChangedListener();
1907     fEditorSelectionChangedListener.install(getSelectionProvider());
1908
1909     if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
1910       enableOverwriteMode(false);
1911     
1912     setWordWrap();
1913     //  getEditorSite().getShell().addShellListener(fActivationListener);
1914   }
1915
1916   private void setWordWrap() {
1917     if (getSourceViewer() != null) {
1918       getSourceViewer().getTextWidget().setWordWrap(
1919           PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_WRAP_WORDS));
1920     }
1921   }
1922
1923   protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
1924
1925     support.setCharacterPairMatcher(fBracketMatcher);
1926     support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
1927
1928     super.configureSourceViewerDecorationSupport(support);
1929   }
1930
1931   /*
1932    * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
1933    */
1934   public void gotoMarker(IMarker marker) {
1935     fLastMarkerTarget = marker;
1936     if (!fIsUpdatingAnnotationViews) {
1937       super.gotoMarker(marker);
1938     }
1939   }
1940
1941   /**
1942    * Jumps to the next enabled annotation according to the given direction. An annotation type is enabled if it is configured to be
1943    * in the Next/Previous tool bar drop down menu and if it is checked.
1944    * 
1945    * @param forward
1946    *          <code>true</code> if search direction is forward, <code>false</code> if backward
1947    */
1948   public void gotoAnnotation(boolean forward) {
1949     ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
1950     Position position = new Position(0, 0);
1951     if (false /* delayed - see bug 18316 */) {
1952       getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
1953       selectAndReveal(position.getOffset(), position.getLength());
1954     } else /* no delay - see bug 18316 */{
1955       Annotation annotation = getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
1956       setStatusLineErrorMessage(null);
1957       setStatusLineMessage(null);
1958       if (annotation != null) {
1959         updateAnnotationViews(annotation);
1960         selectAndReveal(position.getOffset(), position.getLength());
1961         setStatusLineMessage(annotation.getText());
1962       }
1963     }
1964   }
1965
1966   /**
1967    * Returns the lock object for the given annotation model.
1968    * 
1969    * @param annotationModel
1970    *          the annotation model
1971    * @return the annotation model's lock object
1972    * @since 3.0
1973    */
1974   private Object getLockObject(IAnnotationModel annotationModel) {
1975     if (annotationModel instanceof ISynchronizable)
1976       return ((ISynchronizable) annotationModel).getLockObject();
1977     else
1978       return annotationModel;
1979   }
1980
1981   /**
1982    * Updates the annotation views that show the given annotation.
1983    * 
1984    * @param annotation
1985    *          the annotation
1986    */
1987   private void updateAnnotationViews(Annotation annotation) {
1988     IMarker marker = null;
1989     if (annotation instanceof MarkerAnnotation)
1990       marker = ((MarkerAnnotation) annotation).getMarker();
1991     else if (annotation instanceof IJavaAnnotation) {
1992       Iterator e = ((IJavaAnnotation) annotation).getOverlaidIterator();
1993       if (e != null) {
1994         while (e.hasNext()) {
1995           Object o = e.next();
1996           if (o instanceof MarkerAnnotation) {
1997             marker = ((MarkerAnnotation) o).getMarker();
1998             break;
1999           }
2000         }
2001       }
2002     }
2003
2004     if (marker != null && !marker.equals(fLastMarkerTarget)) {
2005       try {
2006         boolean isProblem = marker.isSubtypeOf(IMarker.PROBLEM);
2007         IWorkbenchPage page = getSite().getPage();
2008         IViewPart view = page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW : IPageLayout.ID_TASK_LIST); //$NON-NLS-1$  //$NON-NLS-2$
2009         if (view != null) {
2010           Method method = view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class }); //$NON-NLS-1$
2011           method.invoke(view, new Object[] { new StructuredSelection(marker), Boolean.TRUE });
2012         }
2013       } catch (CoreException x) {
2014       } catch (NoSuchMethodException x) {
2015       } catch (IllegalAccessException x) {
2016       } catch (InvocationTargetException x) {
2017       }
2018       // ignore exceptions, don't update any of the lists, just set status line
2019     }
2020   }
2021
2022   /**
2023    * Returns this document's complete text.
2024    * 
2025    * @return the document's complete text
2026    */
2027   public String get() {
2028     IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
2029     return doc.get();
2030   }
2031
2032   /**
2033    * Sets the outliner's context menu ID.
2034    */
2035   protected void setOutlinerContextMenuId(String menuId) {
2036     fOutlinerContextMenuId = menuId;
2037   }
2038
2039   /**
2040    * Returns the standard action group of this editor.
2041    */
2042   protected ActionGroup getActionGroup() {
2043     return fActionGroups;
2044   }
2045
2046   //  public JavaOutlinePage getfOutlinePage() {
2047   //    return fOutlinePage;
2048   //  }
2049
2050   /**
2051    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method extend the actions to add those
2052    * specific to the receiver
2053    */
2054   protected void createActions() {
2055     super.createActions();
2056
2057     fFoldingGroup = new FoldingActionGroup(this, getViewer());
2058
2059     ResourceAction resAction = new TextOperationAction(PHPEditorMessages.getResourceBundle(),
2060         "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
2061     resAction = new InformationDispatchAction(PHPEditorMessages.getResourceBundle(),
2062         "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
2063     resAction.setActionDefinitionId(net.sourceforge.phpdt.ui.actions.PHPEditorActionDefinitionIds.SHOW_JAVADOC);
2064     setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
2065     //  WorkbenchHelp.setHelp(resAction,
2066     // IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
2067
2068     Action action = new GotoMatchingBracketAction(this);
2069     action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
2070     setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
2071
2072     //  action= new
2073     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.",
2074     // this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
2075     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE);
2076     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action);
2077     //// WorkbenchHelp.setHelp(action,
2078     // IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
2079     //
2080     //  action= new
2081     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.",
2082     // this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
2083     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE);
2084     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE,
2085     // action);
2086     //// WorkbenchHelp.setHelp(action,
2087     // IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
2088     //  
2089     //  action= new
2090     // TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.",
2091     // this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
2092     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY);
2093     //  setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY,
2094     // action);
2095     //// WorkbenchHelp.setHelp(action,
2096     // IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
2097
2098     fEncodingSupport = new DefaultEncodingSupport();
2099     fEncodingSupport.initialize(this);
2100
2101     //  fSelectionHistory= new SelectionHistory(this);
2102     //
2103     //  action= new StructureSelectEnclosingAction(this, fSelectionHistory);
2104     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);
2105     //  setAction(StructureSelectionAction.ENCLOSING, action);
2106     //
2107     //  action= new StructureSelectNextAction(this, fSelectionHistory);
2108     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
2109     //  setAction(StructureSelectionAction.NEXT, action);
2110     //
2111     //  action= new StructureSelectPreviousAction(this, fSelectionHistory);
2112     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
2113     //  setAction(StructureSelectionAction.PREVIOUS, action);
2114     //
2115     //  StructureSelectHistoryAction historyAction= new
2116     // StructureSelectHistoryAction(this, fSelectionHistory);
2117     //  historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);
2118     //  setAction(StructureSelectionAction.HISTORY, historyAction);
2119     //  fSelectionHistory.setHistoryAction(historyAction);
2120     //                  
2121     //  action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
2122     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
2123     //  setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
2124     //
2125     //  action=
2126     // GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
2127     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
2128     //  setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
2129     //  
2130     //  action= new QuickFormatAction();
2131     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
2132     //  setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
2133     //
2134     //  action= new RemoveOccurrenceAnnotations(this);
2135     //  action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
2136     //  setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
2137
2138     // add annotation actions
2139     action = new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
2140     setAction("AnnotationAction", action); //$NON-NLS-1$
2141   }
2142
2143   private void internalDoSetInput(IEditorInput input) throws CoreException {
2144     super.doSetInput(input);
2145
2146     if (getSourceViewer() instanceof JavaSourceViewer) {
2147       JavaSourceViewer viewer = (JavaSourceViewer) getSourceViewer();
2148       if (viewer.getReconciler() == null) {
2149         IReconciler reconciler = getSourceViewerConfiguration().getReconciler(viewer);
2150         if (reconciler != null) {
2151           reconciler.install(viewer);
2152           viewer.setReconciler(reconciler);
2153         }
2154       }
2155     }
2156
2157     if (fEncodingSupport != null)
2158       fEncodingSupport.reset();
2159
2160     setOutlinePageInput(fOutlinePage, input);
2161
2162     if (fProjectionModelUpdater != null)
2163       fProjectionModelUpdater.initialize();
2164
2165     //        if (isShowingOverrideIndicators())
2166     //                  installOverrideIndicator(false);
2167   }
2168
2169   /*
2170    * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
2171    * @since 3.0
2172    */
2173   protected void setPreferenceStore(IPreferenceStore store) {
2174     super.setPreferenceStore(store);
2175     if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
2176       JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
2177       setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this,
2178           IPHPPartitions.PHP_PARTITIONING));
2179     }
2180     if (getSourceViewer() instanceof JavaSourceViewer)
2181       ((JavaSourceViewer) getSourceViewer()).setPreferenceStore(store);
2182   }
2183
2184   /**
2185    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra disposal
2186    * actions required by the php editor.
2187    */
2188   public void dispose() {
2189     if (fProjectionModelUpdater != null) {
2190       fProjectionModelUpdater.uninstall();
2191       fProjectionModelUpdater = null;
2192     }
2193
2194     if (fProjectionSupport != null) {
2195       fProjectionSupport.dispose();
2196       fProjectionSupport = null;
2197     }
2198     //   PHPEditorEnvironment.disconnect(this);
2199     if (fOutlinePage != null)
2200       fOutlinePage.setInput(null);
2201
2202     if (fActionGroups != null)
2203       fActionGroups.dispose();
2204
2205     if (isBrowserLikeLinks())
2206       disableBrowserLikeLinks();
2207
2208     if (fEncodingSupport != null) {
2209       fEncodingSupport.dispose();
2210       fEncodingSupport = null;
2211     }
2212
2213     if (fPropertyChangeListener != null) {
2214       Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
2215       preferences.removePropertyChangeListener(fPropertyChangeListener);
2216       fPropertyChangeListener = null;
2217     }
2218
2219     //    if (fSourceViewerDecorationSupport != null) {
2220     //      fSourceViewerDecorationSupport.dispose();
2221     //      fSourceViewerDecorationSupport = null;
2222     //    }
2223
2224     if (fBracketMatcher != null) {
2225       fBracketMatcher.dispose();
2226       fBracketMatcher = null;
2227     }
2228
2229     if (fEditorSelectionChangedListener != null) {
2230       fEditorSelectionChangedListener.uninstall(getSelectionProvider());
2231       fEditorSelectionChangedListener = null;
2232     }
2233
2234     super.dispose();
2235   }
2236
2237   /**
2238    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra revert behavior
2239    * required by the php editor.
2240    */
2241   //  public void doRevertToSaved() {
2242   //    super.doRevertToSaved();
2243   //    if (fOutlinePage != null)
2244   //      fOutlinePage.update();
2245   //  }
2246   /**
2247    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra save behavior
2248    * required by the php editor.
2249    */
2250   //  public void doSave(IProgressMonitor monitor) {
2251   //    super.doSave(monitor);
2252   // compile or not, according to the user preferences
2253   // IPreferenceStore store = getPreferenceStore();
2254   // the parse on save was changed to the eclipse "builders" concept
2255   //    if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) {
2256   //      IAction a = PHPParserAction.getInstance();
2257   //      if (a != null)
2258   //        a.run();
2259   //    }
2260   //    if (SWT.getPlatform().equals("win32")) {
2261   //      IAction a = ShowExternalPreviewAction.getInstance();
2262   //      if (a != null)
2263   //        a.run();
2264   //    }
2265   //    if (fOutlinePage != null)
2266   //      fOutlinePage.update();
2267   //  }
2268   /**
2269    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs any extra save as
2270    * behavior required by the php editor.
2271    */
2272   //  public void doSaveAs() {
2273   //    super.doSaveAs();
2274   //    if (fOutlinePage != null)
2275   //      fOutlinePage.update();
2276   //  }
2277   /*
2278    * @see StatusTextEditor#getStatusHeader(IStatus)
2279    */
2280   protected String getStatusHeader(IStatus status) {
2281     if (fEncodingSupport != null) {
2282       String message = fEncodingSupport.getStatusHeader(status);
2283       if (message != null)
2284         return message;
2285     }
2286     return super.getStatusHeader(status);
2287   }
2288
2289   /*
2290    * @see StatusTextEditor#getStatusBanner(IStatus)
2291    */
2292   protected String getStatusBanner(IStatus status) {
2293     if (fEncodingSupport != null) {
2294       String message = fEncodingSupport.getStatusBanner(status);
2295       if (message != null)
2296         return message;
2297     }
2298     return super.getStatusBanner(status);
2299   }
2300
2301   /*
2302    * @see StatusTextEditor#getStatusMessage(IStatus)
2303    */
2304   protected String getStatusMessage(IStatus status) {
2305     if (fEncodingSupport != null) {
2306       String message = fEncodingSupport.getStatusMessage(status);
2307       if (message != null)
2308         return message;
2309     }
2310     return super.getStatusMessage(status);
2311   }
2312
2313   /**
2314    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs sets the input of the
2315    * outline page after AbstractTextEditor has set input.
2316    */
2317   //  protected void doSetInput(IEditorInput input) throws CoreException {
2318   //    super.doSetInput(input);
2319   //
2320   //    if (fEncodingSupport != null)
2321   //      fEncodingSupport.reset();
2322   //    if (fOutlinePage != null)
2323   //      fOutlinePage.setInput(input);
2324   //    // setOutlinePageInput(fOutlinePage, input);
2325   //  }
2326   protected void doSetInput(IEditorInput input) throws CoreException {
2327     super.doSetInput(input);
2328     if (fEncodingSupport != null)
2329       fEncodingSupport.reset();
2330     setOutlinePageInput(fOutlinePage, input);
2331   }
2332
2333   /*
2334    * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
2335    */
2336   //  public Object getViewPartInput() {
2337   //    return getEditorInput().getAdapter(IFile.class);
2338   //  }
2339   /**
2340    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method adds any PHPEditor specific
2341    * entries.
2342    */
2343   public void editorContextMenuAboutToShow(MenuManager menu) {
2344     super.editorContextMenuAboutToShow(menu);
2345     menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
2346     menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
2347
2348     ActionContext context = new ActionContext(getSelectionProvider().getSelection());
2349     fContextMenuGroup.setContext(context);
2350     fContextMenuGroup.fillContextMenu(menu);
2351     fContextMenuGroup.setContext(null);
2352     //    addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format");
2353     // //$NON-NLS-1$
2354     //
2355     //    ActionContext context =
2356     //      new ActionContext(getSelectionProvider().getSelection());
2357     //    fContextMenuGroup.setContext(context);
2358     //    fContextMenuGroup.fillContextMenu(menu);
2359     //    fContextMenuGroup.setContext(null);
2360   }
2361
2362   /**
2363    * Creates the outline page used with this editor.
2364    */
2365   protected JavaOutlinePage createOutlinePage() {
2366     JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
2367     fOutlineSelectionChangedListener.install(page);
2368     setOutlinePageInput(page, getEditorInput());
2369     return page;
2370   }
2371
2372   /**
2373    * Informs the editor that its outliner has been closed.
2374    */
2375   public void outlinePageClosed() {
2376     if (fOutlinePage != null) {
2377       fOutlineSelectionChangedListener.uninstall(fOutlinePage);
2378       fOutlinePage = null;
2379       resetHighlightRange();
2380     }
2381   }
2382
2383   /**
2384    * Synchronizes the outliner selection with the given element position in the editor.
2385    * 
2386    * @param element
2387    *          the java element to select
2388    */
2389   protected void synchronizeOutlinePage(ISourceReference element) {
2390     synchronizeOutlinePage(element, true);
2391   }
2392
2393   /**
2394    * Synchronizes the outliner selection with the given element position in the editor.
2395    * 
2396    * @param element
2397    *          the java element to select
2398    * @param checkIfOutlinePageActive
2399    *          <code>true</code> if check for active outline page needs to be done
2400    */
2401   protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
2402     if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
2403       fOutlineSelectionChangedListener.uninstall(fOutlinePage);
2404       fOutlinePage.select(element);
2405       fOutlineSelectionChangedListener.install(fOutlinePage);
2406     }
2407   }
2408
2409   /**
2410    * Synchronizes the outliner selection with the actual cursor position in the editor.
2411    */
2412   public void synchronizeOutlinePageSelection() {
2413     synchronizeOutlinePage(computeHighlightRangeSourceReference());
2414
2415     //    ISourceViewer sourceViewer = getSourceViewer();
2416     //    if (sourceViewer == null || fOutlinePage == null)
2417     //      return;
2418     //
2419     //    StyledText styledText = sourceViewer.getTextWidget();
2420     //    if (styledText == null)
2421     //      return;
2422     //
2423     //    int caret = 0;
2424     //    if (sourceViewer instanceof ITextViewerExtension3) {
2425     //      ITextViewerExtension3 extension = (ITextViewerExtension3)
2426     // sourceViewer;
2427     //      caret =
2428     // extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
2429     //    } else {
2430     //      int offset = sourceViewer.getVisibleRegion().getOffset();
2431     //      caret = offset + styledText.getCaretOffset();
2432     //    }
2433     //
2434     //    IJavaElement element = getElementAt(caret);
2435     //    if (element instanceof ISourceReference) {
2436     //      fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
2437     //      fOutlinePage.select((ISourceReference) element);
2438     //      fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
2439     //    }
2440   }
2441
2442   protected void setSelection(ISourceReference reference, boolean moveCursor) {
2443
2444     ISelection selection = getSelectionProvider().getSelection();
2445     if (selection instanceof TextSelection) {
2446       TextSelection textSelection = (TextSelection) selection;
2447       if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
2448         markInNavigationHistory();
2449     }
2450
2451     if (reference != null) {
2452
2453       StyledText textWidget = null;
2454
2455       ISourceViewer sourceViewer = getSourceViewer();
2456       if (sourceViewer != null)
2457         textWidget = sourceViewer.getTextWidget();
2458
2459       if (textWidget == null)
2460         return;
2461
2462       try {
2463
2464         ISourceRange range = reference.getSourceRange();
2465         if (range == null)
2466           return;
2467
2468         int offset = range.getOffset();
2469         int length = range.getLength();
2470
2471         if (offset < 0 || length < 0)
2472           return;
2473
2474         textWidget.setRedraw(false);
2475
2476         setHighlightRange(offset, length, moveCursor);
2477
2478         if (!moveCursor)
2479           return;
2480
2481         offset = -1;
2482         length = -1;
2483
2484         if (reference instanceof IMember) {
2485           range = ((IMember) reference).getNameRange();
2486           if (range != null) {
2487             offset = range.getOffset();
2488             length = range.getLength();
2489           }
2490         }
2491         //                                      else if (reference instanceof IImportDeclaration) {
2492         //                                              String name= ((IImportDeclaration)
2493         // reference).getElementName();
2494         //                                              if (name != null && name.length() > 0) {
2495         //                                                      String content= reference.getSource();
2496         //                                                      if (content != null) {
2497         //                                                              offset= range.getOffset() + content.indexOf(name);
2498         //                                                              length= name.length();
2499         //                                                      }
2500         //                                              }
2501         //                                      } else if (reference instanceof IPackageDeclaration) {
2502         //                                              String name= ((IPackageDeclaration)
2503         // reference).getElementName();
2504         //                                              if (name != null && name.length() > 0) {
2505         //                                                      String content= reference.getSource();
2506         //                                                      if (content != null) {
2507         //                                                              offset= range.getOffset() + content.indexOf(name);
2508         //                                                              length= name.length();
2509         //                                                      }
2510         //                                              }
2511         //                                      }
2512
2513         if (offset > -1 && length > 0) {
2514           sourceViewer.revealRange(offset, length);
2515           sourceViewer.setSelectedRange(offset, length);
2516         }
2517
2518       } catch (JavaModelException x) {
2519       } catch (IllegalArgumentException x) {
2520       } finally {
2521         if (textWidget != null)
2522           textWidget.setRedraw(true);
2523       }
2524
2525     } else if (moveCursor) {
2526       resetHighlightRange();
2527     }
2528
2529     markInNavigationHistory();
2530   }
2531
2532   public void setSelection(IJavaElement element) {
2533     if (element == null || element instanceof ICompilationUnit) { // ||
2534       // element
2535       // instanceof
2536       // IClassFile)
2537       // {
2538       /*
2539        * If the element is an ICompilationUnit this unit is either the input of this editor or not being displayed. In both cases,
2540        * nothing should happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
2541        */
2542       return;
2543     }
2544
2545     IJavaElement corresponding = getCorrespondingElement(element);
2546     if (corresponding instanceof ISourceReference) {
2547       ISourceReference reference = (ISourceReference) corresponding;
2548       // set highlight range
2549       setSelection(reference, true);
2550       // set outliner selection
2551       if (fOutlinePage != null) {
2552         fOutlineSelectionChangedListener.uninstall(fOutlinePage);
2553         fOutlinePage.select(reference);
2554         fOutlineSelectionChangedListener.install(fOutlinePage);
2555       }
2556     }
2557   }
2558
2559   public synchronized void editingScriptStarted() {
2560     ++fIgnoreOutlinePageSelection;
2561   }
2562
2563   public synchronized void editingScriptEnded() {
2564     --fIgnoreOutlinePageSelection;
2565   }
2566
2567   public synchronized boolean isEditingScriptRunning() {
2568     return (fIgnoreOutlinePageSelection > 0);
2569   }
2570
2571   /**
2572    * The <code>PHPEditor</code> implementation of this <code>AbstractTextEditor</code> method performs gets the java content
2573    * outline page if request is for a an outline page.
2574    */
2575   public Object getAdapter(Class required) {
2576
2577     if (IContentOutlinePage.class.equals(required)) {
2578       if (fOutlinePage == null)
2579         fOutlinePage = createOutlinePage();
2580       return fOutlinePage;
2581     }
2582
2583     if (IEncodingSupport.class.equals(required))
2584       return fEncodingSupport;
2585
2586     if (required == IShowInTargetList.class) {
2587       return new IShowInTargetList() {
2588         public String[] getShowInTargetIds() {
2589           return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
2590         }
2591
2592       };
2593     }
2594     if (fProjectionSupport != null) {
2595       Object adapter = fProjectionSupport.getAdapter(getSourceViewer(), required);
2596       if (adapter != null)
2597         return adapter;
2598     }
2599
2600     return super.getAdapter(required);
2601   }
2602
2603   //  public Object getAdapter(Class required) {
2604   //    if (IContentOutlinePage.class.equals(required)) {
2605   //      if (fOutlinePage == null) {
2606   //        fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this);
2607   //        if (getEditorInput() != null)
2608   //          fOutlinePage.setInput(getEditorInput());
2609   //      }
2610   //      return fOutlinePage;
2611   //    }
2612   //
2613   //    if (IEncodingSupport.class.equals(required))
2614   //      return fEncodingSupport;
2615   //
2616   //    return super.getAdapter(required);
2617   //  }
2618
2619   protected void doSelectionChanged(SelectionChangedEvent event) {
2620     ISourceReference reference = null;
2621
2622     ISelection selection = event.getSelection();
2623     Iterator iter = ((IStructuredSelection) selection).iterator();
2624     while (iter.hasNext()) {
2625       Object o = iter.next();
2626       if (o instanceof ISourceReference) {
2627         reference = (ISourceReference) o;
2628         break;
2629       }
2630     }
2631
2632     if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
2633       PHPeclipsePlugin.getActivePage().bringToTop(this);
2634
2635     try {
2636       editingScriptStarted();
2637       setSelection(reference, !isActivePart());
2638     } finally {
2639       editingScriptEnded();
2640     }
2641   }
2642
2643   /*
2644    * @see AbstractTextEditor#adjustHighlightRange(int, int)
2645    */
2646   protected void adjustHighlightRange(int offset, int length) {
2647
2648     try {
2649
2650       IJavaElement element = getElementAt(offset);
2651       while (element instanceof ISourceReference) {
2652         ISourceRange range = ((ISourceReference) element).getSourceRange();
2653         if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
2654
2655           ISourceViewer viewer = getSourceViewer();
2656           if (viewer instanceof ITextViewerExtension5) {
2657             ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
2658             extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
2659           }
2660
2661           setHighlightRange(range.getOffset(), range.getLength(), true);
2662           if (fOutlinePage != null) {
2663             fOutlineSelectionChangedListener.uninstall(fOutlinePage);
2664             fOutlinePage.select((ISourceReference) element);
2665             fOutlineSelectionChangedListener.install(fOutlinePage);
2666           }
2667
2668           return;
2669         }
2670         element = element.getParent();
2671       }
2672
2673     } catch (JavaModelException x) {
2674       PHPeclipsePlugin.log(x.getStatus());
2675     }
2676
2677     ISourceViewer viewer = getSourceViewer();
2678     if (viewer instanceof ITextViewerExtension5) {
2679       ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
2680       extension.exposeModelRange(new Region(offset, length));
2681     } else {
2682       resetHighlightRange();
2683     }
2684
2685   }
2686
2687   protected boolean isActivePart() {
2688     IWorkbenchWindow window = getSite().getWorkbenchWindow();
2689     IPartService service = window.getPartService();
2690     IWorkbenchPart part = service.getActivePart();
2691     return part != null && part.equals(this);
2692   }
2693
2694   //  public void openContextHelp() {
2695   //    IDocument doc =
2696   // this.getDocumentProvider().getDocument(this.getEditorInput());
2697   //    ITextSelection selection = (ITextSelection)
2698   // this.getSelectionProvider().getSelection();
2699   //    int pos = selection.getOffset();
2700   //    String word = getFunctionName(doc, pos);
2701   //    openContextHelp(word);
2702   //  }
2703   //
2704   //  private void openContextHelp(String word) {
2705   //    open(word);
2706   //  }
2707   //
2708   //  public static void open(String word) {
2709   //    IHelp help = WorkbenchHelp.getHelpSupport();
2710   //    if (help != null) {
2711   //      IHelpResource helpResource = new PHPFunctionHelpResource(word);
2712   //      WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource);
2713   //    } else {
2714   //      // showMessage(shell, dialogTitle, ActionMessages.getString("Open help
2715   // not available"), false); //$NON-NLS-1$
2716   //    }
2717   //  }
2718
2719   //    private String getFunctionName(IDocument doc, int pos) {
2720   //            Point word = PHPWordExtractor.findWord(doc, pos);
2721   //            if (word != null) {
2722   //                    try {
2723   //                            return doc.get(word.x, word.y).replace('_', '-');
2724   //                    } catch (BadLocationException e) {
2725   //                    }
2726   //            }
2727   //            return "";
2728   //    }
2729
2730   /*
2731    * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
2732    */
2733   protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
2734
2735     try {
2736
2737       ISourceViewer sourceViewer = getSourceViewer();
2738       if (sourceViewer == null)
2739         return;
2740
2741       String property = event.getProperty();
2742
2743       if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
2744         Object value = event.getNewValue();
2745         if (value instanceof Integer) {
2746           sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
2747         } else if (value instanceof String) {
2748           sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
2749         }
2750         return;
2751       }
2752
2753       //      if (OVERVIEW_RULER.equals(property)) {
2754       //        if (isOverviewRulerVisible())
2755       //          showOverviewRuler();
2756       //        else
2757       //          hideOverviewRuler();
2758       //        return;
2759       //      }
2760
2761       //      if (LINE_NUMBER_RULER.equals(property)) {
2762       //        if (isLineNumberRulerVisible())
2763       //          showLineNumberRuler();
2764       //        else
2765       //          hideLineNumberRuler();
2766       //        return;
2767       //      }
2768
2769       //      if (fLineNumberRulerColumn != null
2770       //        && (LINE_NUMBER_COLOR.equals(property) ||
2771       // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
2772       // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2773       //
2774       //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2775       //      }
2776
2777       if (isJavaEditorHoverProperty(property))
2778         updateHoverBehavior();
2779
2780       if (BROWSER_LIKE_LINKS.equals(property)) {
2781         if (isBrowserLikeLinks())
2782           enableBrowserLikeLinks();
2783         else
2784           disableBrowserLikeLinks();
2785         return;
2786       }
2787
2788       if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
2789         if ((event.getNewValue() instanceof Boolean) && ((Boolean) event.getNewValue()).booleanValue())
2790           selectionChanged();
2791         return;
2792       }
2793
2794       if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
2795         if (event.getNewValue() instanceof Boolean) {
2796           Boolean disable = (Boolean) event.getNewValue();
2797           enableOverwriteMode(!disable.booleanValue());
2798         }
2799         return;
2800       }
2801
2802       //        if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property))
2803       // {
2804       //                if (event.getNewValue() instanceof Boolean) {
2805       //                        boolean markOccurrenceAnnotations=
2806       // ((Boolean)event.getNewValue()).booleanValue();
2807       //                        if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
2808       //                                fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
2809       //                                if (!fMarkOccurrenceAnnotations)
2810       //                                        uninstallOccurrencesFinder();
2811       //                                else
2812       //                                        installOccurrencesFinder();
2813       //                        }
2814       //                }
2815       //        }
2816       //        if
2817       // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
2818       // {
2819       //                if (event.getNewValue() instanceof Boolean) {
2820       //                        boolean stickyOccurrenceAnnotations=
2821       // ((Boolean)event.getNewValue()).booleanValue();
2822       //                        if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
2823       // {
2824       //                                fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations;
2825       //// if (!fMarkOccurrenceAnnotations)
2826       //// uninstallOccurrencesFinder();
2827       //// else
2828       //// installOccurrencesFinder();
2829       //                        }
2830       //                }
2831       //        }
2832
2833       ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
2834
2835       //                if (affectsOverrideIndicatorAnnotations(event)) {
2836       //                        if (isShowingOverrideIndicators()) {
2837       //                                if (fOverrideIndicatorManager == null)
2838       //                                        installOverrideIndicator(true);
2839       //                        } else {
2840       //                                if (fOverrideIndicatorManager != null)
2841       //                                        uninstallOverrideIndicator();
2842       //                        }
2843       //                        return;
2844       //                }
2845
2846       if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
2847         if (sourceViewer instanceof ProjectionViewer) {
2848           ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer;
2849           if (fProjectionModelUpdater != null)
2850             fProjectionModelUpdater.uninstall();
2851           // either freshly enabled or provider changed
2852           fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
2853           if (fProjectionModelUpdater != null) {
2854             fProjectionModelUpdater.install(this, projectionViewer);
2855           }
2856         }
2857         return;
2858       }
2859     } finally {
2860       super.handlePreferenceStoreChanged(event);
2861     }
2862   }
2863
2864   //  /*
2865   //     * @see
2866   // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
2867   //     */
2868   //  protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
2869   //
2870   //    try {
2871   //
2872   //      ISourceViewer sourceViewer = getSourceViewer();
2873   //      if (sourceViewer == null)
2874   //        return;
2875   //
2876   //      String property = event.getProperty();
2877   //
2878   //      // if
2879   // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
2880   //      // Object value= event.getNewValue();
2881   //      // if (value instanceof Integer) {
2882   //      // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
2883   //      // } else if (value instanceof String) {
2884   //      // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String)
2885   // value));
2886   //      // }
2887   //      // return;
2888   //      // }
2889   //
2890   //      if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
2891   //        if (isLineNumberRulerVisible())
2892   //          showLineNumberRuler();
2893   //        else
2894   //          hideLineNumberRuler();
2895   //        return;
2896   //      }
2897   //
2898   //      if (fLineNumberRulerColumn != null
2899   //        && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
2900   //          || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
2901   //          || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2902   //
2903   //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2904   //      }
2905   //
2906   //    } finally {
2907   //      super.handlePreferenceStoreChanged(event);
2908   //    }
2909   //  }
2910
2911   //  private boolean isJavaEditorHoverProperty(String property) {
2912   //    return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
2913   //      || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
2914   //      || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
2915   //      || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
2916   //      || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
2917   //      || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
2918   //      || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
2919   //      || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
2920   //  }
2921
2922   /**
2923    * Shows the line number ruler column.
2924    */
2925   //  private void showLineNumberRuler() {
2926   //    IVerticalRuler v = getVerticalRuler();
2927   //    if (v instanceof CompositeRuler) {
2928   //      CompositeRuler c = (CompositeRuler) v;
2929   //      c.addDecorator(1, createLineNumberRulerColumn());
2930   //    }
2931   //  }
2932   private boolean isJavaEditorHoverProperty(String property) {
2933     return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
2934   }
2935
2936   /**
2937    * Return whether the browser like links should be enabled according to the preference store settings.
2938    * 
2939    * @return <code>true</code> if the browser like links should be enabled
2940    */
2941   private boolean isBrowserLikeLinks() {
2942     IPreferenceStore store = getPreferenceStore();
2943     return store.getBoolean(BROWSER_LIKE_LINKS);
2944   }
2945
2946   /**
2947    * Enables browser like links.
2948    */
2949   private void enableBrowserLikeLinks() {
2950     if (fMouseListener == null) {
2951       fMouseListener = new MouseClickListener();
2952       fMouseListener.install();
2953     }
2954   }
2955
2956   /**
2957    * Disables browser like links.
2958    */
2959   private void disableBrowserLikeLinks() {
2960     if (fMouseListener != null) {
2961       fMouseListener.uninstall();
2962       fMouseListener = null;
2963     }
2964   }
2965
2966   /**
2967    * Handles a property change event describing a change of the java core's preferences and updates the preference related editor
2968    * properties.
2969    * 
2970    * @param event
2971    *          the property change event
2972    */
2973   protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2974     if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
2975       ISourceViewer sourceViewer = getSourceViewer();
2976       if (sourceViewer != null
2977           && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event
2978               .getNewValue())))
2979         sourceViewer.invalidateTextPresentation();
2980     }
2981     if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
2982       setWordWrap();
2983     }
2984   }
2985
2986   /**
2987    * Return whether the line number ruler column should be visible according to the preference store settings.
2988    * 
2989    * @return <code>true</code> if the line numbers should be visible
2990    */
2991   //  protected boolean isLineNumberRulerVisible() {
2992   //    IPreferenceStore store = getPreferenceStore();
2993   //    return store.getBoolean(LINE_NUMBER_RULER);
2994   //  }
2995   /**
2996    * Hides the line number ruler column.
2997    */
2998   //  private void hideLineNumberRuler() {
2999   //    IVerticalRuler v = getVerticalRuler();
3000   //    if (v instanceof CompositeRuler) {
3001   //      CompositeRuler c = (CompositeRuler) v;
3002   //      try {
3003   //        c.removeDecorator(1);
3004   //      } catch (Throwable e) {
3005   //      }
3006   //    }
3007   //  }
3008   /*
3009    * @see AbstractTextEditor#handleCursorPositionChanged()
3010    */
3011   protected void handleCursorPositionChanged() {
3012     super.handleCursorPositionChanged();
3013     if (!isEditingScriptRunning() && fUpdater != null)
3014       fUpdater.post();
3015   }
3016
3017   /*
3018    * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
3019    */
3020   protected void handleElementContentReplaced() {
3021     super.handleElementContentReplaced();
3022     if (fProjectionModelUpdater != null)
3023       fProjectionModelUpdater.initialize();
3024   }
3025
3026   /**
3027    * Initializes the given line number ruler column from the preference store.
3028    * 
3029    * @param rulerColumn
3030    *          the ruler column to be initialized
3031    */
3032   //  protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
3033   // rulerColumn) {
3034   //    JavaTextTools textTools =
3035   // PHPeclipsePlugin.getDefault().getJavaTextTools();
3036   //    IColorManager manager = textTools.getColorManager();
3037   //
3038   //    IPreferenceStore store = getPreferenceStore();
3039   //    if (store != null) {
3040   //
3041   //      RGB rgb = null;
3042   //      // foreground color
3043   //      if (store.contains(LINE_NUMBER_COLOR)) {
3044   //        if (store.isDefault(LINE_NUMBER_COLOR))
3045   //          rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
3046   //        else
3047   //          rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
3048   //      }
3049   //      rulerColumn.setForeground(manager.getColor(rgb));
3050   //
3051   //      rgb = null;
3052   //      // background color
3053   //      if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
3054   //        if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
3055   //          if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
3056   //            rgb = PreferenceConverter.getDefaultColor(store,
3057   // PREFERENCE_COLOR_BACKGROUND);
3058   //          else
3059   //            rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
3060   //        }
3061   //      }
3062   //      rulerColumn.setBackground(manager.getColor(rgb));
3063   //    }
3064   //  }
3065   /**
3066    * Creates a new line number ruler column that is appropriately initialized.
3067    */
3068   //  protected IVerticalRulerColumn createLineNumberRulerColumn() {
3069   //    fLineNumberRulerColumn = new LineNumberRulerColumn();
3070   //    initializeLineNumberRulerColumn(fLineNumberRulerColumn);
3071   //    return fLineNumberRulerColumn;
3072   //  }
3073   /*
3074    * @see AbstractTextEditor#createVerticalRuler()
3075    */
3076   //  protected IVerticalRuler createVerticalRuler() {
3077   //    CompositeRuler ruler = new CompositeRuler();
3078   //    ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
3079   //    if (isLineNumberRulerVisible())
3080   //      ruler.addDecorator(1, createLineNumberRulerColumn());
3081   //    return ruler;
3082   //  }
3083   //  private static IRegion getSignedSelection(ITextViewer viewer) {
3084   //
3085   //    StyledText text = viewer.getTextWidget();
3086   //    int caretOffset = text.getCaretOffset();
3087   //    Point selection = text.getSelection();
3088   //
3089   //    // caret left
3090   //    int offset, length;
3091   //    if (caretOffset == selection.x) {
3092   //      offset = selection.y;
3093   //      length = selection.x - selection.y;
3094   //
3095   //      // caret right
3096   //    } else {
3097   //      offset = selection.x;
3098   //      length = selection.y - selection.x;
3099   //    }
3100   //
3101   //    return new Region(offset, length);
3102   //  }
3103   protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
3104     StyledText text = sourceViewer.getTextWidget();
3105     Point selection = text.getSelectionRange();
3106
3107     if (text.getCaretOffset() == selection.x) {
3108       selection.x = selection.x + selection.y;
3109       selection.y = -selection.y;
3110     }
3111
3112     selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
3113
3114     return new Region(selection.x, selection.y);
3115   }
3116
3117   /** Preference key for matching brackets */
3118   protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
3119
3120   /** Preference key for matching brackets color */
3121   protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
3122
3123   /** Preference key for highlighting current line */
3124   //  protected final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
3125   /** Preference key for highlight color of current line */
3126   //  protected final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
3127   /** Preference key for showing print marging ruler */
3128   //  protected final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
3129   /** Preference key for print margin ruler color */
3130   //  protected final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
3131   /** Preference key for print margin ruler column */
3132   //  protected final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
3133   /** Preference key for error indication */
3134   //  protected final static String ERROR_INDICATION =
3135   // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
3136   /** Preference key for error color */
3137   //  protected final static String ERROR_INDICATION_COLOR =
3138   // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
3139   /** Preference key for warning indication */
3140   //  protected final static String WARNING_INDICATION =
3141   // PreferenceConstants.EDITOR_WARNING_INDICATION;
3142   /** Preference key for warning color */
3143   //  protected final static String WARNING_INDICATION_COLOR =
3144   // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
3145   /** Preference key for task indication */
3146   protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
3147
3148   /** Preference key for task color */
3149   protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
3150
3151   /** Preference key for bookmark indication */
3152   protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
3153
3154   /** Preference key for bookmark color */
3155   protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
3156
3157   /** Preference key for search result indication */
3158   protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
3159
3160   /** Preference key for search result color */
3161   protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
3162
3163   /** Preference key for unknown annotation indication */
3164   protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
3165
3166   /** Preference key for unknown annotation color */
3167   protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
3168
3169   /** Preference key for shwoing the overview ruler */
3170   protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
3171
3172   /** Preference key for error indication in overview ruler */
3173   protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
3174
3175   /** Preference key for warning indication in overview ruler */
3176   protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
3177
3178   /** Preference key for task indication in overview ruler */
3179   protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
3180
3181   /** Preference key for bookmark indication in overview ruler */
3182   protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
3183
3184   /** Preference key for search result indication in overview ruler */
3185   protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
3186
3187   /** Preference key for unknown annotation indication in overview ruler */
3188   protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
3189
3190   //            /** Preference key for compiler task tags */
3191   //            private final static String COMPILER_TASK_TAGS=
3192   // JavaCore.COMPILER_TASK_TAGS;
3193   /** Preference key for browser like links */
3194   private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
3195
3196   /** Preference key for key modifier of browser like links */
3197   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
3198
3199   /**
3200    * Preference key for key modifier mask of browser like links. The value is only used if the value of
3201    * <code>EDITOR_BROWSER_LIKE_LINKS</code> cannot be resolved to valid SWT modifier bits.
3202    * 
3203    * @since 2.1.1
3204    */
3205   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
3206
3207   private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
3208
3209   private static boolean isBracket(char character) {
3210     for (int i = 0; i != BRACKETS.length; ++i)
3211       if (character == BRACKETS[i])
3212         return true;
3213     return false;
3214   }
3215
3216   private static boolean isSurroundedByBrackets(IDocument document, int offset) {
3217     if (offset == 0 || offset == document.getLength())
3218       return false;
3219
3220     try {
3221       return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
3222
3223     } catch (BadLocationException e) {
3224       return false;
3225     }
3226   }
3227
3228   //  protected void configureSourceViewerDecorationSupport() {
3229   //
3230   //    fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
3231   //
3232   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3233   //      AnnotationType.UNKNOWN,
3234   //      UNKNOWN_INDICATION_COLOR,
3235   //      UNKNOWN_INDICATION,
3236   //      UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
3237   //      0);
3238   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3239   //      AnnotationType.BOOKMARK,
3240   //      BOOKMARK_INDICATION_COLOR,
3241   //      BOOKMARK_INDICATION,
3242   //      BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
3243   //      1);
3244   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3245   //      AnnotationType.TASK,
3246   //      TASK_INDICATION_COLOR,
3247   //      TASK_INDICATION,
3248   //      TASK_INDICATION_IN_OVERVIEW_RULER,
3249   //      2);
3250   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3251   //      AnnotationType.SEARCH,
3252   //      SEARCH_RESULT_INDICATION_COLOR,
3253   //      SEARCH_RESULT_INDICATION,
3254   //      SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
3255   //      3);
3256   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3257   //      AnnotationType.WARNING,
3258   //      WARNING_INDICATION_COLOR,
3259   //      WARNING_INDICATION,
3260   //      WARNING_INDICATION_IN_OVERVIEW_RULER,
3261   //      4);
3262   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3263   //      AnnotationType.ERROR,
3264   //      ERROR_INDICATION_COLOR,
3265   //      ERROR_INDICATION,
3266   //      ERROR_INDICATION_IN_OVERVIEW_RULER,
3267   //      5);
3268   //
3269   //    fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE,
3270   // CURRENT_LINE_COLOR);
3271   //    fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN,
3272   // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
3273   //    fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
3274   // MATCHING_BRACKETS_COLOR);
3275   //
3276   //    fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
3277   //
3278   //  }
3279   /**
3280    * Returns the Java element wrapped by this editors input.
3281    * 
3282    * @return the Java element wrapped by this editors input.
3283    * @since 3.0
3284    */
3285   abstract protected IJavaElement getInputJavaElement();
3286
3287   protected void updateStatusLine() {
3288     ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
3289     Annotation annotation = getAnnotation(selection.getOffset(), selection.getLength());
3290     setStatusLineErrorMessage(null);
3291     setStatusLineMessage(null);
3292     if (annotation != null) {
3293       try {
3294         fIsUpdatingAnnotationViews = true;
3295         updateAnnotationViews(annotation);
3296       } finally {
3297         fIsUpdatingAnnotationViews = false;
3298       }
3299       if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
3300         setStatusLineMessage(annotation.getText());
3301     }
3302   }
3303
3304   /**
3305    * Jumps to the matching bracket.
3306    */
3307   public void gotoMatchingBracket() {
3308
3309     ISourceViewer sourceViewer = getSourceViewer();
3310     IDocument document = sourceViewer.getDocument();
3311     if (document == null)
3312       return;
3313
3314     IRegion selection = getSignedSelection(sourceViewer);
3315
3316     int selectionLength = Math.abs(selection.getLength());
3317     if (selectionLength > 1) {
3318       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$               
3319       sourceViewer.getTextWidget().getDisplay().beep();
3320       return;
3321     }
3322
3323     // #26314
3324     int sourceCaretOffset = selection.getOffset() + selection.getLength();
3325     if (isSurroundedByBrackets(document, sourceCaretOffset))
3326       sourceCaretOffset -= selection.getLength();
3327
3328     IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
3329     if (region == null) {
3330       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$              
3331       sourceViewer.getTextWidget().getDisplay().beep();
3332       return;
3333     }
3334
3335     int offset = region.getOffset();
3336     int length = region.getLength();
3337
3338     if (length < 1)
3339       return;
3340
3341     int anchor = fBracketMatcher.getAnchor();
3342     int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
3343
3344     boolean visible = false;
3345     if (sourceViewer instanceof ITextViewerExtension3) {
3346       ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
3347       visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
3348     } else {
3349       IRegion visibleRegion = sourceViewer.getVisibleRegion();
3350       visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
3351     }
3352
3353     if (!visible) {
3354       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$          
3355       sourceViewer.getTextWidget().getDisplay().beep();
3356       return;
3357     }
3358
3359     if (selection.getLength() < 0)
3360       targetOffset -= selection.getLength();
3361
3362     sourceViewer.setSelectedRange(targetOffset, selection.getLength());
3363     sourceViewer.revealRange(targetOffset, selection.getLength());
3364   }
3365
3366   /**
3367    * Ses the given message as error message to this editor's status line.
3368    * 
3369    * @param msg
3370    *          message to be set
3371    */
3372   protected void setStatusLineErrorMessage(String msg) {
3373     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
3374     if (statusLine != null)
3375       statusLine.setMessage(true, msg, null);
3376   }
3377
3378   /**
3379    * Sets the given message as message to this editor's status line.
3380    * 
3381    * @param msg
3382    *          message to be set
3383    * @since 3.0
3384    */
3385   protected void setStatusLineMessage(String msg) {
3386     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
3387     if (statusLine != null)
3388       statusLine.setMessage(false, msg, null);
3389   }
3390
3391   /**
3392    * Returns the annotation closest to the given range respecting the given direction. If an annotation is found, the annotations
3393    * current position is copied into the provided annotation position.
3394    * 
3395    * @param offset
3396    *          the region offset
3397    * @param length
3398    *          the region length
3399    * @param forward
3400    *          <code>true</code> for forwards, <code>false</code> for backward
3401    * @param annotationPosition
3402    *          the position of the found annotation
3403    * @return the found annotation
3404    */
3405   private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
3406
3407     Annotation nextAnnotation = null;
3408     Position nextAnnotationPosition = null;
3409     Annotation containingAnnotation = null;
3410     Position containingAnnotationPosition = null;
3411     boolean currentAnnotation = false;
3412
3413     IDocument document = getDocumentProvider().getDocument(getEditorInput());
3414     int endOfDocument = document.getLength();
3415     int distance = Integer.MAX_VALUE;
3416
3417     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3418     Iterator e = new JavaAnnotationIterator(model, true, true);
3419     while (e.hasNext()) {
3420       Annotation a = (Annotation) e.next();
3421       if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a))
3422         continue;
3423
3424       Position p = model.getPosition(a);
3425       if (p == null)
3426         continue;
3427
3428       if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
3429         if (containingAnnotation == null
3430             || (forward && p.length >= containingAnnotationPosition.length || !forward
3431                 && p.length >= containingAnnotationPosition.length)) {
3432           containingAnnotation = a;
3433           containingAnnotationPosition = p;
3434           currentAnnotation = p.length == length;
3435         }
3436       } else {
3437         int currentDistance = 0;
3438
3439         if (forward) {
3440           currentDistance = p.getOffset() - offset;
3441           if (currentDistance < 0)
3442             currentDistance = endOfDocument + currentDistance;
3443
3444           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
3445             distance = currentDistance;
3446             nextAnnotation = a;
3447             nextAnnotationPosition = p;
3448           }
3449         } else {
3450           currentDistance = offset + length - (p.getOffset() + p.length);
3451           if (currentDistance < 0)
3452             currentDistance = endOfDocument + currentDistance;
3453
3454           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
3455             distance = currentDistance;
3456             nextAnnotation = a;
3457             nextAnnotationPosition = p;
3458           }
3459         }
3460       }
3461     }
3462     if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
3463       annotationPosition.setOffset(containingAnnotationPosition.getOffset());
3464       annotationPosition.setLength(containingAnnotationPosition.getLength());
3465       return containingAnnotation;
3466     }
3467     if (nextAnnotationPosition != null) {
3468       annotationPosition.setOffset(nextAnnotationPosition.getOffset());
3469       annotationPosition.setLength(nextAnnotationPosition.getLength());
3470     }
3471
3472     return nextAnnotation;
3473   }
3474
3475   /**
3476    * Returns the annotation overlapping with the given range or <code>null</code>.
3477    * 
3478    * @param offset
3479    *          the region offset
3480    * @param length
3481    *          the region length
3482    * @return the found annotation or <code>null</code>
3483    * @since 3.0
3484    */
3485   private Annotation getAnnotation(int offset, int length) {
3486     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3487     Iterator e = new JavaAnnotationIterator(model, true, true);
3488     while (e.hasNext()) {
3489       Annotation a = (Annotation) e.next();
3490       if (!isNavigationTarget(a))
3491         continue;
3492
3493       Position p = model.getPosition(a);
3494       if (p != null && p.overlapsWith(offset, length))
3495         return a;
3496     }
3497
3498     return null;
3499   }
3500
3501   /**
3502    * Returns whether the given annotation is configured as a target for the "Go to Next/Previous Annotation" actions
3503    * 
3504    * @param annotation
3505    *          the annotation
3506    * @return <code>true</code> if this is a target, <code>false</code> otherwise
3507    * @since 3.0
3508    */
3509   private boolean isNavigationTarget(Annotation annotation) {
3510     Preferences preferences = EditorsUI.getPluginPreferences();
3511     AnnotationPreference preference = getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
3512     //          See bug 41689
3513     //          String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
3514     String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
3515     return (key != null && preferences.getBoolean(key));
3516   }
3517
3518   /**
3519    * Returns a segmentation of the line of the given document appropriate for bidi rendering. The default implementation returns
3520    * only the string literals of a php code line as segments.
3521    * 
3522    * @param document
3523    *          the document
3524    * @param lineOffset
3525    *          the offset of the line
3526    * @return the line's bidi segmentation
3527    * @throws BadLocationException
3528    *           in case lineOffset is not valid in document
3529    */
3530   public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
3531
3532     IRegion line = document.getLineInformationOfOffset(lineOffset);
3533     ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());
3534
3535     List segmentation = new ArrayList();
3536     for (int i = 0; i < linePartitioning.length; i++) {
3537       if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType()))
3538         segmentation.add(linePartitioning[i]);
3539     }
3540
3541     if (segmentation.size() == 0)
3542       return null;
3543
3544     int size = segmentation.size();
3545     int[] segments = new int[size * 2 + 1];
3546
3547     int j = 0;
3548     for (int i = 0; i < size; i++) {
3549       ITypedRegion segment = (ITypedRegion) segmentation.get(i);
3550
3551       if (i == 0)
3552         segments[j++] = 0;
3553
3554       int offset = segment.getOffset() - lineOffset;
3555       if (offset > segments[j - 1])
3556         segments[j++] = offset;
3557
3558       if (offset + segment.getLength() >= line.getLength())
3559         break;
3560
3561       segments[j++] = offset + segment.getLength();
3562     }
3563
3564     if (j < segments.length) {
3565       int[] result = new int[j];
3566       System.arraycopy(segments, 0, result, 0, j);
3567       segments = result;
3568     }
3569
3570     return segments;
3571   }
3572
3573   /**
3574    * Returns a segmentation of the given line appropriate for bidi rendering. The default implementation returns only the string
3575    * literals of a php code line as segments.
3576    * 
3577    * @param lineOffset
3578    *          the offset of the line
3579    * @param line
3580    *          the content of the line
3581    * @return the line's bidi segmentation
3582    */
3583   protected int[] getBidiLineSegments(int lineOffset, String line) {
3584     IDocumentProvider provider = getDocumentProvider();
3585     if (provider != null && line != null && line.length() > 0) {
3586       IDocument document = provider.getDocument(getEditorInput());
3587       if (document != null)
3588         try {
3589           return getBidiLineSegments(document, lineOffset);
3590         } catch (BadLocationException x) {
3591           // ignore
3592         }
3593     }
3594     return null;
3595   }
3596
3597   /*
3598    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3599    */
3600   //  protected final ISourceViewer createSourceViewer(
3601   //    Composite parent,
3602   //    IVerticalRuler ruler,
3603   //    int styles) {
3604   //    ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
3605   //    StyledText text = viewer.getTextWidget();
3606   //    text.addBidiSegmentListener(new BidiSegmentListener() {
3607   //      public void lineGetSegments(BidiSegmentEvent event) {
3608   //        event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
3609   //      }
3610   //    });
3611   //    // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
3612   //    return viewer;
3613   //  }
3614   public final ISourceViewer getViewer() {
3615     return getSourceViewer();
3616   }
3617
3618   //  protected void showOverviewRuler() {
3619   //    if (fOverviewRuler != null) {
3620   //      if (getSourceViewer() instanceof ISourceViewerExtension) {
3621   //        ((ISourceViewerExtension)
3622   // getSourceViewer()).showAnnotationsOverview(true);
3623   //        fSourceViewerDecorationSupport.updateOverviewDecorations();
3624   //      }
3625   //    }
3626   //  }
3627   //
3628   //  protected void hideOverviewRuler() {
3629   //    if (getSourceViewer() instanceof ISourceViewerExtension) {
3630   //      fSourceViewerDecorationSupport.hideAnnotationOverview();
3631   //      ((ISourceViewerExtension)
3632   // getSourceViewer()).showAnnotationsOverview(false);
3633   //    }
3634   //  }
3635
3636   //  protected boolean isOverviewRulerVisible() {
3637   //    IPreferenceStore store = getPreferenceStore();
3638   //    return store.getBoolean(OVERVIEW_RULER);
3639   //  }
3640   /*
3641    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3642    */
3643   //  protected ISourceViewer createJavaSourceViewer(
3644   //    Composite parent,
3645   //    IVerticalRuler ruler,
3646   //    IOverviewRuler overviewRuler,
3647   //    boolean isOverviewRulerVisible,
3648   //    int styles) {
3649   //    return new SourceViewer(parent, ruler, overviewRuler,
3650   // isOverviewRulerVisible(), styles);
3651   //  }
3652   /*
3653    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3654    */
3655   protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
3656       boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
3657     return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
3658   }
3659
3660   /*
3661    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3662    */
3663   protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
3664
3665     ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles,
3666         getPreferenceStore());
3667
3668     StyledText text = viewer.getTextWidget();
3669     text.addBidiSegmentListener(new BidiSegmentListener() {
3670       public void lineGetSegments(BidiSegmentEvent event) {
3671         event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
3672       }
3673     });
3674
3675     //          JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
3676
3677     // ensure source viewer decoration support has been created and
3678     // configured
3679     getSourceViewerDecorationSupport(viewer);
3680
3681     return viewer;
3682   }
3683
3684   /*
3685    * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
3686    */
3687   protected boolean affectsTextPresentation(PropertyChangeEvent event) {
3688     return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event)
3689         || super.affectsTextPresentation(event);
3690   }
3691
3692   //
3693   //      protected boolean affectsTextPresentation(PropertyChangeEvent event) {
3694   //        JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
3695   //        return textTools.affectsBehavior(event);
3696   //      }
3697   /**
3698    * Creates and returns the preference store for this Java editor with the given input.
3699    * 
3700    * @param input
3701    *          The editor input for which to create the preference store
3702    * @return the preference store for this editor
3703    * 
3704    * @since 3.0
3705    */
3706   private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
3707     List stores = new ArrayList(3);
3708
3709     IJavaProject project = EditorUtility.getJavaProject(input);
3710     if (project != null)
3711       stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(),
3712           new OptionsAdapter.IPropertyChangeEventFilter() {
3713
3714             public boolean isFiltered(PropertyChangeEvent event) {
3715               IJavaElement inputJavaElement = getInputJavaElement();
3716               IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
3717               if (javaProject == null)
3718                 return true;
3719
3720               return !javaProject.getProject().equals(event.getSource());
3721             }
3722
3723           }));
3724
3725     stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
3726     stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
3727     stores.add(EditorsUI.getPreferenceStore());
3728
3729     return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
3730   }
3731
3732   /**
3733    * Jumps to the error next according to the given direction.
3734    */
3735   public void gotoError(boolean forward) {
3736
3737     ISelectionProvider provider = getSelectionProvider();
3738
3739     ITextSelection s = (ITextSelection) provider.getSelection();
3740     Position errorPosition = new Position(0, 0);
3741     IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition);
3742
3743     if (nextError != null) {
3744
3745       IMarker marker = null;
3746       if (nextError instanceof MarkerAnnotation)
3747         marker = ((MarkerAnnotation) nextError).getMarker();
3748       else {
3749         Iterator e = nextError.getOverlaidIterator();
3750         if (e != null) {
3751           while (e.hasNext()) {
3752             Object o = e.next();
3753             if (o instanceof MarkerAnnotation) {
3754               marker = ((MarkerAnnotation) o).getMarker();
3755               break;
3756             }
3757           }
3758         }
3759       }
3760
3761       if (marker != null) {
3762         IWorkbenchPage page = getSite().getPage();
3763         IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
3764         if (view instanceof TaskList) {
3765           StructuredSelection ss = new StructuredSelection(marker);
3766           ((TaskList) view).setSelection(ss, true);
3767         }
3768       }
3769
3770       selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
3771       //      setStatusLineErrorMessage(nextError.getMessage());
3772
3773     } else {
3774
3775       setStatusLineErrorMessage(null);
3776
3777     }
3778   }
3779
3780   private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
3781
3782     IJavaAnnotation nextError = null;
3783     Position nextErrorPosition = null;
3784
3785     IDocument document = getDocumentProvider().getDocument(getEditorInput());
3786     int endOfDocument = document.getLength();
3787     int distance = 0;
3788
3789     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3790     Iterator e = new JavaAnnotationIterator(model, false);
3791     while (e.hasNext()) {
3792
3793       IJavaAnnotation a = (IJavaAnnotation) e.next();
3794       if (a.hasOverlay() || !a.isProblem())
3795         continue;
3796
3797       Position p = model.getPosition((Annotation) a);
3798       if (!p.includes(offset)) {
3799
3800         int currentDistance = 0;
3801
3802         if (forward) {
3803           currentDistance = p.getOffset() - offset;
3804           if (currentDistance < 0)
3805             currentDistance = endOfDocument - offset + p.getOffset();
3806         } else {
3807           currentDistance = offset - p.getOffset();
3808           if (currentDistance < 0)
3809             currentDistance = offset + endOfDocument - p.getOffset();
3810         }
3811
3812         if (nextError == null || currentDistance < distance) {
3813           distance = currentDistance;
3814           nextError = a;
3815           nextErrorPosition = p;
3816         }
3817       }
3818     }
3819
3820     if (nextErrorPosition != null) {
3821       errorPosition.setOffset(nextErrorPosition.getOffset());
3822       errorPosition.setLength(nextErrorPosition.getLength());
3823     }
3824
3825     return nextError;
3826   }
3827
3828   void removeOccurrenceAnnotations() {
3829     IDocumentProvider documentProvider = getDocumentProvider();
3830     if (documentProvider == null)
3831       return;
3832
3833     IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
3834     if (annotationModel == null || fOccurrenceAnnotations == null)
3835       return;
3836
3837     synchronized (annotationModel) {
3838       if (annotationModel instanceof IAnnotationModelExtension) {
3839         ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
3840       } else {
3841         for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
3842           annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
3843       }
3844       fOccurrenceAnnotations = null;
3845     }
3846   }
3847
3848   protected void uninstallOverrideIndicator() {
3849     //          if (fOverrideIndicatorManager != null) {
3850     //                  fOverrideIndicatorManager.removeAnnotations();
3851     //                  fOverrideIndicatorManager= null;
3852     //          }
3853   }
3854
3855   protected void installOverrideIndicator(boolean waitForReconcilation) {
3856     uninstallOverrideIndicator();
3857     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3858     final IJavaElement inputElement = getInputJavaElement();
3859
3860     if (model == null || inputElement == null)
3861       return;
3862
3863     //  fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
3864     //  
3865     //  if (provideAST) {
3866     //          Job job= new Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) { //$NON-NLS-1$
3867     //                  /*
3868     //                   * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
3869     //                   * @since 3.0
3870     //                   */
3871     //                  protected IStatus run(IProgressMonitor monitor) {
3872     //                          CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
3873     //                          if (fOverrideIndicatorManager != null) // editor might have been closed in the meanwhile
3874     //                                  fOverrideIndicatorManager.reconciled(ast, true, monitor);
3875     //                          return Status.OK_STATUS;
3876     //                  }
3877     //          };
3878     //          job.setPriority(Job.DECORATE);
3879     //          job.setSystem(true);
3880     //          job.schedule();
3881     //  }
3882   }
3883
3884   /**
3885    * Tells whether override indicators are shown.
3886    * 
3887    * @return <code>true</code> if the override indicators are shown
3888    * @since 3.0
3889    */
3890   //    protected boolean isShowingOverrideIndicators() {
3891   //            AnnotationPreference preference=
3892   // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
3893   //            IPreferenceStore store= getPreferenceStore();
3894   //            return getBoolean(store, preference.getHighlightPreferenceKey())
3895   //                    || getBoolean(store, preference.getVerticalRulerPreferenceKey())
3896   //                    || getBoolean(store, preference.getOverviewRulerPreferenceKey())
3897   //                    || getBoolean(store, preference.getTextPreferenceKey());
3898   //    }
3899   /**
3900    * Returns the boolean preference for the given key.
3901    * 
3902    * @param store
3903    *          the preference store
3904    * @param key
3905    *          the preference key
3906    * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
3907    * @since 3.0
3908    */
3909   private boolean getBoolean(IPreferenceStore store, String key) {
3910     return key != null && store.getBoolean(key);
3911   }
3912
3913   /**
3914    * Returns the folding action group, or <code>null</code> if there is none.
3915    * 
3916    * @return the folding action group, or <code>null</code> if there is none
3917    * @since 3.0
3918    */
3919   protected FoldingActionGroup getFoldingActionGroup() {
3920     return fFoldingGroup;
3921   }
3922
3923   /**
3924    * React to changed selection.
3925    * 
3926    * @since 3.0
3927    */
3928   protected void selectionChanged() {
3929     if (getSelectionProvider() == null)
3930       return;
3931     ISourceReference element = computeHighlightRangeSourceReference();
3932     if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
3933       synchronizeOutlinePage(element);
3934     setSelection(element, false);
3935     updateStatusLine();
3936   }
3937
3938   private boolean isJavaOutlinePageActive() {
3939     IWorkbenchPart part = getActivePart();
3940     return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
3941   }
3942
3943   private IWorkbenchPart getActivePart() {
3944     IWorkbenchWindow window = getSite().getWorkbenchWindow();
3945     IPartService service = window.getPartService();
3946     IWorkbenchPart part = service.getActivePart();
3947     return part;
3948   }
3949
3950   /**
3951    * Computes and returns the source reference that includes the caret and serves as provider for the outline page selection and the
3952    * editor range indication.
3953    * 
3954    * @return the computed source reference
3955    * @since 3.0
3956    */
3957   protected ISourceReference computeHighlightRangeSourceReference() {
3958     ISourceViewer sourceViewer = getSourceViewer();
3959     if (sourceViewer == null)
3960       return null;
3961
3962     StyledText styledText = sourceViewer.getTextWidget();
3963     if (styledText == null)
3964       return null;
3965
3966     int caret = 0;
3967     if (sourceViewer instanceof ITextViewerExtension5) {
3968       ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
3969       caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3970     } else {
3971       int offset = sourceViewer.getVisibleRegion().getOffset();
3972       caret = offset + styledText.getCaretOffset();
3973     }
3974
3975     IJavaElement element = getElementAt(caret, false);
3976
3977     if (!(element instanceof ISourceReference))
3978       return null;
3979
3980     if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
3981
3982       IImportDeclaration declaration = (IImportDeclaration) element;
3983       IImportContainer container = (IImportContainer) declaration.getParent();
3984       ISourceRange srcRange = null;
3985
3986       try {
3987         srcRange = container.getSourceRange();
3988       } catch (JavaModelException e) {
3989       }
3990
3991       if (srcRange != null && srcRange.getOffset() == caret)
3992         return container;
3993     }
3994
3995     return (ISourceReference) element;
3996   }
3997
3998   /**
3999    * Returns the most narrow java element including the given offset.
4000    * 
4001    * @param offset
4002    *          the offset inside of the requested element
4003    * @param reconcile
4004    *          <code>true</code> if editor input should be reconciled in advance
4005    * @return the most narrow java element
4006    * @since 3.0
4007    */
4008   protected IJavaElement getElementAt(int offset, boolean reconcile) {
4009     return getElementAt(offset);
4010   }
4011 }