Search in sources :

Example 1 with LineStartingScope

use of org.python.pydev.core.docutils.PySelection.LineStartingScope in project Pydev by fabioz.

the class TddCodeGenerationQuickFixParticipant method checkMethodCreationAtClass.

private boolean checkMethodCreationAtClass(PyEdit edit, IPyRefactoring pyRefactoring, String callWithoutParens, PySelection callPs, List<ICompletionProposalHandle> ret, String lineContents, TddPossibleMatches possibleMatch, File f, IPythonNature nature) throws MisconfigurationException, Exception {
    RefactoringRequest request;
    ItemPointer[] pointers;
    // Ok, no definition found for the full string, so, check if we have a dot there and check
    // if it could be a method in a local variable.
    String[] headAndTail = FullRepIterable.headAndTail(callWithoutParens);
    if (headAndTail[0].length() > 0) {
        String methodToCreate = headAndTail[1];
        if (headAndTail[0].equals("self")) {
            // creating something in the current class -- note that if it was self.bar here, we'd treat it as regular
            // (i.e.: no special support for self), so, we wouldn't enter here!
            int firstCharPosition = PySelection.getFirstCharPosition(lineContents);
            LineStartingScope scopeStart = callPs.getPreviousLineThatStartsScope(PySelection.CLASS_TOKEN, false, firstCharPosition);
            String classNameInLine = null;
            if (scopeStart != null) {
                for (Boolean isCall : new Boolean[] { true, false }) {
                    PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
                    List<String> parametersAfterCall = null;
                    parametersAfterCall = configCreateAsAndReturnParametersAfterCall(callPs, isCall, pyCreateMethod, parametersAfterCall, methodToCreate);
                    String startingScopeLineContents = callPs.getLine(scopeStart.iLineStartingScope);
                    classNameInLine = PySelection.getClassNameInLine(startingScopeLineContents);
                    if (classNameInLine != null && classNameInLine.length() > 0) {
                        pyCreateMethod.setCreateInClass(classNameInLine);
                        addCreateMethodOption(callPs, edit, ret, methodToCreate, parametersAfterCall, pyCreateMethod, classNameInLine);
                    }
                }
            }
            return true;
        }
        int absoluteCursorOffset = callPs.getAbsoluteCursorOffset();
        // +1 for the dot removed too.
        absoluteCursorOffset = absoluteCursorOffset - (1 + methodToCreate.length());
        PySelection newSelection = new PySelection(callPs.getDoc(), absoluteCursorOffset);
        request = new RefactoringRequest(f, newSelection, null, nature, edit);
        // Don't look in additional info.
        request.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
        pointers = pyRefactoring.findDefinition(request);
        if (pointers.length == 1) {
            if (checkCreationBasedOnFoundPointers(edit, callPs, ret, possibleMatch, pointers, methodToCreate, newSelection, nature)) {
                return true;
            }
        }
    }
    return false;
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) PySelection(org.python.pydev.core.docutils.PySelection) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Example 2 with LineStartingScope

use of org.python.pydev.core.docutils.PySelection.LineStartingScope in project Pydev by fabioz.

the class PyAutoIndentStrategy method indentBasedOnStartingScope.

/**
 * @return the text for the indent
 */
private String indentBasedOnStartingScope(String text, PySelection selection, boolean checkForLowestBeforeNewScope) {
    LineStartingScope previousIfLine = selection.getPreviousLineThatStartsScope();
    if (previousIfLine != null) {
        String initial = getCharsBeforeNewLine(text);
        if (previousIfLine.lineWithDedentWhileLookingScope == null) {
            // no dedent was found
            String indent = PySelection.getIndentationFromLine(previousIfLine.lineStartingScope);
            if (checkForLowestBeforeNewScope && previousIfLine.lineWithLowestIndent != null) {
                indent = PySelection.getIndentationFromLine(previousIfLine.lineWithLowestIndent);
                text = initial + indent;
            } else {
                text = initial + indent + prefs.getIndentationString();
            }
        } else {
            // some dedent was found
            String indent = PySelection.getIndentationFromLine(previousIfLine.lineWithDedentWhileLookingScope);
            String indentationString = prefs.getIndentationString();
            final int i = indent.length() - indentationString.length();
            if (i > 0 && indent.length() > i) {
                text = (initial + indent).substring(0, i + 1);
            } else {
                // this can happen if we found a dedent that is 1 level deep
                text = initial;
            }
        }
    }
    return text;
}
Also used : LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope)

Example 3 with LineStartingScope

