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