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 **********************************************************************/
11 package net.sourceforge.phpeclipse.phpeditor.php;
13 import java.io.IOException;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.SortedMap;
23 import net.sourceforge.phpdt.core.ICompilationUnit;
24 import net.sourceforge.phpdt.core.IJavaElement;
25 import net.sourceforge.phpdt.core.IMethod;
26 import net.sourceforge.phpdt.core.IType;
27 import net.sourceforge.phpdt.core.JavaCore;
28 import net.sourceforge.phpdt.core.ToolFactory;
29 import net.sourceforge.phpdt.core.compiler.ITerminalSymbols;
30 import net.sourceforge.phpdt.core.compiler.InvalidInputException;
31 import net.sourceforge.phpdt.internal.compiler.DefaultErrorHandlingPolicies;
32 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
33 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
34 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
35 import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
36 import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo;
37 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
38 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
39 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
40 import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType;
41 import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
42 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
43 import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator;
44 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
45 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
46 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
47 import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal;
48 import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine;
49 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
50 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
51 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
52 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
53 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
54 import net.sourceforge.phpeclipse.phpeditor.PHPSyntaxRdr;
56 import org.eclipse.core.resources.IFile;
57 import org.eclipse.core.resources.IProject;
58 import org.eclipse.jface.text.BadLocationException;
59 import org.eclipse.jface.text.IDocument;
60 import org.eclipse.jface.text.IRegion;
61 import org.eclipse.jface.text.ITextViewer;
62 import org.eclipse.jface.text.Region;
63 import org.eclipse.jface.text.contentassist.ICompletionProposal;
64 import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
65 import org.eclipse.jface.text.contentassist.IContextInformation;
66 import org.eclipse.jface.text.contentassist.IContextInformationExtension;
67 import org.eclipse.jface.text.contentassist.IContextInformationValidator;
68 import org.eclipse.jface.text.templates.TemplateContextType;
69 import org.eclipse.swt.graphics.Image;
70 import org.eclipse.swt.graphics.Point;
71 import org.eclipse.ui.IEditorPart;
72 import org.eclipse.ui.IFileEditorInput;
74 //import com.quantum.ExternalInterface;
75 // import com.quantum.util.connection.NotConnectedException;
78 * Example PHP completion processor.
80 public class PHPCompletionProcessor implements IContentAssistProcessor {
82 * Simple content assist tip closer. The tip is valid in a range of 5 characters around its popup location.
84 // protected static class Validator implements IContextInformationValidator, IContextInformationPresenter {
85 // protected int fInstallOffset;
88 // * @see IContextInformationValidator#isContextInformationValid(int)
90 // public boolean isContextInformationValid(int offset) {
91 // return Math.abs(fInstallOffset - offset) < 5;
95 // * @see IContextInformationValidator#install(IContextInformation, ITextViewer, int)
97 // public void install(IContextInformation info, ITextViewer viewer, int offset) {
98 // fInstallOffset = offset;
102 // * @see org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int, TextPresentation)
104 // public boolean updatePresentation(int documentPosition, TextPresentation presentation) {
109 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
110 private final IContextInformation fContextInformation;
112 private int fPosition;
114 public ContextInformationWrapper(IContextInformation contextInformation) {
115 fContextInformation = contextInformation;
119 * @see IContextInformation#getContextDisplayString()
121 public String getContextDisplayString() {
122 return fContextInformation.getContextDisplayString();
126 * @see IContextInformation#getImage()
128 public Image getImage() {
129 return fContextInformation.getImage();
133 * @see IContextInformation#getInformationDisplayString()
135 public String getInformationDisplayString() {
136 return fContextInformation.getInformationDisplayString();
140 * @see IContextInformationExtension#getContextInformationPosition()
142 public int getContextInformationPosition() {
146 public void setContextInformationPosition(int position) {
147 fPosition = position;
151 private class TableName {
159 * @return Returns the tableName.
161 public String getTableName() {
162 if (fTableName == null) {
163 return "<!--no-table-->";
170 * The tableName to set.
172 public void setTableName(String tableName) {
173 fTableName = tableName;
177 private char[] fProposalAutoActivationSet;
179 protected IContextInformationValidator fValidator = null;// = new Validator();
181 private TemplateEngine fTemplateEngine;
183 private PHPCompletionProposalComparator fComparator;
185 private int fNumberOfComputedResults = 0;
187 private IEditorPart fEditor;
189 protected IWorkingCopyManager fManager;
191 public PHPCompletionProcessor(IEditorPart editor) {
193 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
194 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
195 if (contextType != null)
196 fTemplateEngine = new TemplateEngine(contextType);
197 fComparator = new PHPCompletionProposalComparator();
201 * Tells this processor to order the proposals alphabetically.
204 * <code>true</code> if proposals should be ordered.
206 public void orderProposalsAlphabetically(boolean order) {
207 fComparator.setOrderAlphabetically(order);
211 * Sets this processor's set of characters triggering the activation of the completion proposal computation.
213 * @param activationSet
216 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
217 fProposalAutoActivationSet = activationSet;
221 * (non-Javadoc) Method declared on IContentAssistProcessor
223 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
224 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
225 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
228 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context, TableName tableName) {
229 IDocument document = viewer.getDocument();
230 int start = context.getStart();
231 int end = context.getEnd();
233 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
235 // begin search 2 lines behind of this
240 ch = document.getChar(j);
246 ch = document.getChar(j);
253 // scan the line for the dereferencing operator '->'
254 startText = document.get(j, start - j);
256 System.out.println(startText);
258 int token = ITerminalSymbols.TokenNameEOF;
259 // token = getLastSQLToken(startText);
260 tableName.setTableName(getLastSQLTableName(startText));
261 Scanner scanner = ToolFactory.createScanner(false, false, false);
262 scanner.setSource(startText.toCharArray());
263 scanner.setPHPMode(true);
264 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
265 int lastToken = ITerminalSymbols.TokenNameEOF;
268 token = scanner.getNextToken();
270 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
271 beforeLastToken = lastToken;
272 if (token == ITerminalSymbols.TokenNameVariable) {
273 ident = scanner.getCurrentTokenSource();
274 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
275 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
279 // System.out.println(scanner.toStringAction(lastToken));
280 token = scanner.getNextToken();
282 } catch (InvalidInputException e1) {
283 } catch (SyntaxError e) {
286 case ITerminalSymbols.TokenNameMINUS_GREATER:
287 // dereferencing operator '->' found
288 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
289 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
290 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
292 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
293 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
297 case ITerminalSymbols.TokenNamenew:
298 lastSignificantToken = ITerminalSymbols.TokenNamenew;
302 } catch (BadLocationException e) {
304 return lastSignificantToken;
307 String getSQLTableName(String sqlText, int start) {
308 int tableNameStart = -1;
309 int currentCharacterPosition = start + 1;
313 ch = sqlText.charAt(currentCharacterPosition++);
314 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
315 tableNameStart = currentCharacterPosition - 1;
317 if (!Scanner.isPHPIdentifierPart(ch)) {
318 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
322 } catch (IndexOutOfBoundsException e) {
323 if (tableNameStart >= 0) {
324 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
330 private String getLastSQLTableName(String startText) {
332 // scan for sql identifiers
334 int currentSQLPosition = startText.length();
337 boolean whiteSpace = true;
340 ch = startText.charAt(--currentSQLPosition);
341 if (Scanner.isSQLIdentifierPart(ch)) {
342 // if (ch >= 'A' && ch <= 'Z') {
344 identEnd = currentSQLPosition + 1;
346 // } else if (ch >= 'a' && ch <= 'z') {
347 // if (identEnd < 0) {
348 // identEnd = currentSQLPosition + 1;
350 } else if (identEnd >= 0) {
351 ident = startText.substring(currentSQLPosition + 1, identEnd);
352 // select -- from -- where --
353 // update -- set -- where --
354 // insert into -- ( -- ) values ( -- )
355 if (ident.length() >= 4 && ident.length() <= 6) {
356 ident = ident.toLowerCase();
357 switch (ident.length()) {
359 // if (ident.equals("set")) {
360 // // System.out.println("set");
361 // token = ITerminalSymbols.TokenNameSQLset;
366 if (ident.equals("from")) {
367 // System.out.println("from");
368 token = ITerminalSymbols.TokenNameSQLfrom;
369 return getSQLTableName(startText, identEnd);
370 } else if (ident.equals("into")) {
371 // System.out.println("into");
372 token = ITerminalSymbols.TokenNameSQLinto;
373 return getSQLTableName(startText, identEnd);
377 // if (ident.equals("where")) {
378 // // System.out.println("where");
379 // token = ITerminalSymbols.TokenNameSQLwhere;
384 // if (ident.equals("select")) {
385 // // System.out.println("select");
386 // token = ITerminalSymbols.TokenNameSQLselect;
388 // } else if (ident.equals("insert")) {
389 // // System.out.println("insert");
390 // token = ITerminalSymbols.TokenNameSQLinsert;
393 if (ident.equals("update")) {
394 // System.out.println("update");
395 token = ITerminalSymbols.TokenNameSQLupdate;
396 return getSQLTableName(startText, identEnd);
398 // else if (ident.equals("values")) {
399 // // System.out.println("values");
400 // token = ITerminalSymbols.TokenNameSQLvalues;
408 } else if (Character.isWhitespace(ch)) {
413 } catch (IndexOutOfBoundsException e) {
415 return "<!--no-table-->";
419 * Detect the last significant SQL token in the text before the completion
423 private int getLastSQLToken(String startText) {
425 // scan for sql identifiers
427 int currentSQLPosition = startText.length();
430 boolean whiteSpace = true;
433 ch = startText.charAt(--currentSQLPosition);
434 if (ch >= 'A' && ch <= 'Z') {
436 identEnd = currentSQLPosition + 1;
438 } else if (ch >= 'a' && ch <= 'z') {
440 identEnd = currentSQLPosition + 1;
442 } else if (identEnd >= 0) {
443 ident = startText.substring(currentSQLPosition + 1, identEnd);
444 // select -- from -- where --
445 // update -- set -- where --
446 // insert into -- ( -- ) values ( -- )
447 if (ident.length() >= 3 && ident.length() <= 6) {
448 ident = ident.toLowerCase();
449 switch (ident.length()) {
451 if (ident.equals("set")) {
452 // System.out.println("set");
453 token = ITerminalSymbols.TokenNameSQLset;
458 if (ident.equals("from")) {
459 // System.out.println("from");
460 token = ITerminalSymbols.TokenNameSQLfrom;
463 } else if (ident.equals("into")) {
464 // System.out.println("into");
465 token = ITerminalSymbols.TokenNameSQLinto;
470 if (ident.equals("where")) {
471 // System.out.println("where");
472 token = ITerminalSymbols.TokenNameSQLwhere;
477 if (ident.equals("select")) {
478 // System.out.println("select");
479 token = ITerminalSymbols.TokenNameSQLselect;
481 } else if (ident.equals("insert")) {
482 // System.out.println("insert");
483 token = ITerminalSymbols.TokenNameSQLinsert;
485 } else if (ident.equals("update")) {
486 // System.out.println("update");
487 token = ITerminalSymbols.TokenNameSQLupdate;
489 } else if (ident.equals("values")) {
490 // System.out.println("values");
491 token = ITerminalSymbols.TokenNameSQLvalues;
499 } else if (Character.isWhitespace(ch)) {
504 } catch (IndexOutOfBoundsException e) {
506 return ITerminalSymbols.TokenNameEOF;
509 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
510 ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput());
511 IDocument document = viewer.getDocument();
513 IProject project = null;
515 PHPEditor editor = null;
516 if (fEditor != null && (fEditor instanceof PHPEditor)) {
517 editor = (PHPEditor) fEditor;
518 file = ((IFileEditorInput) editor.getEditorInput()).getFile();
519 project = file.getProject();
523 Point selection = viewer.getSelectedRange();
524 // remember selected text
525 String selectedText = null;
526 if (selection.y != 0) {
528 selectedText = document.get(selection.x, selection.y);
529 } catch (BadLocationException e) {
533 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
534 "php"); //$NON-NLS-1$
535 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
536 context.setVariable("selection", selectedText); //$NON-NLS-1$
537 String prefix = context.getKey();
539 HashMap methodVariables = null;
540 HashMap typeVariables = null;
541 HashMap unitVariables = null;
542 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
543 // if (compilationUnit != null) {
544 // unitVariables = ((CompilationUnit) compilationUnit).variables;
546 IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
547 // if (type != null) {
548 // typeVariables = ((SourceType) type).variables;
550 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
551 // if (method != null) {
552 // methodVariables = ((SourceMethod) method).variables;
555 boolean emptyPrefix = prefix == null || prefix.equals("");
556 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
558 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') { // php Variable ?
559 String lowerCasePrefix = prefix.toLowerCase();
560 HashSet localVariables = new HashSet();
561 if (compilationUnit != null) {
562 unitVariables = getUnitVariables(unitVariables, compilationUnit);
563 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
565 if (method != null) {
566 methodVariables = getMethodVariables(methodVariables, method);
567 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
569 if (!localVariables.isEmpty()) {
570 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
574 TableName sqlTable = new TableName();
575 ArrayList list = new ArrayList();
577 int lastSignificantToken = getLastToken(list, viewer, offset, context, sqlTable);
578 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
579 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
580 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
582 if (fTemplateEngine != null) {
583 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
584 ICompletionProposal[] results;
586 fTemplateEngine.reset();
587 fTemplateEngine.complete(viewer, offset, unit);
588 templateResults = fTemplateEngine.getResults();
591 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
593 // declarations stored in file project.index on project level
594 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
595 if (project != null) {
596 DeclarationEngine declarationEngine;
597 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
598 "php"); //$NON-NLS-1$
599 if (contextType != null) {
600 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
602 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
603 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
604 // complete '$this->'
605 sortedMap = indexManager.getIdentifiers(file);
606 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
608 String typeRef = null;
609 char[] varName = (char[]) list.get(0);
610 if (varName != null) {
611 if (method != null) {
612 methodVariables = getMethodVariables(methodVariables, method);
613 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
614 if (info != null && info.typeIdentifier != null) {
615 typeRef = new String(info.typeIdentifier);
620 if (typeRef != null) {
621 // complete '$variable->' with type information
622 sortedMap = indexManager.getIdentifiers(typeRef);
623 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
625 // complete '$variable->' without type information
626 sortedMap = indexManager.getIdentifierMap();
627 declarationEngine.complete(viewer, offset, sortedMap, unit);
630 declarationResults = declarationEngine.getResults();
633 // built in function names from phpsyntax.xml
634 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
635 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
636 if ((!useClassMembers) && syntaxbuffer != null) {
637 BuiltInEngine builtinEngine;
639 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
640 "php"); //$NON-NLS-1$
641 if (contextType != null) {
642 builtinEngine = new BuiltInEngine(contextType);
643 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
644 builtinResults = builtinEngine.getResults();
647 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
648 // if (project != null) {
649 // sqlResults = getSQLProposals(viewer, project, context, prefix, sqlTable);
651 // concatenate the result arrays
652 IPHPCompletionProposal[] total;
653 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
654 + builtinResults.length + declarationResults.length];// + sqlResults.length];
655 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
656 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
657 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
658 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
659 declarationResults.length);
660 // System.arraycopy(sqlResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
661 // + declarationResults.length, sqlResults.length);
662 // System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
663 // + declarationResults.length + sqlResults.length, localVariableResults.length);
664 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
665 + declarationResults.length, localVariableResults.length);
667 fNumberOfComputedResults = (results == null ? 0 : results.length);
669 * Order here and not in result collector to make sure that the order applies to all proposals and not just those of the
672 return order(results);
674 return new IPHPCompletionProposal[0];
678 * @param unitVariables
681 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
682 if (unitVariables == null) {
684 String unitText = unit.getSource();
685 unitVariables = new HashMap();
687 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
688 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
689 UnitParser parser = new UnitParser(problemReporter);
690 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
691 parser.parse(unitText, unitVariables);
693 } catch (Exception e) {
694 // TODO Auto-generated catch block
696 PHPeclipsePlugin.log(e);
699 return unitVariables;
703 * @param methodVariables
706 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
707 if (methodVariables == null) {
709 String methodText = method.getSource();
710 methodVariables = new HashMap();
711 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
712 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
713 UnitParser parser = new UnitParser(problemReporter);
714 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
715 parser.parseFunction(methodText, methodVariables);
716 } catch (Exception e) {
717 // TODO Auto-generated catch block
719 PHPeclipsePlugin.log(e);
722 return methodVariables;
732 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
733 HashMap variables, String prefix, int relevance) {
735 int start = context.getStart();
736 int end = context.getEnd();
737 IRegion region = new Region(start, end - start);
738 // IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
739 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod) method).variables != null) {
740 // HashMap map = ((SourceMethod) method).variables;
741 Set set = variables.keySet();
742 Iterator iter = set.iterator();
744 boolean matchesVarName;
745 while (iter.hasNext()) {
746 varName = (String) iter.next();
747 if (varName.length() >= prefix.length()) {
748 matchesVarName = true;
749 for (int i = 0; i < prefix.length(); i++) {
750 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
751 matchesVarName = false;
755 if (matchesVarName) {
756 LocalVariableProposal prop;
757 // if (varName.length == prefix.length()) {
758 // prop = new LocalVariableProposal(new String(varName), region, viewer, relevance-10);
760 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
762 localVariables.add(prop);
769 // boolean matchesVarName;
770 // if (method != null) {
771 // ISourceRange range = method.getSourceRange();
772 // char[] source = method.getSource().toCharArray();
773 // Scanner scanner = new Scanner();
774 // scanner.setSource(source);
775 // scanner.phpMode = true;
776 // int token = Scanner.TokenNameWHITESPACE;
777 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
778 // if (token == Scanner.TokenNameVariable) {
779 // varName = scanner.getCurrentTokenSource();
780 // if (varName.length >= prefix.length()) {
781 // matchesVarName = true;
782 // for (int i = 0; i < prefix.length(); i++) {
783 // if (prefix.charAt(i) != varName[i]) {
784 // matchesVarName = false;
788 // if (matchesVarName) {
789 // LocalVariableProposal prop = new LocalVariableProposal(new String(varName), region, viewer);
790 // if (varName.length == prefix.length()) {
791 // prop.setRelevance(98);
793 // localVariables.add(prop);
799 // } catch (Throwable e) {
800 // // ignore - Syntax exceptions could occur, if there are syntax errors !
813 // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject project, DocumentTemplateContext context,
814 // String prefix, TableName sqlTable) {
815 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
816 // // Get The Database bookmark from the Quantum SQL plugin:
817 // // BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
818 // // if (sqlBookMarks != null) {
819 // String bookmarkString = ProjectPrefUtil.getMiscProjectsPreferenceValue(project, IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
820 // if (bookmarkString != null && !bookmarkString.equals("")) {
821 // String[] bookmarks = ExternalInterface.getBookmarkNames();
822 // boolean foundBookmark = false;
823 // for (int i = 0; i < bookmarks.length; i++) {
824 // if (bookmarks[i].equals(bookmarkString)) {
825 // foundBookmark = true;
828 // if (!foundBookmark) {
829 // return sqlResults;
831 // // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
832 // ArrayList sqlList = new ArrayList();
833 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
834 // ExternalInterface.connectBookmark(bookmarkString, null);
835 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
836 // return sqlResults;
839 // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
841 // int start = context.getStart();
842 // int end = context.getEnd();
843 // String foundSQLTableName = sqlTable.getTableName();
845 // String columnName;
846 // String prefixWithoutDollar = prefix;
847 // boolean isDollarPrefix = false;
848 // if (prefix.length() > 0 && prefix.charAt(0) == '$') {
849 // prefixWithoutDollar = prefix.substring(1);
850 // isDollarPrefix = true;
852 // IRegion region = new Region(start, end - start);
854 // if (!isDollarPrefix) {
855 // String[] tableNames = ExternalInterface.getMatchingTableNames(null, bookmarkString, prefixWithoutDollar, null, false);
856 // for (int i = 0; i < tableNames.length; i++) {
857 // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
861 // String[] columnNames = ExternalInterface.getMatchingColumnNames(null, bookmarkString, prefixWithoutDollar, null, false);
862 // for (int i = 0; i < columnNames.length; i++) {
863 // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer, PHPUiImages.get(PHPUiImages.IMG_TABLE)));
866 // sqlResults = new IPHPCompletionProposal[sqlList.size()];
867 // for (int i = 0; i < sqlList.size(); i++) {
868 // sqlResults[i] = (SQLProposal) sqlList.get(i);
870 // } catch (Exception /* NotConnectedException */ e) {
876 // return sqlResults;
879 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
880 int curr = reader.read();
881 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
882 curr = reader.read();
884 if (curr == PHPCodeReader.EOF)
887 return Scanner.isPHPIdentifierPart((char) curr);
890 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
891 int contextPosition = offset;
892 IDocument document = viewer.getDocument();
895 PHPCodeReader reader = new PHPCodeReader();
896 reader.configureBackwardReader(document, offset, true, true);
898 int nestingLevel = 0;
900 int curr = reader.read();
901 while (curr != PHPCodeReader.EOF) {
903 if (')' == (char) curr)
906 else if ('(' == (char) curr) {
909 if (nestingLevel < 0) {
910 int start = reader.getOffset();
911 if (looksLikeMethod(reader))
916 curr = reader.read();
918 } catch (IOException e) {
920 return contextPosition;
924 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
926 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
927 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
928 List result = addContextInformations(viewer, contextInformationPosition);
929 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
932 private List addContextInformations(ITextViewer viewer, int offset) {
933 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
934 List result = new ArrayList();
935 for (int i = 0; i < proposals.length; i++) {
936 IContextInformation contextInformation = proposals[i].getContextInformation();
937 if (contextInformation != null) {
938 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
939 wrapper.setContextInformationPosition(offset);
947 * Order the given proposals.
949 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
950 Arrays.sort(proposals, fComparator);
951 // int len = proposals.length;
955 // for (int i = 0; i < len; i++) {
956 // System.out.println(proposals[i].getDisplayString());
962 * (non-Javadoc) Method declared on IContentAssistProcessor
964 public char[] getCompletionProposalAutoActivationCharacters() {
965 return fProposalAutoActivationSet;
966 // return null; // new char[] { '$' };
970 * (non-Javadoc) Method declared on IContentAssistProcessor
972 public char[] getContextInformationAutoActivationCharacters() {
977 * (non-Javadoc) Method declared on IContentAssistProcessor
979 public IContextInformationValidator getContextInformationValidator() {
980 if (fValidator == null)
981 fValidator= new JavaParameterListValidator();
986 * (non-Javadoc) Method declared on IContentAssistProcessor
988 public String getErrorMessage() {