Sort current file

  • MobiusVortex

    Thanks to Dave B for the powerful plugin.

    Script to sort the current file

    Requires sqlite3. If you have trouble with "import sqlite3" See:
      (Pertains to different packages but the issue is the same)
      May also be necessary to copy sqlite3.dll to:

      Sort the current file.
      Options are:
        Case sensitive y/n?     - Case sensitive sorting or ignore case
        Remove duplicates y/n?  - Remove duplicate lines from file
        Overwrite file y/n?     - Overwrite existing file or open a new one
        Right justify sort y/n? - Right justify data in the column for sort. Good for numeric data
        Column width            - Width of column to sort. Column starts at current caret position
    import sqlite3
    sSchema = 'CREATE TABLE sortLines (lineFrag TEXT {}, lineFull TEXT);'
    sInsertStmt = 'INSERT INTO [sortLines] (lineFrag, lineFull) VALUES (:lineFrag, :lineFull)'
    curPos = editor.getColumn(editor.getCurrentPos())
    def sortLine(contents, lineNumber, totalLines):
        lineFrag = contents[curPos: curPos + searchLen].decode('latin-1')
        if rightJustify == 'y': lineFrag = (padding + lineFrag.rstrip())[-searchLen:]
        conn.execute(sInsertStmt, {'lineFrag':lineFrag, 'lineFull':contents.decode('latin-1') })
    result = notepad.prompt('Case sensitive y/n?  Remove duplicates y/n?  Overwrite file y/n?  Right justify sort y/n?\nColumn width (number of characters to compare)', 'Sort File Options', 'nnnn25')
    if result:
        caseSen = result[0:1].lower()
        removeDup = result[1:2].lower()
        overwriteFile = result[2:3].lower()
        rightJustify = result[3:4].lower()
        searchLen = result[4:]
        searchLen = int(searchLen) if searchLen.isdigit() else 25
        padding = ' ' * searchLen
        conn = sqlite3.connect(':memory:')
        conn.execute(sSchema.format('' if caseSen == 'y' else 'COLLATE NOCASE'))
        if overwriteFile == 'y':
        for row in conn.execute('SELECT {} lineFull FROM sortLines ORDER BY lineFrag'.format('DISTINCT' if removeDup == 'y' else '')):