avoid NPE
[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.util.ArrayList;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.ResourceBundle;
20 import java.util.StringTokenizer;
21
22 import net.sourceforge.phpdt.core.ICompilationUnit;
23 import net.sourceforge.phpdt.core.IJavaElement;
24 import net.sourceforge.phpdt.core.IMember;
25 import net.sourceforge.phpdt.core.ISourceRange;
26 import net.sourceforge.phpdt.core.ISourceReference;
27 import net.sourceforge.phpdt.core.JavaCore;
28 import net.sourceforge.phpdt.core.JavaModelException;
29 import net.sourceforge.phpdt.internal.ui.actions.CompositeActionGroup;
30 import net.sourceforge.phpdt.internal.ui.actions.FoldingActionGroup;
31 import net.sourceforge.phpdt.internal.ui.text.CustomSourceInformationControl;
32 import net.sourceforge.phpdt.internal.ui.text.HTMLTextPresenter;
33 import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions;
34 import net.sourceforge.phpdt.internal.ui.text.PHPPairMatcher;
35 import net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider;
36 import net.sourceforge.phpdt.ui.IContextMenuConstants;
37 import net.sourceforge.phpdt.ui.JavaUI;
38 import net.sourceforge.phpdt.ui.PreferenceConstants;
39 import net.sourceforge.phpdt.ui.actions.GotoMatchingBracketAction;
40 import net.sourceforge.phpdt.ui.text.JavaTextTools;
41 import net.sourceforge.phpdt.ui.text.folding.IJavaFoldingStructureProvider;
42 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
43
44 import org.eclipse.core.resources.IMarker;
45 import org.eclipse.core.resources.IResource;
46 import org.eclipse.core.runtime.CoreException;
47 import org.eclipse.core.runtime.IProgressMonitor;
48 import org.eclipse.core.runtime.IStatus;
49 import org.eclipse.core.runtime.Preferences;
50 import org.eclipse.core.runtime.Status;
51 import org.eclipse.core.runtime.jobs.Job;
52 import org.eclipse.jface.action.Action;
53 import org.eclipse.jface.action.GroupMarker;
54 import org.eclipse.jface.action.IAction;
55 import org.eclipse.jface.action.MenuManager;
56 import org.eclipse.jface.action.Separator;
57 import org.eclipse.jface.preference.IPreferenceStore;
58 import org.eclipse.jface.preference.PreferenceConverter;
59 import org.eclipse.jface.text.BadLocationException;
60 import org.eclipse.jface.text.DefaultInformationControl;
61 import org.eclipse.jface.text.DocumentEvent;
62 import org.eclipse.jface.text.IDocument;
63 import org.eclipse.jface.text.IDocumentListener;
64 import org.eclipse.jface.text.IInformationControl;
65 import org.eclipse.jface.text.IInformationControlCreator;
66 import org.eclipse.jface.text.IRegion;
67 import org.eclipse.jface.text.ITextHover;
68 import org.eclipse.jface.text.ITextInputListener;
69 import org.eclipse.jface.text.ITextSelection;
70 import org.eclipse.jface.text.ITextViewer;
71 import org.eclipse.jface.text.ITextViewerExtension2;
72 import org.eclipse.jface.text.ITextViewerExtension3;
73 import org.eclipse.jface.text.ITypedRegion;
74 import org.eclipse.jface.text.Position;
75 import org.eclipse.jface.text.Region;
76 import org.eclipse.jface.text.TextSelection;
77 import org.eclipse.jface.text.information.IInformationProvider;
78 import org.eclipse.jface.text.information.InformationPresenter;
79 import org.eclipse.jface.text.source.Annotation;
80 import org.eclipse.jface.text.source.IAnnotationModel;
81 import org.eclipse.jface.text.source.IAnnotationModelExtension;
82 import org.eclipse.jface.text.source.IOverviewRuler;
83 import org.eclipse.jface.text.source.ISourceViewer;
84 import org.eclipse.jface.text.source.IVerticalRuler;
85 import org.eclipse.jface.text.source.OverviewRuler;
86 import org.eclipse.jface.text.source.SourceViewerConfiguration;
87 import org.eclipse.jface.text.source.projection.ProjectionSupport;
88 import org.eclipse.jface.text.source.projection.ProjectionViewer;
89 import org.eclipse.jface.util.IPropertyChangeListener;
90 import org.eclipse.jface.util.PropertyChangeEvent;
91 import org.eclipse.jface.viewers.ISelection;
92 import org.eclipse.jface.viewers.ISelectionChangedListener;
93 import org.eclipse.jface.viewers.ISelectionProvider;
94 import org.eclipse.jface.viewers.IStructuredSelection;
95 import org.eclipse.jface.viewers.SelectionChangedEvent;
96 import org.eclipse.jface.viewers.StructuredSelection;
97 import org.eclipse.swt.SWT;
98 import org.eclipse.swt.custom.BidiSegmentEvent;
99 import org.eclipse.swt.custom.BidiSegmentListener;
100 import org.eclipse.swt.custom.StyleRange;
101 import org.eclipse.swt.custom.StyledText;
102 import org.eclipse.swt.events.FocusEvent;
103 import org.eclipse.swt.events.FocusListener;
104 import org.eclipse.swt.events.KeyEvent;
105 import org.eclipse.swt.events.KeyListener;
106 import org.eclipse.swt.events.MouseEvent;
107 import org.eclipse.swt.events.MouseListener;
108 import org.eclipse.swt.events.MouseMoveListener;
109 import org.eclipse.swt.events.PaintEvent;
110 import org.eclipse.swt.events.PaintListener;
111 import org.eclipse.swt.graphics.Color;
112 import org.eclipse.swt.graphics.Cursor;
113 import org.eclipse.swt.graphics.GC;
114 import org.eclipse.swt.graphics.Image;
115 import org.eclipse.swt.graphics.Point;
116 import org.eclipse.swt.graphics.RGB;
117 import org.eclipse.swt.widgets.Composite;
118 import org.eclipse.swt.widgets.Control;
119 import org.eclipse.swt.widgets.Display;
120 import org.eclipse.swt.widgets.Shell;
121 import org.eclipse.ui.IEditorInput;
122 import org.eclipse.ui.IPageLayout;
123 import org.eclipse.ui.IPartService;
124 import org.eclipse.ui.IViewPart;
125 import org.eclipse.ui.IWorkbenchPage;
126 import org.eclipse.ui.IWorkbenchPart;
127 import org.eclipse.ui.IWorkbenchWindow;
128 import org.eclipse.ui.actions.ActionContext;
129 import org.eclipse.ui.actions.ActionGroup;
130 import org.eclipse.ui.editors.text.DefaultEncodingSupport;
131 import org.eclipse.ui.editors.text.IEncodingSupport;
132 import org.eclipse.ui.part.IShowInTargetList;
133 import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
134 import org.eclipse.ui.texteditor.DefaultRangeIndicator;
135 import org.eclipse.ui.texteditor.IDocumentProvider;
136 import org.eclipse.ui.texteditor.IEditorStatusLine;
137 import org.eclipse.ui.texteditor.ITextEditorActionConstants;
138 import org.eclipse.ui.texteditor.MarkerAnnotation;
139 import org.eclipse.ui.texteditor.ResourceAction;
140 import org.eclipse.ui.texteditor.TextEditorAction;
141 import org.eclipse.ui.texteditor.TextOperationAction;
142 import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
143 import org.eclipse.ui.views.tasklist.TaskList;
144
145 /**
146  * PHP specific text editor.
147  */
148 public abstract class PHPEditor  extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
149 //extends StatusTextEditor implements IViewPartInputProvider { // extends TextEditor {
150   /**
151          * "Smart" runnable for updating the outline page's selection.
152          */
153   class OutlinePageSelectionUpdater implements Runnable {
154
155     /** Has the runnable already been posted? */
156     private boolean fPosted = false;
157
158     public OutlinePageSelectionUpdater() {
159     }
160
161     /*
162      * @see Runnable#run()
163      */
164     public void run() {
165       synchronizeOutlinePageSelection();
166       fPosted = false;
167     }
168
169     /**
170      * Posts this runnable into the event queue.
171      */
172     public void post() {
173       if (fPosted)
174         return;
175
176       Shell shell = getSite().getShell();
177       if (shell != null & !shell.isDisposed()) {
178         fPosted = true;
179         shell.getDisplay().asyncExec(this);
180       }
181     }
182   };
183   class SelectionChangedListener implements ISelectionChangedListener {
184     public void selectionChanged(SelectionChangedEvent event) {
185       doSelectionChanged(event);
186     }
187   };
188
189   /*
190   * Link mode.  
191   */
192   class MouseClickListener
193     implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
194
195     /** The session is active. */
196     private boolean fActive;
197
198     /** The currently active style range. */
199     private IRegion fActiveRegion;
200     /** The currently active style range as position. */
201     private Position fRememberedPosition;
202     /** The hand cursor. */
203     private Cursor fCursor;
204
205     /** The link color. */
206     private Color fColor;
207     /** The key modifier mask. */
208     private int fKeyModifierMask;
209
210     public void deactivate() {
211       deactivate(false);
212     }
213
214     public void deactivate(boolean redrawAll) {
215       if (!fActive)
216         return;
217
218       repairRepresentation(redrawAll);
219       fActive = false;
220     }
221
222     public void install() {
223
224       ISourceViewer sourceViewer = getSourceViewer();
225       if (sourceViewer == null)
226         return;
227
228       StyledText text = sourceViewer.getTextWidget();
229       if (text == null || text.isDisposed())
230         return;
231
232       updateColor(sourceViewer);
233
234       sourceViewer.addTextInputListener(this);
235
236       IDocument document = sourceViewer.getDocument();
237       if (document != null)
238         document.addDocumentListener(this);
239
240       text.addKeyListener(this);
241       text.addMouseListener(this);
242       text.addMouseMoveListener(this);
243       text.addFocusListener(this);
244       text.addPaintListener(this);
245
246       updateKeyModifierMask();
247
248       IPreferenceStore preferenceStore = getPreferenceStore();
249       preferenceStore.addPropertyChangeListener(this);
250     }
251
252     private void updateKeyModifierMask() {
253       String modifiers = getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
254       fKeyModifierMask = computeStateMask(modifiers);
255       if (fKeyModifierMask == -1) {
256         // Fallback to stored state mask
257         fKeyModifierMask = getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
258       };
259     }
260
261     private int computeStateMask(String modifiers) {
262       if (modifiers == null)
263         return -1;
264
265       if (modifiers.length() == 0)
266         return SWT.NONE;
267
268       int stateMask = 0;
269       StringTokenizer modifierTokenizer = new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
270       while (modifierTokenizer.hasMoreTokens()) {
271         int modifier = EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
272         if (modifier == 0 || (stateMask & modifier) == modifier)
273           return -1;
274         stateMask = stateMask | modifier;
275       }
276       return stateMask;
277     }
278
279     public void uninstall() {
280
281       if (fColor != null) {
282         fColor.dispose();
283         fColor = null;
284       }
285
286       if (fCursor != null) {
287         fCursor.dispose();
288         fCursor = null;
289       }
290
291       ISourceViewer sourceViewer = getSourceViewer();
292       if (sourceViewer == null)
293         return;
294
295       sourceViewer.removeTextInputListener(this);
296
297       IDocument document = sourceViewer.getDocument();
298       if (document != null)
299         document.removeDocumentListener(this);
300
301       IPreferenceStore preferenceStore = getPreferenceStore();
302       if (preferenceStore != null)
303         preferenceStore.removePropertyChangeListener(this);
304
305       StyledText text = sourceViewer.getTextWidget();
306       if (text == null || text.isDisposed())
307         return;
308
309       text.removeKeyListener(this);
310       text.removeMouseListener(this);
311       text.removeMouseMoveListener(this);
312       text.removeFocusListener(this);
313       text.removePaintListener(this);
314     }
315
316     /*
317      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
318      */
319     public void propertyChange(PropertyChangeEvent event) {
320       if (event.getProperty().equals(PHPEditor.LINK_COLOR)) {
321         ISourceViewer viewer = getSourceViewer();
322         if (viewer != null)
323           updateColor(viewer);
324       } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
325         updateKeyModifierMask();
326       }
327     }
328
329     private void updateColor(ISourceViewer viewer) {
330       if (fColor != null)
331         fColor.dispose();
332
333       StyledText text = viewer.getTextWidget();
334       if (text == null || text.isDisposed())
335         return;
336
337       Display display = text.getDisplay();
338       fColor = createColor(getPreferenceStore(), PHPEditor.LINK_COLOR, display);
339     }
340
341     /**
342      * Creates a color from the information stored in the given preference store.
343      * Returns <code>null</code> if there is no such information available.
344      */
345     private Color createColor(IPreferenceStore store, String key, Display display) {
346
347       RGB rgb = null;
348
349       if (store.contains(key)) {
350
351         if (store.isDefault(key))
352           rgb = PreferenceConverter.getDefaultColor(store, key);
353         else
354           rgb = PreferenceConverter.getColor(store, key);
355
356         if (rgb != null)
357           return new Color(display, rgb);
358       }
359
360       return null;
361     }
362
363     private void repairRepresentation() {
364       repairRepresentation(false);
365     }
366
367     private void repairRepresentation(boolean redrawAll) {
368
369       if (fActiveRegion == null)
370         return;
371
372       ISourceViewer viewer = getSourceViewer();
373       if (viewer != null) {
374         resetCursor(viewer);
375
376         int offset = fActiveRegion.getOffset();
377         int length = fActiveRegion.getLength();
378
379         // remove style
380         if (!redrawAll && viewer instanceof ITextViewerExtension2)
381            ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
382         else
383           viewer.invalidateTextPresentation();
384
385         // remove underline                             
386         if (viewer instanceof ITextViewerExtension3) {
387           ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
388           offset = extension.modelOffset2WidgetOffset(offset);
389         } else {
390           offset -= viewer.getVisibleRegion().getOffset();
391         }
392
393         StyledText text = viewer.getTextWidget();
394         try {
395           text.redrawRange(offset, length, true);
396         } catch (IllegalArgumentException x) {
397           PHPeclipsePlugin.log(x);
398         }
399       }
400
401       fActiveRegion = null;
402     }
403
404     // will eventually be replaced by a method provided by jdt.core             
405     private IRegion selectWord(IDocument document, int anchor) {
406
407       try {
408         int offset = anchor;
409         char c;
410
411         while (offset >= 0) {
412           c = document.getChar(offset);
413           if (!Character.isJavaIdentifierPart(c))
414             break;
415           --offset;
416         }
417
418         int start = offset;
419
420         offset = anchor;
421         int length = document.getLength();
422
423         while (offset < length) {
424           c = document.getChar(offset);
425           if (!Character.isJavaIdentifierPart(c))
426             break;
427           ++offset;
428         }
429
430         int end = offset;
431
432         if (start == end)
433           return new Region(start, 0);
434         else
435           return new Region(start + 1, end - start - 1);
436
437       } catch (BadLocationException x) {
438         return null;
439       }
440     }
441
442     IRegion getCurrentTextRegion(ISourceViewer viewer) {
443
444       int offset = getCurrentTextOffset(viewer);
445       if (offset == -1)
446         return null;
447
448       return null;
449       //                                IJavaElement input= SelectionConverter.getInput(PHPEditor.this);
450       //                                if (input == null)
451       //                                        return null;
452       //      
453       //                                try {
454       //                                
455       //                                        IJavaElement[] elements= null;
456       //                                        synchronized (input) {
457       //                                                elements= ((ICodeAssist) input).codeSelect(offset, 0);
458       //                                        }
459       //                                
460       //                                        if (elements == null || elements.length == 0)
461       //                                                return null;
462       //                                        
463       //                                        return selectWord(viewer.getDocument(), offset);
464       //                                        
465       //                                } catch (JavaModelException e) {
466       //                                        return null;    
467       //                                }
468     }
469
470     private int getCurrentTextOffset(ISourceViewer viewer) {
471
472       try {
473         StyledText text = viewer.getTextWidget();
474         if (text == null || text.isDisposed())
475           return -1;
476
477         Display display = text.getDisplay();
478         Point absolutePosition = display.getCursorLocation();
479         Point relativePosition = text.toControl(absolutePosition);
480
481         int widgetOffset = text.getOffsetAtLocation(relativePosition);
482         if (viewer instanceof ITextViewerExtension3) {
483           ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
484           return extension.widgetOffset2ModelOffset(widgetOffset);
485         } else {
486           return widgetOffset + viewer.getVisibleRegion().getOffset();
487         }
488
489       } catch (IllegalArgumentException e) {
490         return -1;
491       }
492     }
493
494     private void highlightRegion(ISourceViewer viewer, IRegion region) {
495
496       if (region.equals(fActiveRegion))
497         return;
498
499       repairRepresentation();
500
501       StyledText text = viewer.getTextWidget();
502       if (text == null || text.isDisposed())
503         return;
504
505       // highlight region
506       int offset = 0;
507       int length = 0;
508
509       if (viewer instanceof ITextViewerExtension3) {
510         ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
511         IRegion widgetRange = extension.modelRange2WidgetRange(region);
512         if (widgetRange == null)
513           return;
514
515         offset = widgetRange.getOffset();
516         length = widgetRange.getLength();
517
518       } else {
519         offset = region.getOffset() - viewer.getVisibleRegion().getOffset();
520         length = region.getLength();
521       }
522
523       StyleRange oldStyleRange = text.getStyleRangeAtOffset(offset);
524       Color foregroundColor = fColor;
525       Color backgroundColor = oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
526       StyleRange styleRange = new StyleRange(offset, length, foregroundColor, backgroundColor);
527       text.setStyleRange(styleRange);
528
529       // underline
530       text.redrawRange(offset, length, true);
531
532       fActiveRegion = region;
533     }
534
535     private void activateCursor(ISourceViewer viewer) {
536       StyledText text = viewer.getTextWidget();
537       if (text == null || text.isDisposed())
538         return;
539       Display display = text.getDisplay();
540       if (fCursor == null)
541         fCursor = new Cursor(display, SWT.CURSOR_HAND);
542       text.setCursor(fCursor);
543     }
544
545     private void resetCursor(ISourceViewer viewer) {
546       StyledText text = viewer.getTextWidget();
547       if (text != null && !text.isDisposed())
548         text.setCursor(null);
549
550       if (fCursor != null) {
551         fCursor.dispose();
552         fCursor = null;
553       }
554     }
555
556     /*
557      * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
558      */
559     public void keyPressed(KeyEvent event) {
560
561       if (fActive) {
562         deactivate();
563         return;
564       }
565
566       if (event.keyCode != fKeyModifierMask) {
567         deactivate();
568         return;
569       }
570
571       fActive = true;
572
573       //                                removed for #25871                      
574       //
575       //                                ISourceViewer viewer= getSourceViewer();
576       //                                if (viewer == null)
577       //                                        return;
578       //                        
579       //                                IRegion region= getCurrentTextRegion(viewer);
580       //                                if (region == null)
581       //                                        return;
582       //                        
583       //                                highlightRegion(viewer, region);
584       //                                activateCursor(viewer);                                                                                         
585     }
586
587     /*
588      * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
589      */
590     public void keyReleased(KeyEvent event) {
591
592       if (!fActive)
593         return;
594
595       deactivate();
596     }
597
598     /*
599      * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
600      */
601     public void mouseDoubleClick(MouseEvent e) {
602     }
603     /*
604      * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
605      */
606     public void mouseDown(MouseEvent event) {
607
608       if (!fActive)
609         return;
610
611       if (event.stateMask != fKeyModifierMask) {
612         deactivate();
613         return;
614       }
615
616       if (event.button != 1) {
617         deactivate();
618         return;
619       }
620     }
621
622     /*
623      * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
624      */
625     public void mouseUp(MouseEvent e) {
626
627       if (!fActive)
628         return;
629
630       if (e.button != 1) {
631         deactivate();
632         return;
633       }
634
635       boolean wasActive = fCursor != null;
636
637       deactivate();
638
639       if (wasActive) {
640         IAction action = getAction("OpenEditor"); //$NON-NLS-1$
641         if (action != null)
642           action.run();
643       }
644     }
645
646     /*
647      * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
648      */
649     public void mouseMove(MouseEvent event) {
650
651       if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
652         deactivate();
653         return;
654       }
655
656       if (!fActive) {
657         if (event.stateMask != fKeyModifierMask)
658           return;
659         // modifier was already pressed
660         fActive = true;
661       }
662
663       ISourceViewer viewer = getSourceViewer();
664       if (viewer == null) {
665         deactivate();
666         return;
667       }
668
669       StyledText text = viewer.getTextWidget();
670       if (text == null || text.isDisposed()) {
671         deactivate();
672         return;
673       }
674
675       if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
676         deactivate();
677         return;
678       }
679
680       IRegion region = getCurrentTextRegion(viewer);
681       if (region == null || region.getLength() == 0) {
682         repairRepresentation();
683         return;
684       }
685
686       highlightRegion(viewer, region);
687       activateCursor(viewer);
688     }
689
690     /*
691      * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
692      */
693     public void focusGained(FocusEvent e) {
694     }
695
696     /*
697      * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
698      */
699     public void focusLost(FocusEvent event) {
700       deactivate();
701     }
702
703     /*
704      * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
705      */
706     public void documentAboutToBeChanged(DocumentEvent event) {
707       if (fActive && fActiveRegion != null) {
708         fRememberedPosition = new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
709         try {
710           event.getDocument().addPosition(fRememberedPosition);
711         } catch (BadLocationException x) {
712           fRememberedPosition = null;
713         }
714       }
715     }
716
717     /*
718      * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
719      */
720     public void documentChanged(DocumentEvent event) {
721       if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
722         event.getDocument().removePosition(fRememberedPosition);
723         fActiveRegion = new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
724       }
725       fRememberedPosition = null;
726
727       ISourceViewer viewer = getSourceViewer();
728       if (viewer != null) {
729         StyledText widget = viewer.getTextWidget();
730         if (widget != null && !widget.isDisposed()) {
731           widget.getDisplay().asyncExec(new Runnable() {
732             public void run() {
733               deactivate();
734             }
735           });
736         }
737       }
738     }
739
740     /*
741      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
742      */
743     public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
744       if (oldInput == null)
745         return;
746       deactivate();
747       oldInput.removeDocumentListener(this);
748     }
749
750     /*
751      * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
752      */
753     public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
754       if (newInput == null)
755         return;
756       newInput.addDocumentListener(this);
757     }
758
759     /*
760      * @see PaintListener#paintControl(PaintEvent)
761      */
762     public void paintControl(PaintEvent event) {
763       if (fActiveRegion == null)
764         return;
765
766       ISourceViewer viewer = getSourceViewer();
767       if (viewer == null)
768         return;
769
770       StyledText text = viewer.getTextWidget();
771       if (text == null || text.isDisposed())
772         return;
773
774       int offset = 0;
775       int length = 0;
776
777       if (viewer instanceof ITextViewerExtension3) {
778
779         ITextViewerExtension3 extension = (ITextViewerExtension3) viewer;
780         IRegion widgetRange = extension.modelRange2WidgetRange(new Region(offset, length));
781         if (widgetRange == null)
782           return;
783
784         offset = widgetRange.getOffset();
785         length = widgetRange.getLength();
786
787       } else {
788
789         IRegion region = viewer.getVisibleRegion();
790         if (!includes(region, fActiveRegion))
791           return;
792
793         offset = fActiveRegion.getOffset() - region.getOffset();
794         length = fActiveRegion.getLength();
795       }
796
797       // support for bidi
798       Point minLocation = getMinimumLocation(text, offset, length);
799       Point maxLocation = getMaximumLocation(text, offset, length);
800
801       int x1 = minLocation.x;
802       int x2 = minLocation.x + maxLocation.x - minLocation.x - 1;
803       int y = minLocation.y + text.getLineHeight() - 1;
804
805       GC gc = event.gc;
806       if (fColor != null && !fColor.isDisposed())
807         gc.setForeground(fColor);
808       gc.drawLine(x1, y, x2, y);
809     }
810
811     private boolean includes(IRegion region, IRegion position) {
812       return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
813     }
814
815     private Point getMinimumLocation(StyledText text, int offset, int length) {
816       Point minLocation = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
817
818       for (int i = 0; i <= length; i++) {
819         Point location = text.getLocationAtOffset(offset + i);
820
821         if (location.x < minLocation.x)
822           minLocation.x = location.x;
823         if (location.y < minLocation.y)
824           minLocation.y = location.y;
825       }
826
827       return minLocation;
828     }
829
830     private Point getMaximumLocation(StyledText text, int offset, int length) {
831       Point maxLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
832
833       for (int i = 0; i <= length; i++) {
834         Point location = text.getLocationAtOffset(offset + i);
835
836         if (location.x > maxLocation.x)
837           maxLocation.x = location.x;
838         if (location.y > maxLocation.y)
839           maxLocation.y = location.y;
840       }
841
842       return maxLocation;
843     }
844   };
845
846   /**
847    * This action dispatches into two behaviours: If there is no current text
848    * hover, the javadoc is displayed using information presenter. If there is
849    * a current text hover, it is converted into a information presenter in
850    * order to make it sticky.
851    */
852   class InformationDispatchAction extends TextEditorAction {
853
854     /** The wrapped text operation action. */
855     private final TextOperationAction fTextOperationAction;
856
857     /**
858      * Creates a dispatch action.
859      */
860     public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
861       super(resourceBundle, prefix, PHPEditor.this);
862       if (textOperationAction == null)
863         throw new IllegalArgumentException();
864       fTextOperationAction = textOperationAction;
865     }
866
867     /*
868      * @see org.eclipse.jface.action.IAction#run()
869      */
870     public void run() {
871
872       ISourceViewer sourceViewer = getSourceViewer();
873       if (sourceViewer == null) {
874         fTextOperationAction.run();
875         return;
876       }
877
878       if (!(sourceViewer instanceof ITextViewerExtension2)) {
879         fTextOperationAction.run();
880         return;
881       }
882
883       ITextViewerExtension2 textViewerExtension2 = (ITextViewerExtension2) sourceViewer;
884
885       // does a text hover exist?
886       ITextHover textHover = textViewerExtension2.getCurrentTextHover();
887       if (textHover == null) {
888         fTextOperationAction.run();
889         return;
890       }
891
892       Point hoverEventLocation = textViewerExtension2.getHoverEventLocation();
893       int offset = computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
894       if (offset == -1) {
895         fTextOperationAction.run();
896         return;
897       }
898
899       try {
900         // get the text hover content
901         IDocument document = sourceViewer.getDocument();
902         String contentType = document.getContentType(offset);
903
904         final IRegion hoverRegion = textHover.getHoverRegion(sourceViewer, offset);
905         if (hoverRegion == null)
906           return;
907
908         final String hoverInfo = textHover.getHoverInfo(sourceViewer, hoverRegion);
909
910         // with information provider
911         IInformationProvider informationProvider = new IInformationProvider() {
912           /*
913            * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
914            */
915           public IRegion getSubject(ITextViewer textViewer, int offset) {
916             return hoverRegion;
917           }
918           /*
919            * @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
920            */
921           public String getInformation(ITextViewer textViewer, IRegion subject) {
922             return hoverInfo;
923           }
924         };
925
926         fInformationPresenter.setOffset(offset);
927         fInformationPresenter.setInformationProvider(informationProvider, contentType);
928         fInformationPresenter.showInformation();
929
930       } catch (BadLocationException e) {
931       }
932     }
933
934     // modified version from TextViewer
935     private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
936
937       StyledText styledText = textViewer.getTextWidget();
938       IDocument document = textViewer.getDocument();
939
940       if (document == null)
941         return -1;
942
943       try {
944         int widgetLocation = styledText.getOffsetAtLocation(new Point(x, y));
945         if (textViewer instanceof ITextViewerExtension3) {
946           ITextViewerExtension3 extension = (ITextViewerExtension3) textViewer;
947           return extension.widgetOffset2ModelOffset(widgetLocation);
948         } else {
949           IRegion visibleRegion = textViewer.getVisibleRegion();
950           return widgetLocation + visibleRegion.getOffset();
951         }
952       } catch (IllegalArgumentException e) {
953         return -1;
954       }
955
956     }
957   };
958
959 //  static protected class AnnotationAccess implements IAnnotationAccess {
960 //    /*
961 //     * @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
962 //     */
963 //    public Object getType(Annotation annotation) {
964 //      if (annotation instanceof IJavaAnnotation) {
965 //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
966 //   //     if (javaAnnotation.isRelevant())
967 //   //       return javaAnnotation.getAnnotationType();
968 //      }
969 //      return null;
970 //    }
971 //
972 //    /*
973 //     * @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
974 //     */
975 //    public boolean isMultiLine(Annotation annotation) {
976 //      return true;
977 //    }
978 //
979 //    /*
980 //     * @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
981 //     */
982 //    public boolean isTemporary(Annotation annotation) {
983 //      if (annotation instanceof IJavaAnnotation) {
984 //        IJavaAnnotation javaAnnotation = (IJavaAnnotation) annotation;
985 //        if (javaAnnotation.isRelevant())
986 //          return javaAnnotation.isTemporary();
987 //      }
988 //      return false;
989 //    }
990 //  };
991
992   private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
993     /*
994      * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
995      */
996     public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
997       handlePreferencePropertyChanged(event);
998     }
999   };
1000   
1001   /**
1002          * Finds and marks occurrence annotations.
1003          * 
1004          * @since 3.0
1005          */
1006         class OccurrencesFinderJob extends Job implements IDocumentListener {
1007                 
1008                 private IDocument fDocument;
1009                 private boolean fCancelled= false;
1010                 private IProgressMonitor fProgressMonitor;
1011                 private Position[] fPositions;
1012                 
1013                 public OccurrencesFinderJob(IDocument document, Position[] positions) {
1014                         super("Occurrences Marker"); //$NON-NLS-1$
1015                         fDocument= document;
1016                         fPositions= positions;
1017                         fDocument.addDocumentListener(this);
1018                 }
1019                 
1020                 private boolean isCancelled() {
1021                         return fCancelled || fProgressMonitor.isCanceled();
1022                 }
1023                 
1024                 /*
1025                  * @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
1026                  */
1027                 public IStatus run(IProgressMonitor progressMonitor) {
1028                         
1029                         fProgressMonitor= progressMonitor;
1030                         
1031                         try {
1032                                 
1033                                 if (isCancelled())
1034                                         return Status.CANCEL_STATUS;
1035                                 
1036                                 ITextViewer textViewer= getViewer(); 
1037                                 if (textViewer == null)
1038                                         return Status.CANCEL_STATUS;
1039                                 
1040                                 IDocument document= textViewer.getDocument();
1041                                 if (document == null)
1042                                         return Status.CANCEL_STATUS;
1043                                 
1044                                 IDocumentProvider documentProvider= getDocumentProvider();
1045                                 if (documentProvider == null)
1046                                         return Status.CANCEL_STATUS;
1047                         
1048                                 IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
1049                                 if (annotationModel == null)
1050                                         return Status.CANCEL_STATUS;
1051                                 
1052                                 // Add occurrence annotations
1053                                 int length= fPositions.length;
1054                                 Map annotationMap= new HashMap(length);
1055                                 for (int i= 0; i < length; i++) {
1056                                         
1057                                         if (isCancelled())
1058                                                 return Status.CANCEL_STATUS; 
1059                                         
1060                                         String message;
1061                                         Position position= fPositions[i];
1062                                         
1063                                         // Create & add annotation
1064                                         try {
1065                                                 message= document.get(position.offset, position.length);
1066                                         } catch (BadLocationException ex) {
1067                                                 // Skip this match
1068                                                 continue;
1069                                         }
1070                                         annotationMap.put(
1071                                                         new Annotation("net.sourceforge.phpdt.ui.occurrences", false, message), //$NON-NLS-1$
1072                                                         position);
1073                                 }
1074                                 
1075                                 if (isCancelled())
1076                                         return Status.CANCEL_STATUS;
1077                                 
1078                                 synchronized (annotationModel) {
1079                                         if (annotationModel instanceof IAnnotationModelExtension) {
1080                                                 ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
1081                                         } else {
1082                                                 removeOccurrenceAnnotations();
1083                                                 Iterator iter= annotationMap.entrySet().iterator();
1084                                                 while (iter.hasNext()) {
1085                                                         Map.Entry mapEntry= (Map.Entry)iter.next(); 
1086                                                         annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
1087                                                 }
1088                                         }
1089                                         fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
1090                                 }
1091                         } finally {
1092                                 fDocument.removeDocumentListener(this);
1093                         }
1094                         return Status.OK_STATUS;
1095                 }
1096
1097                 /*
1098                  * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
1099                  */
1100                 public void documentAboutToBeChanged(DocumentEvent event) {
1101                         fCancelled= true;
1102                 }
1103
1104                 /*
1105                  * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
1106                  */
1107                 public void documentChanged(DocumentEvent event) {
1108                 }
1109         }
1110         
1111         
1112         /**
1113          * Holds the current occurrence annotations.
1114          * @since 3.0
1115          */
1116   private Annotation[] fOccurrenceAnnotations= null;
1117   
1118   private Job fOccurrencesFinderJob;
1119         
1120   /** Preference key for showing the line number ruler */
1121 //  private final static String LINE_NUMBER_RULER = PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
1122   /** Preference key for the foreground color of the line numbers */
1123  // private final static String LINE_NUMBER_COLOR = PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
1124   /** Preference key for the link color */
1125   private final static String LINK_COLOR = PreferenceConstants.EDITOR_LINK_COLOR;
1126   /** Preference key for compiler task tags */
1127   private final static String COMPILER_TASK_TAGS = JavaCore.COMPILER_TASK_TAGS;
1128
1129   // protected PHPActionGroup fActionGroups;
1130   //  /** The outline page */
1131   //  private AbstractContentOutlinePage fOutlinePage;
1132   /** The outline page */
1133   protected JavaOutlinePage fOutlinePage;
1134   /** Outliner context menu Id */
1135   protected String fOutlinerContextMenuId;
1136         /**
1137          * The editor selection changed listener.
1138          * 
1139          * @since 3.0
1140          */
1141 //  private EditorSelectionChangedListener fEditorSelectionChangedListener;
1142   /** Indicates whether this editor should react on outline page selection changes */
1143   private int fIgnoreOutlinePageSelection;
1144   
1145         /** The outline page selection updater */
1146         private OutlinePageSelectionUpdater fUpdater;
1147   //  protected PHPSyntaxParserThread fValidationThread = null;
1148
1149   // private IPreferenceStore fPHPPrefStore;
1150   /** The selection changed listener */
1151   protected ISelectionChangedListener fSelectionChangedListener = new SelectionChangedListener();
1152
1153   /** The editor's bracket matcher */
1154   private PHPPairMatcher fBracketMatcher = new PHPPairMatcher(BRACKETS);
1155
1156
1157   /** The line number ruler column */
1158 //  private LineNumberRulerColumn fLineNumberRulerColumn;
1159   /** This editor's encoding support */
1160   private DefaultEncodingSupport fEncodingSupport;
1161   /** The mouse listener */
1162   private MouseClickListener fMouseListener;
1163
1164   protected CompositeActionGroup fActionGroups;
1165   protected CompositeActionGroup fContextMenuGroup;
1166
1167   /** 
1168          * This editor's projection support 
1169          * @since 3.0
1170          */
1171         private ProjectionSupport fProjectionSupport;
1172         /** 
1173          * This editor's projection model updater 
1174          * @since 3.0
1175          */
1176         private IJavaFoldingStructureProvider fProjectionModelUpdater;
1177   /**
1178          * The action group for folding.
1179          *  
1180          * @since 3.0
1181          */
1182         private FoldingActionGroup fFoldingGroup;
1183         
1184   /** The information presenter. */
1185   private InformationPresenter fInformationPresenter;
1186   /** The annotation access */
1187 //  protected IAnnotationAccess fAnnotationAccess = new AnnotationAccess();
1188   /** The overview ruler */
1189   protected OverviewRuler isOverviewRulerVisible;
1190   /** The source viewer decoration support */
1191   //protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
1192   /** The overview ruler */
1193   //protected OverviewRuler fOverviewRuler;
1194
1195   /** The preference property change listener for java core. */
1196   private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener = new PropertyChangeListener();
1197   /**
1198    * Returns the most narrow java element including the given offset
1199    * 
1200    * @param offset the offset inside of the requested element
1201    */
1202   abstract protected IJavaElement getElementAt(int offset);
1203
1204   /**
1205    * Returns the java element of this editor's input corresponding to the given IJavaElement
1206    */
1207   abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
1208   /**
1209          * Sets the input of the editor's outline page.
1210          */
1211   abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
1212
1213   /**
1214    * Default constructor.
1215    */
1216   public PHPEditor() {
1217     super();
1218         JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools();
1219         setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools, this)); //, IJavaPartitions.JAVA_PARTITIONING));
1220         setRangeIndicator(new DefaultRangeIndicator());
1221         IPreferenceStore store= PHPeclipsePlugin.getDefault().getPreferenceStore();
1222         setPreferenceStore(store);
1223         setKeyBindingScopes(new String[] { "net.sourceforge.phpdt.ui.phpEditorScope" });  //$NON-NLS-1$
1224 //      fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
1225 //      fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
1226     
1227         // TODO changed in 3.x ?
1228     if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
1229       fUpdater= new OutlinePageSelectionUpdater();
1230   }
1231  
1232   /*
1233    * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
1234    */
1235   protected void updatePropertyDependentActions() {
1236     super.updatePropertyDependentActions();
1237     if (fEncodingSupport != null)
1238       fEncodingSupport.reset();
1239   }
1240
1241   /*
1242    * Update the hovering behavior depending on the preferences.
1243    */
1244   private void updateHoverBehavior() {
1245     SourceViewerConfiguration configuration = getSourceViewerConfiguration();
1246     String[] types = configuration.getConfiguredContentTypes(getSourceViewer());
1247
1248     for (int i = 0; i < types.length; i++) {
1249
1250       String t = types[i];
1251
1252       int[] stateMasks = configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
1253
1254       ISourceViewer sourceViewer = getSourceViewer();
1255       if (sourceViewer instanceof ITextViewerExtension2) {
1256         if (stateMasks != null) {
1257           for (int j = 0; j < stateMasks.length; j++) {
1258             int stateMask = stateMasks[j];
1259             ITextHover textHover = configuration.getTextHover(sourceViewer, t, stateMask);
1260             ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, stateMask);
1261           }
1262         } else {
1263           ITextHover textHover = configuration.getTextHover(sourceViewer, t);
1264           ((ITextViewerExtension2) sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
1265         }
1266       } else
1267         sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
1268     }
1269   }
1270
1271   public void updatedTitleImage(Image image) {
1272     setTitleImage(image);
1273   }
1274   /*
1275    * @see net.sourceforge.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
1276    */
1277   public Object getViewPartInput() {
1278     return getEditorInput().getAdapter(IResource.class);
1279   }
1280   /*
1281    * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
1282    */
1283   protected void doSetSelection(ISelection selection) {
1284     super.doSetSelection(selection);
1285     synchronizeOutlinePageSelection();
1286   }
1287         boolean isFoldingEnabled() {
1288                 return PHPeclipsePlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
1289         }
1290   /*
1291    * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
1292    * widgets.Composite)
1293    */
1294   public void createPartControl(Composite parent) {
1295     super.createPartControl(parent);
1296
1297     //fSourceViewerDecorationSupport.install(getPreferenceStore());
1298
1299     ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
1300         
1301         fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
1302         fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
1303         fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
1304         fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
1305                 public IInformationControl createInformationControl(Shell shell) {
1306                         return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
1307                 }
1308         });
1309     fProjectionSupport.install();
1310         
1311         fProjectionModelUpdater= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
1312         if (fProjectionModelUpdater != null)
1313                 fProjectionModelUpdater.install(this, projectionViewer);
1314                         
1315         if (isFoldingEnabled())
1316                 projectionViewer.doOperation(ProjectionViewer.TOGGLE);
1317         Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
1318     preferences.addPropertyChangeListener(fPropertyChangeListener);
1319     
1320     IInformationControlCreator informationControlCreator = new IInformationControlCreator() {
1321       public IInformationControl createInformationControl(Shell parent) {
1322         boolean cutDown = false;
1323         int style = cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
1324         return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
1325       }
1326     };
1327
1328     fInformationPresenter = new InformationPresenter(informationControlCreator);
1329     fInformationPresenter.setSizeConstraints(60, 10, true, true);
1330     fInformationPresenter.install(getSourceViewer());
1331
1332   }
1333
1334   /**
1335    * Returns this document's complete text.
1336    *
1337    * @return the document's complete text
1338    */
1339   public String get() {
1340     IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
1341     return doc.get();
1342   }
1343
1344   /**
1345          * Sets the outliner's context menu ID.
1346          */
1347   protected void setOutlinerContextMenuId(String menuId) {
1348     fOutlinerContextMenuId = menuId;
1349   }
1350
1351   /**
1352    *  Returns the standard action group of this editor.
1353    */
1354   protected ActionGroup getActionGroup() {
1355     return fActionGroups;
1356   }
1357
1358   //  public JavaOutlinePage getfOutlinePage() {
1359   //    return fOutlinePage;
1360   //  }
1361
1362   /** The <code>PHPEditor</code> implementation of this 
1363    * <code>AbstractTextEditor</code> method extend the 
1364    * actions to add those specific to the receiver
1365    */
1366   protected void createActions() {
1367     super.createActions();
1368     
1369     fFoldingGroup= new FoldingActionGroup(this, getViewer());
1370     
1371         ResourceAction resAction= new TextOperationAction(PHPEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
1372         resAction= new InformationDispatchAction(PHPEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
1373         resAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_JAVADOC);
1374         setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
1375 //      WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
1376         
1377         Action action= new GotoMatchingBracketAction(this);
1378         action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);                               
1379         setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
1380                 
1381 //      action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
1382 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE);
1383 //      setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE, action);
1384 ////    WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
1385 //
1386 //      action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
1387 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE);
1388 //      setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_STRUCTURE, action);
1389 ////    WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
1390 //      
1391 //      action= new TextOperationAction(PHPEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
1392 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY);
1393 //      setAction(PHPEditorActionDefinitionIds.SHOW_OUTLINE.OPEN_HIERARCHY, action);
1394 ////    WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
1395         
1396         fEncodingSupport= new DefaultEncodingSupport();
1397         fEncodingSupport.initialize(this);
1398         
1399 //      fSelectionHistory= new SelectionHistory(this);
1400 //
1401 //      action= new StructureSelectEnclosingAction(this, fSelectionHistory);
1402 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_ENCLOSING);                            
1403 //      setAction(StructureSelectionAction.ENCLOSING, action);
1404 //
1405 //      action= new StructureSelectNextAction(this, fSelectionHistory);
1406 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_NEXT);
1407 //      setAction(StructureSelectionAction.NEXT, action);
1408 //
1409 //      action= new StructureSelectPreviousAction(this, fSelectionHistory);
1410 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_PREVIOUS);
1411 //      setAction(StructureSelectionAction.PREVIOUS, action);
1412 //
1413 //      StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
1414 //      historyAction.setActionDefinitionId(PHPEditorActionDefinitionIds.SELECT_LAST);          
1415 //      setAction(StructureSelectionAction.HISTORY, historyAction);
1416 //      fSelectionHistory.setHistoryAction(historyAction);
1417 //                      
1418 //      action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
1419 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_NEXT_MEMBER);                            
1420 //      setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
1421 //
1422 //      action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
1423 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);                                
1424 //      setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
1425 //      
1426 //      action= new QuickFormatAction();
1427 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.QUICK_FORMAT);
1428 //      setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action);
1429 //
1430 //      action= new RemoveOccurrenceAnnotations(this);
1431 //      action.setActionDefinitionId(PHPEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
1432 //      setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
1433
1434         // add annotation actions
1435         action= new JavaSelectMarkerRulerAction2(PHPEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
1436         setAction("AnnotationAction", action); //$NON-NLS-1$
1437   }
1438
1439         private void internalDoSetInput(IEditorInput input) throws CoreException {
1440                 super.doSetInput(input);
1441                 
1442                 if (fEncodingSupport != null)
1443                         fEncodingSupport.reset();
1444                 
1445                 setOutlinePageInput(fOutlinePage, input);
1446                                 
1447                 if (fProjectionModelUpdater != null)
1448                         fProjectionModelUpdater.initialize();
1449                 
1450 //              if (isShowingOverrideIndicators())
1451 //                      installOverrideIndicator(true);
1452         }
1453
1454         /*
1455          * @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
1456          * @since 3.0
1457          */
1458         protected void setPreferenceStore(IPreferenceStore store) {
1459                 super.setPreferenceStore(store);
1460                 if (getSourceViewerConfiguration() instanceof PHPSourceViewerConfiguration) {
1461                         JavaTextTools textTools= PHPeclipsePlugin.getDefault().getJavaTextTools();
1462                         setSourceViewerConfiguration(new PHPSourceViewerConfiguration(textTools.getColorManager(), store, this, IPHPPartitions.PHP_PARTITIONING));
1463                 }
1464                 if (getSourceViewer() instanceof JavaSourceViewer)
1465                         ((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
1466         }
1467   /** The <code>PHPEditor</code> implementation of this 
1468    * <code>AbstractTextEditor</code> method performs any extra 
1469    * disposal actions required by the php editor.
1470    */
1471   public void dispose() {
1472         if (fProjectionModelUpdater != null) {
1473                 fProjectionModelUpdater.uninstall();
1474                 fProjectionModelUpdater= null;
1475         }
1476         
1477         if (fProjectionSupport != null) {
1478                 fProjectionSupport.dispose();
1479                 fProjectionSupport= null;
1480         }
1481     //   PHPEditorEnvironment.disconnect(this);
1482     if (fOutlinePage != null)
1483       fOutlinePage.setInput(null);
1484
1485     if (fActionGroups != null)
1486       fActionGroups.dispose();
1487
1488     if (isBrowserLikeLinks())
1489       disableBrowserLikeLinks();
1490
1491     if (fEncodingSupport != null) {
1492       fEncodingSupport.dispose();
1493       fEncodingSupport = null;
1494     }
1495
1496     if (fPropertyChangeListener != null) {
1497       Preferences preferences = PHPeclipsePlugin.getDefault().getPluginPreferences();
1498       preferences.removePropertyChangeListener(fPropertyChangeListener);
1499       fPropertyChangeListener = null;
1500     }
1501
1502 //    if (fSourceViewerDecorationSupport != null) {
1503 //      fSourceViewerDecorationSupport.dispose();
1504 //      fSourceViewerDecorationSupport = null;
1505 //    }
1506
1507     if (fBracketMatcher != null) {
1508       fBracketMatcher.dispose();
1509       fBracketMatcher = null;
1510     }
1511     super.dispose();
1512   }
1513
1514   /** The <code>PHPEditor</code> implementation of this 
1515    * <code>AbstractTextEditor</code> method performs any extra 
1516    * revert behavior required by the php editor.
1517    */
1518   //  public void doRevertToSaved() {
1519   //    super.doRevertToSaved();
1520   //    if (fOutlinePage != null)
1521   //      fOutlinePage.update();
1522   //  }
1523
1524   /** The <code>PHPEditor</code> implementation of this 
1525    * <code>AbstractTextEditor</code> method performs any extra 
1526    * save behavior required by the php editor.
1527    */
1528   //  public void doSave(IProgressMonitor monitor) {
1529   //    super.doSave(monitor);
1530   // compile or not, according to the user preferences
1531   // IPreferenceStore store = getPreferenceStore(); 
1532
1533   // the parse on save was changed to the eclipse "builders" concept
1534   //    if (store.getBoolean(PHPeclipsePlugin.PHP_PARSE_ON_SAVE)) {
1535   //      IAction a = PHPParserAction.getInstance();
1536   //      if (a != null)
1537   //        a.run();
1538   //    }
1539
1540   //    if (SWT.getPlatform().equals("win32")) {
1541   //      IAction a = ShowExternalPreviewAction.getInstance();
1542   //      if (a != null)
1543   //        a.run();
1544   //    }
1545   //    if (fOutlinePage != null)
1546   //      fOutlinePage.update();
1547   //  }
1548
1549   /** The <code>PHPEditor</code> implementation of this 
1550    * <code>AbstractTextEditor</code> method performs any extra 
1551    * save as behavior required by the php editor.
1552    */
1553   //  public void doSaveAs() {
1554   //    super.doSaveAs();
1555   //    if (fOutlinePage != null)
1556   //      fOutlinePage.update();
1557   //  }
1558   /*
1559          * @see StatusTextEditor#getStatusHeader(IStatus)
1560          */
1561   protected String getStatusHeader(IStatus status) {
1562     if (fEncodingSupport != null) {
1563       String message = fEncodingSupport.getStatusHeader(status);
1564       if (message != null)
1565         return message;
1566     }
1567     return super.getStatusHeader(status);
1568   }
1569
1570   /*
1571    * @see StatusTextEditor#getStatusBanner(IStatus)
1572    */
1573   protected String getStatusBanner(IStatus status) {
1574     if (fEncodingSupport != null) {
1575       String message = fEncodingSupport.getStatusBanner(status);
1576       if (message != null)
1577         return message;
1578     }
1579     return super.getStatusBanner(status);
1580   }
1581
1582   /*
1583    * @see StatusTextEditor#getStatusMessage(IStatus)
1584    */
1585   protected String getStatusMessage(IStatus status) {
1586     if (fEncodingSupport != null) {
1587       String message = fEncodingSupport.getStatusMessage(status);
1588       if (message != null)
1589         return message;
1590     }
1591     return super.getStatusMessage(status);
1592   }
1593   /** The <code>PHPEditor</code> implementation of this 
1594    * <code>AbstractTextEditor</code> method performs sets the 
1595    * input of the outline page after AbstractTextEditor has set input.
1596    */
1597   //  protected void doSetInput(IEditorInput input) throws CoreException {
1598   //    super.doSetInput(input);
1599   //
1600   //    if (fEncodingSupport != null)
1601   //      fEncodingSupport.reset();
1602   //    if (fOutlinePage != null)
1603   //      fOutlinePage.setInput(input);
1604   //    //              setOutlinePageInput(fOutlinePage, input);
1605   //  } 
1606   protected void doSetInput(IEditorInput input) throws CoreException {
1607     super.doSetInput(input);
1608     if (fEncodingSupport != null)
1609       fEncodingSupport.reset();
1610     setOutlinePageInput(fOutlinePage, input);
1611   }
1612   /*
1613    * @see org.phpeclipse.phpdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
1614    */
1615   //  public Object getViewPartInput() {
1616   //    return getEditorInput().getAdapter(IFile.class);
1617   //  }
1618
1619   /** The <code>PHPEditor</code> implementation of this 
1620    * <code>AbstractTextEditor</code> method adds any 
1621    * PHPEditor specific entries.
1622    */
1623   public void editorContextMenuAboutToShow(MenuManager menu) {
1624     super.editorContextMenuAboutToShow(menu);
1625     menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
1626     menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
1627
1628     ActionContext context = new ActionContext(getSelectionProvider().getSelection());
1629     fContextMenuGroup.setContext(context);
1630     fContextMenuGroup.fillContextMenu(menu);
1631     fContextMenuGroup.setContext(null);
1632     //    addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$
1633     //
1634     //    ActionContext context =
1635     //      new ActionContext(getSelectionProvider().getSelection());
1636     //    fContextMenuGroup.setContext(context);
1637     //    fContextMenuGroup.fillContextMenu(menu);
1638     //    fContextMenuGroup.setContext(null);
1639   }
1640
1641   /**
1642    * Creates the outline page used with this editor.
1643    */
1644   protected JavaOutlinePage createOutlinePage() {
1645
1646     //    AbstractContentOutlinePage page = new PHPContentOutlinePage(getDocumentProvider(), this);
1647     //
1648     //    page.addSelectionChangedListener(fSelectionChangedListener);
1649     //    //    setOutlinePageInput(page, getEditorInput());
1650     //    if (getEditorInput() != null)
1651     //      fOutlinePage.setInput(getEditorInput());
1652     //
1653     //    return page;
1654     JavaOutlinePage page = new JavaOutlinePage(fOutlinerContextMenuId, this);
1655
1656     page.addSelectionChangedListener(fSelectionChangedListener);
1657     setOutlinePageInput(page, getEditorInput());
1658
1659     return page;
1660   }
1661
1662   /**
1663    * Informs the editor that its outliner has been closed.
1664    */
1665   public void outlinePageClosed() {
1666     if (fOutlinePage != null) {
1667       fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
1668       fOutlinePage = null;
1669       resetHighlightRange();
1670     }
1671   }
1672   /**
1673    * Synchronizes the outliner selection with the actual cursor
1674    * position in the editor.
1675    */
1676   public void synchronizeOutlinePageSelection() {
1677
1678     //          if (isEditingScriptRunning())
1679     //                  return;
1680
1681     ISourceViewer sourceViewer = getSourceViewer();
1682     if (sourceViewer == null || fOutlinePage == null)
1683       return;
1684
1685     StyledText styledText = sourceViewer.getTextWidget();
1686     if (styledText == null)
1687       return;
1688
1689     int caret = 0;
1690     if (sourceViewer instanceof ITextViewerExtension3) {
1691       ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
1692       caret = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
1693     } else {
1694       int offset = sourceViewer.getVisibleRegion().getOffset();
1695       caret = offset + styledText.getCaretOffset();
1696     }
1697
1698     IJavaElement element = getElementAt(caret);
1699     if (element instanceof ISourceReference) {
1700       fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
1701       fOutlinePage.select((ISourceReference) element);
1702       fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
1703     }
1704   }
1705
1706   protected void setSelection(ISourceReference reference, boolean moveCursor) {
1707
1708     ISelection selection = getSelectionProvider().getSelection();
1709     if (selection instanceof TextSelection) {
1710       TextSelection textSelection = (TextSelection) selection;
1711       if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
1712         markInNavigationHistory();
1713     }
1714
1715     if (reference != null) {
1716
1717       StyledText textWidget = null;
1718
1719       ISourceViewer sourceViewer = getSourceViewer();
1720       if (sourceViewer != null)
1721         textWidget = sourceViewer.getTextWidget();
1722
1723       if (textWidget == null)
1724         return;
1725
1726       try {
1727
1728         ISourceRange range = reference.getSourceRange();
1729         if (range == null)
1730           return;
1731
1732         int offset = range.getOffset();
1733         int length = range.getLength();
1734
1735         if (offset < 0 || length < 0)
1736           return;
1737
1738         textWidget.setRedraw(false);
1739
1740         setHighlightRange(offset, length, moveCursor);
1741
1742         if (!moveCursor)
1743           return;
1744
1745         offset = -1;
1746         length = -1;
1747
1748         if (reference instanceof IMember) {
1749           range = ((IMember) reference).getNameRange();
1750           if (range != null) {
1751             offset = range.getOffset();
1752             length = range.getLength();
1753           }
1754         }
1755         //                                      else if (reference instanceof IImportDeclaration) {
1756         //                                              String name= ((IImportDeclaration) reference).getElementName();
1757         //                                              if (name != null && name.length() > 0) {
1758         //                                                      String content= reference.getSource();
1759         //                                                      if (content != null) {
1760         //                                                              offset= range.getOffset() + content.indexOf(name);
1761         //                                                              length= name.length();
1762         //                                                      }
1763         //                                              }
1764         //                                      } else if (reference instanceof IPackageDeclaration) {
1765         //                                              String name= ((IPackageDeclaration) reference).getElementName();
1766         //                                              if (name != null && name.length() > 0) {
1767         //                                                      String content= reference.getSource();
1768         //                                                      if (content != null) {
1769         //                                                              offset= range.getOffset() + content.indexOf(name);
1770         //                                                              length= name.length();
1771         //                                                      }
1772         //                                              }
1773         //                                      }
1774
1775         if (offset > -1 && length > 0) {
1776           sourceViewer.revealRange(offset, length);
1777           sourceViewer.setSelectedRange(offset, length);
1778         }
1779
1780       } catch (JavaModelException x) {
1781       } catch (IllegalArgumentException x) {
1782       } finally {
1783         if (textWidget != null)
1784           textWidget.setRedraw(true);
1785       }
1786
1787     } else if (moveCursor) {
1788       resetHighlightRange();
1789     }
1790
1791     markInNavigationHistory();
1792   }
1793
1794   public void setSelection(IJavaElement element) {
1795
1796     if (element == null || element instanceof ICompilationUnit) { // || element instanceof IClassFile) {
1797       /*
1798        * If the element is an ICompilationUnit this unit is either the input
1799        * of this editor or not being displayed. In both cases, nothing should
1800        * happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
1801        */
1802       return;
1803     }
1804
1805     IJavaElement corresponding = getCorrespondingElement(element);
1806     if (corresponding instanceof ISourceReference) {
1807       ISourceReference reference = (ISourceReference) corresponding;
1808       // set hightlight range
1809       setSelection(reference, true);
1810       // set outliner selection
1811       if (fOutlinePage != null) {
1812         fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
1813         fOutlinePage.select(reference);
1814         fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
1815       }
1816     }
1817   }
1818
1819         public synchronized void editingScriptStarted() {
1820                 ++ fIgnoreOutlinePageSelection;
1821         }
1822         
1823         public synchronized void editingScriptEnded() {
1824                 -- fIgnoreOutlinePageSelection;
1825         }
1826         
1827         public synchronized boolean isEditingScriptRunning() {
1828                 return (fIgnoreOutlinePageSelection > 0);
1829         }
1830         
1831   /** The <code>PHPEditor</code> implementation of this 
1832    * <code>AbstractTextEditor</code> method performs gets
1833    * the java content outline page if request is for a an 
1834    * outline page.
1835    */
1836   public Object getAdapter(Class required) {
1837
1838     if (IContentOutlinePage.class.equals(required)) {
1839       if (fOutlinePage == null)
1840         fOutlinePage = createOutlinePage();
1841       return fOutlinePage;
1842     }
1843
1844     if (IEncodingSupport.class.equals(required))
1845       return fEncodingSupport;
1846
1847     if (required == IShowInTargetList.class) {
1848       return new IShowInTargetList() {
1849         public String[] getShowInTargetIds() {
1850           return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
1851         }
1852
1853       };
1854     }
1855     if (fProjectionSupport != null) {
1856                 Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
1857                 if (adapter != null)
1858                         return adapter;
1859         }
1860                 
1861     return super.getAdapter(required);
1862   }
1863   //  public Object getAdapter(Class required) {
1864   //    if (IContentOutlinePage.class.equals(required)) {
1865   //      if (fOutlinePage == null) {
1866   //        fOutlinePage = new PHPContentOutlinePage(getDocumentProvider(), this);
1867   //        if (getEditorInput() != null)
1868   //          fOutlinePage.setInput(getEditorInput());
1869   //      }
1870   //      return fOutlinePage;
1871   //    }
1872   //
1873   //    if (IEncodingSupport.class.equals(required))
1874   //      return fEncodingSupport;
1875   //
1876   //    return super.getAdapter(required);
1877   //  }
1878
1879   protected void doSelectionChanged(SelectionChangedEvent event) {
1880     ISourceReference reference = null;
1881
1882     ISelection selection = event.getSelection();
1883     Iterator iter = ((IStructuredSelection) selection).iterator();
1884     while (iter.hasNext()) {
1885       Object o = iter.next();
1886       if (o instanceof ISourceReference) {
1887         reference = (ISourceReference) o;
1888         break;
1889       }
1890     }
1891
1892     if (!isActivePart() && PHPeclipsePlugin.getActivePage() != null)
1893       PHPeclipsePlugin.getActivePage().bringToTop(this);
1894
1895     try {
1896       editingScriptStarted();
1897       setSelection(reference, !isActivePart());
1898     } finally {
1899       editingScriptEnded();
1900     }
1901   }
1902   /*
1903          * @see AbstractTextEditor#adjustHighlightRange(int, int)
1904          */
1905   protected void adjustHighlightRange(int offset, int length) {
1906
1907     try {
1908
1909       IJavaElement element = getElementAt(offset);
1910       while (element instanceof ISourceReference) {
1911         ISourceRange range = ((ISourceReference) element).getSourceRange();
1912         if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
1913           setHighlightRange(range.getOffset(), range.getLength(), true);
1914           if (fOutlinePage != null) {
1915             fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
1916             fOutlinePage.select((ISourceReference) element);
1917             fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
1918           }
1919           return;
1920         }
1921         element = element.getParent();
1922       }
1923
1924     } catch (JavaModelException x) {
1925       PHPeclipsePlugin.log(x.getStatus());
1926     }
1927
1928     resetHighlightRange();
1929   }
1930   protected boolean isActivePart() {
1931     IWorkbenchWindow window = getSite().getWorkbenchWindow();
1932     IPartService service = window.getPartService();
1933     IWorkbenchPart part = service.getActivePart();
1934     return part != null && part.equals(this);
1935   }
1936
1937
1938   //  public void openContextHelp() {
1939   //    IDocument doc = this.getDocumentProvider().getDocument(this.getEditorInput());
1940   //    ITextSelection selection = (ITextSelection) this.getSelectionProvider().getSelection();
1941   //    int pos = selection.getOffset();
1942   //    String word = getFunctionName(doc, pos);
1943   //    openContextHelp(word);
1944   //  }
1945   //
1946   //  private void openContextHelp(String word) {
1947   //    open(word);
1948   //  }
1949   //
1950   //  public static void open(String word) {
1951   //    IHelp help = WorkbenchHelp.getHelpSupport();
1952   //    if (help != null) {
1953   //      IHelpResource helpResource = new PHPFunctionHelpResource(word);
1954   //      WorkbenchHelp.getHelpSupport().displayHelpResource(helpResource);
1955   //    } else {
1956   //      //   showMessage(shell, dialogTitle, ActionMessages.getString("Open help not available"), false); //$NON-NLS-1$
1957   //    }
1958   //  }
1959
1960   //    private String getFunctionName(IDocument doc, int pos) {
1961   //            Point word = PHPWordExtractor.findWord(doc, pos);
1962   //            if (word != null) {
1963   //                    try {
1964   //                            return doc.get(word.x, word.y).replace('_', '-');
1965   //                    } catch (BadLocationException e) {
1966   //                    }
1967   //            }
1968   //            return "";
1969   //    }
1970
1971   /*
1972    * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
1973    */
1974   protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
1975
1976     try {
1977
1978       ISourceViewer sourceViewer = getSourceViewer();
1979       if (sourceViewer == null)
1980         return;
1981
1982       String property = event.getProperty();
1983
1984       if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
1985         Object value = event.getNewValue();
1986         if (value instanceof Integer) {
1987           sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
1988         } else if (value instanceof String) {
1989           sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
1990         }
1991         return;
1992       }
1993       
1994 //      if (OVERVIEW_RULER.equals(property)) {
1995 //        if (isOverviewRulerVisible())
1996 //          showOverviewRuler();
1997 //        else
1998 //          hideOverviewRuler();
1999 //        return;
2000 //      }
2001
2002 //      if (LINE_NUMBER_RULER.equals(property)) {
2003 //        if (isLineNumberRulerVisible())
2004 //          showLineNumberRuler();
2005 //        else
2006 //          hideLineNumberRuler();
2007 //        return;
2008 //      }
2009
2010 //      if (fLineNumberRulerColumn != null
2011 //        && (LINE_NUMBER_COLOR.equals(property) || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2012 //
2013 //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2014 //      }
2015
2016       if (isJavaEditorHoverProperty(property))
2017         updateHoverBehavior();
2018
2019       if (BROWSER_LIKE_LINKS.equals(property)) {
2020         if (isBrowserLikeLinks())
2021           enableBrowserLikeLinks();
2022         else
2023           disableBrowserLikeLinks();
2024         return;
2025       }
2026
2027 //      if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
2028 //              if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
2029 //                      fEditorSelectionChangedListener.selectionChanged();
2030 //              return;
2031 //      }
2032         
2033         if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
2034                 if (event.getNewValue() instanceof Boolean) {
2035                         Boolean disable= (Boolean) event.getNewValue();
2036                         enableOverwriteMode(!disable.booleanValue());
2037                 }
2038                 return;
2039         }
2040         
2041 //      if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
2042 //              if (event.getNewValue() instanceof Boolean) {
2043 //                      boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
2044 //                      if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
2045 //                              fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
2046 //                              if (!fMarkOccurrenceAnnotations)
2047 //                                      uninstallOccurrencesFinder();
2048 //                              else
2049 //                                      installOccurrencesFinder();
2050 //                      }
2051 //              }
2052 //      }
2053 //      if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
2054 //              if (event.getNewValue() instanceof Boolean) {
2055 //                      boolean stickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
2056 //                      if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) {
2057 //                              fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations;
2058 ////                            if (!fMarkOccurrenceAnnotations)
2059 ////                                    uninstallOccurrencesFinder();
2060 ////                            else
2061 ////                                    installOccurrencesFinder();
2062 //                      }
2063 //              }
2064 //      }
2065         if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
2066                 if (sourceViewer instanceof ProjectionViewer) {
2067                         ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
2068                         if (fProjectionModelUpdater != null)
2069                                 fProjectionModelUpdater.uninstall();
2070                         // either freshly enabled or provider changed
2071                         fProjectionModelUpdater= PHPeclipsePlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
2072                         if (fProjectionModelUpdater != null) {
2073                                 fProjectionModelUpdater.install(this, projectionViewer);
2074                         }
2075                 }
2076                 return;
2077         }
2078     } finally {
2079       super.handlePreferenceStoreChanged(event);
2080     }
2081   }
2082
2083   //  /*
2084   //     * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
2085   //     */
2086   //  protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
2087   //
2088   //    try {
2089   //
2090   //      ISourceViewer sourceViewer = getSourceViewer();
2091   //      if (sourceViewer == null)
2092   //        return;
2093   //
2094   //      String property = event.getProperty();
2095   //
2096   //      //      if (JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH.equals(property)) {
2097   //      //        Object value= event.getNewValue();
2098   //      //        if (value instanceof Integer) {
2099   //      //          sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
2100   //      //        } else if (value instanceof String) {
2101   //      //          sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
2102   //      //        }
2103   //      //        return;
2104   //      //      }
2105   //
2106   //      if (IPreferenceConstants.LINE_NUMBER_RULER.equals(property)) {
2107   //        if (isLineNumberRulerVisible())
2108   //          showLineNumberRuler();
2109   //        else
2110   //          hideLineNumberRuler();
2111   //        return;
2112   //      }
2113   //
2114   //      if (fLineNumberRulerColumn != null
2115   //        && (IPreferenceConstants.LINE_NUMBER_COLOR.equals(property)
2116   //          || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
2117   //          || PREFERENCE_COLOR_BACKGROUND.equals(property))) {
2118   //
2119   //        initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2120   //      }
2121   //
2122   //    } finally {
2123   //      super.handlePreferenceStoreChanged(event);
2124   //    }
2125   //  }
2126
2127   //  private boolean isJavaEditorHoverProperty(String property) {
2128   //    return PreferenceConstants.EDITOR_DEFAULT_HOVER.equals(property)
2129   //      || PreferenceConstants.EDITOR_NONE_HOVER.equals(property)
2130   //      || PreferenceConstants.EDITOR_CTRL_HOVER.equals(property)
2131   //      || PreferenceConstants.EDITOR_SHIFT_HOVER.equals(property)
2132   //      || PreferenceConstants.EDITOR_CTRL_ALT_HOVER.equals(property)
2133   //      || PreferenceConstants.EDITOR_CTRL_SHIFT_HOVER.equals(property)
2134   //      || PreferenceConstants.EDITOR_CTRL_ALT_SHIFT_HOVER.equals(property)
2135   //      || PreferenceConstants.EDITOR_ALT_SHIFT_HOVER.equals(property);
2136   //  }
2137
2138   /**
2139    * Shows the line number ruler column.
2140    */
2141 //  private void showLineNumberRuler() {
2142 //    IVerticalRuler v = getVerticalRuler();
2143 //    if (v instanceof CompositeRuler) {
2144 //      CompositeRuler c = (CompositeRuler) v;
2145 //      c.addDecorator(1, createLineNumberRulerColumn());
2146 //    }
2147 //  }
2148   private boolean isJavaEditorHoverProperty(String property) {
2149     return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
2150   }
2151
2152   /**
2153          * Return whether the browser like links should be enabled
2154          * according to the preference store settings.
2155          * @return <code>true</code> if the browser like links should be enabled
2156          */
2157   private boolean isBrowserLikeLinks() {
2158     IPreferenceStore store = getPreferenceStore();
2159     return store.getBoolean(BROWSER_LIKE_LINKS);
2160   }
2161
2162   /**
2163    * Enables browser like links.
2164    */
2165   private void enableBrowserLikeLinks() {
2166     if (fMouseListener == null) {
2167       fMouseListener = new MouseClickListener();
2168       fMouseListener.install();
2169     }
2170   }
2171
2172   /**
2173    * Disables browser like links.
2174    */
2175   private void disableBrowserLikeLinks() {
2176     if (fMouseListener != null) {
2177       fMouseListener.uninstall();
2178       fMouseListener = null;
2179     }
2180   }
2181   /**
2182    * Handles a property change event describing a change
2183    * of the java core's preferences and updates the preference
2184    * related editor properties.
2185    * 
2186    * @param event the property change event
2187    */
2188   protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
2189     if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
2190       ISourceViewer sourceViewer = getSourceViewer();
2191       if (sourceViewer != null
2192         && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
2193         sourceViewer.invalidateTextPresentation();
2194     }
2195   }
2196
2197   /**
2198    * Return whether the line number ruler column should be 
2199    * visible according to the preference store settings.
2200    * @return <code>true</code> if the line numbers should be visible
2201    */
2202 //  protected boolean isLineNumberRulerVisible() {
2203 //    IPreferenceStore store = getPreferenceStore();
2204 //    return store.getBoolean(LINE_NUMBER_RULER);
2205 //  }
2206   /**
2207    * Hides the line number ruler column.
2208    */
2209 //  private void hideLineNumberRuler() {
2210 //    IVerticalRuler v = getVerticalRuler();
2211 //    if (v instanceof CompositeRuler) {
2212 //      CompositeRuler c = (CompositeRuler) v;
2213 //      try {
2214 //        c.removeDecorator(1);
2215 //      } catch (Throwable e) {
2216 //      }
2217 //    }
2218 //  }
2219
2220         /*
2221          * @see AbstractTextEditor#handleCursorPositionChanged()
2222          */
2223         protected void handleCursorPositionChanged() {
2224                 super.handleCursorPositionChanged();
2225                 if (!isEditingScriptRunning() && fUpdater != null)
2226                         fUpdater.post();
2227         }
2228         /*
2229          * @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
2230          */
2231         protected void handleElementContentReplaced() {
2232                 super.handleElementContentReplaced();
2233                 if (fProjectionModelUpdater != null)
2234                         fProjectionModelUpdater.initialize();
2235         }
2236   /**
2237    * Initializes the given line number ruler column from the preference store.
2238    * @param rulerColumn the ruler column to be initialized
2239    */
2240 //  protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
2241 //    JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
2242 //    IColorManager manager = textTools.getColorManager();
2243 //
2244 //    IPreferenceStore store = getPreferenceStore();
2245 //    if (store != null) {
2246 //
2247 //      RGB rgb = null;
2248 //      // foreground color
2249 //      if (store.contains(LINE_NUMBER_COLOR)) {
2250 //        if (store.isDefault(LINE_NUMBER_COLOR))
2251 //          rgb = PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
2252 //        else
2253 //          rgb = PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
2254 //      }
2255 //      rulerColumn.setForeground(manager.getColor(rgb));
2256 //
2257 //      rgb = null;
2258 //      // background color
2259 //      if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
2260 //        if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
2261 //          if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
2262 //            rgb = PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
2263 //          else
2264 //            rgb = PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
2265 //        }
2266 //      }
2267 //      rulerColumn.setBackground(manager.getColor(rgb));
2268 //    }
2269 //  }
2270
2271   /**
2272    * Creates a new line number ruler column that is appropriately initialized.
2273    */
2274 //  protected IVerticalRulerColumn createLineNumberRulerColumn() {
2275 //    fLineNumberRulerColumn = new LineNumberRulerColumn();
2276 //    initializeLineNumberRulerColumn(fLineNumberRulerColumn);
2277 //    return fLineNumberRulerColumn;
2278 //  }
2279
2280   /*
2281    * @see AbstractTextEditor#createVerticalRuler()
2282    */
2283 //  protected IVerticalRuler createVerticalRuler() {
2284 //    CompositeRuler ruler = new CompositeRuler();
2285 //    ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
2286 //    if (isLineNumberRulerVisible())
2287 //      ruler.addDecorator(1, createLineNumberRulerColumn());
2288 //    return ruler;
2289 //  }
2290
2291   private static IRegion getSignedSelection(ITextViewer viewer) {
2292
2293     StyledText text = viewer.getTextWidget();
2294     int caretOffset = text.getCaretOffset();
2295     Point selection = text.getSelection();
2296
2297     // caret left
2298     int offset, length;
2299     if (caretOffset == selection.x) {
2300       offset = selection.y;
2301       length = selection.x - selection.y;
2302
2303       // caret right
2304     } else {
2305       offset = selection.x;
2306       length = selection.y - selection.x;
2307     }
2308
2309     return new Region(offset, length);
2310   }
2311
2312   /** Preference key for matching brackets */
2313   protected final static String MATCHING_BRACKETS = PreferenceConstants.EDITOR_MATCHING_BRACKETS;
2314   /** Preference key for matching brackets color */
2315   protected final static String MATCHING_BRACKETS_COLOR = PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
2316   /** Preference key for highlighting current line */
2317   protected final static String CURRENT_LINE = PreferenceConstants.EDITOR_CURRENT_LINE;
2318   /** Preference key for highlight color of current line */
2319   protected final static String CURRENT_LINE_COLOR = PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
2320   /** Preference key for showing print marging ruler */
2321   protected final static String PRINT_MARGIN = PreferenceConstants.EDITOR_PRINT_MARGIN;
2322   /** Preference key for print margin ruler color */
2323   protected final static String PRINT_MARGIN_COLOR = PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
2324   /** Preference key for print margin ruler column */
2325   protected final static String PRINT_MARGIN_COLUMN = PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
2326   /** Preference key for error indication */
2327 //  protected final static String ERROR_INDICATION = PreferenceConstants.EDITOR_PROBLEM_INDICATION;
2328   /** Preference key for error color */
2329 //  protected final static String ERROR_INDICATION_COLOR = PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
2330   /** Preference key for warning indication */
2331 //  protected final static String WARNING_INDICATION = PreferenceConstants.EDITOR_WARNING_INDICATION;
2332   /** Preference key for warning color */
2333 //  protected final static String WARNING_INDICATION_COLOR = PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
2334   /** Preference key for task indication */
2335   protected final static String TASK_INDICATION = PreferenceConstants.EDITOR_TASK_INDICATION;
2336   /** Preference key for task color */
2337   protected final static String TASK_INDICATION_COLOR = PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
2338   /** Preference key for bookmark indication */
2339   protected final static String BOOKMARK_INDICATION = PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
2340   /** Preference key for bookmark color */
2341   protected final static String BOOKMARK_INDICATION_COLOR = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
2342   /** Preference key for search result indication */
2343   protected final static String SEARCH_RESULT_INDICATION = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
2344   /** Preference key for search result color */
2345   protected final static String SEARCH_RESULT_INDICATION_COLOR = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
2346   /** Preference key for unknown annotation indication */
2347   protected final static String UNKNOWN_INDICATION = PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
2348   /** Preference key for unknown annotation color */
2349   protected final static String UNKNOWN_INDICATION_COLOR = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
2350   /** Preference key for shwoing the overview ruler */
2351   protected final static String OVERVIEW_RULER = PreferenceConstants.EDITOR_OVERVIEW_RULER;
2352   /** Preference key for error indication in overview ruler */
2353   protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
2354   /** Preference key for warning indication in overview ruler */
2355   protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
2356   /** Preference key for task indication in overview ruler */
2357   protected final static String TASK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
2358   /** Preference key for bookmark indication in overview ruler */
2359   protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
2360   /** Preference key for search result indication in overview ruler */
2361   protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
2362   /** Preference key for unknown annotation indication in overview ruler */
2363   protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER = PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
2364   //            /** Preference key for compiler task tags */
2365   //            private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
2366   /** Preference key for browser like links */
2367   private final static String BROWSER_LIKE_LINKS = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
2368   /** Preference key for key modifier of browser like links */
2369   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
2370   /**
2371    * Preference key for key modifier mask of browser like links.
2372    * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
2373    * cannot be resolved to valid SWT modifier bits.
2374    * 
2375    * @since 2.1.1
2376    */
2377   private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK = PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
2378
2379   private final static char[] BRACKETS = { '{', '}', '(', ')', '[', ']' };
2380
2381   private static boolean isBracket(char character) {
2382     for (int i = 0; i != BRACKETS.length; ++i)
2383       if (character == BRACKETS[i])
2384         return true;
2385     return false;
2386   }
2387
2388   private static boolean isSurroundedByBrackets(IDocument document, int offset) {
2389     if (offset == 0 || offset == document.getLength())
2390       return false;
2391
2392     try {
2393       return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset));
2394
2395     } catch (BadLocationException e) {
2396       return false;
2397     }
2398   }
2399
2400 //  protected void configureSourceViewerDecorationSupport() {
2401 //
2402 //    fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
2403 //
2404 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2405 //      AnnotationType.UNKNOWN,
2406 //      UNKNOWN_INDICATION_COLOR,
2407 //      UNKNOWN_INDICATION,
2408 //      UNKNOWN_INDICATION_IN_OVERVIEW_RULER,
2409 //      0);
2410 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2411 //      AnnotationType.BOOKMARK,
2412 //      BOOKMARK_INDICATION_COLOR,
2413 //      BOOKMARK_INDICATION,
2414 //      BOOKMARK_INDICATION_IN_OVERVIEW_RULER,
2415 //      1);
2416 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2417 //      AnnotationType.TASK,
2418 //      TASK_INDICATION_COLOR,
2419 //      TASK_INDICATION,
2420 //      TASK_INDICATION_IN_OVERVIEW_RULER, 
2421 //      2);
2422 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2423 //      AnnotationType.SEARCH,
2424 //      SEARCH_RESULT_INDICATION_COLOR,
2425 //      SEARCH_RESULT_INDICATION,
2426 //      SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER,
2427 //      3);
2428 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2429 //      AnnotationType.WARNING,
2430 //      WARNING_INDICATION_COLOR,
2431 //      WARNING_INDICATION,
2432 //      WARNING_INDICATION_IN_OVERVIEW_RULER,
2433 //      4);
2434 //    fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(
2435 //      AnnotationType.ERROR,
2436 //      ERROR_INDICATION_COLOR,
2437 //      ERROR_INDICATION,
2438 //      ERROR_INDICATION_IN_OVERVIEW_RULER,
2439 //      5);
2440 //
2441 //    fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
2442 //    fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
2443 //    fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
2444 //
2445 //    fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
2446 //
2447 //  }
2448   /**
2449     * Jumps to the matching bracket.
2450     */
2451   public void gotoMatchingBracket() {
2452
2453     ISourceViewer sourceViewer = getSourceViewer();
2454     IDocument document = sourceViewer.getDocument();
2455     if (document == null)
2456       return;
2457
2458     IRegion selection = getSignedSelection(sourceViewer);
2459
2460     int selectionLength = Math.abs(selection.getLength());
2461     if (selectionLength > 1) {
2462       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$               
2463       sourceViewer.getTextWidget().getDisplay().beep();
2464       return;
2465     }
2466
2467     // #26314
2468     int sourceCaretOffset = selection.getOffset() + selection.getLength();
2469     if (isSurroundedByBrackets(document, sourceCaretOffset))
2470       sourceCaretOffset -= selection.getLength();
2471
2472     IRegion region = fBracketMatcher.match(document, sourceCaretOffset);
2473     if (region == null) {
2474       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$              
2475       sourceViewer.getTextWidget().getDisplay().beep();
2476       return;
2477     }
2478
2479     int offset = region.getOffset();
2480     int length = region.getLength();
2481
2482     if (length < 1)
2483       return;
2484
2485     int anchor = fBracketMatcher.getAnchor();
2486     int targetOffset = (PHPPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
2487
2488     boolean visible = false;
2489     if (sourceViewer instanceof ITextViewerExtension3) {
2490       ITextViewerExtension3 extension = (ITextViewerExtension3) sourceViewer;
2491       visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1);
2492     } else {
2493       IRegion visibleRegion = sourceViewer.getVisibleRegion();
2494       visible = (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
2495     }
2496
2497     if (!visible) {
2498       setStatusLineErrorMessage(PHPEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$          
2499       sourceViewer.getTextWidget().getDisplay().beep();
2500       return;
2501     }
2502
2503     if (selection.getLength() < 0)
2504       targetOffset -= selection.getLength();
2505
2506     sourceViewer.setSelectedRange(targetOffset, selection.getLength());
2507     sourceViewer.revealRange(targetOffset, selection.getLength());
2508   }
2509   /**
2510      * Ses the given message as error message to this editor's status line.
2511      * @param msg message to be set
2512      */
2513   protected void setStatusLineErrorMessage(String msg) {
2514     IEditorStatusLine statusLine = (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
2515     if (statusLine != null)
2516       statusLine.setMessage(true, msg, null);
2517   }
2518
2519   /**
2520      * Returns a segmentation of the line of the given document appropriate for bidi rendering.
2521      * The default implementation returns only the string literals of a php code line as segments.
2522      * 
2523      * @param document the document
2524      * @param lineOffset the offset of the line
2525      * @return the line's bidi segmentation
2526      * @throws BadLocationException in case lineOffset is not valid in document
2527      */
2528   public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
2529
2530     IRegion line = document.getLineInformationOfOffset(lineOffset);
2531     ITypedRegion[] linePartitioning = document.computePartitioning(lineOffset, line.getLength());
2532
2533     List segmentation = new ArrayList();
2534     for (int i = 0; i < linePartitioning.length; i++) {
2535       if (IPHPPartitions.PHP_STRING_DQ.equals(linePartitioning[i].getType()))
2536         segmentation.add(linePartitioning[i]);
2537     }
2538
2539     if (segmentation.size() == 0)
2540       return null;
2541
2542     int size = segmentation.size();
2543     int[] segments = new int[size * 2 + 1];
2544
2545     int j = 0;
2546     for (int i = 0; i < size; i++) {
2547       ITypedRegion segment = (ITypedRegion) segmentation.get(i);
2548
2549       if (i == 0)
2550         segments[j++] = 0;
2551
2552       int offset = segment.getOffset() - lineOffset;
2553       if (offset > segments[j - 1])
2554         segments[j++] = offset;
2555
2556       if (offset + segment.getLength() >= line.getLength())
2557         break;
2558
2559       segments[j++] = offset + segment.getLength();
2560     }
2561
2562     if (j < segments.length) {
2563       int[] result = new int[j];
2564       System.arraycopy(segments, 0, result, 0, j);
2565       segments = result;
2566     }
2567
2568     return segments;
2569   }
2570   /**
2571      * Returns a segmentation of the given line appropriate for bidi rendering. The default
2572      * implementation returns only the string literals of a php code line as segments.
2573      * 
2574      * @param lineOffset the offset of the line
2575      * @param line the content of the line
2576      * @return the line's bidi segmentation
2577      */
2578   protected int[] getBidiLineSegments(int lineOffset, String line) {
2579     IDocumentProvider provider = getDocumentProvider();
2580     if (provider != null && line != null && line.length() > 0) {
2581       IDocument document = provider.getDocument(getEditorInput());
2582       if (document != null)
2583         try {
2584           return getBidiLineSegments(document, lineOffset);
2585         } catch (BadLocationException x) {
2586           // ignore
2587         }
2588     }
2589     return null;
2590   }
2591
2592   /*
2593    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
2594    */
2595   //  protected final ISourceViewer createSourceViewer(
2596   //    Composite parent,
2597   //    IVerticalRuler ruler,
2598   //    int styles) {
2599   //    ISourceViewer viewer = createJavaSourceViewer(parent, ruler, styles);
2600   //    StyledText text = viewer.getTextWidget();
2601   //    text.addBidiSegmentListener(new BidiSegmentListener() {
2602   //      public void lineGetSegments(BidiSegmentEvent event) {
2603   //        event.segments = getBidiLineSegments(event.lineOffset, event.lineText);
2604   //      }
2605   //    });
2606   //    //   JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
2607   //    return viewer;
2608   //  }
2609   
2610   public final ISourceViewer getViewer() {
2611         return getSourceViewer();
2612   }
2613   
2614
2615 //  protected void showOverviewRuler() {
2616 //    if (fOverviewRuler != null) {
2617 //      if (getSourceViewer() instanceof ISourceViewerExtension) {
2618 //        ((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
2619 //        fSourceViewerDecorationSupport.updateOverviewDecorations();
2620 //      }
2621 //    }
2622 //  }
2623 //
2624 //  protected void hideOverviewRuler() {
2625 //    if (getSourceViewer() instanceof ISourceViewerExtension) {
2626 //      fSourceViewerDecorationSupport.hideAnnotationOverview();
2627 //      ((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
2628 //    }
2629 //  }
2630
2631 //  protected boolean isOverviewRulerVisible() {
2632 //    IPreferenceStore store = getPreferenceStore();
2633 //    return store.getBoolean(OVERVIEW_RULER);
2634 //  }
2635   /*
2636    * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
2637    */
2638 //  protected ISourceViewer createJavaSourceViewer(
2639 //    Composite parent,
2640 //    IVerticalRuler ruler,
2641 //    IOverviewRuler overviewRuler,
2642 //    boolean isOverviewRulerVisible,
2643 //    int styles) {
2644 //    return new SourceViewer(parent, ruler, overviewRuler, isOverviewRulerVisible(), styles);
2645 //  }
2646         /*
2647          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
2648          */
2649         protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
2650                 return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
2651         }
2652   /*
2653          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
2654          */
2655         protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
2656                 
2657                 ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
2658                 
2659                 StyledText text= viewer.getTextWidget();
2660                 text.addBidiSegmentListener(new  BidiSegmentListener() {
2661                         public void lineGetSegments(BidiSegmentEvent event) {
2662                                 event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
2663                         }
2664                 });
2665                 
2666 //              JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
2667
2668                 // ensure source viewer decoration support has been created and configured
2669                 getSourceViewerDecorationSupport(viewer);                               
2670                 
2671                 return viewer;
2672         }
2673           /*
2674          * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
2675          */
2676 //      protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
2677 //              return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
2678 //      }
2679   /*
2680    * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
2681    */
2682   protected boolean affectsTextPresentation(PropertyChangeEvent event) {
2683     JavaTextTools textTools = PHPeclipsePlugin.getDefault().getJavaTextTools();
2684     return textTools.affectsBehavior(event);
2685   }
2686
2687   /**
2688    * Jumps to the error next according to the given direction.
2689    */
2690   public void gotoError(boolean forward) {
2691
2692     ISelectionProvider provider = getSelectionProvider();
2693
2694     ITextSelection s = (ITextSelection) provider.getSelection();
2695     Position errorPosition = new Position(0, 0);
2696     IJavaAnnotation nextError = getNextError(s.getOffset(), forward, errorPosition);
2697
2698     if (nextError != null) {
2699
2700       IMarker marker = null;
2701       if (nextError instanceof MarkerAnnotation)
2702         marker = ((MarkerAnnotation) nextError).getMarker();
2703       else {
2704         Iterator e = nextError.getOverlaidIterator();
2705         if (e != null) {
2706           while (e.hasNext()) {
2707             Object o = e.next();
2708             if (o instanceof MarkerAnnotation) {
2709               marker = ((MarkerAnnotation) o).getMarker();
2710               break;
2711             }
2712           }
2713         }
2714       }
2715
2716       if (marker != null) {
2717         IWorkbenchPage page = getSite().getPage();
2718         IViewPart view = view = page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
2719         if (view instanceof TaskList) {
2720           StructuredSelection ss = new StructuredSelection(marker);
2721           ((TaskList) view).setSelection(ss, true);
2722         }
2723       }
2724
2725       selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
2726 //      setStatusLineErrorMessage(nextError.getMessage());
2727
2728     } else {
2729
2730       setStatusLineErrorMessage(null);
2731
2732     }
2733   }
2734
2735   private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
2736
2737     IJavaAnnotation nextError = null;
2738     Position nextErrorPosition = null;
2739
2740     IDocument document = getDocumentProvider().getDocument(getEditorInput());
2741     int endOfDocument = document.getLength();
2742     int distance = 0;
2743
2744     IAnnotationModel model = getDocumentProvider().getAnnotationModel(getEditorInput());
2745     Iterator e = new JavaAnnotationIterator(model, false);
2746     while (e.hasNext()) {
2747
2748       IJavaAnnotation a = (IJavaAnnotation) e.next();
2749       if (a.hasOverlay() || !a.isProblem())
2750         continue;
2751
2752       Position p = model.getPosition((Annotation) a);
2753       if (!p.includes(offset)) {
2754
2755         int currentDistance = 0;
2756
2757         if (forward) {
2758           currentDistance = p.getOffset() - offset;
2759           if (currentDistance < 0)
2760             currentDistance = endOfDocument - offset + p.getOffset();
2761         } else {
2762           currentDistance = offset - p.getOffset();
2763           if (currentDistance < 0)
2764             currentDistance = offset + endOfDocument - p.getOffset();
2765         }
2766
2767         if (nextError == null || currentDistance < distance) {
2768           distance = currentDistance;
2769           nextError = a;
2770           nextErrorPosition = p;
2771         }
2772       }
2773     }
2774
2775     if (nextErrorPosition != null) {
2776       errorPosition.setOffset(nextErrorPosition.getOffset());
2777       errorPosition.setLength(nextErrorPosition.getLength());
2778     }
2779
2780     return nextError;
2781   }
2782   void removeOccurrenceAnnotations() {
2783         IDocumentProvider documentProvider= getDocumentProvider();
2784         if (documentProvider == null)
2785                 return;
2786         
2787         IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
2788         if (annotationModel == null || fOccurrenceAnnotations == null)
2789                 return;
2790
2791         synchronized (annotationModel) {
2792                 if (annotationModel instanceof IAnnotationModelExtension) {
2793                         ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
2794                 } else {
2795                         for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
2796                                 annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
2797                 }
2798                 fOccurrenceAnnotations= null;
2799         }
2800 }
2801 //  protected void uninstallOverrideIndicator() {
2802 //      if (fOverrideIndicatorManager != null) {
2803 //              fOverrideIndicatorManager.removeAnnotations();
2804 //              fOverrideIndicatorManager= null;
2805 //      }
2806 //}
2807
2808 protected void installOverrideIndicator(boolean waitForReconcilation) {
2809 //      uninstallOverrideIndicator();
2810         IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
2811 //      IJavaElement inputElement= getInputJavaElement();
2812
2813 //      if (model == null || inputElement == null)
2814 //              return;
2815
2816 //      CompilationUnit ast= PHPeclipsePlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
2817 //      fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);              
2818 }
2819
2820 /**
2821  * Tells whether override indicators are shown.
2822  * 
2823  * @return <code>true</code> if the override indicators are shown
2824  * @since 3.0
2825  */
2826 //protected boolean isShowingOverrideIndicators() {
2827 //      AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
2828 //      IPreferenceStore store= getPreferenceStore();
2829 //      return getBoolean(store, preference.getHighlightPreferenceKey())
2830 //              || getBoolean(store, preference.getVerticalRulerPreferenceKey())
2831 //              || getBoolean(store, preference.getOverviewRulerPreferenceKey())
2832 //              || getBoolean(store, preference.getTextPreferenceKey());
2833 //}
2834
2835 /**
2836  * Returns the boolean preference for the given key.
2837  * 
2838  * @param store the preference store
2839  * @param key the preference key
2840  * @return <code>true</code> if the key exists in the store and its value is <code>true</code>
2841  * @since 3.0
2842  */
2843 private boolean getBoolean(IPreferenceStore store, String key) {
2844         return key != null && store.getBoolean(key);
2845 }
2846
2847   /**
2848          * Returns the folding action group, or <code>null</code> if there is none.
2849          * 
2850          * @return the folding action group, or <code>null</code> if there is none
2851          * @since 3.0
2852          */
2853         protected FoldingActionGroup getFoldingActionGroup() {
2854                 return fFoldingGroup;
2855         }
2856 }