use of org.python.pydev.core.docutils.PySelection.LineStartingScope in project Pydev by fabioz.

the class PyMoveImportsToLocalCompletionProposal method apply.

@Override
public void apply(IDocument doc) {
    RefactoringRequest req = refactoringRequest;
    final IPyRefactoring2 r = (IPyRefactoring2) AbstractPyRefactoring.getPyRefactoring();
    if (req.qualifier != null && req.qualifier.trim().length() > 0) {
        try {
            final Map<Tuple<String, File>, HashSet<ASTEntry>> occurrences = r.findAllOccurrences(req);
            final Set<Entry<Tuple<String, File>, HashSet<ASTEntry>>> entrySet = occurrences.entrySet();
            final MultiTextEdit multiTextEdit = new MultiTextEdit();
            final IDocument document = req.getDoc();
            final Set<Integer> appliedContextLines = new HashSet<Integer>();
            for (Map.Entry<Tuple<String, File>, HashSet<ASTEntry>> o : entrySet) {
                HashSet<ASTEntry> entries = o.getValue();
                ASTEntry[] ordered = entries.toArray(new ASTEntry[0]);
                Arrays.sort(ordered, (entry0, entry1) -> {
                    // Note: order is reversed.
                    return Integer.compare(entry1.node.beginLine, entry0.node.beginLine);
                });
                for (ASTEntry entry : entries) {
                    if (entry.node != null) {
                        int beginLine = entry.node.beginLine;
                        int useLine = beginLine - 1;
                        if (useLine >= importHandleInfo.getStartLine() && useLine <= importHandleInfo.getEndLine()) {
                            // Skip the import itself.
                            continue;
                        }
                        String currLine = TextSelectionUtils.getLine(document, useLine);
                        if (!currLine.isEmpty() && !Character.isWhitespace(currLine.charAt(0))) {
                            // Skip global occurrences of the token
                            continue;
                        }
                        for (int i = useLine; i < document.getNumberOfLines(); i++) {
                            String line = TextSelectionUtils.getLine(document, i);
                            if (!line.trim().isEmpty()) {
                                if (Character.isWhitespace(line.charAt(0))) {
                                    useLine = i;
                                    break;
                                }
                            }
                        }
                        boolean addLocalImport = true;
                        boolean addLocalImportsOnTopOfMethod = true;
                        boolean groupImports = false;
                        int offset = new PySelection(req.ps.getDoc(), useLine, 0).getAbsoluteCursorOffset();
                        int maxCols = 200;
                        char trigger = ' ';
                        String fromImportStr = importHandleInfo.getFromImportStr();
                        String realImportRep;
                        if (fromImportStr == null || fromImportStr.isEmpty()) {
                            realImportRep = "import " + this.importedToken;
                        } else {
                            realImportRep = "from " + fromImportStr + " import " + this.importedToken;
                        }
                        int fReplacementOffset = offset;
                        int fLen = 0;
                        String indentString = "               ";
                        this.fReplacementString = "";
                        AddTokenAndImportStatement.ComputedInfo computedInfo = new AddTokenAndImportStatement.ComputedInfo(realImportRep, fReplacementOffset, fLen, indentString, fReplacementString, appliedWithTrigger, importLen, document);
                        this.appliedWithTrigger = computedInfo.appliedWithTrigger;
                        this.importLen = computedInfo.importLen;
                        AddTokenAndImportStatement t = new AddTokenAndImportStatement(document, trigger, offset, addLocalImport, addLocalImportsOnTopOfMethod, groupImports, maxCols);
                        LineStartingScope previousLineThatStartsScope = t.getPreviousLineThatStartsScope();
                        if (previousLineThatStartsScope != null) {
                            if (appliedContextLines.contains(previousLineThatStartsScope.iLineStartingScope)) {
                                continue;
                            }
                            appliedContextLines.add(previousLineThatStartsScope.iLineStartingScope);
                            t.createTextEdit(computedInfo);
                            for (ReplaceEdit edit : computedInfo.replaceEdit) {
                                multiTextEdit.addChild(edit);
                            }
                        }
                    }
                }
            }
            try {
                multiTextEdit.apply(document);
            } catch (Exception e) {
                Log.log(e);
            }
        } catch (OperationCanceledException | CoreException e) {
            Log.log(e);
        }
    }
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) AddTokenAndImportStatement(com.python.pydev.analysis.refactoring.quick_fixes.AddTokenAndImportStatement) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IPyRefactoring2(org.python.pydev.ast.refactoring.IPyRefactoring2) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) Entry(java.util.Map.Entry) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) HashSet(java.util.HashSet) Point(org.eclipse.swt.graphics.Point) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) CoreException(org.eclipse.core.runtime.CoreException) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) PySelection(org.python.pydev.core.docutils.PySelection) File(java.io.File) Map(java.util.Map) Tuple(org.python.pydev.shared_core.structure.Tuple) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IDocument(org.eclipse.jface.text.IDocument)

Example 4 with LineStartingScope

use of org.python.pydev.core.docutils.PySelection.LineStartingScope in project Pydev by fabioz.

the class PyCodeCompletion method createOverrideCodeCompletions.

private void createOverrideCodeCompletions(CompletionRequest request, ArrayList<ICompletionProposalHandle> ret, PySelection ps) throws BadLocationException {
    IImageCache imageCache = SharedCorePlugin.getImageCache();
    IImageHandle imageOverride = imageCache != null ? imageCache.get(UIConstants.METHOD_ICON) : null;
    String lineContentsToCursor = ps.getLineContentsToCursor();
    LineStartingScope scopeStart = ps.getPreviousLineThatStartsScope(PySelection.CLASS_TOKEN, false, PySelection.getFirstCharPosition(lineContentsToCursor));
    String className = null;
    if (scopeStart != null) {
        className = PySelection.getClassNameInLine(scopeStart.lineStartingScope);
        if (className != null && className.length() > 0) {
            Tuple<List<String>, Integer> insideParensBaseClasses = ps.getInsideParentesisToks(true, scopeStart.iLineStartingScope);
            if (insideParensBaseClasses != null) {
                // representation -> token and base class
                OrderedMap<String, ImmutableTuple<IToken, String>> map = new OrderedMap<String, ImmutableTuple<IToken, String>>();
                for (String baseClass : insideParensBaseClasses.o1) {
                    try {
                        ICompletionState state = new CompletionState(-1, -1, null, request.nature, baseClass);
                        state.setActivationToken(baseClass);
                        state.setIsInCalltip(false);
                        IPythonNature pythonNature = request.nature;
                        checkPythonNature(pythonNature);
                        ICodeCompletionASTManager astManager = pythonNature.getAstManager();
                        if (astManager == null) {
                            // we're probably still loading it.
                            return;
                        }
                        // Ok, looking for a token in globals.
                        IModule module = request.getModule();
                        if (module == null) {
                            continue;
                        }
                        TokensList comps = astManager.getCompletionsForModule(module, state, true, true);
                        for (IterTokenEntry entry : comps) {
                            IToken iToken = entry.getToken();
                            String representation = iToken.getRepresentation();
                            ImmutableTuple<IToken, String> curr = map.get(representation);
                            if (curr != null && curr.o1 instanceof SourceToken) {
                                // source tokens are never reset!
                                continue;
                            }
                            int type = iToken.getType();
                            if (iToken instanceof SourceToken && ((SourceToken) iToken).getAst() instanceof FunctionDef) {
                                map.put(representation, new ImmutableTuple<IToken, String>(iToken, baseClass));
                            } else if (type == IToken.TYPE_FUNCTION || type == IToken.TYPE_UNKNOWN || type == IToken.TYPE_BUILTIN) {
                                map.put(representation, new ImmutableTuple<IToken, String>(iToken, baseClass));
                            }
                        }
                    } catch (Exception e) {
                        Log.log(e);
                    }
                }
                for (ImmutableTuple<IToken, String> tokenAndBaseClass : map.values()) {
                    FunctionDef functionDef = null;
                    // No checkings needed for type (we already did that above).
                    if (tokenAndBaseClass.o1 instanceof SourceToken) {
                        SourceToken sourceToken = (SourceToken) tokenAndBaseClass.o1;
                        SimpleNode ast = sourceToken.getAst();
                        if (ast instanceof FunctionDef) {
                            functionDef = (FunctionDef) ast;
                        } else {
                            functionDef = sourceToken.getAliased().createCopy();
                            NameTok t = (NameTok) functionDef.name;
                            t.id = sourceToken.getRepresentation();
                        }
                    } else {
                        // unfortunately, for builtins we usually cannot trust the parameters.
                        String representation = tokenAndBaseClass.o1.getRepresentation();
                        PyAstFactory factory = new PyAstFactory(new AdapterPrefs(ps.getEndLineDelim(), request.nature));
                        functionDef = factory.createFunctionDef(representation);
                        functionDef.args = factory.createArguments(true);
                        functionDef.args.vararg = new NameTok("args", NameTok.VarArg);
                        functionDef.args.kwarg = new NameTok("kwargs", NameTok.KwArg);
                        if (!representation.equals("__init__")) {
                            // signal that the return should be added
                            functionDef.body = new stmtType[] { new Return(null) };
                        }
                    }
                    if (functionDef != null) {
                        ret.add(CompletionProposalFactory.get().createOverrideMethodCompletionProposal(request, ps, ps.getAbsoluteCursorOffset(), 0, 0, imageOverride, functionDef, tokenAndBaseClass.o2, className));
                    }
                }
            }
        }
    }
}
Also used : IModule(org.python.pydev.core.IModule) IPythonNature(org.python.pydev.core.IPythonNature) ICompletionState(org.python.pydev.core.ICompletionState) CompletionState(org.python.pydev.ast.codecompletion.revisited.CompletionState) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) SimpleNode(org.python.pydev.parser.jython.SimpleNode) ISimpleNode(org.python.pydev.shared_core.model.ISimpleNode) IToken(org.python.pydev.core.IToken) ICompletionState(org.python.pydev.core.ICompletionState) TokensList(org.python.pydev.core.TokensList) List(java.util.List) TokensOrProposalsList(org.python.pydev.core.TokensOrProposalsList) ArrayList(java.util.ArrayList) PyAstFactory(org.python.pydev.parser.jython.ast.factory.PyAstFactory) TokensList(org.python.pydev.core.TokensList) Return(org.python.pydev.parser.jython.ast.Return) IImageCache(org.python.pydev.shared_core.image.IImageCache) IterTokenEntry(org.python.pydev.core.IterTokenEntry) ImmutableTuple(org.python.pydev.shared_core.structure.ImmutableTuple) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope) CoreException(org.eclipse.core.runtime.CoreException) PythonNatureWithoutProjectException(org.python.pydev.core.PythonNatureWithoutProjectException) CompletionRecursionException(org.python.pydev.core.structure.CompletionRecursionException) BadLocationException(org.eclipse.jface.text.BadLocationException) IOException(java.io.IOException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ICodeCompletionASTManager(org.python.pydev.core.ICodeCompletionASTManager) IImageHandle(org.python.pydev.shared_core.image.IImageHandle) AdapterPrefs(org.python.pydev.parser.jython.ast.factory.AdapterPrefs) OrderedMap(org.python.pydev.shared_core.structure.OrderedMap) SourceToken(org.python.pydev.ast.codecompletion.revisited.modules.SourceToken) NameTok(org.python.pydev.parser.jython.ast.NameTok)

Example 5 with LineStartingScope

use of org.python.pydev.core.docutils.PySelection.LineStartingScope in project Pydev by fabioz.

the class PySelectionTest method testLineStartingScope.

public void testLineStartingScope() throws Exception {
    String str = "" + "class Bar:\n" + "\n" + "    def m1(self):\n" + "        pass\n" + "";
    doc = new Document(str);
    PySelection ps = new PySelection(doc, 0);
    LineStartingScope nextLineThatStartsScope = ps.getNextLineThatStartsScope();
    assertEquals(0, nextLineThatStartsScope.iLineStartingScope);
    ps = new PySelection(doc, 12);
    nextLineThatStartsScope = ps.getNextLineThatStartsScope();
    assertEquals(2, nextLineThatStartsScope.iLineStartingScope);
}
Also used : PySelection(org.python.pydev.core.docutils.PySelection) Document(org.eclipse.jface.text.Document) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope)

Aggregations

LineStartingScope (org.python.pydev.core.docutils.PySelection.LineStartingScope)10 PySelection (org.python.pydev.core.docutils.PySelection)4 BadLocationException (org.eclipse.jface.text.BadLocationException)3 RefactoringRequest (org.python.pydev.ast.refactoring.RefactoringRequest)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CoreException (org.eclipse.core.runtime.CoreException)2 CompletionState (org.python.pydev.ast.codecompletion.revisited.CompletionState)2 IPyRefactoring2 (org.python.pydev.ast.refactoring.IPyRefactoring2)2 ICodeCompletionASTManager (org.python.pydev.core.ICodeCompletionASTManager)2 ICompletionState (org.python.pydev.core.ICompletionState)2 IModule (org.python.pydev.core.IModule)2 IPythonNature (org.python.pydev.core.IPythonNature)2 TokensList (org.python.pydev.core.TokensList)2 TokensOrProposalsList (org.python.pydev.core.TokensOrProposalsList)2 AddTokenAndImportStatement (com.python.pydev.analysis.refactoring.quick_fixes.AddTokenAndImportStatement)1 File (java.io.File)1 IOException (java.io.IOException)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1