This is indeed possible; the target
key in a sublime-build
file will tell Sublime that it should execute a custom command instead of what it would normally execute in order to run a build (the internal exec
command). In order to do what you want here, you would need to modify the sublime-build
file and also have a small glue plugin that does what you want.
An example plugin is below; if you’re not sure how to use it, there is a video here that goes over that.
import sublime
import sublime_plugin
from Default.exec import ExecCommand
class CopyThenExecCommand(ExecCommand):
"""
Drop in replacement for the internal exec command that copies
text to the clipboard before executing the build.
"""
def run(self, **kwargs):
view = self.window.active_view()
select_whole_line = kwargs.pop("select_whole_line", False)
span = view.sel()[0]
if span.empty() or select_whole_line:
span = view.line(span.b)
sublime.set_clipboard(view.substr(span))
super().run(**kwargs)
The first thing this does is grab some text and stick it in the clipboard. Specifically, if there is text selected, it will copy that text to the clipboard, but if there is no current selection it will copy the line that the cursor is on instead. You can also add a key named select_whole_line
to your build to force it to always copy the whole line no matter what.
When this copies a whole line, it doesn’t grab the \n
on the end of the line that terminates it; if you want that, replace view.line
with view.full_line
instead. Additionally, this only grabs the text from the first cursor if there is more than one; slight modifications are needed if you want this to grab the selected text from all of the cursors and not just the first one.
To use it, you need to modify your sublime-build
file to add some extra keys:
"target": "copy_then_exec",
"cancel": {"kill": true},
"select_whole_line": true,
The target
key is required; it tells Sublime to run the new command instead of the default when the build runs. The cancel
key tells Sublime how to go about cancelling a running build started by the custom target; if you never cancel builds you could leave that key out.
The select_whole_line
key is optional; it’s given to the custom command which will use it as outlined above to ensure that the whole line is copied even if there is some selected text.