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;
}
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;
}
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);
}
}
}
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));
}
}
}
}
}
}
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);
}
Aggregations