Last active
March 16, 2017 08:14
-
-
Save leonid-ed/74058d32c3336530c3c7e64d476f2551 to your computer and use it in GitHub Desktop.
Sublime Text 3 plugin that copies selected lines to the clipboard.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The MIT License (MIT) | |
# Copyright (c) 2016 Leonid Edrenkin | |
# | |
# This is a Sublime Text 3 plugin that copies selected lines to the clipboard. | |
# You should select text lines and apply command: | |
# view.run_command('copy_lines_to_clipboard') | |
# view.run_command('copy_lines_to_clipboard', {"with_filename": True}) | |
# view.run_command('copy_lines_to_clipboard', {"with_filename": True, "tabsize" : 4}) | |
import sublime | |
import sublime_plugin | |
class CopyLinesToClipboardCommand(sublime_plugin.TextCommand): | |
def getDigitLen(num): | |
i = 1 | |
while num > 0: | |
num = int(num / 10) | |
i += 1 | |
return i | |
def run(self, edit, **args): | |
v = self.view | |
regions = [ s for s in self.view.sel() if not s.empty() ] | |
if len(regions) == 0: | |
return | |
src_leftmargin = 2 | |
src_tabsize = 2 | |
if args.get('tabsize') and args['tabsize'] > 2: | |
src_tabsize = args.get('tabsize') | |
trail_space_num = -1 | |
new_lines = [] | |
for region in regions: | |
if region.empty(): | |
continue | |
region = v.full_line(region) | |
lines = v.split_by_newlines(region) | |
line_start , _ = v.rowcol(region.begin()) | |
line_end , _ = v.rowcol(region.end()) | |
line_num = line_start | |
for i, line in enumerate(lines): | |
line_num += 1 | |
s = v.substr(line) | |
# count trailing spaces | |
if len(s.rstrip()) > 0: | |
s = s.rstrip() | |
spaces = 0 | |
for c in s: | |
if c in ' \t': | |
spaces += 1 | |
else: | |
break | |
if trail_space_num == -1: | |
trail_space_num = spaces | |
else: | |
trail_space_num = min(spaces, trail_space_num) | |
# copy lines | |
zero_num = CopyLinesToClipboardCommand.getDigitLen(line_end) - CopyLinesToClipboardCommand.getDigitLen(line_num) | |
line_pref = "%s%s%d: " % (" "*src_leftmargin, "0"*zero_num, line_num) | |
new_lines.append( [line_pref, s] ) | |
for i in range(len(lines)): | |
new_lines[i][1] = new_lines[i][1][trail_space_num:] | |
new_lines[i] = new_lines[i][0] + new_lines[i][1].replace("\t", " "*src_tabsize) | |
# paste filename in the beginning | |
if args.get('with_filename') and args['with_filename']: | |
folders = v.window().folders() | |
filename = v.file_name() | |
for f in folders: | |
if filename.startswith(f): | |
filename = filename[len(f) + 1:] | |
break | |
new_lines.insert(0, "%s:%d" % (filename, line_start)) | |
sublime.set_clipboard("\n".join(new_lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment