Menu

Automatic Detection of Python Tabs or Spaces

2015-07-01
2015-11-16
  • Josef H. B. Schneider

    This script isn't written by me, but I found it on StackOverflow and find it very usefull.
    You add this to your startup.py and every time the buffer is switched, it tries to detect automatically if the file is using tabs or spaces. I made one small change to check only the first 100 lines of the file because it was slow for very large files.

        from itertools import islice
        def guess_tab(text):
            count = 0
            for line in islice(text.split("\n"),100):
                indents = line[:len(line)-len(line.lstrip())]
                if "\t" in indents:
                    count += 1
            if count > 5: 
                return True
            else:
                return False
    
        def buffer_active(arg):
            editor.setBackSpaceUnIndents(True)
            use_tab = guess_tab(editor.getText())
            editor.setUseTabs(use_tab)
            sys.stderr.write( "setUseTabs %s\n" % use_tab )
    
        notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED])    
        notepad.callback(buffer_active, [NOTIFICATION.BUFFERACTIVATED])
    

    As stated on stackoverflow, it could be improved by storing the setting for open files.
    One problem I notices is, it isn't called if notepad++ is started by opening a file. If I then add another empty file and switch back, it works. Maybe someone who knows which callback to use could add this.

     
  • Vincent Paré

    Vincent Paré - 2015-11-16

    You can use this improved version that works from the startup file, not only on tab switch : https://gist.github.com/vincepare/8a204172d959defb2122

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.