Create a gist now

Instantly share code, notes, and snippets.

@nilium /
Last active May 17, 2017

What would you like to do?
capture_snippet command for Sublime Text to stuff selected text into a snippet.


The capture_snippet command is fairly simple: it grabs the current selection (or the concatentation of all your selections [joined by newlines]) and stuffs it in a .sublime-snippet file. It takes a few measures to ensure the snippet has sane indentation, but otherwise it's as dumb as it sounds, and surprisingly useful in spite of that.

capture_snippet takes only one possible argument: name, which is a path relative to the Packages/ directory of your Sublime Text installation's user directory. By default, it uses "User/captured-snippet.sublime-snippet".

To use the snippet, just set up a key-binding to insert it.

This gist should contain example keybindings that show the command's usage and an example keybinding for the insert_snippet command.

Obligatory Example .GIF

A .GIF image demonstrating a contrived and basic example of capture_snippet usage


capture_snippet is public domain because who cares as long as someone finds it useful.

# public domain, use as you see fit.
import sublime, sublime_plugin
def line_indent(line):
index = 0
if len(line) == 0:
return 0
indent_char = line[0]
if indent_char != ' ' and indent_char != '\t':
return 0
while index < len(line) and line[index] == indent_char: index += 1
return index
def unindent(lines, first_column = None):
lines = lines.splitlines(True)
if len(lines) == 1:
return ''.join(s.lstrip() for s in lines)
lines[0] = lines[0].lstrip()
indentation_levels = list(line_indent(l) for l in lines[1:] if l != '\n')
if first_column is not None:
indent = min(indentation_levels)
if indent != 0:
for idx, l in enumerate(lines[1:], 1):
if len(l) == 0: continue
lines[idx] = l[indent:]
return ''.join(lines)
class CaptureSnippetCommand(sublime_plugin.WindowCommand):
def run(self, name = None):
if name is None:
name = 'User/captured-snippet.sublime-snippet'
snippet_path = sublime.packages_path() + '/' + name
view = self.window.active_view()
sel = view.sel()
selections = []
for region in sel:
if region.empty(): continue
min_indent = line_indent(view.substr(view.line(region.begin())))
selections.append(unindent(view.substr(region), min_indent))
if len(selections) == 0:
snippet = '\n'.join(selections)
if len(snippet) == 0:
snippet_out = open(snippet_path, 'wb')
snippet_out.write(bytes('<snippet><content><![CDATA[\n', 'UTF-8'))
snippet_out.write(bytes(snippet, 'UTF-8'))
snippet_out.write(bytes('\n]]></content></snippet>', 'UTF-8'))
"keys": ["alt+enter"],
"command": "insert_snippet",
"args": {
"name": "Packages/User/captured-snippet.sublime-snippet"
"keys": ["alt+shift+enter"],
"command": "capture_snippet",
"args": {
"name": "User/captured-snippet.sublime-snippet"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment