Skip to content

Instantly share code, notes, and snippets.

@FichteFoll
Created June 26, 2014 17:02
Show Gist options
  • Save FichteFoll/41492d6399f3694a9acf to your computer and use it in GitHub Desktop.
Save FichteFoll/41492d6399f3694a9acf to your computer and use it in GitHub Desktop.
Sublime Plugin: Always ensures a newline at eof
import sublime_plugin
# Override default command here that is restricted onto real views
# (and also does not modify selection)
class EnsureNewlineAtEofCommand(sublime_plugin.TextCommand):
def insert_nosel(self, view, edit, p, text):
"""Insert text without changing selection. Use with care.
"""
sel = list(view.sel())
view.sel().clear()
view.insert(edit, p, text)
view.sel().add_all(sel)
def run(self, edit):
v = self.view
if v.settings().get("is_widget"):
return
if v.substr(v.size() - 1) != "\n":
self.insert_nosel(v, edit, v.size(), "\n")
# Use Sublime's internal function to get the command name.
# `None` is only written to `self.view`, which we don't need here.
cmd_name = EnsureNewlineAtEofCommand(None).name()
setting_name = "ensure_newline_at_eof"
class ExampleEventListener(sublime_plugin.EventListener):
# Used for locking on specific views
undoing = []
def on_modified(self, view):
# Must be sync
if view.id() not in self.undoing and view.command_history(0)[0] != cmd_name:
view.run_command(cmd_name)
def on_text_command(self, view, cmd, args):
if cmd == "undo":
# Check if disabled
if not view.settings().get(setting_name, True):
return
# Prevent undoing if enaeof was the first command TODO test
if view.command_history(-1)[0] is None:
return ('', None)
if view.command_history(0, True)[0] == cmd_name:
# Don't have on_text_modified interfere here and create a lock
self.undoing.append(view.id())
view.run_command("undo") # Note: this does not trigger the event hook, for some reason
self.undoing.remove(view.id())
def last_command_was_enaeof(self, view):
last_command = view.command_history(0, True)[0]
print(last_command)
# Don't undo if enaeof was the last command
if bool(view.command_history(1)[0]):
return ('', None)
return last_command == cmd_name
# Also apply to new files
on_load = on_modified
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment