Skip to content

Commit

Permalink
Starting to move templates from pytemplate_defaults.py to java code.
Browse files Browse the repository at this point in the history
  • Loading branch information
fabioz committed Apr 18, 2024
1 parent d9bddb9 commit ae01bc4
Show file tree
Hide file tree
Showing 4 changed files with 138 additions and 19 deletions.
22 changes: 4 additions & 18 deletions plugins/org.python.pydev.jython/jysrc/pytemplate_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,27 +59,18 @@ def _IsGrammar3(context):
def GetISODate(context):
return time.strftime("%Y-%m-%d")

template_helper.AddTemplateVariable(py_context_type, 'isodate', 'ISO-8601 Ymd date', GetISODate)

def GetISODateString1(context):
return time.strftime("%Y-%m-%d %H:%M")

template_helper.AddTemplateVariable(py_context_type, 'isodatestr', 'ISO-8601 Ymd HM date', GetISODateString1)

def GetISODateString2(context):
return time.strftime("%Y-%m-%d %H:%M:%S")

template_helper.AddTemplateVariable(py_context_type, 'isodatestr2', 'ISO-8601 Ymd HMS date', GetISODateString2)


#===================================================================================================
# GetModuleName
#===================================================================================================
def GetModuleName(context):
return context.getModuleName()

template_helper.AddTemplateVariable(py_context_type, 'module', 'Current module', GetModuleName)


#===================================================================================================
# _GetCurrentASTPath
Expand Down Expand Up @@ -113,11 +104,6 @@ def GetQualifiedNameScope(context):
return ret


template_helper.AddTemplateVariable(
py_context_type, 'current_qualified_scope', 'Current qualified scope.', GetQualifiedNameScope)



#===================================================================================================
# _GetCurrentClassStmt
#===================================================================================================
Expand Down Expand Up @@ -153,18 +139,18 @@ def GetCurrentClass(context):
#===================================================================================================
def GetSelfOrCls(context):
FunctionDef = context.getFunctionDefClass() # from org.python.pydev.parser.jython.ast import ClassDef

FastParser = context.getFastParserClass() # from org.python.pydev.parser.fastparser import FastParser
selection = _CreateSelection(context)

node = FastParser.firstClassOrFunction(context.getDocument(), selection.getStartLineIndex(), False, False)
if isinstance(node, FunctionDef):
firstToken = selection.getFirstInsideParentesisTok(node.beginLine-1)
if firstToken == 'cls':
return 'cls'

return 'self'

template_helper.AddTemplateVariable(py_context_type, 'self_or_cls', 'Get `self` or `cls`', GetSelfOrCls)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class PyContextType extends TemplateContextType {
private IPythonInterpreter interpreter;

/**
* Creates a new XML context type.
* Creates a new XML context type.
*/
public PyContextType() {
//Note: created twice because we have 2 registries:
Expand All @@ -57,6 +57,11 @@ private void addGlobalResolvers() {
addResolver(new GlobalTemplateVariables.Year());
addResolver(new GlobalTemplateVariables.Time());
addResolver(new GlobalTemplateVariables.User());
addResolver(PyTemplatesDefault.IsoDate());
addResolver(PyTemplatesDefault.IsoDate1());
addResolver(PyTemplatesDefault.IsoDate2());
addResolver(PyTemplatesDefault.ModuleName());
addResolver(PyTemplatesDefault.QualifiedNameScope());

PyContextTypeVariables.addResolvers(this);
HashMap<String, Object> locals = new HashMap<String, Object>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package org.python.pydev.editor.templates;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.eclipse.jface.text.templates.TemplateContext;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.editor.codecompletion.templates.PyDocumentTemplateContext;
import org.python.pydev.parser.fastparser.FastParser;
import org.python.pydev.parser.jython.ast.stmtType;
import org.python.pydev.parser.visitors.NodeUtils;
import org.python.pydev.shared_core.callbacks.ICallback;
import org.python.pydev.shared_core.string.FastStringBuffer;

public class PyTemplatesDefault {

public static class CallableTemplateVariableResolver extends PyTemplateVariableResolver {

private ICallback<String, PyDocumentTemplateContext> callable;

public CallableTemplateVariableResolver(String type, String description,
ICallback<String, PyDocumentTemplateContext> callable) {
super(type, description);
this.callable = callable;
}

@Override
public String[] resolveAll(TemplateContext context) {
String ret = this.callable.call((PyDocumentTemplateContext) context);
if (ret == null) {
return new String[0];
}
return new String[] { ret };
}
}

public static CallableTemplateVariableResolver IsoDate() {
return new PyTemplatesDefault.CallableTemplateVariableResolver("isodate", "ISO-8601 Ymd date", (context) -> {
// in Python: time.strftime("%Y-%m-%d")
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return formatter.format(date);
});
}

public static CallableTemplateVariableResolver IsoDate1() {
return new PyTemplatesDefault.CallableTemplateVariableResolver("isodatestr", "ISO-8601 Ymd HM date",
(context) -> {
// in Python: time.strftime("%Y-%m-%d %H:%M")
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date();
return formatter.format(date);
});
}

public static CallableTemplateVariableResolver IsoDate2() {
return new PyTemplatesDefault.CallableTemplateVariableResolver("isodatestr2", "ISO-8601 Ymd HM date",
(context) -> {
// in Python: time.strftime("%Y-%m-%d %H:%M:%S")
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return formatter.format(date);
});
}

public static CallableTemplateVariableResolver ModuleName() {
return new PyTemplatesDefault.CallableTemplateVariableResolver("module", "Current module",
(context) -> {
return context.getModuleName();
});
}

public static List<stmtType> getCurrentAstPath(PyDocumentTemplateContext context) {
return getCurrentAstPath(context, false);
}

public static List<stmtType> getCurrentAstPath(PyDocumentTemplateContext context, boolean reverse) {
PySelection selection = context.createPySelection();
List<stmtType> ret = FastParser.parseToKnowGloballyAccessiblePath(context.getDocument(),
selection.getStartLineIndex());
if (reverse) {
Collections.reverse(ret);
}
return ret;
}

public static CallableTemplateVariableResolver QualifiedNameScope() {
return new PyTemplatesDefault.CallableTemplateVariableResolver("current_qualified_scope",
"Current qualified scope",
(context) -> {
List<stmtType> stmts = getCurrentAstPath(context);
FastStringBuffer buf = new FastStringBuffer();
for (stmtType stmt : stmts) {
if (!buf.isEmpty()) {
buf.append('.');
}
buf.append(NodeUtils.getRepresentationString(stmt));
}
return "";
});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.python.pydev.ast.codecompletion.templates;

import org.python.pydev.editor.templates.PyTemplatesDefault;
import org.python.pydev.shared_core.string.StringUtils;

import junit.framework.TestCase;

public class TemplatesTest extends TestCase {

public void testIsoDate() throws Exception {
String found = PyTemplatesDefault.IsoDate().resolveAll(null)[0];
assertEquals(StringUtils.count(found, '-'), 2);

found = PyTemplatesDefault.IsoDate1().resolveAll(null)[0];
assertEquals(StringUtils.count(found, '-'), 2);
assertEquals(StringUtils.count(found, ':'), 1);

found = PyTemplatesDefault.IsoDate2().resolveAll(null)[0];
assertEquals(StringUtils.count(found, '-'), 2);
assertEquals(StringUtils.count(found, ':'), 2);
}

}

0 comments on commit ae01bc4

Please sign in to comment.