1 /**********************************************************************
2 Copyright (c) 2000, 2002 IBM Corp. and others.
3 All rights reserved. This program and the accompanying materials
4 are made available under the terms of the Common Public License v1.0
5 which accompanies this distribution, and is available at
6 http://www.eclipse.org/legal/cpl-v10.html
9 IBM Corporation - Initial implementation
10 Klaus Hartlage - www.eclipseproject.de
11 **********************************************************************/
12 package net.sourceforge.phpeclipse.phpeditor.php;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.List;
17 import java.util.SortedMap;
19 import net.sourceforge.phpdt.core.ToolFactory;
20 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
21 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
22 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
23 import net.sourceforge.phpdt.internal.corext.template.ContextType;
24 import net.sourceforge.phpdt.internal.corext.template.ContextTypeRegistry;
25 import net.sourceforge.phpdt.internal.corext.template.php.CompilationUnitContextType;
26 import net.sourceforge.phpdt.internal.corext.template.php.PHPUnitContext;
27 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
28 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
29 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
30 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
31 import net.sourceforge.phpdt.internal.ui.text.template.IdentifierEngine;
32 import net.sourceforge.phpdt.internal.ui.text.template.TemplateEngine;
33 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
34 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
35 import net.sourceforge.phpeclipse.phpeditor.AbstractContentOutlinePage;
36 import net.sourceforge.phpeclipse.phpeditor.PHPContentOutlinePage;
37 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
38 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
40 import org.eclipse.core.resources.IFile;
41 import org.eclipse.core.resources.IProject;
42 import org.eclipse.jface.text.BadLocationException;
43 import org.eclipse.jface.text.IDocument;
44 import org.eclipse.jface.text.IRegion;
45 import org.eclipse.jface.text.ITextViewer;
46 import org.eclipse.jface.text.Region;
47 import org.eclipse.jface.text.TextPresentation;
48 import org.eclipse.jface.text.contentassist.ICompletionProposal;
49 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
50 import org.eclipse.jface.text.contentassist.IContextInformation;
51 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
52 import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
53 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
54 import org.eclipse.swt.graphics.Image;
55 import org.eclipse.ui.IEditorPart;
56 import org.eclipse.ui.IFileEditorInput;
59 * Example PHP completion processor.
61 public class PHPCompletionProcessor implements IContentAssistProcessor {
64 * Simple content assist tip closer. The tip is valid in a range
65 * of 5 characters around its popup location.
67 protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
69 protected int fInstallOffset;
72 * @see IContextInformationValidator#isContextInformationValid(int)
74 public boolean isContextInformationValid(int offset) {
75 return Math.abs(fInstallOffset - offset) < 5;
79 * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
81 public void install(IContextInformation info, ITextViewer viewer, int offset) {
82 fInstallOffset = offset;
86 * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
88 public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
93 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
95 private final IContextInformation fContextInformation;
96 private int fPosition;
98 public ContextInformationWrapper(IContextInformation contextInformation) {
99 fContextInformation = contextInformation;
103 * @see IContextInformation#getContextDisplayString()
105 public String getContextDisplayString() {
106 return fContextInformation.getContextDisplayString();
110 * @see IContextInformation#getImage()
112 public Image getImage() {
113 return fContextInformation.getImage();
117 * @see IContextInformation#getInformationDisplayString()
119 public String getInformationDisplayString() {
120 return fContextInformation.getInformationDisplayString();
124 * @see IContextInformationExtension#getContextInformationPosition()
126 public int getContextInformationPosition() {
130 public void setContextInformationPosition(int position) {
131 fPosition = position;
135 // public final class VariablesCompletionProposal implements IJavaCompletionProposal {
136 // private String fDisplayString;
137 // private String fReplacementString;
138 // private int fReplacementOffset;
139 // private int fReplacementLength;
140 // private int fCursorPosition;
141 // private Image fImage;
142 // private IContextInformation fContextInformation;
143 // private String fAdditionalProposalInfo;
146 // * Creates a new completion proposal based on the provided information. The replacement string is
147 // * considered being the display string too. All remaining fields are set to <code>null</code>.
149 // * @param replacementString the actual string to be inserted into the document
150 // * @param replacementOffset the offset of the text to be replaced
151 // * @param replacementLength the length of the text to be replaced
152 // * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
154 // public VariablesCompletionProposal(
155 // String replacementString,
156 // int replacementOffset,
157 // int replacementLength,
158 // int cursorPosition) {
159 // this(replacementString, replacementOffset, replacementLength, cursorPosition, null, null, null, null);
163 // * Creates a new completion proposal. All fields are initialized based on the provided information.
165 // * @param replacementString the actual string to be inserted into the document
166 // * @param replacementOffset the offset of the text to be replaced
167 // * @param replacementLength the length of the text to be replaced
168 // * @param cursorPosition the position of the cursor following the insert relative to replacementOffset
169 // * @param image the image to display for this proposal
170 // * @param displayString the string to be displayed for the proposal
171 // * @param contentInformation the context information associated with this proposal
172 // * @param additionalProposalInfo the additional information associated with this proposal
174 // public VariablesCompletionProposal(
175 // String replacementString,
176 // int replacementOffset,
177 // int replacementLength,
178 // int cursorPosition,
180 // String displayString,
181 // IContextInformation contextInformation,
182 // String additionalProposalInfo) {
183 // // Assert.isNotNull(replacementString);
184 // // Assert.isTrue(replacementOffset >= 0);
185 // // Assert.isTrue(replacementLength >= 0);
186 // // Assert.isTrue(cursorPosition >= 0);
188 // fReplacementString = replacementString;
189 // fReplacementOffset = replacementOffset;
190 // fReplacementLength = replacementLength;
191 // fCursorPosition = cursorPosition;
193 // fDisplayString = displayString;
194 // fContextInformation = contextInformation;
195 // fAdditionalProposalInfo = additionalProposalInfo;
199 // * @see ICompletionProposal#apply
201 // public void apply(IDocument document) {
203 // document.replace(fReplacementOffset, fReplacementLength, fReplacementString);
204 // } catch (BadLocationException x) {
210 // * @see ICompletionProposal#getSelection
212 // public Point getSelection(IDocument document) {
213 // return new Point(fReplacementOffset + fCursorPosition, 0);
217 // * @see ICompletionProposal#getContextInformation()
219 // public IContextInformation getContextInformation() {
220 // return fContextInformation;
224 // * @see ICompletionProposal#getImage()
226 // public Image getImage() {
231 // * @see ICompletionProposal#getDisplayString()
233 // public String getDisplayString() {
234 // if (fDisplayString != null)
235 // return fDisplayString;
236 // return fReplacementString;
240 // * @see ICompletionProposal#getAdditionalProposalInfo()
242 // public String getAdditionalProposalInfo() {
243 // return fAdditionalProposalInfo;
246 // * Returns the relevance of the proposal.
248 // public int getRelevance() {
253 // protected final static String[] fgProposals = PHPFunctionNames.FUNCTION_NAMES;
255 private char[] fProposalAutoActivationSet;
256 protected IContextInformationValidator fValidator = new Validator();
257 private TemplateEngine fTemplateEngine;
258 private PHPCompletionProposalComparator fComparator;
259 private int fNumberOfComputedResults = 0;
261 public PHPCompletionProcessor() {
263 ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
264 if (contextType != null)
265 fTemplateEngine = new TemplateEngine(contextType);
267 fComparator = new PHPCompletionProposalComparator();
271 * Tells this processor to order the proposals alphabetically.
273 * @param order <code>true</code> if proposals should be ordered.
275 public void orderProposalsAlphabetically(boolean order) {
276 fComparator.setOrderAlphabetically(order);
280 * Sets this processor's set of characters triggering the activation of the
281 * completion proposal computation.
283 * @param activationSet the activation set
285 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
286 fProposalAutoActivationSet = activationSet;
289 * Method declared on IContentAssistProcessor
291 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
292 // IDocument document = viewer.getDocument();
293 // if (documentOffset > 0) {
295 // ICompletionProposal[] result;
296 // char character = document.getChar(documentOffset - 1);
297 // if (character == '$') {
298 ////viewer. .getActivePage().getActiveEditor();
299 // result = new ICompletionProposal[fgProposals.length];
300 // for (int i = 0; i < fgProposals.length; i++) {
301 // IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
302 // result[i] = new CompletionProposal(fgProposals[i], documentOffset, 0, fgProposals[i].length(), null, fgProposals[i], info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
306 // } catch (BadLocationException e) {
307 // return new ICompletionProposal[0];
311 // ICompletionProposal[] result = new ICompletionProposal[fgProposals.length];
312 // for (int i = 0; i < fgProposals.length; i++) {
313 // IContextInformation info = new ContextInformation(fgProposals[i], MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
314 // result[i] = new CompletionProposal(fgProposals[i], documentOffset, 0, fgProposals[i].length(), null, fgProposals[i], info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { fgProposals[i] })); //$NON-NLS-1$
317 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
318 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
322 private boolean isReference(ITextViewer viewer, int completionPosition) {
323 IDocument document = viewer.getDocument();
324 ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
325 ((CompilationUnitContextType) contextType).setContextParameters(document, completionPosition, 0);
327 PHPUnitContext context = (PHPUnitContext) contextType.createContext();
328 int start = context.getStart();
329 int end = context.getEnd();
330 String prefix = context.getKey();
331 IRegion region = new Region(start, end - start);
334 boolean useClassEntries = false;
336 // search begin of 2 lines behind this
341 ch = document.getChar(j);
347 ch = document.getChar(j);
354 // scan the line for the dereferencing operator '->'
355 startText = document.get(j, start - j);
356 // System.out.println(startText);
357 Scanner scanner = ToolFactory.createScanner(false, false, false);
358 scanner.setSource(startText.toCharArray());
359 scanner.setPHPMode(true);
360 int token = ITerminalSymbols.TokenNameEOF;
361 int lastToken = ITerminalSymbols.TokenNameEOF;
364 token = scanner.getNextToken();
366 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
368 // System.out.println(scanner.toStringAction(lastToken));
369 token = scanner.getNextToken();
371 } catch (InvalidInputException e1) {
373 if (lastToken == ITerminalSymbols.TokenNameMINUS_GREATER) {
374 // dereferencing operator '->' found
375 useClassEntries = true;
376 // System.out.println("useClassEntries = true");
379 } catch (BadLocationException e) {
381 return useClassEntries;
384 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
385 IDocument document = viewer.getDocument();
386 Object[] identifiers = null;
387 IProject project = null;
390 PHPEditor editor = null;
391 AbstractContentOutlinePage outlinePage = null;
393 IEditorPart targetEditor = PHPeclipsePlugin.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
394 if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
395 editor = (PHPEditor) targetEditor;
396 IFile f = ((IFileEditorInput) editor.getEditorInput()).getFile();
397 project = f.getProject();
398 outlinePage = editor.getfOutlinePage();
399 if (outlinePage instanceof PHPContentOutlinePage) {
400 identifiers = ((PHPContentOutlinePage) outlinePage).getVariables();
405 if (fTemplateEngine != null) {
406 ICompletionProposal[] results;
408 fTemplateEngine.reset();
409 fTemplateEngine.complete(viewer, offset); //, unit);
410 // } catch (JavaModelException x) {
411 // Shell shell= viewer.getTextWidget().getShell();
412 // ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$
415 IPHPCompletionProposal[] templateResults = fTemplateEngine.getResults();
417 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
418 if (identifiers != null) {
419 IdentifierEngine identifierEngine;
422 // for (int i = templateResults.length; i < templateResults.length + variables.length; i++) {
423 // proposal = (String) variables[j++];
424 // IContextInformation info = new ContextInformation(proposal, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.ContextInfo.pattern"), new Object[] { proposal })); //$NON-NLS-1$
425 // results[i] = new VariablesCompletionProposal(proposal, offset, 0, proposal.length(), null, proposal, info, MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.Proposal.hoverinfo.pattern"), new Object[] { proposal })); //$NON-NLS-1$
428 ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
429 if (contextType != null) {
430 identifierEngine = new IdentifierEngine(contextType);
431 identifierEngine.complete(viewer, offset, identifiers);
432 identifierResults = identifierEngine.getResults();
436 boolean useClassEntries = isReference(viewer, offset);
437 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
438 if (project != null) {
439 DeclarationEngine identifierEngine;
442 ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
443 if (contextType != null) {
444 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
445 SortedMap sortedMap = indexManager.getIdentifierMap();
447 identifierEngine = new DeclarationEngine(contextType, useClassEntries);
448 identifierEngine.complete(viewer, offset, sortedMap);
449 identifierResults = identifierEngine.getResults();
453 // built in function names from phpsyntax.xml
454 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
455 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
456 if ((!useClassEntries)&&syntaxbuffer != null) {
457 BuiltInEngine builtinEngine;
460 ContextType contextType = ContextTypeRegistry.getInstance().getContextType("php"); //$NON-NLS-1$
461 if (contextType != null) {
462 builtinEngine = new BuiltInEngine(contextType);
463 builtinEngine.complete(viewer, offset, syntaxbuffer);
464 builtinResults = builtinEngine.getResults();
468 // concatenate arrays
469 IPHPCompletionProposal[] total;
471 new IPHPCompletionProposal[templateResults.length
472 + identifierResults.length
473 + builtinResults.length
474 + declarationResults.length];
475 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
476 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
477 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
482 templateResults.length + identifierResults.length + builtinResults.length,
483 declarationResults.length);
487 fNumberOfComputedResults = (results == null ? 0 : results.length);
489 * Order here and not in result collector to make sure that the order
490 * applies to all proposals and not just those of the compilation unit.
492 return order(results);
494 return new IPHPCompletionProposal[0];
497 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
498 int contextPosition = offset;
500 IDocument document = viewer.getDocument();
504 // PHPCodeReader reader= new PHPCodeReader();
505 // reader.configureBackwardReader(document, offset, true, true);
507 // int nestingLevel= 0;
509 // int curr= reader.read();
510 // while (curr != PHPCodeReader.EOF) {
512 // if (')' == (char) curr)
515 // else if ('(' == (char) curr) {
518 // if (nestingLevel < 0) {
519 // int start= reader.getOffset();
520 // if (looksLikeMethod(reader))
525 // curr= reader.read();
527 // } catch (IOException e) {
530 return contextPosition;
534 * Method declared on IContentAssistProcessor
536 // public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
537 // IContextInformation[] result = new IContextInformation[5];
538 // for (int i = 0; i < result.length; i++)
539 // result[i] = new ContextInformation(MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.display.pattern"), new Object[] { new Integer(i), new Integer(documentOffset)}), //$NON-NLS-1$
540 // MessageFormat.format(PHPEditorMessages.getString("CompletionProcessor.ContextInfo.value.pattern"), new Object[] { new Integer(i), new Integer(documentOffset - 5), new Integer(documentOffset + 5)})); //$NON-NLS-1$
544 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
546 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
547 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
548 List result = addContextInformations(viewer, contextInformationPosition);
549 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
552 private List addContextInformations(ITextViewer viewer, int offset) {
553 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
555 List result = new ArrayList();
556 for (int i = 0; i < proposals.length; i++) {
557 IContextInformation contextInformation = proposals[i].getContextInformation();
558 if (contextInformation != null) {
559 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
560 wrapper.setContextInformationPosition(offset);
568 * Order the given proposals.
570 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
571 Arrays.sort(proposals, fComparator);
576 * Method declared on IContentAssistProcessor
578 public char[] getCompletionProposalAutoActivationCharacters() {
579 return fProposalAutoActivationSet;
580 // return null; // new char[] { '$' };
584 * Method declared on IContentAssistProcessor
586 public char[] getContextInformationAutoActivationCharacters() {
592 * Method declared on IContentAssistProcessor
594 public IContextInformationValidator getContextInformationValidator() {
599 * Method declared on IContentAssistProcessor
601 public String getErrorMessage() {