Skip to content

Instantly share code, notes, and snippets.

@cjmeyer
Last active December 16, 2015 18:39
Show Gist options
  • Save cjmeyer/5479581 to your computer and use it in GitHub Desktop.
Save cjmeyer/5479581 to your computer and use it in GitHub Desktop.
Sublime Text 2: Insert text and maintain viewport
# The code below only manages vertical position and assumes the text is
# being inserted before the current cursor (of which there is only one
# and no text is highlited). This can be expanded to manage the
# horizontal position and multi-selected text if needed using the same
# principals as used below.
v = sublime.active_window().active_view()
pos = v.sel()[0][0]
y0 = v.viewport_position()[1]
y1 = v.text_to_layout(pos)[1]
offset = y1 - y0
e = v.begin_edit()
n = v.insert(e, pos, (("*" * 30) + "\n") * 30)
v.sel().clear()
v.sel().add(sublime.Region(pos + n, pos + n))
y2 = v.text_to_layout(pos + n)[1]
v.set_viewport_position((0.0, y2 - offset), False)
v.end_edit(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment