Example #1
0
    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):
     # 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):
        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)
Example #4
0
    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
Example #5
0
    def historyCopy(self):

        self.view.run_command("copy")

        try:
            with open(sublime.packages_path() + "\handy-harness\Context.sublime-menu") as contextMenu:
                menuData = json.load(contextMenu)
            valid = True
        except IOError:
            valid = False
            print "Could not open Context File"

        if valid:
            for item in menuData:
                if "caption" not in item:
                    continue
                if item["caption"] == "History":
                    historyItem = item
                    break

                    # if number of children are less than 5, just append child
            if len(historyItem["children"]) < 5:
                historyItem["children"].append(
                    {
                        "caption": sublime.get_clipboard(),
                        "command": "handy_harness",
                        "args": {"op": "history_paste", "text": sublime.get_clipboard()},
                    }
                )
            else:
                # if number of children equal five, slide 2-5 up, then set 5 to new entry
                # can do this with arr[::] notation
                i = 1
                while i <= 5 - 1:
                    historyItem["children"][i - 1] = historyItem["children"][i]
                    i += 1
                historyItem["children"].pop(5 - 1)
                historyItem["children"].append(
                    {
                        "caption": sublime.get_clipboard(),
                        "command": "handy_harness",
                        "args": {"op": "history_paste", "text": sublime.get_clipboard()},
                    }
                )

            with open(sublime.packages_path() + "\handy-harness\Context.sublime-menu", "w") as contextMenu:
                menuData[menuData.index(item)] = historyItem
                json.dump(menuData, contextMenu)
    def run(self, edit):
        clipboardText = sublime.get_clipboard()
        regions = self.view.sel()

        i = len(regions) - 1
        # using backward looping to ensure the infinite stack with regions.add()
        while i > -1:
            region = regions[i]
            if region.empty():
                line = self.view.line(region)
                lineStr = self.view.substr(line)
                matchObj = re.search("\S", lineStr)
                if matchObj:
                    self.view.insert(
                        edit,
                        line.end(),
                        "\n"
                        + lineStr[0 : matchObj.start()]
                        + self.parseText(lineStr[matchObj.start() :], "", clipboardText, 0, 1),
                    )
                else:

                    self.view.insert(edit, line.end(), "\n" + lineStr)
            else:
                text = self.view.substr(region)
                lines = text.splitlines()
                parsedTextArr = []
                for j in range(0, len(lines)):
                    parsedTextArr.append(self.parseText(lines[j], text, clipboardText, j, len(lines)))
                parsedText = "\n".join(parsedTextArr)
                self.view.insert(edit, region.end(), parsedText)
                newRegion = sublime.Region(region.end(), region.end() + len(parsedText))
                regions.subtract(region)
                regions.add(newRegion)
            i = i - 1
 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)
Example #8
0
        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)
Example #9
0
 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])
Example #10
0
 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)
Example #11
0
    def run(self):
        # example:
        # <!-- END INCLUDE /srv/epages/eproot/Cartridges/DE_EPAGES/ShopCSVExportImport/Templates/MBO/MBO.INC-CSVExportImportTabPage.Script.html -->
        # or:
        # Use of uninitialized value in string ne at /srv/epages/eproot/Cartridges/DE_EPAGES/Amazon/UI/AmazonOffer.pm line 125.
        clipboard = sublime.get_clipboard()
        line = 0

        # is there a "line = $line_number" ?
        line_regex = re.compile(r"^.*line (\d+).*$").match(clipboard)
        if line_regex:
            line = int(line_regex.group(1))

        m = re.compile(r"^.*\s(\/.*?)\s.*$").match(clipboard)
        if m:
            if line > 0:
                path = (
                    execute(
                        ep6tools(
                            self.window.active_view(), ["--get-file-from-vm-path", m.group(1) + ":" + str(line)], True
                        )
                    )[0]
                    .decode("utf-8")
                    .strip()
                )
                self.window.open_file(path, sublime.ENCODED_POSITION)
            else:
                path = (
                    execute(ep6tools(self.window.active_view(), ["--get-file-from-vm-path", m.group(1)], True))[0]
                    .decode("utf-8")
                    .strip()
                )
                self.window.open_file(path)
    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()))
Example #13
0
    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))
Example #14
0
    def run(self, edit):
        # クリップボードの中身を取得する
        clip = sublime.get_clipboard()
        # 選択中の文字列を取得する(複数選択は未対応)
        select_txt = self.view.substr(self.view.sel()[0])
        # 書式が連番指定になっているか調べる
        m = re.match("(\d+)-(\d+)", select_txt)
        if m:
            # 書式が正しいので、番号を書き換えながら連続ペーストする
            # 開始番号
            start = int(m.group(1))
            # 終了番号
            end = int(m.group(2))
            # 開始番号1文字目が0の場合、足りない桁をゼロで埋めてから書き出す
            # 桁数は開始番号のものを参照
            if m.group(1)[0] == "0":
                zero_padding = len(m.group(1))
            else:
                zero_padding = 0

            paste = ""
            for i in range(start, end + 1):
                # 桁数ゼロ
                if len(str(i)) > zero_padding:
                    num = str(i)
                else:
                    num = str(i).zfill(zero_padding)
                paste += clip.replace("$$$", num) + "\n"
            # 最後にまとめてペースト
            self.view.replace(edit, self.view.sel()[0], paste)
        else:
            # 想定する書式と違っているので、何もせず終了
            # (エラーメッセージを出したい。英語で、日本人にもわかりそうなのを)
            pass
Example #15
0
 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):
        filename = self.view.file_name()

        type = "unknown"

        if filename:
            if filename.endswith(".sass"):
                type = "sass"
            elif filename.endswith(".styl"):
                type = "stylus"
        else:
            if self.view.match_selector(0, "source.sass"):
                type = "sass"
            elif self.view.match_selector(0, "source.stylus"):
                type = "stylus"

        print(self.view.match_selector(0, "source.stylus"))

        if type is "sass" or type is "stylus":
            settings = sublime.load_settings("css_to_sass.sublime-settings")
            self.eol = self.detectEol()
            self.indent = self.detectIndentation()
            self.options["colon"] = ":" if type is "sass" or settings.get("colon") else ""
            self.convert(sublime.get_clipboard(), edit)
        else:
            self.view.run_command("paste")
    def run(self, view, edit):
        """Returns True for pass or False for fail.

        Sets self.fail_message if the test fails.
        """
        # Initial state
        view.replace(edit, sublime.Region(0, view.size()), self.initial_text)
        sublime.set_clipboard(self.initial_clipboard)
        view.sel().clear()
        for selection_region in self.initial_selection:
            view.sel().add(selection_region)
        # Run the command (cut/copy/paste/duplicate).
        try:
            # Call the command directly instead of using view.run_command, so
            # that errors can be caught and displayed.
            class_name = "Ccpl" + self.command.capitalize() + "Command"
            command_class = getattr(CopyCutAndPasteLines.main, class_name)
            command_object = command_class(view)
            command_object.run(edit)
        except:
            # Get the traceback message.
            self.fail_message = "\n" + traceback.format_exc()
            # Trim down long file paths.
            self.fail_message = self.fail_message.replace(sublime.packages_path(), "Packages")
            self.fail_message = self.fail_message.replace(sublime.installed_packages_path(), "Installed Packages")
            return False  # Fail due to an exception.
        end_text = view.substr(sublime.Region(0, view.size()))
        # Check that the end state matches the correct state.
        pass_selection = self._test_value("selection", self.correct_selection, list(view.sel()), selections_equal)
        pass_clipboard = self._test_value("clipboard", self.correct_clipboard, sublime.get_clipboard())
        pass_text = self._test_value("text", self.correct_text, end_text)
        return pass_text and pass_clipboard and pass_selection
    def run(self):
        clip = sublime.get_clipboard()

        fileName = "/Users/maks/temp"
        filer.write(fileName, clip)
        self.window.open_file(fileName, sublime.ENCODED_POSITION)
        self.window.run_command("go_to_line", {"line": "0"})
    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)
Example #20
0
    def run(self, edit):
        view = self.view
        cursors = view.sel()

        for cursor in cursors:
            line_region = view.line(cursor)
            string = view.substr(line_region)
            match = re.search(r"(\s*)", string)

            if is_log_string(string):
                change_log_type(view, edit, line_region, string)
            else:
                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:
                        indent_str = get_indent(view, line_region)
                        text = get_wrapper(view, var_text, indent_str)
                        view.insert(edit, line_region.end(), text)
                        end = view.line(line_region.end() + 1).end()

        if not is_log_statement(string):
            view.sel().clear()
            view.sel().add(sublime.Region(end, end))
Example #21
0
    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
    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):
     CLIPBOARD_SIZE = 64
     clipboard = sublime.get_clipboard(CLIPBOARD_SIZE)
     initial = ""
     if len(clipboard) < CLIPBOARD_SIZE:
         initial = clipboard
     self.win.show_input_panel("Search Symbol", initial, self.on_done, None, None)
 def run(self, edit):
     target_view = self.view
     ScreencastDirector.the_director.target_view = target_view
     ScreencastDirector.the_director.write(sublime.get_clipboard(), delay_min=10, delay_max=20)
     region = self.view.sel()[0]
     target_view.add_regions("screencast_director", [region], "source", "", sublime.HIDDEN)
     ScreencastDirector.the_director._start_timer()
Example #25
0
 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)
Example #26
0
 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
Example #27
0
    def run(self, edit, alt="last_search"):
        """Find next instance of selected text.

If selection empty then look for the last Find command search term or the clipboard depending on the passed argument.

"""
        view = self.view
        # Get the first highlighted string to search for
        selected = view.sel()[0]
        # Note if we're searching for the clipboard or a selection
        selection = True

        # If start and end cursor points are different then we have some text selected
        if selected.a != selected.b:
            # We DO want to call "find_under" and populate the find buffer
            if alt == "slurp_search":
                return view.window().run_command("find_under")
            # We don't call "find_under" here as it populates the find panel and
            # so we would lose its value in case we wanted to use it later
            # Get the text of the selection
            searchText = view.substr(sublime.Region(selected.a, selected.b))
            # If we've selected right to left then ensure that we use the higher
            # of the two for comparison
            if selected.a < selected.b:
                selectedPos = selected.b
            else:
                selectedPos = selected.a
        elif alt == "last_search" or alt == "slurp_search":
            # Run the built in find_next command from the window context
            return view.window().run_command("find_next")
        elif alt == "clipboard":
            selection = False
            # Search for what's on the clipboard
            searchText = sublime.get_clipboard()
            selectedPos = selected.a

        # Find the next instance of our search string after the cursor position
        match = view.find(searchText, selectedPos, sublime.LITERAL | sublime.IGNORECASE)

        # If nothing found underneath our cursor position
        if not match:
            # Try from the top of the page
            match = view.find(searchText, 0, sublime.LITERAL | sublime.IGNORECASE)

        # If still nothing found
        if not match:
            return sublime.status_message('''Unable to find "%s"''' % removeNewlinesAndCut(searchText))

        # If we only find our current selection then message to say only 1 found
        if selection and match.b == selectedPos:
            return sublime.status_message("""Only 1 instance of "%s" found""" % removeNewlinesAndCut(searchText))

        # Highlight it
        view.sel().clear()
        view.sel().add(match)
        # Scroll to it
        view.show(match)
        # Zoidberg eyeball, iris out!
        return sublime.status_message('''Found "%s"''' % removeNewlinesAndCut(searchText))
Example #28
0
    def get_right(self):
        """Get right."""

        return {
            "win_id": None,
            "view_id": None,
            "clip": EasyDiffView("**clipboard**", sublime.get_clipboard(), "UTF-8"),
        }
Example #29
0
 def run(self, edit, **kwargs):
     from_file = self.view.file_name()
     for region in self.view.sel():
         if not region.empty():
             from_file += " (Selection)"
             break
     clipboard = sublime.get_clipboard()
     self.run_diff(self.diff_content(), clipboard, from_file=from_file, to_file="(clipboard)", **kwargs)
Example #30
0
 def choices(self):
     # tuples of integers with kill-ring entries.
     # Used by the yank choice command
     choiceArr = []
     for i in range(1, len(self.killRing)):
         choiceArr.append((i, self.killRing[i]))
     choiceArr.append(("clipboard", "Windows Clipboard: " + sublime.get_clipboard()))
     return choiceArr