Reverse Line Order

2012-10-30
2013-01-25
  • Reck Dickhard
    Reck Dickhard
    2012-10-30

    Reverses the order of either selected lines, or the entire document if nothing is selected.
    Here it is with nicer syntax highlighting: http://pastebin.com/nG9zeBkW

    def reverseAllLines():
        lines   = editor.getText().splitlines()
        lines.reverse()
        editor.setText(os.linesep.join(lines))
    def reverseSelectedLines():
        import os
        staline = editor.lineFromPosition(editor.getSelectionStart())
        endline = editor.lineFromPosition(editor.getSelectionEnd())
        start   = editor.positionFromLine(staline)
        end     = editor.positionFromLine(endline)+editor.lineLength(endline)
        text    = editor.getTextRange(start, end)
    
        if text.endswith(os.linesep):
            eol = os.linesep
        else:
            eol = ''
        lines   = text.splitlines()
        lines.reverse()
        text    = os.linesep.join(lines)+eol
        editor.setSelection(start, end)
        editor.replaceSel(text)
        editor.setSelection(start, end) #keep selection after replace
    editor.beginUndoAction()
    if editor.getSelectionStart() == editor.getSelectionEnd():
        reverseAllLines()
    else:
        reverseSelectedLines()
    editor.endUndoAction()