Skip to content

Instantly share code, notes, and snippets.

@mattst
Created March 19, 2019 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattst/e069deeb0d58d9d3af31823fa6fc718d to your computer and use it in GitHub Desktop.
Save mattst/e069deeb0d58d9d3af31823fa6fc718d to your computer and use it in GitHub Desktop.
ST Plugin OpenSelectedTextInNewBufferCommand
# Command: open_selected_text_in_new_buffer
import sublime
import sublime_plugin
class OpenSelectedTextInNewBufferCommand(sublime_plugin.TextCommand):
"""
A Sublime Text plugin to create a new buffer, possibly in a new window,
which contains the selected text from the current buffer (if any). The
arg 'open_in_new_window': bool, controls whether to create a new window.
"""
def run(self, edit, open_in_new_window=False):
text_inserter = "open_selected_text_in_new_buffer_text_inserter"
if open_in_new_window:
sublime.run_command("new_window")
active_window = sublime.active_window()
new_file = active_window.new_file()
is_any_text_to_insert = False
for sel in self.view.sel():
if sel.size() > 0:
is_any_text_to_insert = True
break
# Insert a blank line if text is going to be inserted, this
# serves to prevent the buffer name from being a long line.
if is_any_text_to_insert:
active_window.run_command(text_inserter, {"text": "\n"})
for sel in self.view.sel():
if sel.size() > 0:
text = self.view.substr(sel)
active_window.run_command(text_inserter, {"text": text})
last_char_is_newline = text[-1:] == "\n"
# Insert a final blank line if text was inserted and one is needed.
if is_any_text_to_insert and not last_char_is_newline:
active_window.run_command(text_inserter, {"text": "\n"})
class OpenSelectedTextInNewBufferTextInserterCommand(sublime_plugin.TextCommand):
"""
A Sublime Text helper plugin to act as a text inserter.
"""
def run(self, edit, text):
eof = self.view.size()
line = self.view.line(eof)
# Insert a new line to act as a separator unless
# 'text' already consists of just a blank line.
if line.size() > 0 and text != "\n":
self.view.insert(edit, eof, "\n")
eof = self.view.size()
self.view.insert(edit, eof, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment