omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Change indent on multiple lines

    Pythonista
    2
    3
    3045
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • lrr
      lrr last edited by

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

      1 Reply Last reply Reply Quote 0
      • JonB
        JonB last edited by

        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))
        
        1 Reply Last reply Reply Quote 0
        • lrr
          lrr last edited by

          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.

          1 Reply Last reply Reply Quote 0
          • First post
            Last post
          Powered by NodeBB Forums | Contributors