Search code examples
sublime-text-plugin

How do I echo the changes to a file in a sublime text plugin


I am experimenting with a sublime text plugin and I'd like to capture every keystroke and print the inserted/deleted characters in the console along with the line number and position in the line.

There is an on_modified event in the event listener class that I can wire up but it returns a view object. I would like just the change that was made along with some info about the change (line and column number). I have extended other editors in the past and this info was available as a group of edits.

Is the inserted or deleted text along with a position in the file available from the event listener in a sublime plugin?


Solution

  • I'd avoid using the console.   Panels are very limited compared to views, and you'd be competing with the standard console output.   If you really want to use a panel, use create_output_panel & show_input_panel

    I'd go with a stored string or stringarray that you continuously append the info to, and also create a command to print that stored info to a new view whenever you need it.   You could implement a dictionary to store change info per file.

    You can use substr & rowcol to find the most recently entered character, along with it's position.

     



     

    Example:

    Demo

     

    Code:

    import sublime, sublime_plugin
    
    class EventListener ( sublime_plugin.EventListener ):
    
        def on_modified ( self, view ):
    
            selectedRegions = view.sel()
    
            for region in selectedRegions:
    
                row, column = view.rowcol ( region.a )
                line = row + 1
                lastCharacter_Region = sublime.Region ( region.a - 1, region.a )
                lastCharacter = view.substr ( lastCharacter_Region )
    
                print ( "line: " + str ( line ) + "   col: " + str ( column ) + "   char: " + lastCharacter )
    

     



     

    Notes:

    [1]

    I did not implement an output panel in the example above, for the sake of keeping it simple.   You can use the code as is, but if you're planning to release your plugin I would avoid using the console.

    For example: I have the commands sublime.log_input ( True ) & sublime.log_commands ( True ) enabled by default ( for development purposes ), so any system prints will be interspersed with all of the log output.

    [2]

    I'm working on a somewhat related plugin, LineDiff.   The solutions I mentioned above will work great for keyboard-entered changes, but keeping track of programmatic changes is a bit more involved. See this thread for some of my thoughts & proposed solutions to that issue.

    [3]

    OP created a thread to further discuss this @ the SublimeText forum.

    Significant progress has been made, check it out @:

    Retrieving inserted and deleted text