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.ast.CompilationUnitDeclaration;
33 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
34 import net.sourceforge.phpdt.internal.compiler.parser.Scanner;
35 import net.sourceforge.phpdt.internal.compiler.parser.SyntaxError;
36 import net.sourceforge.phpdt.internal.compiler.parser.UnitParser;
37 import net.sourceforge.phpdt.internal.compiler.parser.VariableInfo;
38 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
39 import net.sourceforge.phpdt.internal.compiler.problem.ProblemReporter;
40 import net.sourceforge.phpdt.internal.corext.template.php.JavaContext;
41 import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType;
42 import net.sourceforge.phpdt.internal.ui.text.PHPCodeReader;
43 import net.sourceforge.phpdt.internal.ui.text.java.IPHPCompletionProposal;
44 import net.sourceforge.phpdt.internal.ui.text.java.JavaParameterListValidator;
45 import net.sourceforge.phpdt.internal.ui.text.java.PHPCompletionProposalComparator;
46 import net.sourceforge.phpdt.internal.ui.text.template.BuiltInEngine;
47 import net.sourceforge.phpdt.internal.ui.text.template.DeclarationEngine;
48 import net.sourceforge.phpdt.internal.ui.text.template.LocalVariableProposal;
49 import net.sourceforge.phpdt.internal.ui.text.template.contentassist.TemplateEngine;
50 import net.sourceforge.phpdt.ui.IWorkingCopyManager;
51 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
52 import net.sourceforge.phpeclipse.builder.IdentifierIndexManager;
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;
75 * Example PHP completion processor.
77 public class PHPCompletionProcessor implements IContentAssistProcessor {
79 * Simple content assist tip closer. The tip is valid in a range of 5
80 * characters around its popup location.
82 // protected static class Validator implements IContextInformationValidator,
83 // IContextInformationPresenter {
84 // protected int fInstallOffset;
87 // * @see IContextInformationValidator#isContextInformationValid(int)
89 // public boolean isContextInformationValid(int offset) {
90 // return Math.abs(fInstallOffset - offset) < 5;
94 // * @see IContextInformationValidator#install(IContextInformation,
97 // public void install(IContextInformation info, ITextViewer viewer, int
99 // fInstallOffset = offset;
104 // org.eclipse.jface.text.contentassist.IContextInformationPresenter#updatePresentation(int,
107 // public boolean updatePresentation(int documentPosition, TextPresentation
112 private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
113 private final IContextInformation fContextInformation;
115 private int fPosition;
117 public ContextInformationWrapper(IContextInformation contextInformation) {
118 fContextInformation = contextInformation;
122 * @see IContextInformation#getContextDisplayString()
124 public String getContextDisplayString() {
125 return fContextInformation.getContextDisplayString();
129 * @see IContextInformation#getImage()
131 public Image getImage() {
132 return fContextInformation.getImage();
136 * @see IContextInformation#getInformationDisplayString()
138 public String getInformationDisplayString() {
139 return fContextInformation.getInformationDisplayString();
143 * @see IContextInformationExtension#getContextInformationPosition()
145 public int getContextInformationPosition() {
149 public void setContextInformationPosition(int position) {
150 fPosition = position;
154 // private class TableName {
155 // String fTableName;
158 // fTableName = null;
162 // * @return Returns the tableName.
164 // public String getTableName() {
165 // if (fTableName == null) {
166 // return "<!--no-table-->";
168 // return fTableName;
172 // * @param tableName
173 // * The tableName to set.
175 // public void setTableName(String tableName) {
176 // fTableName = tableName;
180 private char[] fProposalAutoActivationSet;
182 protected IContextInformationValidator fValidator = null;
184 private TemplateEngine fTemplateEngine;
186 private PHPCompletionProposalComparator fComparator;
188 private IEditorPart fEditor;
190 protected IWorkingCopyManager fManager;
192 public PHPCompletionProcessor(IEditorPart editor) {
194 fManager = PHPeclipsePlugin.getDefault().getWorkingCopyManager();
195 TemplateContextType contextType = PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType("php"); //$NON-NLS-1$
196 if (contextType != null)
197 fTemplateEngine = new TemplateEngine(contextType);
198 fComparator = new PHPCompletionProposalComparator();
202 * Tells this processor to order the proposals alphabetically.
205 * <code>true</code> if proposals should be ordered.
207 public void orderProposalsAlphabetically(boolean order) {
208 fComparator.setOrderAlphabetically(order);
212 * Sets this processor's set of characters triggering the activation of the
213 * completion proposal computation.
215 * @param activationSet
218 public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
219 fProposalAutoActivationSet = activationSet;
223 * (non-Javadoc) Method declared on IContentAssistProcessor
225 public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
226 int contextInformationPosition = guessContextInformationPosition(viewer, documentOffset);
227 return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition);
230 private int getLastToken(List list, ITextViewer viewer, int completionPosition, JavaContext context) {
231 // TableName tableName) {
232 IDocument document = viewer.getDocument();
233 int start = context.getStart();
234 // int end = context.getEnd();
236 int lastSignificantToken = ITerminalSymbols.TokenNameEOF;
238 // begin search 2 lines behind of this
243 ch = document.getChar(j);
249 ch = document.getChar(j);
256 // scan the line for the dereferencing operator '->'
257 startText = document.get(j, start - j);
259 System.out.println(startText);
261 int token = ITerminalSymbols.TokenNameEOF;
262 // token = getLastSQLToken(startText);
263 // tableName.setTableName(getLastSQLTableName(startText));
264 Scanner scanner = ToolFactory.createScanner(false, false, false);
265 scanner.setSource(startText.toCharArray());
266 scanner.setPHPMode(true);
267 int beforeLastToken = ITerminalSymbols.TokenNameEOF;
268 int lastToken = ITerminalSymbols.TokenNameEOF;
271 token = scanner.getNextToken();
273 while (token != ITerminalSymbols.TokenNameERROR && token != ITerminalSymbols.TokenNameEOF) {
274 beforeLastToken = lastToken;
275 if (token == ITerminalSymbols.TokenNameVariable) {
276 ident = scanner.getCurrentTokenSource();
277 if (ident.length == 5 && ident[0] == '$' && ident[1] == 't' && ident[2] == 'h' && ident[3] == 'i' && ident[4] == 's') {
278 token = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
282 // System.out.println(scanner.toStringAction(lastToken));
283 token = scanner.getNextToken();
285 } catch (InvalidInputException e1) {
286 } catch (SyntaxError e) {
289 case ITerminalSymbols.TokenNameMINUS_GREATER:
290 // dereferencing operator '->' found
291 lastSignificantToken = ITerminalSymbols.TokenNameMINUS_GREATER;
292 if (beforeLastToken == ITerminalSymbols.TokenNameVariable) {
293 lastSignificantToken = ITerminalSymbols.TokenNameVariable;
295 } else if (beforeLastToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
296 lastSignificantToken = ITerminalSymbols.TokenNamethis_PHP_COMPLETION;
300 case ITerminalSymbols.TokenNamenew:
301 lastSignificantToken = ITerminalSymbols.TokenNamenew;
305 } catch (BadLocationException e) {
307 return lastSignificantToken;
310 String getSQLTableName(String sqlText, int start) {
311 int tableNameStart = -1;
312 int currentCharacterPosition = start + 1;
316 ch = sqlText.charAt(currentCharacterPosition++);
317 if (tableNameStart == -1 && Scanner.isPHPIdentifierStart(ch)) {
318 tableNameStart = currentCharacterPosition - 1;
320 if (!Scanner.isPHPIdentifierPart(ch)) {
321 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
325 } catch (IndexOutOfBoundsException e) {
326 if (tableNameStart >= 0) {
327 return sqlText.substring(tableNameStart, currentCharacterPosition - 1);
333 // private String getLastSQLTableName(String startText) {
334 // // scan for sql identifiers
336 // int currentSQLPosition = startText.length();
337 // int identEnd = -1;
338 // String ident = null;
341 // ch = startText.charAt(--currentSQLPosition);
342 // if (Scanner.isSQLIdentifierPart(ch)) {
343 // // if (ch >= 'A' && ch <= 'Z') {
344 // if (identEnd < 0) {
345 // identEnd = currentSQLPosition + 1;
347 // // } else if (ch >= 'a' && ch <= 'z') {
348 // // if (identEnd < 0) {
349 // // identEnd = currentSQLPosition + 1;
351 // } else if (identEnd >= 0) {
352 // ident = startText.substring(currentSQLPosition + 1, identEnd);
353 // // select -- from -- where --
354 // // update -- set -- where --
355 // // insert into -- ( -- ) values ( -- )
356 // if (ident.length() >= 4 && ident.length() <= 6) {
357 // ident = ident.toLowerCase();
358 // switch (ident.length()) {
360 // // if (ident.equals("set")) {
361 // // // System.out.println("set");
362 // // token = ITerminalSymbols.TokenNameSQLset;
367 // if (ident.equals("from")) {
368 // // System.out.println("from");
369 // return getSQLTableName(startText, identEnd);
370 // } else if (ident.equals("into")) {
371 // // System.out.println("into");
372 // return getSQLTableName(startText, identEnd);
376 // if (ident.equals("update")) {
377 // // System.out.println("update");
378 // return getSQLTableName(startText, identEnd);
384 // } else if (Character.isWhitespace(ch)) {
387 // } catch (IndexOutOfBoundsException e) {
389 // return "<!--no-table-->";
393 * Detect the last significant SQL token in the text before the completion
397 // private int getLastSQLToken(String startText) {
399 // // scan for sql identifiers
401 // int currentSQLPosition = startText.length();
402 // int identEnd = -1;
403 // String ident = null;
406 // ch = startText.charAt(--currentSQLPosition);
407 // if (ch >= 'A' && ch <= 'Z') {
408 // if (identEnd < 0) {
409 // identEnd = currentSQLPosition + 1;
411 // } else if (ch >= 'a' && ch <= 'z') {
412 // if (identEnd < 0) {
413 // identEnd = currentSQLPosition + 1;
415 // } else if (identEnd >= 0) {
416 // ident = startText.substring(currentSQLPosition + 1, identEnd);
417 // // select -- from -- where --
418 // // update -- set -- where --
419 // // insert into -- ( -- ) values ( -- )
420 // if (ident.length() >= 3 && ident.length() <= 6) {
421 // ident = ident.toLowerCase();
422 // switch (ident.length()) {
424 // if (ident.equals("set")) {
425 // // System.out.println("set");
426 // token = ITerminalSymbols.TokenNameSQLset;
431 // if (ident.equals("from")) {
432 // // System.out.println("from");
433 // token = ITerminalSymbols.TokenNameSQLfrom;
434 // // getSQLTableName();
436 // } else if (ident.equals("into")) {
437 // // System.out.println("into");
438 // token = ITerminalSymbols.TokenNameSQLinto;
443 // if (ident.equals("where")) {
444 // // System.out.println("where");
445 // token = ITerminalSymbols.TokenNameSQLwhere;
450 // if (ident.equals("select")) {
451 // // System.out.println("select");
452 // token = ITerminalSymbols.TokenNameSQLselect;
454 // } else if (ident.equals("insert")) {
455 // // System.out.println("insert");
456 // token = ITerminalSymbols.TokenNameSQLinsert;
458 // } else if (ident.equals("update")) {
459 // // System.out.println("update");
460 // token = ITerminalSymbols.TokenNameSQLupdate;
462 // } else if (ident.equals("values")) {
463 // // System.out.println("values");
464 // token = ITerminalSymbols.TokenNameSQLvalues;
473 // } catch (IndexOutOfBoundsException e) {
475 // return ITerminalSymbols.TokenNameEOF;
478 private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
479 ICompilationUnit unit = fManager.getWorkingCopy(fEditor.getEditorInput());
480 IDocument document = viewer.getDocument();
482 IProject project = null;
484 PHPEditor editor = null;
485 if (fEditor != null && (fEditor instanceof PHPEditor)) {
486 editor = (PHPEditor) fEditor;
487 file = ((IFileEditorInput) editor.getEditorInput()).getFile();
488 project = file.getProject();
492 Point selection = viewer.getSelectedRange();
493 // remember selected text
494 String selectedText = null;
495 if (selection.y != 0) {
497 selectedText = document.get(selection.x, selection.y);
498 } catch (BadLocationException e) {
502 if (offset > 2 && fProposalAutoActivationSet != null) {
503 // restrict auto activation for '>' character to '->' token
506 char ch = document.getChar(offset-1);
508 for (int i = 0; i < fProposalAutoActivationSet.length; i++) {
509 ch = fProposalAutoActivationSet[i];
510 if (ch == '>') { // auto activation enabled
511 ch = document.getChar(offset - 2);
513 return new IPHPCompletionProposal[0];
519 } catch (BadLocationException e) {
524 JavaContextType phpContextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
525 "php"); //$NON-NLS-1$
526 JavaContext context = (JavaContext) phpContextType.createContext(document, offset, selection.y, unit);
527 context.setVariable("selection", selectedText); //$NON-NLS-1$
528 String prefix = context.getKey();
530 HashMap methodVariables = null;
531 // HashMap typeVariables = null;
532 HashMap unitVariables = null;
533 ICompilationUnit compilationUnit = (ICompilationUnit) context.findEnclosingElement(IJavaElement.COMPILATION_UNIT);
534 // if (compilationUnit != null) {
535 // unitVariables = ((CompilationUnit) compilationUnit).variables;
537 IType type = (IType) context.findEnclosingElement(IJavaElement.TYPE);
539 // typeVariables = ((SourceType) type).variables;
541 IMethod method = (IMethod) context.findEnclosingElement(IJavaElement.METHOD);
542 // if (method != null) {
543 // methodVariables = ((SourceMethod) method).variables;
546 boolean emptyPrefix = prefix == null || prefix.equals("");
547 IPHPCompletionProposal[] localVariableResults = new IPHPCompletionProposal[0];
549 if (!emptyPrefix && prefix.length() >= 1 && prefix.charAt(0) == '$') {
551 String lowerCasePrefix = prefix.toLowerCase();
552 HashSet localVariables = new HashSet();
553 if (compilationUnit != null) {
554 unitVariables = getUnitVariables(unitVariables, compilationUnit);
555 getVariableProposals(localVariables, viewer, project, context, unitVariables, lowerCasePrefix, 94);
557 if (method != null) {
558 methodVariables = getMethodVariables(methodVariables, method);
559 getVariableProposals(localVariables, viewer, project, context, methodVariables, lowerCasePrefix, 99);
561 if (!localVariables.isEmpty()) {
562 localVariableResults = (IPHPCompletionProposal[]) localVariables.toArray(new IPHPCompletionProposal[localVariables.size()]);
566 // TableName sqlTable = new TableName();
567 ArrayList list = new ArrayList();
569 int lastSignificantToken = getLastToken(list, viewer, offset, context); //, sqlTable);
570 boolean useClassMembers = (lastSignificantToken == ITerminalSymbols.TokenNameMINUS_GREATER)
571 || (lastSignificantToken == ITerminalSymbols.TokenNameVariable) || (lastSignificantToken == ITerminalSymbols.TokenNamenew)
572 || (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION);
574 if (fTemplateEngine != null) {
575 IPHPCompletionProposal[] templateResults = new IPHPCompletionProposal[0];
576 ICompletionProposal[] results;
578 fTemplateEngine.reset();
579 fTemplateEngine.complete(viewer, offset, unit);
580 templateResults = fTemplateEngine.getResults();
583 IPHPCompletionProposal[] identifierResults = new IPHPCompletionProposal[0];
585 // declarations stored in file project.index on project level
586 IPHPCompletionProposal[] declarationResults = new IPHPCompletionProposal[0];
587 if (project != null) {
588 DeclarationEngine declarationEngine;
589 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
590 "php"); //$NON-NLS-1$
591 if (contextType != null) {
592 IdentifierIndexManager indexManager = PHPeclipsePlugin.getDefault().getIndexManager(project);
594 declarationEngine = new DeclarationEngine(project, contextType, lastSignificantToken, file);
595 if (lastSignificantToken == ITerminalSymbols.TokenNamethis_PHP_COMPLETION) {
596 // complete '$this->'
597 sortedMap = indexManager.getIdentifiers(file);
598 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
600 String typeRef = null;
601 char[] varName = (char[]) list.get(0);
602 if (varName != null) {
603 if (method != null) {
604 methodVariables = getMethodVariables(methodVariables, method);
605 VariableInfo info = (VariableInfo) methodVariables.get(new String(varName));
606 if (info != null && info.typeIdentifier != null) {
607 typeRef = new String(info.typeIdentifier);
611 if (typeRef != null) {
612 // complete '$variable->' with type information
613 sortedMap = indexManager.getIdentifiers(typeRef);
614 declarationEngine.completeObject(viewer, offset, sortedMap, unit);
616 // complete '$variable->' without type information
617 sortedMap = indexManager.getIdentifierMap();
618 declarationEngine.complete(viewer, offset, sortedMap, unit);
621 declarationResults = declarationEngine.getResults();
624 // built in function names from phpsyntax.xml
625 ArrayList syntaxbuffer = PHPSyntaxRdr.getSyntaxData();
626 IPHPCompletionProposal[] builtinResults = new IPHPCompletionProposal[0];
627 if ((!useClassMembers) && syntaxbuffer != null) {
628 BuiltInEngine builtinEngine;
629 JavaContextType contextType = (JavaContextType) PHPeclipsePlugin.getDefault().getTemplateContextRegistry().getContextType(
630 "php"); //$NON-NLS-1$
631 if (contextType != null) {
632 builtinEngine = new BuiltInEngine(contextType);
633 builtinEngine.complete(viewer, offset, syntaxbuffer, unit);
634 builtinResults = builtinEngine.getResults();
637 // ICompletionProposal[] sqlResults = new ICompletionProposal[0];
638 // if (project != null) {
639 // sqlResults = getSQLProposals(viewer, project, context, prefix,
642 // concatenate the result arrays
643 IPHPCompletionProposal[] total;
644 total = new IPHPCompletionProposal[localVariableResults.length + templateResults.length + identifierResults.length
645 + builtinResults.length + declarationResults.length];// +
646 // sqlResults.length];
647 System.arraycopy(templateResults, 0, total, 0, templateResults.length);
648 System.arraycopy(identifierResults, 0, total, templateResults.length, identifierResults.length);
649 System.arraycopy(builtinResults, 0, total, templateResults.length + identifierResults.length, builtinResults.length);
650 System.arraycopy(declarationResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length,
651 declarationResults.length);
652 // System.arraycopy(sqlResults, 0, total, templateResults.length +
653 // identifierResults.length + builtinResults.length
654 // + declarationResults.length, sqlResults.length);
655 // System.arraycopy(localVariableResults, 0, total, templateResults.length
656 // + identifierResults.length + builtinResults.length
657 // + declarationResults.length + sqlResults.length,
658 // localVariableResults.length);
659 System.arraycopy(localVariableResults, 0, total, templateResults.length + identifierResults.length + builtinResults.length
660 + declarationResults.length, localVariableResults.length);
662 // fNumberOfComputedResults = (results == null ? 0 : results.length);
664 * Order here and not in result collector to make sure that the order
665 * applies to all proposals and not just those of the compilation unit.
667 return order(results);
669 return new IPHPCompletionProposal[0];
673 * @param unitVariables
676 private HashMap getUnitVariables(HashMap unitVariables, ICompilationUnit unit) {
677 if (unitVariables == null) {
679 String unitText = unit.getSource();
680 unitVariables = new HashMap();
682 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
683 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
684 UnitParser parser = new UnitParser(problemReporter);
685 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, unitText.length());
686 parser.parse(unitText, unitVariables);
688 } catch (Exception e) {
689 // TODO Auto-generated catch block
691 PHPeclipsePlugin.log(e);
694 return unitVariables;
698 * @param methodVariables
701 private HashMap getMethodVariables(HashMap methodVariables, IMethod method) {
702 if (methodVariables == null) {
704 String methodText = method.getSource();
705 methodVariables = new HashMap();
706 ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitAfterAllProblems(),
707 new CompilerOptions(JavaCore.getOptions()), new DefaultProblemFactory());
708 UnitParser parser = new UnitParser(problemReporter);
709 parser.compilationUnit = new CompilationUnitDeclaration(problemReporter, null, methodText.length());
710 parser.parseFunction(methodText, methodVariables);
711 } catch (Exception e) {
712 // TODO Auto-generated catch block
714 PHPeclipsePlugin.log(e);
717 return methodVariables;
727 private void getVariableProposals(HashSet localVariables, ITextViewer viewer, IProject project, JavaContext context,
728 HashMap variables, String prefix, int relevance) {
730 int start = context.getStart();
731 int end = context.getEnd();
732 IRegion region = new Region(start, end - start);
733 // IMethod method = (IMethod)
734 // context.findEnclosingElement(IJavaElement.METHOD);
735 // if (method != null && (method instanceof SourceMethod) && ((SourceMethod)
736 // method).variables != null) {
737 // HashMap map = ((SourceMethod) method).variables;
738 Set set = variables.keySet();
739 Iterator iter = set.iterator();
741 boolean matchesVarName;
742 while (iter.hasNext()) {
743 varName = (String) iter.next();
744 if (varName.length() >= prefix.length()) {
745 matchesVarName = true;
746 for (int i = 0; i < prefix.length(); i++) {
747 if (prefix.charAt(i) != Character.toLowerCase(varName.charAt(i))) {
748 matchesVarName = false;
752 if (matchesVarName) {
753 LocalVariableProposal prop;
754 // if (varName.length == prefix.length()) {
755 // prop = new LocalVariableProposal(new String(varName), region,
756 // viewer, relevance-10);
758 prop = new LocalVariableProposal(new String(varName), region, viewer, relevance);
760 localVariables.add(prop);
767 // boolean matchesVarName;
768 // if (method != null) {
769 // ISourceRange range = method.getSourceRange();
770 // char[] source = method.getSource().toCharArray();
771 // Scanner scanner = new Scanner();
772 // scanner.setSource(source);
773 // scanner.phpMode = true;
774 // int token = Scanner.TokenNameWHITESPACE;
775 // while ((token = scanner.getNextToken()) != Scanner.TokenNameEOF) {
776 // if (token == Scanner.TokenNameVariable) {
777 // varName = scanner.getCurrentTokenSource();
778 // if (varName.length >= prefix.length()) {
779 // matchesVarName = true;
780 // for (int i = 0; i < prefix.length(); i++) {
781 // if (prefix.charAt(i) != varName[i]) {
782 // matchesVarName = false;
786 // if (matchesVarName) {
787 // LocalVariableProposal prop = new LocalVariableProposal(new
788 // String(varName), region, viewer);
789 // if (varName.length == prefix.length()) {
790 // prop.setRelevance(98);
792 // localVariables.add(prop);
798 // } catch (Throwable e) {
799 // // ignore - Syntax exceptions could occur, if there are syntax errors !
812 // private ICompletionProposal[] getSQLProposals(ITextViewer viewer, IProject
813 // 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 =
820 // ProjectPrefUtil.getMiscProjectsPreferenceValue(project,
821 // IPreferenceConstants.PHP_BOOKMARK_DEFAULT);
822 // if (bookmarkString != null && !bookmarkString.equals("")) {
823 // String[] bookmarks = ExternalInterface.getBookmarkNames();
824 // boolean foundBookmark = false;
825 // for (int i = 0; i < bookmarks.length; i++) {
826 // if (bookmarks[i].equals(bookmarkString)) {
827 // foundBookmark = true;
830 // if (!foundBookmark) {
831 // return sqlResults;
833 // // Bookmark bookmark = sqlBookMarks.find(bookmarkString);
834 // ArrayList sqlList = new ArrayList();
835 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
836 // ExternalInterface.connectBookmark(bookmarkString, null);
837 // if (!ExternalInterface.isBookmarkConnected(bookmarkString)) {
838 // return sqlResults;
841 // // if (ExternalInterface.isBookmarkConnected(bookmarkString)) {
843 // int start = context.getStart();
844 // int end = context.getEnd();
845 // String foundSQLTableName = sqlTable.getTableName();
847 // String columnName;
848 // String prefixWithoutDollar = prefix;
849 // boolean isDollarPrefix = false;
850 // if (prefix.length() > 0 && prefix.charAt(0) == '$') {
851 // prefixWithoutDollar = prefix.substring(1);
852 // isDollarPrefix = true;
854 // IRegion region = new Region(start, end - start);
856 // if (!isDollarPrefix) {
857 // String[] tableNames = ExternalInterface.getMatchingTableNames(null,
858 // bookmarkString, prefixWithoutDollar, null, false);
859 // for (int i = 0; i < tableNames.length; i++) {
860 // sqlList.add(new SQLProposal(tableNames[i], context, region, viewer,
861 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
865 // String[] columnNames = ExternalInterface.getMatchingColumnNames(null,
866 // bookmarkString, prefixWithoutDollar, null, false);
867 // for (int i = 0; i < columnNames.length; i++) {
868 // sqlList.add(new SQLProposal(columnNames[i], context, region, viewer,
869 // PHPUiImages.get(PHPUiImages.IMG_TABLE)));
872 // sqlResults = new IPHPCompletionProposal[sqlList.size()];
873 // for (int i = 0; i < sqlList.size(); i++) {
874 // sqlResults[i] = (SQLProposal) sqlList.get(i);
876 // } catch (Exception /* NotConnectedException */ e) {
882 // return sqlResults;
884 private boolean looksLikeMethod(PHPCodeReader reader) throws IOException {
885 int curr = reader.read();
886 while (curr != PHPCodeReader.EOF && Character.isWhitespace((char) curr))
887 curr = reader.read();
889 if (curr == PHPCodeReader.EOF)
892 return Scanner.isPHPIdentifierPart((char) curr);
895 private int guessContextInformationPosition(ITextViewer viewer, int offset) {
896 int contextPosition = offset;
897 IDocument document = viewer.getDocument();
900 PHPCodeReader reader = new PHPCodeReader();
901 reader.configureBackwardReader(document, offset, true, true);
903 int nestingLevel = 0;
905 int curr = reader.read();
906 while (curr != PHPCodeReader.EOF) {
908 if (')' == (char) curr)
911 else if ('(' == (char) curr) {
914 if (nestingLevel < 0) {
915 int start = reader.getOffset();
916 if (looksLikeMethod(reader))
921 curr = reader.read();
923 } catch (IOException e) {
925 return contextPosition;
929 * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
931 public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
932 int contextInformationPosition = guessContextInformationPosition(viewer, offset);
933 List result = addContextInformations(viewer, contextInformationPosition);
934 return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
937 private List addContextInformations(ITextViewer viewer, int offset) {
938 ICompletionProposal[] proposals = internalComputeCompletionProposals(viewer, offset, -1);
939 List result = new ArrayList();
940 for (int i = 0; i < proposals.length; i++) {
941 IContextInformation contextInformation = proposals[i].getContextInformation();
942 if (contextInformation != null) {
943 ContextInformationWrapper wrapper = new ContextInformationWrapper(contextInformation);
944 wrapper.setContextInformationPosition(offset);
952 * Order the given proposals.
954 private ICompletionProposal[] order(ICompletionProposal[] proposals) {
955 Arrays.sort(proposals, fComparator);
956 // int len = proposals.length;
960 // for (int i = 0; i < len; i++) {
961 // System.out.println(proposals[i].getDisplayString());
967 * (non-Javadoc) Method declared on IContentAssistProcessor
969 public char[] getCompletionProposalAutoActivationCharacters() {
970 return fProposalAutoActivationSet;
971 // return null; // new char[] { '$' };
975 * (non-Javadoc) Method declared on IContentAssistProcessor
977 public char[] getContextInformationAutoActivationCharacters() {
982 * (non-Javadoc) Method declared on IContentAssistProcessor
984 public IContextInformationValidator getContextInformationValidator() {
985 if (fValidator == null)
986 fValidator = new JavaParameterListValidator();
991 * (non-Javadoc) Method declared on IContentAssistProcessor
993 public String getErrorMessage() {