Sort current file

2012-02-13
2013-01-25
  • MobiusVortex
    MobiusVortex
    2012-02-13

    Thanks to Dave B for the powerful plugin.

    Script to sort the current file

    Requires sqlite3. If you have trouble with "import sqlite3" See:
      http://sourceforge.net/projects/npppythonscript/forums/forum/1188886/topic/4581184?message=10334403
      https://sourceforge.net/projects/npppythonscript/forums/forum/1188886/topic/4438530
      (Pertains to different packages but the issue is the same)
      May also be necessary to copy sqlite3.dll to:
        …\Notepad++\plugins\PythonScript\lib\

    '''
      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'))
        editor.forEachLine(sortLine)
        if overwriteFile == 'y':
            editor.clearAll()
        else:
            notepad.new()
        for row in conn.execute('SELECT {} lineFull FROM sortLines ORDER BY lineFrag'.format('DISTINCT' if removeDup == 'y' else '')):
            editor.addText(row[0].encode('latin-1'))
        conn.close()