fixed bug #1038071
[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           try {
2749             sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
2750           } catch (NumberFormatException e){
2751             // bug #1038071 - set default tab:
2752             sourceViewer.getTextWidget().setTabs(80);
2753           }
2754         }
2755         return;
2756       }
2757
2758       //      if (OVERVIEW_RULER.equals(property)) {
2759       //        if (isOverviewRulerVisible())
2760       //          showOverviewRuler();
2761       //        else
2762       //          hideOverviewRuler();
2763       //        return;
2764       //      }
2765
2766       //      if (LINE_NUMBER_RULER.equals(property)) {
2767       //        if (isLineNumberRulerVisible())
2768       //          showLineNumberRuler();
2769       //        else
2770       //          hideLineNumberRuler();
2771       //        return;
2772       //      }
2773
2774       //      if (fLineNumberRulerColumn != null
2775       //        && (LINE_NUMBER_COLOR.equals(property) ||
2776       // PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
2777       // PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2778       //
2779       //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2780       //      }
2781
2782       if (isJavaEditorHoverProperty(property))
2783         updateHoverBehavior();
2784
2785       if (BROWSER_LIKE_LINKS.equals(property)) {
2786         if (isBrowserLikeLinks())
2787           enableBrowserLikeLinks();
2788         else
2789           disableBrowserLikeLinks();
2790         return;
2791       }
2792
2793       if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
2794         if ((event.getNewValue() instanceof Boolean) && ((Boolean) event.getNewValue()).booleanValue())
2795           selectionChanged();
2796         return;
2797       }
2798
2799       if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
2800         if (event.getNewValue() instanceof Boolean) {
2801           Boolean disable = (Boolean) event.getNewValue();
2802           enableOverwriteMode(!disable.booleanValue());
2803         }
2804         return;
2805       }
2806
2807       //        if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property))
2808       // {
2809       //                if (event.getNewValue() instanceof Boolean) {
2810       //                        boolean markOccurrenceAnnotations=
2811       // ((Boolean)event.getNewValue()).booleanValue();
2812       //                        if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
2813       //                                fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
2814       //                                if (!fMarkOccurrenceAnnotations)
2815       //                                        uninstallOccurrencesFinder();
2816       //                                else
2817       //                                        installOccurrencesFinder();
2818       //                        }
2819       //                }
2820       //        }
2821       //        if
2822       // (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property))
2823       // {
2824       //                if (event.getNewValue() instanceof Boolean) {
2825       //                        boolean stickyOccurrenceAnnotations=
2826       // ((Boolean)event.getNewValue()).booleanValue();
2827       //                        if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations)
2828       // {
2829       //                                fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations;
2830       //// if (!fMarkOccurrenceAnnotations)
2831       //// uninstallOccurrencesFinder();
2832       //// else
2833       //// installOccurrencesFinder();
2834       //                        }
2835       //                }
2836       //        }
2837
2838       ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
2839
2840       //                if (affectsOverrideIndicatorAnnotations(event)) {
2841       //                        if (isShowingOverrideIndicators()) {
2842       //                                if (fOverrideIndicatorManager == null)
2843       //                                        installOverrideIndicator(true);
2844       //                        } else {
2845       //                                if (fOverrideIndicatorManager != null)
2846       //                                        uninstallOverrideIndicator();
2847       //                        }
2848       //                        return;
2849       //                }
2850
2851       if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
2852         if (sourceViewer instanceof ProjectionViewer) {
2853           ProjectionViewer projectionViewer = (ProjectionViewer) sourceViewer;
2854           if (fProjectionModelUpdater != null)
2855             fProjectionModelUpdater.uninstall();
2856           // either freshly enabled or provider changed
2857           fProjectionModelUpdater = PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
2858           if (fProjectionModelUpdater != null) {
2859             fProjectionModelUpdater.install(this, projectionViewer);
2860           }
2861         }
2862         return;
2863       }
2864     } finally {
2865       super.handlePreferenceStoreChanged(event);
2866     }
2867   }
2868
2869   //  /*
2870   //     * @see
2871   // AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
2872   //     */
2873   //  protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
2874   //
2875   //    try {
2876   //
2877   //      ISourceViewer sourceViewer = getSourceViewer();
2878   //      if (sourceViewer == null)
2879   //        return;
2880   //
2881   //      String property = event.getProperty();
2882   //
2883   //      // if
2884   // (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
2885   //      // Object value= event.getNewValue();
2886   //      // if (value instanceof Integer) {
2887   //      // sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
2888   //      // } else if (value instanceof String) {
2889   //      // sourceViewer.getTextWidget().setTabs(Integer.parseInt((String)
2890   // value));
2891   //      // }
2892   //      // return;
2893   //      // }
2894   //
2895   //      if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
2896   //        if (isLineNumberRulerVisible())
2897   //          showLineNumberRuler();
2898   //        else
2899   //          hideLineNumberRuler();
2900   //        return;
2901   //      }
2902   //
2903   //      if (fLineNumberRulerColumn != null
2904   //        && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
2905   //          || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
2906   //          || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2907   //
2908   //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2909   //      }
2910   //
2911   //    } finally {
2912   //      super.handlePreferenceStoreChanged(event);
2913   //    }
2914   //  }
2915
2916   //  private boolean isJavaEditorHoverProperty(String property) {
2917   //    return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
2918   //      || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
2919   //      || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
2920   //      || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
2921   //      || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
2922   //      || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
2923   //      || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
2924   //      || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
2925   //  }
2926
2927   /**
2928    * Shows the line number ruler column.
2929    */
2930   //  private void showLineNumberRuler() {
2931   //    IVerticalRuler v = getVerticalRuler();
2932   //    if (v instanceof CompositeRuler) {
2933   //      CompositeRuler c = (CompositeRuler) v;
2934   //      c.addDecorator(1, createLineNumberRulerColumn());
2935   //    }
2936   //  }
2937   private boolean isJavaEditorHoverProperty(String property) {
2938     return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
2939   }
2940
2941   /**
2942    * Return whether the browser like links should be enabled according to the preference store settings.
2943    * 
2944    * @return <code>true</code> if the browser like links should be enabled
2945    */
2946   private boolean isBrowserLikeLinks() {
2947     IPreferenceStore store = getPreferenceStore();
2948     return store.getBoolean(BROWSER_LIKE_LINKS);
2949   }
2950
2951   /**
2952    * Enables browser like links.
2953    */
2954   private void enableBrowserLikeLinks() {
2955     if (fMouseListener == null) {
2956       fMouseListener = new MouseClickListener();
2957       fMouseListener.install();
2958     }
2959   }
2960
2961   /**
2962    * Disables browser like links.
2963    */
2964   private void disableBrowserLikeLinks() {
2965     if (fMouseListener != null) {
2966       fMouseListener.uninstall();
2967       fMouseListener = null;
2968     }
2969   }
2970
2971   /**
2972    * Handles a property change event describing a change of the java core's preferences and updates the preference related editor
2973    * properties.
2974    * 
2975    * @param event
2976    *          the property change event
2977    */
2978   protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2979     if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
2980       ISourceViewer sourceViewer = getSourceViewer();
2981       if (sourceViewer != null
2982           && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event
2983               .getNewValue())))
2984         sourceViewer.invalidateTextPresentation();
2985     }
2986     if (PreferenceConstants.EDITOR_WRAP_WORDS.equals(event.getProperty())) {
2987       setWordWrap();
2988     }
2989   }
2990
2991   /**
2992    * Return whether the line number ruler column should be visible according to the preference store settings.
2993    * 
2994    * @return <code>true</code> if the line numbers should be visible
2995    */
2996   //  protected boolean isLineNumberRulerVisible() {
2997   //    IPreferenceStore store = getPreferenceStore();
2998   //    return store.getBoolean(LINE_NUMBER_RULER);
2999   //  }
3000   /**
3001    * Hides the line number ruler column.
3002    */
3003   //  private void hideLineNumberRuler() {
3004   //    IVerticalRuler v = getVerticalRuler();
3005   //    if (v instanceof CompositeRuler) {
3006   //      CompositeRuler c = (CompositeRuler) v;
3007   //      try {
3008   //        c.removeDecorator(1);
3009   //      } catch (Throwable e) {
3010   //      }
3011   //    }
3012   //  }
3013   /*
3014    * @see AbstractTextEditor#handleCursorPositionChanged()
3015    */
3016   protected void handleCursorPositionChanged() {
3017     super.handleCursorPositionChanged();
3018     if (!isEditingScriptRunning() && fUpdater != null)
3019       fUpdater.post();
3020   }
3021
3022   /*
3023    * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
3024    */
3025   protected void handleElementContentReplaced() {
3026     super.handleElementContentReplaced();
3027     if (fProjectionModelUpdater != null)
3028       fProjectionModelUpdater.initialize();
3029   }
3030
3031   /**
3032    * Initializes the given line number ruler column from the preference store.
3033    * 
3034    * @param rulerColumn
3035    *          the ruler column to be initialized
3036    */
3037   //  protected void initializeLineNumberRulerColumn(LineNumberRulerColumn
3038   // rulerColumn) {
3039   //    JavaTextTools textTools =
3040   // PHPeclipsePlugin.getDefault().getJavaTextTools();
3041   //    IColorManager manager = textTools.getColorManager();
3042   //
3043   //    IPreferenceStore store = getPreferenceStore();
3044   //    if (store != null) {
3045   //
3046   //      RGB rgb = null;
3047   //      // foreground color
3048   //      if (store.contains(LINE_NUMBER_COLOR)) {
3049   //        if (store.isDefault(LINE_NUMBER_COLOR))
3050   //          rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
3051   //        else
3052   //          rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
3053   //      }
3054   //      rulerColumn.setForeground(manager.getColor(rgb));
3055   //
3056   //      rgb = null;
3057   //      // background color
3058   //      if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
3059   //        if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
3060   //          if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
3061   //            rgb = PreferenceConverter.getDefaultColor(store,
3062   // PREFERENCE_COLOR_BACKGROUND);
3063   //          else
3064   //            rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
3065   //        }
3066   //      }
3067   //      rulerColumn.setBackground(manager.getColor(rgb));
3068   //    }
3069   //  }
3070   /**
3071    * Creates a new line number ruler column that is appropriately initialized.
3072    */
3073   //  protected IVerticalRulerColumn createLineNumberRulerColumn() {
3074   //    fLineNumberRulerColumn = new LineNumberRulerColumn();
3075   //    initializeLineNumberRulerColumn(fLineNumberRulerColumn);
3076   //    return fLineNumberRulerColumn;
3077   //  }
3078   /*
3079    * @see AbstractTextEditor#createVerticalRuler()
3080    */
3081   //  protected IVerticalRuler createVerticalRuler() {
3082   //    CompositeRuler ruler = new CompositeRuler();
3083   //    ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
3084   //    if (isLineNumberRulerVisible())
3085   //      ruler.addDecorator(1, createLineNumberRulerColumn());
3086   //    return ruler;
3087   //  }
3088   //  private static IRegion getSignedSelection(ITextViewer viewer) {
3089   //
3090   //    StyledText text = viewer.getTextWidget();
3091   //    int caretOffset = text.getCaretOffset();
3092   //    Point selection = text.getSelection();
3093   //
3094   //    // caret left
3095   //    int offset, length;
3096   //    if (caretOffset == selection.x) {
3097   //      offset = selection.y;
3098   //      length = selection.x - selection.y;
3099   //
3100   //      // caret right
3101   //    } else {
3102   //      offset = selection.x;
3103   //      length = selection.y - selection.x;
3104   //    }
3105   //
3106   //    return new Region(offset, length);
3107   //  }
3108   protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
3109     StyledText text = sourceViewer.getTextWidget();
3110     Point selection = text.getSelectionRange();
3111
3112     if (text.getCaretOffset() == selection.x) {
3113       selection.x = selection.x + selection.y;
3114       selection.y = -selection.y;
3115     }
3116
3117     selection.x = widgetOffset2ModelOffset(sourceViewer, selection.x);
3118
3119     return new Region(selection.x, selection.y);
3120   }
3121
3122   /** Preference key for matching brackets */
3123   protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
3124
3125   /** Preference key for matching brackets color */
3126   protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
3127
3128   /** Preference key for highlighting current line */
3129   //  protected final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
3130   /** Preference key for highlight color of current line */
3131   //  protected final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
3132   /** Preference key for showing print marging ruler */
3133   //  protected final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
3134   /** Preference key for print margin ruler color */
3135   //  protected final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
3136   /** Preference key for print margin ruler column */
3137   //  protected final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
3138   /** Preference key for error indication */
3139   //  protected final static String ERROR_INDICATION =
3140   // PreferenceConstants.EDITOR_PROBLEM_INDICATION;
3141   /** Preference key for error color */
3142   //  protected final static String ERROR_INDICATION_COLOR =
3143   // PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
3144   /** Preference key for warning indication */
3145   //  protected final static String WARNING_INDICATION =
3146   // PreferenceConstants.EDITOR_WARNING_INDICATION;
3147   /** Preference key for warning color */
3148   //  protected final static String WARNING_INDICATION_COLOR =
3149   // PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
3150   /** Preference key for task indication */
3151   protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
3152
3153   /** Preference key for task color */
3154   protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
3155
3156   /** Preference key for bookmark indication */
3157   protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
3158
3159   /** Preference key for bookmark color */
3160   protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
3161
3162   /** Preference key for search result indication */
3163   protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
3164
3165   /** Preference key for search result color */
3166   protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
3167
3168   /** Preference key for unknown annotation indication */
3169   protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
3170
3171   /** Preference key for unknown annotation color */
3172   protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
3173
3174   /** Preference key for shwoing the overview ruler */
3175   protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
3176
3177   /** Preference key for error indication in overview ruler */
3178   protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
3179
3180   /** Preference key for warning indication in overview ruler */
3181   protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
3182
3183   /** Preference key for task indication in overview ruler */
3184   protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
3185
3186   /** Preference key for bookmark indication in overview ruler */
3187   protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
3188
3189   /** Preference key for search result indication in overview ruler */
3190   protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
3191
3192   /** Preference key for unknown annotation indication in overview ruler */
3193   protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
3194
3195   //            /** Preference key for compiler task tags */
3196   //            private final static String COMPILER_TASK_TAGS=
3197   // JavaCore.COMPILER_TASK_TAGS;
3198   /** Preference key for browser like links */
3199   private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
3200
3201   /** Preference key for key modifier of browser like links */
3202   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
3203
3204   /**
3205    * Preference key for key modifier mask of browser like links. The value is only used if the value of
3206    * <code>EDITOR_BROWSER_LIKE_LINKS</code> cannot be resolved to valid SWT modifier bits.
3207    * 
3208    * @since 2.1.1
3209    */
3210   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
3211
3212   private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
3213
3214   private static boolean isBracket(char character) {
3215     for (int i = 0; i != BRACKETS.length; ++i)
3216       if (character == BRACKETS[i])
3217         return true;
3218     return false;
3219   }
3220
3221   private static boolean isSurroundedByBrackets(IDocument document, int offset) {
3222     if (offset == 0 || offset == document.getLength())
3223       return false;
3224
3225     try {
3226       return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
3227
3228     } catch (BadLocationException e) {
3229       return false;
3230     }
3231   }
3232
3233   //  protected void configureSourceViewerDecorationSupport() {
3234   //
3235   //    fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
3236   //
3237   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3238   //      AnnotationType.UNKNOWN,
3239   //      UNKNOWN_INDICATION_COLOR,
3240   //      UNKNOWN_INDICATION,
3241   //      UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
3242   //      0);
3243   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3244   //      AnnotationType.BOOKMARK,
3245   //      BOOKMARK_INDICATION_COLOR,
3246   //      BOOKMARK_INDICATION,
3247   //      BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
3248   //      1);
3249   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3250   //      AnnotationType.TASK,
3251   //      TASK_INDICATION_COLOR,
3252   //      TASK_INDICATION,
3253   //      TASK_INDICATION_IN_OVERVIEW_RULER,
3254   //      2);
3255   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3256   //      AnnotationType.SEARCH,
3257   //      SEARCH_RESULT_INDICATION_COLOR,
3258   //      SEARCH_RESULT_INDICATION,
3259   //      SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
3260   //      3);
3261   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3262   //      AnnotationType.WARNING,
3263   //      WARNING_INDICATION_COLOR,
3264   //      WARNING_INDICATION,
3265   //      WARNING_INDICATION_IN_OVERVIEW_RULER,
3266   //      4);
3267   //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
3268   //      AnnotationType.ERROR,
3269   //      ERROR_INDICATION_COLOR,
3270   //      ERROR_INDICATION,
3271   //      ERROR_INDICATION_IN_OVERVIEW_RULER,
3272   //      5);
3273   //
3274   //    fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE,
3275   // CURRENT_LINE_COLOR);
3276   //    fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN,
3277   // PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
3278   //    fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS,
3279   // MATCHING_BRACKETS_COLOR);
3280   //
3281   //    fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
3282   //
3283   //  }
3284   /**
3285    * Returns the Java element wrapped by this editors input.
3286    * 
3287    * @return the Java element wrapped by this editors input.
3288    * @since 3.0
3289    */
3290   abstract protected IJavaElement getInputJavaElement();
3291
3292   protected void updateStatusLine() {
3293     ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
3294     Annotation annotation = getAnnotation(selection.getOffset(), selection.getLength());
3295     setStatusLineErrorMessage(null);
3296     setStatusLineMessage(null);
3297     if (annotation != null) {
3298       try {
3299         fIsUpdatingAnnotationViews = true;
3300         updateAnnotationViews(annotation);
3301       } finally {
3302         fIsUpdatingAnnotationViews = false;
3303       }
3304       if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
3305         setStatusLineMessage(annotation.getText());
3306     }
3307   }
3308
3309   /**
3310    * Jumps to the matching bracket.
3311    */
3312   public void gotoMatchingBracket() {
3313
3314     ISourceViewer sourceViewer = getSourceViewer();
3315     IDocument document = sourceViewer.getDocument();
3316     if (document == null)
3317       return;
3318
3319     IRegion selection = getSignedSelection(sourceViewer);
3320
3321     int selectionLength = Math.abs(selection.getLength());
3322     if (selectionLength > 1) {
3323       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$               
3324       sourceViewer.getTextWidget().getDisplay().beep();
3325       return;
3326     }
3327
3328     // #26314
3329     int sourceCaretOffset = selection.getOffset() + selection.getLength();
3330     if (isSurroundedByBrackets(document, sourceCaretOffset))
3331       sourceCaretOffset -= selection.getLength();
3332
3333     IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
3334     if (region == null) {
3335       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$              
3336       sourceViewer.getTextWidget().getDisplay().beep();
3337       return;
3338     }
3339
3340     int offset = region.getOffset();
3341     int length = region.getLength();
3342
3343     if (length < 1)
3344       return;
3345
3346     int anchor = fBracketMatcher.getAnchor();
3347     int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
3348
3349     boolean visible = false;
3350     if (sourceViewer instanceof ITextViewerExtension3) {
3351       ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
3352       visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
3353     } else {
3354       IRegion visibleRegion = sourceViewer.getVisibleRegion();
3355       visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
3356     }
3357
3358     if (!visible) {
3359       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$          
3360       sourceViewer.getTextWidget().getDisplay().beep();
3361       return;
3362     }
3363
3364     if (selection.getLength() < 0)
3365       targetOffset -= selection.getLength();
3366
3367     sourceViewer.setSelectedRange(targetOffset, selection.getLength());
3368     sourceViewer.revealRange(targetOffset, selection.getLength());
3369   }
3370
3371   /**
3372    * Ses the given message as error message to this editor's status line.
3373    * 
3374    * @param msg
3375    *          message to be set
3376    */
3377   protected void setStatusLineErrorMessage(String msg) {
3378     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
3379     if (statusLine != null)
3380       statusLine.setMessage(true, msg, null);
3381   }
3382
3383   /**
3384    * Sets the given message as message to this editor's status line.
3385    * 
3386    * @param msg
3387    *          message to be set
3388    * @since 3.0
3389    */
3390   protected void setStatusLineMessage(String msg) {
3391     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
3392     if (statusLine != null)
3393       statusLine.setMessage(false, msg, null);
3394   }
3395
3396   /**
3397    * Returns the annotation closest to the given range respecting the given direction. If an annotation is found, the annotations
3398    * current position is copied into the provided annotation position.
3399    * 
3400    * @param offset
3401    *          the region offset
3402    * @param length
3403    *          the region length
3404    * @param forward
3405    *          <code>true</code> for forwards, <code>false</code> for backward
3406    * @param annotationPosition
3407    *          the position of the found annotation
3408    * @return the found annotation
3409    */
3410   private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
3411
3412     Annotation nextAnnotation = null;
3413     Position nextAnnotationPosition = null;
3414     Annotation containingAnnotation = null;
3415     Position containingAnnotationPosition = null;
3416     boolean currentAnnotation = false;
3417
3418     IDocument document = getDocumentProvider().getDocument(getEditorInput());
3419     int endOfDocument = document.getLength();
3420     int distance = Integer.MAX_VALUE;
3421
3422     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3423     Iterator e = new JavaAnnotationIterator(model, true, true);
3424     while (e.hasNext()) {
3425       Annotation a = (Annotation) e.next();
3426       if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation) a).hasOverlay() || !isNavigationTarget(a))
3427         continue;
3428
3429       Position p = model.getPosition(a);
3430       if (p == null)
3431         continue;
3432
3433       if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
3434         if (containingAnnotation == null
3435             || (forward && p.length >= containingAnnotationPosition.length || !forward
3436                 && p.length >= containingAnnotationPosition.length)) {
3437           containingAnnotation = a;
3438           containingAnnotationPosition = p;
3439           currentAnnotation = p.length == length;
3440         }
3441       } else {
3442         int currentDistance = 0;
3443
3444         if (forward) {
3445           currentDistance = p.getOffset() - offset;
3446           if (currentDistance < 0)
3447             currentDistance = endOfDocument + currentDistance;
3448
3449           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
3450             distance = currentDistance;
3451             nextAnnotation = a;
3452             nextAnnotationPosition = p;
3453           }
3454         } else {
3455           currentDistance = offset + length - (p.getOffset() + p.length);
3456           if (currentDistance < 0)
3457             currentDistance = endOfDocument + currentDistance;
3458
3459           if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
3460             distance = currentDistance;
3461             nextAnnotation = a;
3462             nextAnnotationPosition = p;
3463           }
3464         }
3465       }
3466     }
3467     if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
3468       annotationPosition.setOffset(containingAnnotationPosition.getOffset());
3469       annotationPosition.setLength(containingAnnotationPosition.getLength());
3470       return containingAnnotation;
3471     }
3472     if (nextAnnotationPosition != null) {
3473       annotationPosition.setOffset(nextAnnotationPosition.getOffset());
3474       annotationPosition.setLength(nextAnnotationPosition.getLength());
3475     }
3476
3477     return nextAnnotation;
3478   }
3479
3480   /**
3481    * Returns the annotation overlapping with the given range or <code>null</code>.
3482    * 
3483    * @param offset
3484    *          the region offset
3485    * @param length
3486    *          the region length
3487    * @return the found annotation or <code>null</code>
3488    * @since 3.0
3489    */
3490   private Annotation getAnnotation(int offset, int length) {
3491     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3492     Iterator e = new JavaAnnotationIterator(model, true, true);
3493     while (e.hasNext()) {
3494       Annotation a = (Annotation) e.next();
3495       if (!isNavigationTarget(a))
3496         continue;
3497
3498       Position p = model.getPosition(a);
3499       if (p != null && p.overlapsWith(offset, length))
3500         return a;
3501     }
3502
3503     return null;
3504   }
3505
3506   /**
3507    * Returns whether the given annotation is configured as a target for the "Go to Next/Previous Annotation" actions
3508    * 
3509    * @param annotation
3510    *          the annotation
3511    * @return <code>true</code> if this is a target, <code>false</code> otherwise
3512    * @since 3.0
3513    */
3514   private boolean isNavigationTarget(Annotation annotation) {
3515     Preferences preferences = EditorsUI.getPluginPreferences();
3516     AnnotationPreference preference = getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
3517     //          See bug 41689
3518     //          String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
3519     String key = preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
3520     return (key != null && preferences.getBoolean(key));
3521   }
3522
3523   /**
3524    * Returns a segmentation of the line of the given document appropriate for bidi rendering. The default implementation returns
3525    * only the string literals of a php code line as segments.
3526    * 
3527    * @param document
3528    *          the document
3529    * @param lineOffset
3530    *          the offset of the line
3531    * @return the line's bidi segmentation
3532    * @throws BadLocationException
3533    *           in case lineOffset is not valid in document
3534    */
3535   public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
3536
3537     IRegion line = document.getLineInformationOfOffset(lineOffset);
3538     ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());
3539
3540     List segmentation = new ArrayList();
3541     for (int i = 0; i < linePartitioning.length; i++) {
3542       if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType()))
3543         segmentation.add(linePartitioning[i]);
3544     }
3545
3546     if (segmentation.size() == 0)
3547       return null;
3548
3549     int size = segmentation.size();
3550     int[] segments = new int[size * 2 + 1];
3551
3552     int j = 0;
3553     for (int i = 0; i < size; i++) {
3554       ITypedRegion segment = (ITypedRegion) segmentation.get(i);
3555
3556       if (i == 0)
3557         segments[j++] = 0;
3558
3559       int offset = segment.getOffset() - lineOffset;
3560       if (offset > segments[j - 1])
3561         segments[j++] = offset;
3562
3563       if (offset + segment.getLength() >= line.getLength())
3564         break;
3565
3566       segments[j++] = offset + segment.getLength();
3567     }
3568
3569     if (j < segments.length) {
3570       int[] result = new int[j];
3571       System.arraycopy(segments, 0, result, 0, j);
3572       segments = result;
3573     }
3574
3575     return segments;
3576   }
3577
3578   /**
3579    * Returns a segmentation of the given line appropriate for bidi rendering. The default implementation returns only the string
3580    * literals of a php code line as segments.
3581    * 
3582    * @param lineOffset
3583    *          the offset of the line
3584    * @param line
3585    *          the content of the line
3586    * @return the line's bidi segmentation
3587    */
3588   protected int[] getBidiLineSegments(int lineOffset, String line) {
3589     IDocumentProvider provider = getDocumentProvider();
3590     if (provider != null && line != null && line.length() > 0) {
3591       IDocument document = provider.getDocument(getEditorInput());
3592       if (document != null)
3593         try {
3594           return getBidiLineSegments(document, lineOffset);
3595         } catch (BadLocationException x) {
3596           // ignore
3597         }
3598     }
3599     return null;
3600   }
3601
3602   /*
3603    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3604    */
3605   //  protected final ISourceViewer createSourceViewer(
3606   //    Composite parent,
3607   //    IVerticalRuler ruler,
3608   //    int styles) {
3609   //    ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
3610   //    StyledText text = viewer.getTextWidget();
3611   //    text.addBidiSegmentListener(new BidiSegmentListener() {
3612   //      public void lineGetSegments(BidiSegmentEvent event) {
3613   //        event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
3614   //      }
3615   //    });
3616   //    // JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
3617   //    return viewer;
3618   //  }
3619   public final ISourceViewer getViewer() {
3620     return getSourceViewer();
3621   }
3622
3623   //  protected void showOverviewRuler() {
3624   //    if (fOverviewRuler != null) {
3625   //      if (getSourceViewer() instanceof ISourceViewerExtension) {
3626   //        ((ISourceViewerExtension)
3627   // getSourceViewer()).showAnnotationsOverview(true);
3628   //        fSourceViewerDecorationSupport.updateOverviewDecorations();
3629   //      }
3630   //    }
3631   //  }
3632   //
3633   //  protected void hideOverviewRuler() {
3634   //    if (getSourceViewer() instanceof ISourceViewerExtension) {
3635   //      fSourceViewerDecorationSupport.hideAnnotationOverview();
3636   //      ((ISourceViewerExtension)
3637   // getSourceViewer()).showAnnotationsOverview(false);
3638   //    }
3639   //  }
3640
3641   //  protected boolean isOverviewRulerVisible() {
3642   //    IPreferenceStore store = getPreferenceStore();
3643   //    return store.getBoolean(OVERVIEW_RULER);
3644   //  }
3645   /*
3646    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3647    */
3648   //  protected ISourceViewer createJavaSourceViewer(
3649   //    Composite parent,
3650   //    IVerticalRuler ruler,
3651   //    IOverviewRuler overviewRuler,
3652   //    boolean isOverviewRulerVisible,
3653   //    int styles) {
3654   //    return new SourceViewer(parent, ruler, overviewRuler,
3655   // isOverviewRulerVisible(), styles);
3656   //  }
3657   /*
3658    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3659    */
3660   protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler,
3661       boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
3662     return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
3663   }
3664
3665   /*
3666    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
3667    */
3668   protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
3669
3670     ISourceViewer viewer = createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles,
3671         getPreferenceStore());
3672
3673     StyledText text = viewer.getTextWidget();
3674     text.addBidiSegmentListener(new BidiSegmentListener() {
3675       public void lineGetSegments(BidiSegmentEvent event) {
3676         event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
3677       }
3678     });
3679
3680     //          JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
3681
3682     // ensure source viewer decoration support has been created and
3683     // configured
3684     getSourceViewerDecorationSupport(viewer);
3685
3686     return viewer;
3687   }
3688
3689   /*
3690    * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
3691    */
3692   protected boolean affectsTextPresentation(PropertyChangeEvent event) {
3693     return ((PHPSourceViewerConfiguration) getSourceViewerConfiguration()).affectsTextPresentation(event)
3694         || super.affectsTextPresentation(event);
3695   }
3696
3697   //
3698   //      protected boolean affectsTextPresentation(PropertyChangeEvent event) {
3699   //        JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
3700   //        return textTools.affectsBehavior(event);
3701   //      }
3702   /**
3703    * Creates and returns the preference store for this Java editor with the given input.
3704    * 
3705    * @param input
3706    *          The editor input for which to create the preference store
3707    * @return the preference store for this editor
3708    * 
3709    * @since 3.0
3710    */
3711   private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
3712     List stores = new ArrayList(3);
3713
3714     IJavaProject project = EditorUtility.getJavaProject(input);
3715     if (project != null)
3716       stores.add(new OptionsAdapter(project.getOptions(false), PHPeclipsePlugin.getDefault().getMockupPreferenceStore(),
3717           new OptionsAdapter.IPropertyChangeEventFilter() {
3718
3719             public boolean isFiltered(PropertyChangeEvent event) {
3720               IJavaElement inputJavaElement = getInputJavaElement();
3721               IJavaProject javaProject = inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
3722               if (javaProject == null)
3723                 return true;
3724
3725               return !javaProject.getProject().equals(event.getSource());
3726             }
3727
3728           }));
3729
3730     stores.add(PHPeclipsePlugin.getDefault().getPreferenceStore());
3731     stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
3732     stores.add(EditorsUI.getPreferenceStore());
3733
3734     return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
3735   }
3736
3737   /**
3738    * Jumps to the error next according to the given direction.
3739    */
3740   public void gotoError(boolean forward) {
3741
3742     ISelectionProvider provider = getSelectionProvider();
3743
3744     ITextSelection s = (ITextSelection) provider.getSelection();
3745     Position errorPosition = new Position(0, 0);
3746     IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition);
3747
3748     if (nextError != null) {
3749
3750       IMarker marker = null;
3751       if (nextError instanceof MarkerAnnotation)
3752         marker = ((MarkerAnnotation) nextError).getMarker();
3753       else {
3754         Iterator e = nextError.getOverlaidIterator();
3755         if (e != null) {
3756           while (e.hasNext()) {
3757             Object o = e.next();
3758             if (o instanceof MarkerAnnotation) {
3759               marker = ((MarkerAnnotation) o).getMarker();
3760               break;
3761             }
3762           }
3763         }
3764       }
3765
3766       if (marker != null) {
3767         IWorkbenchPage page = getSite().getPage();
3768         IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
3769         if (view instanceof TaskList) {
3770           StructuredSelection ss = new StructuredSelection(marker);
3771           ((TaskList) view).setSelection(ss, true);
3772         }
3773       }
3774
3775       selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
3776       //      setStatusLineErrorMessage(nextError.getMessage());
3777
3778     } else {
3779
3780       setStatusLineErrorMessage(null);
3781
3782     }
3783   }
3784
3785   private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
3786
3787     IJavaAnnotation nextError = null;
3788     Position nextErrorPosition = null;
3789
3790     IDocument document = getDocumentProvider().getDocument(getEditorInput());
3791     int endOfDocument = document.getLength();
3792     int distance = 0;
3793
3794     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3795     Iterator e = new JavaAnnotationIterator(model, false);
3796     while (e.hasNext()) {
3797
3798       IJavaAnnotation a = (IJavaAnnotation) e.next();
3799       if (a.hasOverlay() || !a.isProblem())
3800         continue;
3801
3802       Position p = model.getPosition((Annotation) a);
3803       if (!p.includes(offset)) {
3804
3805         int currentDistance = 0;
3806
3807         if (forward) {
3808           currentDistance = p.getOffset() - offset;
3809           if (currentDistance < 0)
3810             currentDistance = endOfDocument - offset + p.getOffset();
3811         } else {
3812           currentDistance = offset - p.getOffset();
3813           if (currentDistance < 0)
3814             currentDistance = offset + endOfDocument - p.getOffset();
3815         }
3816
3817         if (nextError == null || currentDistance < distance) {
3818           distance = currentDistance;
3819           nextError = a;
3820           nextErrorPosition = p;
3821         }
3822       }
3823     }
3824
3825     if (nextErrorPosition != null) {
3826       errorPosition.setOffset(nextErrorPosition.getOffset());
3827       errorPosition.setLength(nextErrorPosition.getLength());
3828     }
3829
3830     return nextError;
3831   }
3832
3833   void removeOccurrenceAnnotations() {
3834     IDocumentProvider documentProvider = getDocumentProvider();
3835     if (documentProvider == null)
3836       return;
3837
3838     IAnnotationModel annotationModel = documentProvider.getAnnotationModel(getEditorInput());
3839     if (annotationModel == null || fOccurrenceAnnotations == null)
3840       return;
3841
3842     synchronized (annotationModel) {
3843       if (annotationModel instanceof IAnnotationModelExtension) {
3844         ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
3845       } else {
3846         for (int i = 0, length = fOccurrenceAnnotations.length; i < length; i++)
3847           annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
3848       }
3849       fOccurrenceAnnotations = null;
3850     }
3851   }
3852
3853   protected void uninstallOverrideIndicator() {
3854     //          if (fOverrideIndicatorManager != null) {
3855     //                  fOverrideIndicatorManager.removeAnnotations();
3856     //                  fOverrideIndicatorManager= null;
3857     //          }
3858   }
3859
3860   protected void installOverrideIndicator(boolean waitForReconcilation) {
3861     uninstallOverrideIndicator();
3862     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
3863     final IJavaElement inputElement = getInputJavaElement();
3864
3865     if (model == null || inputElement == null)
3866       return;
3867
3868     //  fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);
3869     //  
3870     //  if (provideAST) {
3871     //          Job job= new Job(JavaEditorMessages.getString("OverrideIndicatorManager.intallJob")) { //$NON-NLS-1$
3872     //                  /*
3873     //                   * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
3874     //                   * @since 3.0
3875     //                   */
3876     //                  protected IStatus run(IProgressMonitor monitor) {
3877     //                          CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
3878     //                          if (fOverrideIndicatorManager != null) // editor might have been closed in the meanwhile
3879     //                                  fOverrideIndicatorManager.reconciled(ast, true, monitor);
3880     //                          return Status.OK_STATUS;
3881     //                  }
3882     //          };
3883     //          job.setPriority(Job.DECORATE);
3884     //          job.setSystem(true);
3885     //          job.schedule();
3886     //  }
3887   }
3888
3889   /**
3890    * Tells whether override indicators are shown.
3891    * 
3892    * @return <code>true</code> if the override indicators are shown
3893    * @since 3.0
3894    */
3895   //    protected boolean isShowingOverrideIndicators() {
3896   //            AnnotationPreference preference=
3897   // getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
3898   //            IPreferenceStore store= getPreferenceStore();
3899   //            return getBoolean(store, preference.getHighlightPreferenceKey())
3900   //                    || getBoolean(store, preference.getVerticalRulerPreferenceKey())
3901   //                    || getBoolean(store, preference.getOverviewRulerPreferenceKey())
3902   //                    || getBoolean(store, preference.getTextPreferenceKey());
3903   //    }
3904   /**
3905    * Returns the boolean preference for the given key.
3906    * 
3907    * @param store
3908    *          the preference store
3909    * @param key
3910    *          the preference key
3911    * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
3912    * @since 3.0
3913    */
3914   private boolean getBoolean(IPreferenceStore store, String key) {
3915     return key != null && store.getBoolean(key);
3916   }
3917
3918   /**
3919    * Returns the folding action group, or <code>null</code> if there is none.
3920    * 
3921    * @return the folding action group, or <code>null</code> if there is none
3922    * @since 3.0
3923    */
3924   protected FoldingActionGroup getFoldingActionGroup() {
3925     return fFoldingGroup;
3926   }
3927
3928   /**
3929    * React to changed selection.
3930    * 
3931    * @since 3.0
3932    */
3933   protected void selectionChanged() {
3934     if (getSelectionProvider() == null)
3935       return;
3936     ISourceReference element = computeHighlightRangeSourceReference();
3937     if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
3938       synchronizeOutlinePage(element);
3939     setSelection(element, false);
3940     updateStatusLine();
3941   }
3942
3943   private boolean isJavaOutlinePageActive() {
3944     IWorkbenchPart part = getActivePart();
3945     return part instanceof ContentOutline && ((ContentOutline) part).getCurrentPage() == fOutlinePage;
3946   }
3947
3948   private IWorkbenchPart getActivePart() {
3949     IWorkbenchWindow window = getSite().getWorkbenchWindow();
3950     IPartService service = window.getPartService();
3951     IWorkbenchPart part = service.getActivePart();
3952     return part;
3953   }
3954
3955   /**
3956    * Computes and returns the source reference that includes the caret and serves as provider for the outline page selection and the
3957    * editor range indication.
3958    * 
3959    * @return the computed source reference
3960    * @since 3.0
3961    */
3962   protected ISourceReference computeHighlightRangeSourceReference() {
3963     ISourceViewer sourceViewer = getSourceViewer();
3964     if (sourceViewer == null)
3965       return null;
3966
3967     StyledText styledText = sourceViewer.getTextWidget();
3968     if (styledText == null)
3969       return null;
3970
3971     int caret = 0;
3972     if (sourceViewer instanceof ITextViewerExtension5) {
3973       ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
3974       caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
3975     } else {
3976       int offset = sourceViewer.getVisibleRegion().getOffset();
3977       caret = offset + styledText.getCaretOffset();
3978     }
3979
3980     IJavaElement element = getElementAt(caret, false);
3981
3982     if (!(element instanceof ISourceReference))
3983       return null;
3984
3985     if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
3986
3987       IImportDeclaration declaration = (IImportDeclaration) element;
3988       IImportContainer container = (IImportContainer) declaration.getParent();
3989       ISourceRange srcRange = null;
3990
3991       try {
3992         srcRange = container.getSourceRange();
3993       } catch (JavaModelException e) {
3994       }
3995
3996       if (srcRange != null && srcRange.getOffset() == caret)
3997         return container;
3998     }
3999
4000     return (ISourceReference) element;
4001   }
4002
4003   /**
4004    * Returns the most narrow java element including the given offset.
4005    * 
4006    * @param offset
4007    *          the offset inside of the requested element
4008    * @param reconcile
4009    *          <code>true</code> if editor input should be reconciled in advance
4010    * @return the most narrow java element
4011    * @since 3.0
4012    */
4013   protected IJavaElement getElementAt(int offset, boolean reconcile) {
4014     return getElementAt(offset);
4015   }
4016 }