use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.
the class PydevConsoleInterpreter method getCompletions.
@Override
@SuppressWarnings("unchecked")
public ICompletionProposalHandle[] getCompletions(IScriptConsoleViewer viewer, String commandLine, int position, int offset, int whatToShow) throws Exception {
final String text = commandLine.substring(0, position);
ActivationTokenAndQualifier tokenAndQual = PySelection.getActivationTokenAndQualifier(new Document(text), text.length(), true, false);
String textForCompletionInConsole = PySelection.getTextForCompletionInConsole(new Document(text), text.length());
if (PySelection.isCompletionForLiteralNumber(tokenAndQual.activationToken)) {
// suppress completions that would be invalid
return new ICompletionProposalHandle[0];
}
// Code-completion for imports
ImportInfo importsTipper = ImportsSelection.getImportsTipperStr(text, false);
Set<IPythonNature> natureAndRelatedNatures = getNatureAndRelatedNatures();
if (importsTipper.importsTipperStr.length() != 0) {
importsTipper.importsTipperStr = importsTipper.importsTipperStr.trim();
Set<IToken> tokens = new TreeSet<IToken>();
final boolean onlyGetDirectModules = true;
// Check all the natures.
for (final IPythonNature nature : natureAndRelatedNatures) {
ICodeCompletionASTManager astManager = nature.getAstManager();
TokensList importTokens = astManager.getCompletionsForImport(importsTipper, new ICompletionRequest() {
@Override
public IPythonNature getNature() {
return nature;
}
@Override
public File getEditorFile() {
return null;
}
@Override
public IModule getModule() throws MisconfigurationException {
return null;
}
}, onlyGetDirectModules);
// only get all modules for the 1st one we analyze (no need to get on the others)
for (IterTokenEntry entry : importTokens) {
IToken iToken = entry.getToken();
tokens.add(iToken);
}
}
int qlen = tokenAndQual.qualifier.length();
List<ICompletionProposalHandle> ret = new ArrayList<ICompletionProposalHandle>(tokens.size());
Iterator<IToken> it = tokens.iterator();
for (int i = 0; i < tokens.size(); i++) {
IToken t = it.next();
int replacementOffset = offset - qlen;
String representation = t.getRepresentation();
if (representation.startsWith(tokenAndQual.qualifier)) {
ret.add(CompletionProposalFactory.get().createPyLinkedModeCompletionProposal(representation, replacementOffset, qlen, representation.length(), t, null, null, IPyCompletionProposal.PRIORITY_DEFAULT, IPyCompletionProposal.ON_APPLY_DEFAULT, "", null));
}
}
return ret.toArray(new ICompletionProposalHandle[ret.size()]);
}
// END Code-completion for imports
String actTok = tokenAndQual.activationToken;
if (tokenAndQual.qualifier != null && tokenAndQual.qualifier.length() > 0) {
if (actTok.length() > 0 && actTok.charAt(actTok.length() - 1) != '.') {
actTok += '.';
}
actTok += tokenAndQual.qualifier;
}
boolean showOnlyTemplates = whatToShow == AbstractCompletionProcessorWithCycling.SHOW_ONLY_TEMPLATES;
boolean showForTabCompletion = whatToShow == AbstractCompletionProcessorWithCycling.SHOW_FOR_TAB_COMPLETIONS;
// simple completions (clients)
ArrayList<ICompletionProposalHandle> results = new ArrayList<ICompletionProposalHandle>();
if (!showForTabCompletion) {
for (ISimpleAssistParticipant2 participant : simpleParticipants) {
results.addAll(participant.computeConsoleProposals(tokenAndQual.activationToken, tokenAndQual.qualifier, offset));
}
}
ProposalsComparator proposalsComparator = new ProposalsComparator(tokenAndQual.qualifier, null);
ArrayList<ICompletionProposalHandle> results2 = new ArrayList<ICompletionProposalHandle>();
if (!showOnlyTemplates) {
// shell completions
if (consoleCommunication != null) {
ICompletionProposalHandle[] consoleCompletions = consoleCommunication.getCompletions(text, textForCompletionInConsole, offset, showForTabCompletion);
// If we're only showing ipython completions, then short-circuit the rest
if (showForTabCompletion) {
return consoleCompletions;
}
results2.addAll(Arrays.asList(consoleCompletions));
}
}
if (tokenAndQual.activationToken.length() == 0) {
// templates (only if we have no activation token)
IPyTemplateCompletionProcessor pyTemplateCompletionProcessor = new PyTemplateCompletionProcessor();
pyTemplateCompletionProcessor.addTemplateProposals((ITextViewer) viewer, offset, results2);
}
Collections.sort(results2, proposalsComparator);
ArrayList<ICompletionProposalHandle> results3 = new ArrayList<ICompletionProposalHandle>();
if (!showOnlyTemplates) {
// other participants
List<Object> participants = ExtensionHelper.getParticipants(ExtensionHelper.PYDEV_COMPLETION);
for (Object participant : participants) {
if (participant instanceof IPyDevCompletionParticipant2) {
IPyDevCompletionParticipant2 participant2 = (IPyDevCompletionParticipant2) participant;
results3.addAll(participant2.computeConsoleCompletions(tokenAndQual, natureAndRelatedNatures, viewer, offset));
}
}
Collections.sort(results3, proposalsComparator);
}
results.addAll(results2);
results.addAll(results3);
return results.toArray(new ICompletionProposalHandle[results.size()]);
}
use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.
the class PydevConsoleQuickAssistProcessor method computeQuickAssistProposals.
/**
* Computes quick assists for the console.
*/
@Override
public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) {
ISourceViewer sourceViewer = invocationContext.getSourceViewer();
List<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
if (sourceViewer instanceof ScriptConsoleViewer) {
ScriptConsoleViewer viewer = (ScriptConsoleViewer) sourceViewer;
// currently, only the assign quick assist is used
AssistAssign assistAssign = new AssistAssign();
ISelection selection = sourceViewer.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
PySelection ps = PySelectionFromEditor.createPySelectionFromEditor(sourceViewer, (ITextSelection) selection);
int offset = viewer.getCaretOffset();
String commandLine = viewer.getCommandLine();
// let's calculate the 1st line that is not a whitespace.
if (assistAssign.isValid(ps.getSelLength(), commandLine, offset)) {
int commandLineOffset = viewer.getCommandLineOffset();
try {
IDocument doc = sourceViewer.getDocument();
while (true) {
if (commandLineOffset == doc.getLength() - 1) {
break;
}
char c = doc.getChar(commandLineOffset);
if (Character.isWhitespace(c)) {
commandLineOffset++;
} else {
break;
}
}
props.addAll(assistAssign.getProps(ps, SharedUiPlugin.getImageCache(), sourceViewer, offset, commandLine, commandLineOffset));
} catch (BadLocationException e) {
Log.log(e);
}
}
}
}
return ConvertCompletionProposals.convertHandlesToProposals(props.toArray(new ICompletionProposalHandle[props.size()]));
}
use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.
the class PydevDebugConsoleCommunication method getCompletions.
@Override
public ICompletionProposalHandle[] getCompletions(String text, String actTok, int offset, boolean showForTabCompletion) throws Exception {
ICompletionProposalHandle[] receivedCompletions = {};
if (waitingForInput) {
return new ICompletionProposalHandle[0];
}
PyStackFrame frame = consoleFrameProvider.getLastSelectedFrame();
if (frame == null) {
return new ICompletionProposalHandle[0];
}
final EvaluateDebugConsoleExpression evaluateDebugConsoleExpression = new EvaluateDebugConsoleExpression(frame);
String result = evaluateDebugConsoleExpression.getCompletions(actTok, offset);
if (result.length() > 0) {
List<Object[]> fromServer = XMLUtils.convertXMLcompletionsFromConsole(result);
List<ICompletionProposalHandle> ret = new ArrayList<ICompletionProposalHandle>();
PydevConsoleCommunication.convertConsoleCompletionsToICompletions(text, actTok, offset, fromServer, ret, false);
receivedCompletions = ret.toArray(new ICompletionProposalHandle[ret.size()]);
}
return receivedCompletions;
}
use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.
the class PydevConsoleCommunication method convertToICompletions.
private static void convertToICompletions(final String text, String actTok, int offset, Object fromServer, List<ICompletionProposalHandle> ret, boolean showForTabCompletion, IFilterCompletion filter) {
if (fromServer instanceof Object[]) {
Object[] objects = (Object[]) fromServer;
fromServer = Arrays.asList(objects);
}
if (fromServer instanceof List) {
int length = actTok.lastIndexOf('.');
if (length == -1) {
length = actTok.length();
} else {
length = actTok.length() - length - 1;
}
final String trimmedText = text.trim();
List comps = (List) fromServer;
for (Object o : comps) {
if (o instanceof Object[]) {
// name, doc, args, type
Object[] comp = (Object[]) o;
String name = (String) comp[0];
String docStr = (String) comp[1];
int type = extractInt(comp[3]);
String args = AbstractPyCodeCompletion.getArgs((String) comp[2], type, ICompletionState.LookingFor.LOOKING_FOR_INSTANCED_VARIABLE);
String nameAndArgs = name + args;
int priority = IPyCompletionProposal.PRIORITY_DEFAULT;
if (type == IToken.TYPE_LOCAL) {
priority = IPyCompletionProposal.PRIORITY_LOCALS;
} else if (type == IToken.TYPE_PARAM) {
priority = IPyCompletionProposal.PRIORITY_LOCALS_1;
} else if (type == IToken.TYPE_IPYTHON_MAGIC) {
priority = IPyCompletionProposal.PRIORTTY_IPYTHON_MAGIC;
}
// ret.add(new PyCompletionProposal(name,
// offset-length, length, name.length(),
// PyCodeCompletionImages.getImageForType(type), name, null, docStr, priority));
int cursorPos = name.length();
if (args.length() > 1) {
cursorPos += 1;
}
int replacementOffset = offset - length;
PyCalltipsContextInformation pyContextInformation = null;
if (args.length() > 2) {
pyContextInformation = new PyCalltipsContextInformation(args, replacementOffset + name.length() + // just after the parenthesis
1);
} else {
// i.e.: %completions, cd ...
if (name.length() > 0) {
// as ipthon completes a<tab> to %alias etc.
if (name.charAt(0) == '%' && text.length() > 0 && text.charAt(0) == '%') {
replacementOffset -= 1;
// handle cd -- we handle this by returning the full path from ipython
// TODO: perhaps we could do this for all completions
} else if (trimmedText.equals("cd") || trimmedText.startsWith("cd ") || trimmedText.equals("%cd") || trimmedText.startsWith("%cd ")) {
if (showForTabCompletion) {
replacementOffset = 0;
length = text.length();
} else {
if (name.charAt(0) == '/') {
// Should be something as cd c:/temp/foo (and name is /temp/foo)
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == name.charAt(0)) {
String sub = text.substring(i, text.length());
if (name.startsWith(sub)) {
replacementOffset -= (sub.length() - FullRepIterable.getLastPart(actTok).length());
break;
}
}
}
}
}
}
}
}
ICompletionProposalHandle completion = CompletionProposalFactory.get().createPyLinkedModeCompletionProposal(nameAndArgs, replacementOffset, length, cursorPos, PyCodeCompletionImages.getImageForType(type), nameAndArgs, pyContextInformation, docStr, priority, IPyCompletionProposal.ON_APPLY_DEFAULT, args, false, null);
if (filter == null || filter.acceptCompletion(type, completion)) {
ret.add(completion);
}
}
}
}
}
use of org.python.pydev.shared_core.code_completion.ICompletionProposalHandle in project Pydev by fabioz.
the class PydevConsoleCompletionProcessor method computeCompletionProposals.
/**
* Get the completions (and cycle the completion mode if needed).
*/
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer v, int offset) {
// cycle if we're in a new activation for requests (a second ctrl+space or
// a new request)
boolean cycleRequest;
if (lastActivationCount == -1) {
// new request: don't cycle
lastActivationCount = this.contentAssistant.lastActivationCount;
cycleRequest = false;
updateStatus();
} else {
// we already had a request (so, we may cycle or not depending on the activation count)
cycleRequest = this.contentAssistant.lastActivationCount != lastActivationCount;
}
if (cycleRequest) {
lastActivationCount = this.contentAssistant.lastActivationCount;
doCycle();
updateStatus();
}
IScriptConsoleViewer viewer = (IScriptConsoleViewer) v;
try {
if (!PyCodeCompletionPreferences.useCodeCompletion()) {
return new ICompletionProposal[0];
}
String commandLine = viewer.getCommandLine();
int cursorPosition = offset - viewer.getCommandLineOffset();
ICompletionProposalHandle[] completions = interpreterShell.getCompletions(viewer, commandLine, cursorPosition, offset, this.whatToShow);
return ConvertCompletionProposals.convertHandlesToProposals(completions);
} catch (Exception e) {
Log.log(e);
CompletionError completionError = new CompletionError(e);
this.errorMessage = completionError.getErrorMessage();
// Make the error visible to the user!
return new ICompletionProposal[] { completionError };
}
}
Aggregations