Skip to content

Instantly share code, notes, and snippets.

@FichteFoll
Created August 15, 2012 12:37
Show Gist options
  • Save FichteFoll/3359801 to your computer and use it in GitHub Desktop.
Save FichteFoll/3359801 to your computer and use it in GitHub Desktop.
Sublime Text 2 plugin; copys multiple selections linewise to the clipboard an prepends the line numbers
[
{ "caption": "Copy with line numbers", "command": "copy_with_line_numbers" }
]
# Source and idea: http://sublimetext.userecho.com/topic/54873
import sublime
import sublime_plugin
class CopyWithLineNumbersCommand(sublime_plugin.TextCommand):
def run(self, edit):
sels = self.view.sel()
# To print all the line numbers with the same lenght
max_line_num = self.get_line_num(sels[-1].end())
max_line_num_len = len(str(max_line_num))
format_string = "%0" + str(max_line_num_len) + "d: %s\n"
# Assign output
output = "File: %s\n" % (self.view.file_name() or '')
is_followup = False
for sel in sels:
if is_followup:
output += "-" * (max_line_num_len + 1) + "\n"
else:
is_followup = True
sel = self.view.line(sel) # Extend selection to full lines
first_line_num = self.get_line_num(sel.begin())
lines = self.view.substr(sel).split("\n") # Considers all line breaks
for i, line in enumerate(lines):
output += format_string % (first_line_num + i, line)
# Do "output"
sublime.set_clipboard(output)
def get_line_num(self, point):
return self.view.rowcol(point)[0] + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment