Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sublime Text 3 - Clean Paste

Sublime Text 3 is looking great, but one item that is keeping me from switching is the compatibility of Clipboard Commands. The only thing I use this plugin for is the "clean_paste" function which basically makes pasting copied content from Microsoft Word (or any other text editor) strip out the funny characters it normally comes with. Does anyone know of a native function that ST3 provides that I can map a keybinding to? Here is what ClipboardCommand does (in the ST2 version):

class ClipboardCommandsPastePlainText(sublime_plugin.TextCommand):
    def run(self, edit):
        copy(clean_paste(clipboard()))
        self.view.run_command('paste')

Possibly more of a Python question in general as well, but you can also create your own keybindings and this one basically just references that command:

"caption": "Clipboard: Paste Plain Text",
"command": "clipboard_commands_paste_plain_text"

So if the command is something I could just put that function into that'd be great, but not sure how that works in Python. Thanks for any help!

like image 961
Zach Avatar asked Oct 03 '22 05:10

Zach


1 Answers

Not too much work to make this python 3 compatible:

# coding=utf8
import sublime_plugin, sublime, re, html

def clipboard():
    return sublime.get_clipboard()

def copy(data):
    sublime.set_clipboard(data)

# to transfer data to sublime text
def clean_paste(data):
    # clean word
    data = str(data)
    data = data.replace(u'”', '"').replace(u'“', '"').replace(u'’', "'")
    data = data.replace('________________________________________', '\n')
    # clean htmlentities
    data = re.sub('&([^;]+);', lambda m: unichr(html.entities.name2codepoint[m.group(1)]), data)
    return data;

# to transfer data from sublime text
def clean_copy(data):
    # clean html
    data = str(data)
    data = re.sub(r'<br ?/?>', '\n', data, re.I);
    data = re.sub(r'<[^>]*>', '', data);
    # clean htmlentities
    data = re.sub('&([^;]+);', lambda m: unichr(html.entities.name2codepoint[m.group(1)]), data)
    return data;

I've forked the linked plugin and uploaded the changes here

Tested it in sublime3 and it appears to work, but without test cases I'll leave that one to you.

like image 125
Noelkd Avatar answered Oct 18 '22 07:10

Noelkd