Forum Archive

Change indent on multiple lines

lrr

I'm used to selecting multiple lines and hitting tab to indent them further, but this doesn't work in Pythonista.

JonB

Create the following scripts, and place in action menu

def indent():
  # """indent selected lines
    import editor
    import re
    INDENTSTR='  ' #two spaces
    i=editor.get_line_selection()   
    t=editor.get_text()
    # replace every occurance of newline with  ewline plus indent, except last newline
    editor.replace_text(i[0],i[1]-1,INDENTSTR+re.sub(r'\n',r'\n'+INDENTSTR,t[i[0]:i[1]-1]))
indent()
def unindent():
#   """unindent selected lines one level
  import editor
  import textwrap

  i=editor.get_line_selection()   
  t=editor.get_text()
  editor.replace_text(i[0],i[1], textwrap.dedent(t[i[0]:i[1]]))
unindent()

Unindent is rather stupid, and just removes the same leading white space from all lines, but doesn't try to match indent level from previous lines. If I were less lazy I'd have modified to grab previous lines leading white space, then called indent with that, after dedent.

Another useful use of dedent... executes a block in the interpreter, sort of a matlab style F9. Useful for debugging or real time coding

## executes selected lines
import editor
import textwrap

a=editor.get_text()[editor.get_line_selection()[0]:editor.get_line_selection()[1]]

exec(textwrap.dedent(a))
lrr

I think your regex breaks for the last line in files without a trailing newline.

Here is one that restores the selection, so it can be run several times in a row. Use like this.