Python Indent Script
14 Nov 2005So, Python scripting for PN is shaping up nicely. I fixed some leaks, I exposed some more classes, and look what I can do now:
`
def findPrevLineLastChar(p, sci):
while p > 0:
p = p - 1
c = chr( sci.GetCharAt(p) )
# Look for a non-whitespace character ending the previous line.
if not c in ['\n','\r','\t',' ']:
return c
return None
def python_indent(c, doc):
sci = scintilla.Scintilla(doc)
if c == '\n' or c == '\r':
pos = sci.CurrentPos
line = sci.LineFromPosition( pos )
lc = findPrevLineLastChar( pos, sci )
# If the previous line ended with a colon, then indent
if lc == ':':
indent = sci.GetLineIndentation( line )
# Modify DumbIndent(tm) Indenting...
previndent = sci.GetLineIndentation( line - 1 )
if indent == previndent or indent == 0:
indent += 4
sci.IndentLine( line, indent )
# Hook up the python indenter.
s = getSchemeConfig("python")
s.indenter = python_indent
`
For those of you that can’t be bothered to read the above code to find out what it does, it provides a simplistic smart-indent algorithm for Python. If you add a new line after a “:” character, it indents the line.
Sure the algorithm could be more clever (it won’t work if there’s a comment after the ‘:’ for example) but the code basically works, and I can now write Python code with smart indenting. PN with Python rocks.