def run(self, edit): try: # Get remote file full path from clipboard self.remote_file_path = sublime.get_clipboard() # Get the path of file where this command is executed self.local_file_path = self.view.file_name() # If both of above are in same level of dir, just take the remote file name # Else determine relative path if (os.path.dirname(self.local_file_path) == os.path.dirname( self.remote_file_path)): self.rel_path = os.path.basename(self.remote_file_path) else: self.rel_path = os.path.relpath( sublime.get_clipboard(), os.path.dirname(self.view.file_name())) # covert to unix/linux path self.rel_path = self.rel_path.replace('\\', '/') # Reference to selection where to insert relative path selections = self.view.sel() for selection in selections: # Erase selected text self.view.erase(edit, selection) # Insert at current cursor position self.view.insert(edit, selection.begin(), self.rel_path) # End edit self.view.end_edit(edit) except Exception as e: sublime.error_message(str(e).capitalize())
def run(self): # init self.update_latest(sublime.get_clipboard()) # check is_enabled in loop so we can deactivate it at any time while self.is_valid(): # load inverval setting here, so we can mess with the settings while it's running interval = ClipboardTracker.interval() # let's assign since this method can be time consuming data = sublime.get_clipboard() if self.has_changed(data): self.trigger_event("change", data) if ClipboardTracker.is_log_enabled(): ClipboardTracker.log(self) # sleep time.sleep(interval) if self.stop: print(self.id, 'Stop set, ClipboardTracker stopped') elif len(self.get_listeners()) == 0: print(self.id, 'No listeners left, ClipboardTracker stopped') elif not self.id in ClipboardTracker.valid_id_list: print(self.id, 'Clipboardtracker not in valid ID list, stopped') else: print(self.id, 'ClipboardTracker stopped') if self.id in ClipboardTracker.valid_id_list: ClipboardTracker.valid_id_list.remove(self.id)
def run(self, edit, **args): global killRing if len(args) == 0: # no arguments means the command # is being called directly valueToYank = sublime.get_clipboard() elif args[0] == "clipboard": # the user has chosen to yank windows clipboard. valueToYank = sublime.get_clipboard() else: # an argument means it's been called from # the EmacsYankChoiceCommand idx = int(args[0]) valueToYank = killRing.get(idx) for s in self.view.sel(): self.view.erase(edit, s) self.view.insert(edit, s.begin(), valueToYank) # once we've yanked, we definitely don't want to # reuse the old kill buffer killRing.LastKillPosition = -1 # Clear mark marks.clearMark(self.view)
def run(self): path = sublime.get_clipboard().strip() parentDirsMatch = re.search("(\\.\\.[/\\\\])*(.*)", path) if (parentDirsMatch): path = parentDirsMatch.groups()[1] gitPathPrefixMatch = re.search("^[ab][/\\\\](.*)", path) if (gitPathPrefixMatch): path = gitPathPrefixMatch.groups()[0] line = None colonLineMatch = re.search(r'(.*?):(\d+).*', path) parenthesesLineMatch = re.search(r'(.*?)\((\d+)\).*', path) junkMatch = re.search(r'(.*?[^\w]+.*?)[:,].*', path) if (colonLineMatch): path = colonLineMatch.groups()[0] line = colonLineMatch.groups()[1] elif (parenthesesLineMatch): path = parenthesesLineMatch.groups()[0] line = parenthesesLineMatch.groups()[1] elif (junkMatch): path = junkMatch.groups()[0] resolvedPath = self.resolvePath(path) if not resolvedPath: sublime.status_message("Couldn't find a file matching [%s]" % sublime.get_clipboard().strip()) return if line: self.window.open_file(resolvedPath + ':' + line, sublime.ENCODED_POSITION) else: self.window.open_file(resolvedPath)
def get(self, name=REG_UNNAMED): # We accept integers or strings a register names. name = str(name) assert len(str(name)) == 1, "Register names must be 1 char long." # Did we request a special register? if name == REG_BLACK_HOLE: return elif name == REG_FILE_NAME: try: return os.path.basename(self.view.file_name()) except AttributeError: return '' elif name in REG_SYS_CLIPBOARD_ALL: return [sublime.get_clipboard()] elif name != REG_UNNAMED and name in REG_ALL: return # Special case lumped among these --user always wants the sys # clipboard. elif name == REG_UNNAMED and self.settings.view['vintageous_use_sys_clipboard'] == True: return sublime.get_clipboard() # We requested an [a-z0-9"] register. try: # In Vim, "A and "a seem to be synonyms, so accept either. return _REGISTER_DATA[name.lower()] except KeyError: # sublime.status_message("Vintage.Next: E353 Nothing in register %s", name) pass
def run(self, edit): # Copy to Clipboard and Convert Entity => Variable |OR| Variable => Entity # # @param {Regionset} self # @param {Edit} edit # Save previous clipboard value / reset clipboard original_clipboard = sublime.get_clipboard() sublime.set_clipboard('') selections = self.view.sel() for selection in selections: # Get the selection's value and length string_value = self.view.substr(selection) v2e_output = variable_to_entity(string_value) e2v_output = entity_to_variable(string_value) if (v2e_output is False) and (e2v_output is False): # Revert clipboard to value captured before command run sublime.set_clipboard(original_clipboard) # Output error message self.view.set_status( mvt_error_status_key, 'No valid variable or entity available for conversion') threading.Timer(3, self.view.erase_status, args=[mvt_error_status_key]).start() return False else: if v2e_output is not False: output = v2e_output elif e2v_output is not False: output = e2v_output # Copy output to clipboard previous_clipboard = sublime.get_clipboard() if previous_clipboard is '': sublime.set_clipboard(output) else: sublime.set_clipboard(previous_clipboard + '\n' + output) # Status message display self.view.set_status( mvt_copy_status_key, 'Converted and copied ' + str(len(sublime.get_clipboard())) + ' characters') threading.Timer(3, self.view.erase_status, args=[mvt_copy_status_key]).start()
def run(self, edit): the_sels = self.view.sel() for a_sel in the_sels: he_text = self.view.substr(a_sel) copylen = len(sublime.get_clipboard()) self.view.insert(edit, a_sel.begin(), sublime.get_clipboard()) self.view.replace(edit,a_sel,"") eraseRegion = sublime.Region(a_sel.end() + copylen, a_sel.end() + copylen*2) self.view.erase(edit, eraseRegion)
def parse(self, text): result = None if not text: return None if text: m1 = re.compile('(-?\d+) (-?\d+) (\d+)$').match(text) m2 = re.compile('\\\\i(\d+)(,(-?\d+))?').match(text) m3 = re.compile('\\\\i\((\d+)(,(-?\d+))?').match(text) m4 = re.compile('\\\\p\((.*?)\)?').match(text) m5 = re.compile('^(\$\d+\s?)+$').match(text) if m1: (current, step, padding) = map(str, text.split(" ")) History.save_history("insert_nums", text, label=text) sublime.status_message("Inserting Nums: " + text) result = dict(Command="insert_nums", args={"current" : current, "step" : step, "padding" : padding}) elif text == "\i": History.save_history("insert_nums", "1 1 1", label="\i") sublime.status_message("Inserting #: " + text) result = dict(Command="insert_nums", args={"current" : "1", "step" : "1", "padding" : "1"}) elif m2 or m3: m = None if m2: m = m2 else: m = m3 current = m.group(1) step = m.group(3) if not current: current = "1" if not step: step = "1" History.save_history("insert_nums", text=current + " " + step + " 1", label=text) sublime.status_message("Inserting #" + text) result = dict(Command="insert_nums", args={"current" : current, "step" : step, "padding" : "1"}) elif text == "\\p": History.save_history("text_pastry_insert_text", text=sublime.get_clipboard(), label=text) sublime.status_message("Inserting from clipboard") result = dict(Command="text_pastry_insert_text", args={"text": sublime.get_clipboard(), "clipboard": True}) elif m4: separator = m4.group(1) if not separator: separator = None History.save_history("text_pastry_insert_text", text=sublime.get_clipboard(), label=text, separator=separator) sublime.status_message("Inserting from clipboard with separator: " + str(separator)) result = dict(Command="text_pastry_insert_text", args={"text": sublime.get_clipboard(), "separator": separator, "clipboard": True}) elif text == "\\UUID": sublime.status_message("Inserting UUID") History.save_history("text_pastry_insert", text=text, label="Generate UUID") result = dict(Command="text_pastry_insert", args={"command": "uuid", "options": {"uppercase": True} }) elif text == "\\uuid": sublime.status_message("Inserting UUID") History.save_history("text_pastry_insert", text=text, label="Generate uuid") result = dict(Command="text_pastry_insert", args={"command": "uuid"}) elif m5: items = ','.join(filter(None, map(lambda x: x.strip(), text.split("$")))) result = dict(Command="text_pastry_insert", args={"command": "backreference", "text": items, "separator": ","}) else: sublime.status_message("Inserting " + text) result = dict(Command="text_pastry_insert_text", args={"text": text}) else: pass return result
def run(self, edit): old = sublime.get_clipboard() self.view.run_command('copy') new = sublime.get_clipboard() sublime.set_clipboard(old) self.view.run_command('paste') sublime.set_clipboard(new)
def get(self, name=_REG_UNNAMED): # Args: # name (str|int) # # Returns: # (list|str|None) # We accept integers or strings a register names. name = str(name) assert len(name) == 1, "Register names must be 1 char long." # Did we request a special register? if name == _REG_BLACK_HOLE: return if name == _REG_FILE_NAME: try: return [self.view.file_name()] except AttributeError: return '' if name in _REG_SYS_CLIPBOARD_ALL: return [get_clipboard()] if ((name not in (_REG_UNNAMED, _REG_SMALL_DELETE)) and (name in _REG_SPECIAL)): return # Special case lumped among these --user always wants the sys clipboard if ((name == _REG_UNNAMED) and (self.settings.view['vintageous_use_sys_clipboard'] is True)): return [get_clipboard()] # If the expression register holds a value and we're requesting the # unnamed register, return the expression register and clear it # aftwerwards. if name == _REG_UNNAMED and _data.get(_REG_EXPRESSION, ''): value = _data[_REG_EXPRESSION] _data[_REG_EXPRESSION] = '' return value # We requested an [a-z0-9"] register. if name.isdigit(): if name == '0': return _data[name] return _data['1-9'][int(name) - 1] try: # In Vim, "A and "a seem to be synonyms, so accept either. return _data[name.lower()] except KeyError: pass
def run(self, edit): view = self.view for thisregion in view.sel(): thisregionfullline = view.full_line(thisregion) thisregionfulllineBeginning = thisregionfullline.begin() sublimeclipboard = sublime.get_clipboard() if(sublimeclipboard[-1:] != chr(10)): sublime.status_message("PasteIntoLines: There is not newlines ending content in clipboard, adding newline after") view.insert(edit, thisregionfulllineBeginning, sublime.get_clipboard() + chr(10)) view.show(thisregion.a + len(sublimeclipboard) + 1) else: view.insert(edit, thisregionfulllineBeginning, sublime.get_clipboard()) view.show(thisregion.a + len(sublimeclipboard) + 1)
def run(self, edit): # Copy to Clipboard and Convert Entity => Variable |OR| Variable => Entity # # @param {Regionset} self # @param {Edit} edit # Save previous clipboard value / reset clipboard original_clipboard = sublime.get_clipboard() sublime.set_clipboard('') selections = self.view.sel() for selection in selections: # Get the selection's value and length string_value = self.view.substr(selection) v2e_output = variable_to_entity(string_value, self.view) e2v_output = entity_to_variable(string_value) if (v2e_output is False) and (e2v_output is False): # Revert clipboard to value captured before command run sublime.set_clipboard(original_clipboard) # Output error message self.view.set_status(mvt_error_status_key, 'No valid variable or entity available for conversion') threading.Timer(3, self.view.erase_status, args=[mvt_error_status_key]).start() return False else: if v2e_output is not False: output = v2e_output elif e2v_output is not False: output = e2v_output # Copy output to clipboard previous_clipboard = sublime.get_clipboard() if previous_clipboard is '': sublime.set_clipboard(output) else: sublime.set_clipboard(previous_clipboard + '\n' + output) # Status message display self.view.set_status(mvt_copy_status_key, 'Converted and copied ' + str(len(sublime.get_clipboard())) + ' characters') threading.Timer(3, self.view.erase_status, args=[mvt_copy_status_key]).start()
def run(self, edit, register=None, content=None): if register: self.view.run_command('copy') if content is None: content = sublime.get_clipboard() HISTORY.register(register, content) update_output_panel(self.view.window(), True) else: self.view.run_command('copy') content = sublime.get_clipboard() chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' lines = list(chars) def on_done(idx): self.view.window().run_command('clipboard_manager_copy_to_register', {'register': lines[idx], 'content': content}) sublime.active_window().show_quick_panel(lines, on_done)
def insert_cb(self, edit): v = self.view s = sublime.get_clipboard() lst = s.split('\n') for i in range(len(lst) - 1): self.tester.insert(lst[i] + '\n', call_on_insert=True) self.tester.insert(lst[-1], call_on_insert=True)
def run(self, edit): print("MyPaste") v = self.view new_regions = [] # interpret clipboard clipboard = sublime.get_clipboard() clipboard_state = oneof['solid', 'iterable', 'doubled'] # interpret selections # if total number of sel is a multiple of cb length # then normal paste multiples (by cols or rows?) # aka 1 1 2 2 3 3 or 1 2 3 1 2 3 # if all lines have the same number of selections # then fancy paste, repeating each cb line for each sel on the line # if blunt: just call the builtin? # we [default to blunt paste, basic fancy paste,(fancy?) paste onto newline] # iterate for region in v.sel(): # design goals: # - always do the paste onto newline thing if # splitting on /\n\n|\n\EOF/ leaves no \n left # ^^ doing it literally like this sounds inefficient # - selections on the same line get special consideration # InsertToAlign had similar requirements # - default to fancy paste, option for blunt paste # - new_regions.append(region) if len(new_regions) > 0: v.show(new_regions[0]) v.sel().clear() v.sel().add_all(new_regions)
def set_clipboard(cls, cmd): if not cls.thread: cls.cb = sublime.get_clipboard() else: cls.thread.cancel() cls.thread = None sublime.set_clipboard(cmd)
def run(self, edit, **kwargs): regions = self.view.sel() if kwargs.get('source') == 'clipboard': del kwargs['source'] text = sublime.get_clipboard() replacement = self.encode(text, **kwargs) for region in regions: if region.empty(): self.view.insert(edit, region.begin(), replacement) else: self.view.replace(edit, region, replacement) return elif 'source' in kwargs: sublime.status_message('Unsupported source {0!r}'.format( kwargs['source'])) return if any(map(lambda region: region.empty(), regions)): regions = [sublime.Region(0, self.view.size())] for region in regions: text = self.view.substr(region) replacement = self.encode(text, **kwargs) self.view.replace(edit, region, replacement)
def run(self, edit, **kwargs): current = sublime.get_clipboard() diffs = self.run_diff(self.diff_content(), current, from_file=self.view.file_name(), to_file='(clipboard)') self.show_diff(diffs)
def get_right(self): """Get right.""" return { "win_id": None, "view_id": None, "clip": EasyDiffView("**clipboard**", sublime.get_clipboard(), "UTF-8") }
def process(self): text = sublime.get_clipboard() tree = {'children': {}} # Remove comments text = re.sub("\/\*[\s\S]*?\*\/", "", text) results = re.findall("([^{]+)\{([^}]+)\}", text) # Process each css block for (selector, declaration) in results: selectors = [] path = tree selector = selector.strip() if re.search(",", selector): path = self.addRule(path, selector) else: selector = re.sub("\s*([>\+~])\s*", r' &\1' , selector) selector = re.sub("(\w)([:\.])", r'\1 &\2' , selector) selectors = re.split("[\s]+", selector) for item in selectors: #fix back special chars _sel = re.sub("&(.)", r'& \1 ', item) _sel = re.sub("& ([:\.]) ", r'&\1', _sel) path = self.addRule(path, _sel) for (_property, value) in re.findall("([^:;]+):([^;]+)", declaration): obj = { "property": _property.strip(), "value": value.strip() } path['declarations'].append(obj) if len(results) == 0: return self.clean(text) return self.generateOutput(tree)
def run(self, edit): """ 0. Validate any settings that might be set badly 1. Add a diff view to the window (scratch) 2. Set its properties (name / syntax etc) 3. Fetch the current selection and the clipboard 4. Use difflib to compare them 5. Write the diff to the view """ validateSettings() current_window = self.view.window() diff_view = current_window.new_file() diff_view.set_scratch(True) diff_view.set_name("Clipboard Diff") diff_view.set_syntax_file("Packages/Diff/Diff.tmLanguage") current_selection = selectionToString(self.view) previous_selection = sublime.get_clipboard() settings = sublime.load_settings("clipboard_diff.sublime-settings") diff_type = settings.get("diff_type") diff_function = difflib.unified_diff if diff_type == "context": diff_function = difflib.context_diff diff = diff_function(getLinesHelper(previous_selection), getLinesHelper(current_selection), settings.get("clipboard_file_name"), settings.get("selection_file_name")) current_window.focus_view(diff_view) writeLinesToViewHelper(diff_view, edit, diff, index=0)
def run(self, action, title=''): self.action = action if self.action == 'mediawiker_show_page': if mw_get_setting('mediawiker_newtab_ongetpage'): self.run_in_new_window = True if not title: pagename_default = '' #use clipboard or selected text for page name if bool(mw_get_setting('mediawiker_clipboard_as_defaultpagename')): pagename_default = sublime.get_clipboard().strip() if not pagename_default: selection = self.window.active_view().sel() for selreg in selection: pagename_default = self.window.active_view().substr(selreg).strip() break self.window.show_input_panel('Wiki page name:', mw_pagename_clear(pagename_default), self.on_done, self.on_change, None) else: self.on_done(title) elif self.action == 'mediawiker_reopen_page': #get page name if not title: title = mw_get_title() self.action = 'mediawiker_show_page' self.on_done(title) elif self.action in ('mediawiker_publish_page', 'mediawiker_add_category', 'mediawiker_category_list', 'mediawiker_search_string_list', 'mediawiker_add_image', 'mediawiker_add_template', 'mediawiker_upload'): self.on_done('')
def run(self, edit): nonempty_sels = [] # set aside nonempty selections for s in reversed(self.view.sel()): if not s.empty(): nonempty_sels.append(s) self.view.sel().subtract(s) # expand remaining (empty) selections to words self.view.run_command("expand_selection", {"to": "word"}) # add nonempty selections back in for s in nonempty_sels: self.view.sel().add(s) txt = sublime.get_clipboard().strip() url = self.make_url(txt) title = None if re.match(r"^https?://", url) and url != "http://example.com/": title = { 'title': self.get_url_title(url) } # apply the links old_sels = [] for s in (self.view.sel()): old_sels.append(s) self.view.sel().clear() for s in reversed(old_sels): if not s.empty(): txt = self.view.substr(s) link = pystache.render(self.view.settings().get('hyperlink_helper_link_format'), {'url': url, 'title?': title, 'input': txt}) self.view.replace(edit, s, link) pos = s.begin() + len(link) self.view.sel().add(sublime.Region(pos, pos))
def run(self, edit, bracketed=False): # Lookup the sublime buffer instance for this view sub_buffer = SublimeBufferManager.load_from_id(self.view.id()) keypress_cb = sub_buffer.keypress_callback() if not keypress_cb: return # Check if bracketed paste mode is enabled bracketed = bracketed or sub_buffer.terminal_emulator( ).bracketed_paste_mode_enabled() if bracketed: keypress_cb("bracketed_paste_mode_start") copied = sublime.get_clipboard() copied = copied.replace("\r\n", "\n") for char in copied: if char == "\n" or char == "\r": keypress_cb("enter") elif char == "\t": keypress_cb("tab") else: keypress_cb(char) if bracketed: keypress_cb("bracketed_paste_mode_end")
def run(self, edit): content = sublime.get_clipboard() indent = self.get_indent(content) has_eol = content[-1] == '\n' # Dedent content. content = self.dedent_content(content) # print content content = self.generate_table_from_content(content) # print repr(content) # Now replace selections. rowcol = self.view.rowcol for sel in self.view.sel(): if sel.empty(): row, col = rowcol(sel.begin()) indent = ' ' * col data = self.indent_content(content, indent) if col: data = data.lstrip() else: data = content row, col = rowcol(sel.begin()) if indent: # print repr(indent), col, len(indent) subindent = indent if col: subindent += ' ' * col data = self.indent_content(content, indent, subindent) else: indent = ' ' * col data = self.indent_content(content, '', indent) if has_eol: data += '\n' self.view.replace(edit, sel, data)
def run(self, edit): try: text = sublime.get_clipboard() if text is not None and len(text) > 0: regions = [] sel = self.view.sel() items = text.split("\n") if len(items) == 1: items = [text]; strip = True settings = sublime.load_settings("TextPastry.sublime-settings") for idx, region in enumerate(sel): if idx < len(items): row = items[idx].strip() if region.empty(): sublime.status_message("empty") row = self.view.substr(self.view.line(self.view.line(region).begin()-1)) + "\n" i = 0 if len(row.strip()): i = self.view.insert(edit, region.end(), row) regions.append( sublime.Region(region.end() + i, region.end() + i) ) else: sublime.status_message("selection") self.view.replace(edit, region, row) i = len(row) regions.append( sublime.Region(region.begin() + i, region.begin() + i) ) sel.clear() for region in regions: sel.add(region) pass else: sublime.status_message("No text found for Insert Text, canceled") except ValueError: sublime.status_message("Error while executing Insert Text, canceled") pass
def run(self, edit): # Get text from clipboard self.text_to_print = sublime.get_clipboard() # Override from settings self.intervalLow = self.view.settings().get('robotype_keystroke_interval_low') self.intervalHigh = self.view.settings().get('robotype_keystroke_interval_high') # Establish an initial timout self.timeout = self.getInterval() # Loop through the string while self.stringIndex < len(self.text_to_print): # If there is a typo on the screen, and the robot "notices" it, backspace. if(self.typoIndex is not None): if(self.willBackspace()): self.backspaceTo(self.typoIndex) self.typoIndex = None nextChar = self.text_to_print[self.stringIndex] keystroke = self.generateKeystroke(nextChar) # If a typo was rendered, capture its position if( (keystroke is not nextChar) and (self.typoIndex is None) ): self.typoIndex = self.stringIndex self.renderChar(keystroke) self.stringIndex += 1 self.reset()
def OpenFile(): output = [] filePath = [] def open(index): if index < 0: return self.view.window().open_file(filePath[index]) path = sublime.get_clipboard() if not path.strip(): return if os.path.isfile(path): filePath.append(path) open(0) elif os.path.isdir(path): listDir = os.listdir(path) for f in listDir: if os.path.isfile(path + "/" + f): output.append(f) filePath.append(path + "/" + f) self.view.window().show_quick_panel(output, open)
def run(self, edit): import re def on_done(link): import urllib.request with urllib.request.urlopen(link) as page: encoding = page.headers.get_content_charset() text = self.decode_page(page.read(), encoding) match = re.search("<title>(.+?)</title>", text, re.IGNORECASE | re.DOTALL) if match is None: title = link else: title = match.group(1).strip() markdown_link = MARKDOWN_LINK_SNIPPET.format(title, link) self.view.run_command("insert_snippet", {"contents": markdown_link}) clipboard_text = sublime.get_clipboard(2000) if re.match("https?://", clipboard_text, re.IGNORECASE) is not None: initial_text = clipboard_text else: initial_text = "" input_view = self.view.window().show_input_panel("Link", initial_text, on_done, None, None) input_view.sel().clear() input_view.sel().add(sublime.Region(0, input_view.size()))
def process(self): text = sublime.get_clipboard() tree = {'children': {}} # Remove comments text = re.sub("\/\*[\s\S]*?\*\/", "", text) results = re.findall("([^{]+)\{([^}]+)\}", text) # Process each css block for (selector, declaration) in results: selectors = [] path = tree selector = selector.strip() if re.search(",", selector): path = self.addRule(path, selector) else: selector = re.sub("\s*([>\+~])\s*", r' &\1', selector) selector = re.sub("(\w)([:\.])", r'\1 &\2', selector) selectors = re.split("[\s]+", selector) for item in selectors: #fix back special chars _sel = re.sub("&(.)", r'& \1 ', item) _sel = re.sub("& ([:\.]) ", r'&\1', _sel) path = self.addRule(path, _sel) for (_property, value) in re.findall("([^:;]+):([^;]+)", declaration): obj = {"property": _property.strip(), "value": value.strip()} path['declarations'].append(obj) if len(results) == 0: return self.clean(text) return self.generateOutput(tree)
def run(self, edit): text = sublime.get_clipboard(); resp = '' for line in text.split('\n'): tmp = line.split(':'); resp += "'" + tmp[0] + "': '" + tmp[1][1:-1] + "',\n" self.view.insert(edit, self.view.sel()[0].a, resp[:-2])
def on_done(self, index): if index == -1: return self.sobject = self.sobjects[index] path = sublime.get_clipboard() if not os.path.isfile(path): path = "" self.window.show_input_panel("Input CSV Path: ", path, self.on_input, None, None)
def run(self, edit): view = self.view cursor = view.sel()[0] line_region = view.line(cursor) string = view.substr(line_region) match = re.search(r"(\s*)", string) file_name = view.file_name() if file_name is None: extension = None else: extension = file_name[file_name.rfind('.') + 1:] if match: if cursor.empty(): var_text = sublime.get_clipboard() else: var_text = view.substr(cursor) if var_text[-1:] == ";": var_text = var_text[:-1] if len(var_text) == 0: sublime.status_message('Please make a selection or copy something.') else: var_text_escaped = var_text.replace("'", "\\'") text = ChromephpwrapCommand.get_wrapper(extension, match.group(1), var_text, var_text_escaped) view.insert(edit, line_region.end(), text) end = view.line(line_region.end() + 1).end() view.sel().clear() view.sel().add(sublime.Region(end, end))
def run(self, edit, flags, re_delimiter=" "): print("Split") if not re_delimiter: re_delimiter = " " v = self.view if flags is None: for region in v.sel(): split_str = re.split(re_delimiter, v.substr(region)) delims = re.findall(re_delimiter, v.substr(region)) offset = region.begin() v.sel().subtract(region) l = len(split_str[0]) # TODO: flip region if initial region flipped if l > 0: v.sel().add(sublime.Region(offset, offset + l)) offset += l for i in range(len(delims)): offset += len(delims[i]) l = len(split_str[i + 1]) # TODO: flip region if initial region flipped if l > 0: v.sel().add(sublime.Region(offset, offset + l)) offset += l else: if re.findall("-c", flags): string = "".join( re.split(re_delimiter, sublime.get_clipboard())) print("Setting clipboard to \"" + string + "\"") sublime.set_clipboard(string)
def run(self, edit): # print('select_text_from_clipboard') view = self.view sel = view.sel() r=sublime.Region(0, view.size()) lines = view.lines(r) before_region = sel[0] match_found = False sel.clear() text = sublime.get_clipboard() cp_lines = text.split() for cp_line in cp_lines: cp_line = cp_line.strip() if not len(cp_line): continue for line_region in lines: line_text = view.substr(line_region).strip() text_found = line_text.find(cp_line) != -1 if text_found: match_found = True sel.add(line_region) if not match_found: sel.add(before_region)
def run(self, edit): for region in self.view.sel(): # Collect the texts that may possibly be filenames quoted_text = self.get_quoted_selection(region).split(os.sep)[-1] selected_text = self.get_selection(region) whole_line = self.get_line(region) clipboard = sublime.get_clipboard().strip() candidates = [quoted_text, selected_text, whole_line, clipboard] for text in candidates: if len(text) == 0: continue self.potential_files = self.get_filename(text) if len(self.potential_files) > 0: break if len(self.potential_files) > 1: self.view.window().show_quick_panel(self.potential_files, self.open_file) elif len(self.potential_files) == 1: print("Opening file '%s'" % (self.potential_files[0])) self.view.window().open_file(self.potential_files[0]) else: sublime.error_message("No file found!")
def run(self, edit): if jch_kill_ring.isEmpty( ) or sublime.get_clipboard() != jch_kill_ring.get(0).text: # Initial state, or OS clipboard updated, read from that self.view.run_command("paste") else: jch_kill_ring.insert(self.view, edit, 0)
def on_modified(self, view): # print(view.command_history(0, False)) # print(view.command_history(-1, False)) session = registry.getSessionByView(view) if session: if (session.state == pi.STATE_CONNECTED) and (session.role == pi.HOST_ROLE): command = view.command_history(0, False) lastCommand = session.lastViewCommand session.lastViewCommand = command payload = '' # handle history-capturable edit commands on this view if command[0] == 'insert': # because of the way the insert commands are captured in the command_history # this seems to be the most sensible way to handle this... grab latest character # inserted and send it... not most efficient but it is a start if command[0] == lastCommand[0]: chars = command[1]['characters'] lastChars = lastCommand[1]['characters'] if chars.startswith(lastChars): payload = chars.replace(lastChars, '', 1) else: payload = chars else: payload = command[1]['characters'] session.sendEdit(pi.EDIT_TYPE_INSERT, payload) elif command[0] == 'insert_snippet': payload = command[1]['contents'] session.sendEdit(pi.EDIT_TYPE_INSERT_SNIPPET, payload) elif command[0] == 'left_delete': session.sendEdit(pi.EDIT_TYPE_LEFT_DELETE, payload) elif command[0] == 'right_delete': session.sendEdit(pi.EDIT_TYPE_RIGHT_DELETE, payload) elif command[0] == 'paste': payload = sublime.get_clipboard() session.sendEdit(pi.EDIT_TYPE_PASTE, payload)
def run(self, edit): text = sublime.get_clipboard() command_match = _RE_COMMAND_PATTERN.match(text) py_command_match = _RE_PY_COMMAND_PATTERN.match(text) if command_match: command = command_match.group("command") args = command_match.group("args") argstr = "" if args: argstr = ",\n\t\"args\": { %s }" % args template = get_template(self.view) keybinding = ( template .replace("<<command>>", command) .replace("<<args>>", argstr)) self.view.run_command("insert_snippet", {"contents": keybinding}) elif py_command_match: command = _to_snake_case_command(text) template = get_template(self.view) keybinding = ( template .replace("<<command>>", command) .replace("<<args>>", "")) self.view.run_command("insert_snippet", {"contents": keybinding}) else: self.view.run_command("paste")
def run(self, edit): for region in self.view.sel(): selected_text = self.view.substr(region) python_cmd = sublime.get_clipboard() cmd_output = '' if python_cmd and 's' in python_cmd: try: python_cmd += "\nwith open('/tmp/tmp_sublime_buffer', 'w') as f:\n\tf.write(str(s))" print("RunPythonOnText: " + python_cmd) s = selected_text exec(python_cmd) with open('/tmp/tmp_sublime_buffer', 'r') as f: cmd_output_from_file = f.readlines() cmd_output = cmd_output_from_file[0] except Exception as exception: cmd_output = eval(selected_text) elif selected_text: cmd_output = eval(selected_text) cmd_output = str(cmd_output) print("RunPythonOnText: " + cmd_output) self.view.replace(edit, region, cmd_output)
def run(self, edit): import re def on_done(link): import urllib.request request = urllib.request.Request( link, headers={'User-Agent': 'Google Internal-Only Browser'}) with urllib.request.urlopen(request) as page: encoding = page.headers.get_content_charset() text = self.decode_page(page.read(), encoding) match = re.search("<title>(.+?)</title>", text, re.IGNORECASE | re.DOTALL) if match is None: title = link else: title = match.group(1).strip() markdown_link = MARKDOWN_LINK_SNIPPET.format(title, link) self.view.run_command("insert_snippet", {"contents": markdown_link}) clipboard_text = sublime.get_clipboard(2000) if re.match("https?://", clipboard_text, re.IGNORECASE) is not None: initial_text = clipboard_text else: initial_text = "" input_view = self.view.window().show_input_panel( "Link", initial_text, on_done, None, None) input_view.sel().clear() input_view.sel().add(sublime.Region(0, input_view.size()))
def run(self, edit, **kw): if not eutils.is_css_view(self.view, True): return sublime.error_message('You should run this action on CSS file') # build sources list sources = [view for view in eutils.all_views() if re.search(r'[\/\\]lspatch-[\w\-]+\.json$', view.file_name() or '')] # gather all available items display_items = [] patches = [] def add_item(patch, name): for p in patch: display_items.append([p['file'], 'Updated selectors: %s' % ', '.join(p['selectors']), name]) patches.append(json.dumps(p['data'])) for view in sources: add_item(lsutils.diff.parse_patch(eutils.content(view)), view.file_name()) # check if buffer contains valid patch pb = sublime.get_clipboard() if lsutils.diff.is_valid_patch(pb): add_item(lsutils.diff.parse_patch(pb), 'Clipboard') def on_done(ix): if ix == -1: return apply_patch_on_view(self.view, patches[ix]) if len(display_items) == 1: on_done(0) elif display_items: self.view.window().show_quick_panel(display_items, on_done) else: sublime.error_message('No patches found. You have to open patch files in Sublime Text or copy patch file contents into clipboard and run this action again.')
def run(self, edit): # get selectioncontent selectionContent = "" selections = self.view.sel() for sel in selections: selectionContent += self.view.substr(sel) if not selectionContent.endswith("\n"): selectionContent += "\n" if(selectionContent != ""): viewContent = selectionContent # todo: fetch appropriate names leftName = "(Selection)" else: viewContent = self.view.substr(sublime.Region(0,self.view.size())) # todo: fetch appropriate names leftName = "" # clipboard clipboardContent = sublime.get_clipboard() if not clipboardContent.endswith("\n"): clipboardContent += "\n" rightName = "Clipboard" leftResult, rightResult, hunks = doDiff(viewContent, clipboardContent) showDiff(leftResult, rightResult, hunks) diffSession = DiffSession(leftName, rightName, viewContent, clipboardContent) diffSession.diff() diffSession.show()
def opSetBase(self): content = sublime.get_clipboard() if content is None: raise ValueError("failed to get content from clipboard!") self.snippetBase = content.rstrip("\n\r") sublime.status_message("snippet base is set to: {}".format(self.snippetBase))
def run(self, edit): target_from_clipboard = sublime.get_clipboard() print("SmartSelectionFromClipboard: " + target_from_clipboard) targets = [] for region in self.view.sel(): current_begin = region.begin() current_end = region.end() found_all = False while current_begin < current_end and not found_all: current_region = sublime.Region(current_begin, current_end) content = self.view.substr(current_region) begin = content.find(target_from_clipboard) if begin == -1: found_all = True else: begin = begin + current_begin end = begin + len(target_from_clipboard) target_region = sublime.Region(begin, end) print("SmartSelectionFromClipboard: added region " + str(begin) + " - " + str(end)) targets.append(target_region) current_begin = end + 1 self.view.sel().clear() for t in targets: self.view.sel().add(t)
def run(self, edit, image=False): view = self.view edit_regions = [] contents = sublime.get_clipboard().strip() link = mangle_url(contents) if is_url(contents) else "" suggested_name = "" if len(link) > 0: # If link already exists, reuse existing reference suggested_link_name = suggested_name = check_for_link(view, link) for sel in view.sel(): text = view.substr(sel) if not suggested_name: suggested_link_name = suggest_default_link_name(text, image) suggested_name = suggested_link_name if suggested_link_name != text else "" edit_position = sel.end() + 3 if image: edit_position += 1 view.replace(edit, sel, "![" + text + "][" + suggested_name + "]") else: view.replace(edit, sel, "[" + text + "][" + suggested_name + "]") edit_regions.append(sublime.Region(edit_position, edit_position + len(suggested_name))) if len(edit_regions) > 0: selection = view.sel() selection.clear() reference_region = append_reference_link(edit, view, suggested_link_name, link) selection.add(reference_region) selection.add_all(edit_regions)
def run(self, edit, force=False): if self.has_changed() or force: content = sublime.get_clipboard() self.view.replace(edit, sublime.Region(0, self.view.size()), content) # store md5 hash so we can compare changes hash = ClipboardHelper.create_hash(content.encode('utf-8')) self.view.settings().set("tp_clipboard_hash", hash)
def run(self, edit, wrap_quotes=True, new_line=False): # print('paste_with_commas') view = self.view text = sublime.get_clipboard() lines = text.split('\n') res = '' print(lines) for i in range(0, len(lines)): line = lines[i].strip() if not len(line): continue if wrap_quotes: line = '\'' + line + '\'' sep = ', ' if new_line: sep = ',\n' if i == len(lines) - 1: sep = '' res += line + sep view.insert(edit, view.sel()[0].a, res)
def run(self, edit, image=False): view = self.view edit_regions = [] contents = sublime.get_clipboard().strip() link = mangle_url(contents) if is_url(contents) else "" suggested_name = "" if len(link) > 0: # If link already exists, reuse existing reference suggested_link_name = suggested_name = check_for_link(view, link) for sel in view.sel(): text = view.substr(sel) if not suggested_name: suggested_link_name = suggest_default_link_name(text, image) suggested_name = suggested_link_name if suggested_link_name != text else "" edit_position = sel.end() + 3 if image: edit_position += 1 view.replace(edit, sel, "![" + text + "][" + suggested_name + "]") else: view.replace(edit, sel, "[" + text + "][" + suggested_name + "]") edit_regions.append( sublime.Region(edit_position, edit_position + len(suggested_name))) if len(edit_regions) > 0: selection = view.sel() selection.clear() reference_region = append_reference_link(edit, view, suggested_link_name, link) selection.add(reference_region) selection.add_all(edit_regions)
def run(self, edit): """Called when the plugin is called. Grabs the clipboard, formats it, and puts it into the text area """ global use_clipboard_data_g global clipboard_string_g global clipboard_bytearray_g self.encoding = self.view.encoding() if self.encoding == "Undefined": self.encoding = "utf_8" print("Encoding:", self.encoding) clip = sublime.get_clipboard() if clip != clipboard_string_g: print("Clipboard data changed") fdata = bytearray(clip, "utf_8") elif use_clipboard_data_g: fdata = clipboard_bytearray_g else: fdata = bytearray(clip, "utf_8") try: fmt = self.formatter(fdata) if isinstance(fmt, (bytes, bytearray)): fmt = fmt.decode(self.encoding) except: sublime.error_message(traceback.format_exc()) fmt = None if fmt is not None: self.put(edit, fmt)
def run(self, edit): clip = sublime.get_clipboard() if re.search('\n$', clip): n = re.sub('\n$', '', clip) self.view.replace(edit, self.view.sel()[0], n) else: self.view.replace(edit, self.view.sel()[0], clip)
def appendClipboard(self): global _clipboardIndex # append the contents of the clipboard to the history if it is unique if not self.onTop(): _clipboardHistory.append(sublime.get_clipboard()) _clipboardIndex = len(_clipboardHistory) - 1