Example #1
0
 def run(self, edit, **kwargs):
     self.deactivate_mark()
     self.view.run_command(
         "delete_word",
         kwargs
     )
     set_clipboard(kill_ring.kill_ring.top())
    def on_done_filename(self, value):
        self.filename = value
        # get selected text, or the whole file if nothing selected
        if all([region.empty() for region in self.view.sel()]):
            text = self.view.substr(sublime.Region(0, self.view.size()))
        else:
            text = "\n".join([self.view.substr(region) for region in self.view.sel()])

        try:
            gist = self.gistapi.create_gist(description=self.description,
                                            filename=self.filename,
                                            content=text,
                                            public=self.public)
            self.view.settings().set('gist', gist)
            sublime.set_clipboard(gist["html_url"])
            sublime.status_message(self.MSG_SUCCESS)
        except GitHubApi.UnauthorizedException:
            # clear out the bad token so we can reset it
            self.settings.set("github_token", "")
            sublime.save_settings("GitHub.sublime-settings")
            sublime.error_message(self.ERR_UNAUTHORIZED_TOKEN)
            sublime.set_timeout(self.get_username, 50)
        except GitHubApi.UnknownException as e:
            sublime.error_message(e.message)
        except GitHubApi.ConnectionException as e:
            sublime.error_message(e.message)
  def run(self):
    sublime.status_message('Sending to PasteBin...')

    response = urlopen(url=API_URL, data=urlencode(self.call_args).encode('utf8')).read().decode('utf8')

    sublime.set_clipboard(response)
    sublime.status_message('PasteBin URL copied to clipboard: ' + response)
Example #4
0
def create_gist(description, public):
    data = json.dumps({ 'description': description, 'public': public, 'files': { _fileName: {'content': _selectedText} }})
    result = api_request(url, data)
    sublime.set_clipboard(result['html_url'])
    if settings.get("open_in_browser"):
        webbrowser.open(result['html_url'])
    sublime.status_message("Gist: " + result['html_url'])
 def on_done(self, idx):
     if idx == -1:
         return
     gist = self.gists[idx]
     filename = list(gist["files"].keys())[0]
     filedata = gist["files"][filename]
     content = self.gistapi.get(filedata["raw_url"])
     if self.open_in_editor:
         new_view = self.view.window().new_file()
         if expat:  # not present in Linux
             # set syntax file
             if not self.syntax_file_map:
                 self.syntax_file_map = self._generate_syntax_file_map()
             try:
                 extension = os.path.splitext(filename)[1][1:].lower()
                 syntax_file = self.syntax_file_map[extension]
                 new_view.set_syntax_file(syntax_file)
             except KeyError:
                 logger.warn("no mapping for '%s'" % extension)
                 pass
         # insert the gist
         new_view.run_command("insert_text", {'text': content})
         new_view.set_name(filename)
         new_view.settings().set('gist', gist)
     elif self.copy_gist_id:
         sublime.set_clipboard(gist["html_url"])
     else:
         sublime.set_clipboard(content)
         sublime.status_message(self.MSG_SUCCESS % filename)
            def on_gist_filename(filename):
                # We need to figure out the filenames. Right now, the following logic is used:
                #   If there's only 1 selection, just pass whatever the user typed to Github. It'll rename empty files for us.
                #   If there are multiple selections and user entered a filename, rename the files from foo.js to
                #       foo (1).js, foo (2).js, etc.
                #   If there are multiple selections and user didn't enter anything, post the files as
                #       $SyntaxName 1, $SyntaxName 2, etc.
                if len(region_data) == 1:
                    gist_data = {filename: region_data[0]}
                else:
                    if filename:
                        (namepart, extpart) = os.path.splitext(filename)
                        make_filename = lambda num: "%s (%d)%s" % (namepart, num, extpart)
                    else:
                        syntax_name, _ = os.path.splitext(os.path.basename(self.view.settings().get('syntax')))
                        make_filename = lambda num: "%s %d" % (syntax_name, num)
                    gist_data = dict((make_filename(idx), data) for idx, data in enumerate(region_data, 1))

                gist = create_gist(self.public, description, gist_data)

                gist_html_url = gist['html_url']
                sublime.set_clipboard(gist_html_url)
                sublime.status_message("%s Gist: %s" % (self.mode(), gist_html_url))

                if gistify:
                    gistify_view(self.view, gist, gist['files'].keys()[0])
Example #7
0
def set_register(view, register, forward):
    delta = 1
    if not forward:
        delta = -1

    text = []
    regions = []
    for s in view.sel():
        if s.empty():
            s = sublime.Region(s.a, s.a + delta)
        text.append(view.substr(s))
        regions.append(s)

    text = '\n'.join(text)

    use_sys_clipboard = view.settings().get('vintage_use_clipboard', False) == True

    if (use_sys_clipboard and register == '"') or (register in ('*', '+')):
        sublime.set_clipboard(text)
        # If the system's clipboard is used, Vim always propagates the data to
        # the unnamed register too.
        register = '"'

    if register == '%':
        pass
    else:
        reg = register.lower()
        append = (reg != register)

        if append and reg in g_registers:
            g_registers[reg] += text
        else:
            g_registers[reg] = text
    def run(self, edit, target='external', output_type='html'):
        output_type = output_type if output_type in FORMATS else 'html'
        pygmented = self.highlight(output_type)

        if target == 'external':
            filename = '%s.%s' % (self.view.id(), output_type,)
            tmp_file = self.write_file(filename, pygmented)
            sublime.status_message(u'Written %s preview file: %s'
                                   % (output_type.upper(), tmp_file))
            if desktop.get_desktop() == 'Mac OS X':
                # for some reason desktop.open is broken under OSX Lion
                subprocess.call("open %s" % tmp_file, shell=True)
            else:
                desktop.open(tmp_file)
        elif target == 'clipboard':
            if desktop.get_desktop() == 'Mac OS X':
                # on mac osx we have `pbcopy` :)
                filename = '%s.%s' % (self.view.id(), output_type,)
                tmp_file = self.write_file(filename, pygmented)
                subprocess.call("cat %s | pbcopy -Prefer %s"
                                % (tmp_file, output_type,), shell=True)
                os.remove(tmp_file)
            else:
                sublime.set_clipboard(pygmented)
        elif target == 'sublime':
            new_view = self.view.window().new_file()
            if output_type == 'html':
                new_view.set_syntax_file('Packages/HTML/HTML.tmLanguage')
            new_edit = new_view.begin_edit()
            new_view.insert(new_edit, 0, pygmented)
            new_view.end_edit(new_edit)
        else:
            sublime.error_message(u'Unsupported target "%s"' % target)
	def choose(self, flag):
		if flag != -1:
			if flag == len(self.item) - 1:
				self.word = self.word.replace('_','-')
				open_tab('http://www.php.net/manual/%(lang)s/function.%(function)s.php' % {'lang':'zh', 'function': self.word})
			else:
				sublime.set_clipboard(self.item[flag])
Example #10
0
  def run(self):
    view = self.window.active_view()
    current_path = view.file_name()
    for path in self.window.folders():
      current_path = current_path.replace(path + '/', '')

    sublime.set_clipboard(current_path)
Example #11
0
	def run(self, edit):
		selectedRegions = self.view.sel()
		regionsToDelete = map(lambda r: self.view.full_line(r), selectedRegions)
		copyStr = ''.join(map(lambda r: self.view.substr(r), regionsToDelete))
		for region in regionsToDelete:
			self.view.erase(edit, region)
		sublime.set_clipboard(copyStr)
Example #12
0
 def on_idle(self, view):
     string = ""
     for region in view.sel():
         if not region.empty():
             string += view.substr(region)
     if string != "":
         sublime.set_clipboard(string)
    def run(self, view, paste_name=None):
        if paste_name is None:
            paste_name = self.view.file_name()
        if paste_name is not None:
            paste_name = os.path.basename(paste_name)   # Extract base name
        else:
            paste_name = "Untitled"

        text = ""
        for region in self.view.sel():

            syntax = SYNTAXES.get(self.view.settings().get('syntax').split('/')[-1], 'text')
            if text:
                text = text + '\n' + self.view.substr(region).encode('utf8')
            else:
                text = self.view.substr(region).encode('utf8')

        if not text:
            sublime.status_message('Error sending to %s: Nothing selected' % FRIENDPASTE_URL)
        else:
            self._data = json.dumps({
                'title': paste_name,
                'snippet': text,
                'language': syntax
            })

            paste = self.send_paste()

            sublime.set_clipboard(paste['url'])
            sublime.status_message('PasteBin URL copied to clipboard: ' + paste['url'])
Example #14
0
 def run(self, edit):
     self.deactivate_mark()
     self.view.run_command(
         "run_macro_file",
         {"file": "Packages/Default/Delete to Hard EOL.sublime-macro"}
     )
     set_clipboard(kill_ring.kill_ring.top())
	def show_list(self):
		self.awaits_files=[]
		self.missing=[]
		for rf in self.root_files:
			files=[]
			if rf.isnumeric():
				files=self.searchFileForAwaits(rf)
				self.awaits_files+=(files)
				for f in files:
					if f not in self.input_files:
						self.missing.append("Page {pagefile}: {awaitname}.tex".format(awaitname=f, pagefile=rf))
			

		self.unimplemented=list(set(self.input_files)-set(self.awaits_files))
		# self.missing=list(set(self.awaits_files)-set(self.input_files))

		if (self.mode=="unimplemented"):
			diff=list(set(self.unimplemented))
			self.quicklist=self.unimplemented
			self.window.show_quick_panel(sorted(set(diff)), self.setChosenToClipboard)
		elif self.mode=="all":
			diff=list(set(self.unimplemented))
			awaits_code=""
			for i in sorted(set(diff)):
				awaits_code+="\\awaits{"+i+"}\n"
			sublime.set_clipboard(awaits_code)
		elif self.mode=="missing":
			self.quicklist=self.missing
			self.window.show_quick_panel(sorted(set(self.missing)), self.setChosenToClipboard)
		else:
			return
    def run(self, edit, parser='markdown', target='browser'):
        settings = sublime.load_settings('MarkdownPreview.sublime-settings')

        # backup parser+target for later saves
        self.view.settings().set('parser', parser)
        self.view.settings().set('target', target)

        html, body = compiler.run(self.view, parser)

        if target in ['disk', 'browser']:
            # check if LiveReload ST2 extension installed and add its script to the resulting HTML
            livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path()))
            # build the html
            if livereload_installed:
                port = sublime.load_settings('LiveReload.sublime-settings').get('port', 35729)
                html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':%d/livereload.js?snipver=1"></\' + \'script>\')</script>' % port
            # update output html file
            tmp_fullpath = getTempMarkdownPreviewPath(self.view)
            save_utf8(tmp_fullpath, html)
            # now opens in browser if needed
            if target == 'browser':
                self.__class__.open_in_browser(tmp_fullpath, settings.get('browser', 'default'))
        elif target == 'sublime':
            # create a new buffer and paste the output HTML
            embed_css = settings.get('embed_css_for_sublime_output', True)
            if embed_css:
                new_scratch_view(self.view.window(), html)
            else:
                new_scratch_view(self.view.window(), body)
            sublime.status_message('Markdown preview launched in sublime')
        elif target == 'clipboard':
            # clipboard copy the full HTML
            sublime.set_clipboard(html)
            sublime.status_message('Markdown export copied to clipboard')
 def run(self):
   """
   This command copies the current scope to the clipboard
   """
   current_scope = self.window.active_view().get_status(status_key)
   if type(current_scope) is str:
     sublime.set_clipboard(current_scope.rstrip())
Example #18
0
def set_register(view, register, forward):
    delta = 1
    if not forward:
        delta = -1

    text = []
    regions = []
    for s in view.sel():
        if s.empty():
            s = sublime.Region(s.a, s.a + delta)
        text.append(view.substr(s))
        regions.append(s)

    text = "\n".join(text)

    if register == '*' or register == '+':
        sublime.set_clipboard(text)
    elif register == '%':
        pass
    else:
        reg = register.lower()
        append = (reg != register)

        if append and reg in g_registers:
            g_registers[reg] += text
        else:
            g_registers[reg] = text
    def run(self, edit):
        suggested_setting = self._build_suggested_setting()

        if not suggested_setting:
            sublime.set_clipboard('Unable to create syntax setting')
        else:
            sublime.set_clipboard(suggested_setting)
Example #20
0
 def setUp(self):
     sublime.set_clipboard('')
     registers._REGISTER_DATA = {}
     TestsState.view.settings().erase('vintage')
     TestsState.view.settings().erase('vintageous_use_sys_clipboard')
     self.regs = Registers(view=TestsState.view,
                           settings=SettingsManager(view=TestsState.view))
Example #21
0
 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)
Example #22
0
 def setUp(self):
     sublime.set_clipboard('')
     registers._REGISTER_DATA = {}
     TestsState.view.settings().erase('vintage')
     TestsState.view.settings().erase('vintageous_use_sys_clipboard')
     self.regs = VintageState(TestsState.view).registers
     self.regs.view = mock.Mock()
    def run(self, edit):

        syntax_current_file = self.view.settings().get("syntax")
        sublime.set_clipboard(syntax_current_file)

        msg = "Syntax copied to the clipboard"
        sublime.status_message(msg)
Example #24
0
  def convert(self, text, edit):
      if (";" in text):
        sublime.set_clipboard(self.process())
        self.view.run_command('paste_and_indent')

      else:
        self.view.run_command('paste')
Example #25
0
    def open_url(self, url):
        if self.copy_url_on_open:
            sublime.set_clipboard(url)
            sublime.status_message('URL Copied: `%s`' % url)

        if url[0:3] == 'www': url = 'http://' + url
        webbrowser.open_new_tab(url)
Example #26
0
    def run(self, edit):
        t = time.strftime('%Y-%m-%d',time.localtime(time.time()));
        sublime.status_message(t)                                       # 将时间显示在状态栏,显示一段时间后自动消失
        sublime.set_clipboard(t)                                        # 将当前时间放入剪贴板,可用于粘贴(ctrl+v)
        date_str = "yyyy-mm-dd"
        # 第一种方法
        # reg = sublime.Region(0, self.view.size())                       # 获取当前文件全部区域
        # text = self.view.substr(reg)                                    # 获取指定区域的文本
        # text = text.replace(date_str,t)                                 # 把text中yyyy-mm-dd替换为当前时间t
        # self.view.erase(edit,reg)                                       # 清除指定区域的文本
        # self.view.insert(edit,0,text)                                   # 将text插入本文档

        # 另一种方法,更简便
        reg = self.view.find(date_str,0,sublime.IGNORECASE)
        if reg != None:                                                 # 不加这个条件也不会出错,最好加上
            self.view.replace(edit,reg,t)

        # 以下为将“module 模块名.v”替换为“module 模块名”,如果存在;用于配合verilog的module snippet
        file_full_name = self.view.file_name()                          # 这个文件名包括路径
        last_index = file_full_name.rfind('\\')                         # 得到最后一个\的位置
        file_name = file_full_name[last_index+1:]                       # 取得最后的文件名,不包括路径
        module_str = 'module '+ file_name
        reg = self.view.find(module_str,0,sublime.IGNORECASE)
        if reg != None:                                                 # 如果存在这个字符串
            self.view.replace(edit,reg,module_str[:-2])                 # 去掉后缀.v并插入
Example #27
0
  def run( self, view ):
    try:
      s = re.findall(r'\bphp|html|css|xml|haml|python|js|java|css|c\+\+|cs|c\b', self.view.scope_name(0))[0]
      if s == 'js':
        s = 'javascript'
      if s == 'cs':
        s = 'csharp'
      if s == 'c++':
        s = 'cpp'
    except:
      s = 'other'

    c, v, i = self.view.substr(sublime.Region(0, self.view.size())), self.view.sel()[0], 0
    if v.begin() != v.end():
      for x in self.view.lines(v):
        b = x.begin()+i
        c = c[:b] + '@@' + c[b:]
        i = i + 2
       
    r, p = httplib.HTTPConnection('www.pastebin.com'), urllib.urlencode({'paste_private': 1, 'paste_code': c, 'paste_format': s})
    h = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    r.request("POST", "/api_public.php", p, h)
    g = r.getresponse()
    if g.status == 200:
      l = g.read()
      if l[0:5] == 'ERROR':
        sublime.status_message('Something went wrong:\n' + l)
      else:
        sublime.set_clipboard(l)
        sublime.status_message('Link has been copied to your clipboard')
    else:
      sublime.status_message('Something went wrong: ' + g.status, g.reason)
    r.close()
Example #28
0
    def run(self, edit):
        view = sublime.Window.active_view(sublime.active_window())
        sels = self.view.sel()

        # set file name
        if view.file_name():
        	output = "File: " + view.file_name() + "\n"
        else:
        	output = "File: <unsaved>\n"

        # 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"

        # handle text
        isFollowupSelection = None
        for selection in sels:
            if isFollowupSelection:
            	# split multi selections with ---
            	output += "---\n"
            else:
            	# but not the first one
            	isFollowupSelection = True
            # for each selection
            selection = self.view.line(selection)  # Extend selection to full lines
            first_line_num = self.get_line_num(selection.begin())
            lines = self.view.substr(selection).split("\n")  # Considers all line breaks
            for i, line in enumerate(lines):
                output += format_string % (first_line_num + i, line)

        # send to clipboard
        sublime.set_clipboard(output)
Example #29
0
File: gist.py Project: dresende/st2
	def run(self):
		self.view = self.window.active_view()

		tmp_gist = tempfile.TemporaryFile()
		tmp_gist.write(self.view.substr(sublime.Region(0, self.view.size())))
		tmp_gist.seek(0)

		self.showMsg("Creating gist...")

		p = subprocess.Popen([ "gist", "--no-open" ],
							bufsize = 4096,
							stdin = tmp_gist,
							stdout = subprocess.PIPE,
							stderr = subprocess.PIPE)
		stdout, stderr = p.communicate()

		output = stdout
		if stderr != "":
			output = stderr

		output = output.splitlines()

		sublime.set_clipboard(output[0])

		print "URL", output[0]

		tmp_gist.close()

		self.clearTemporaryMsg()
		self.window.show_input_panel("Gist:", output[0], None, None, None)
 def status(self):
     copy = self.current()
     copy = copy.replace("\t", "\\t")
     copy = copy.replace("\n", "\\n")
     copy = copy.replace("\r", "\\r")
     sublime.status_message(u'Set Clipboard to "{copy}"'.format(copy=copy))
     sublime.set_clipboard(self.current())
Example #31
0
 def on_done(self):
     sublime.set_clipboard(self.url)
     sublime.status_message("Remote URL copied to clipboard")
    def run(self, edit):
        filename = self.view.file_name()

        if len(filename) > 0:
            sublime.set_clipboard(filename + ':' + getLines(self))
            sublime.status_message("Copied path with line")
 def run(self, edit):
     if 'JSON' in self.view.settings().get('syntax'):
         sublime.set_clipboard(self.view.get_status(STATUS_KEY))
Example #34
0
    def update_from_source(self):

        current_filename = self.view.file_name()
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)
        markup = Markup()
        meta, content = markup.get_meta_and_content(contents)
        syntax = self.view.settings().get("syntax")
        new_content = markup.to_html("\n".join(content), syntax)
        if not new_content:
            sublime.error_message(
                "Can't update: this doesn't appear to be a valid Confluence page.")
            return
        self.confluence_api = ConfluenceApi(self.username, self.password, self.base_uri)

        get_content_by_title_resp = self.confluence_api.get_content_by_title(
            meta["space_key"], meta["title"])
        if get_content_by_title_resp.ok:
            content_id = get_content_by_title_resp.json()["results"][0]["id"]

            get_content_by_id_resp = self.confluence_api.get_content_by_id(content_id)
            if get_content_by_id_resp.ok:
                content = get_content_by_id_resp.json()
                space = dict(key=meta["space_key"])
                version_number = content["version"]["number"] + 1
                version = dict(number=version_number, minorEdit=False)
                # ancestor_id = int(ancestor["id"])
                body = dict(storage=dict(value=new_content, representation="storage"))
                data = dict(id=content_id, type="page", title=meta["title"],
                            space=space, version=version, body=body)

                update_content_resp, mod_content = self.confluence_api.update_content(content_id,
                                                                                      data,
                                                                                      current_filename)

                if update_content_resp.ok:
                    self.view.settings().set("confluence_content", update_content_resp.json())
                    content_uri = self.confluence_api.get_content_uri(update_content_resp.json())

                    sublime.set_clipboard(content_uri)
                    sublime.status_message(self.MSG_SUCCESS)
                else:
                    print(update_content_resp.text)

                    debug_tab(self, new_content, "Source")
                    debug_tab(self, mod_content, "Modified")

                    sublime.error_message("Can not update content, reason: {}".format(
                        update_content_resp.reason))
            else:
                print(get_content_by_id_resp.text)

                debug_tab(self, new_content, "Source")

                sublime.error_message("Can not get content by id, reason: {}".format(
                    get_content_by_id_resp.reason))
        else:
            print(get_content_by_title_resp.text)

            sublime.error_message("Can not get content by title, reason: {}".format(
                get_content_by_title_resp.reason))
Example #35
0
    def update_from_editor(self):
        # Example Data:
        """
        {
          "id": "3604482",
          "type": "page",
          "title": "new page",
          "space": {
            "key": "TST"
          },
          "body": {
            "storage": {
              "value": "<p>This is the updated text for the new page</p>",
              "representation": "storage"
            }
          },
          "version": {
            "number": 2
          }
        }
        """
        content_id = self.content["id"]
        title = self.content["title"]
        space_key = self.content["space"]["key"]
        version_number = self.content["version"]["number"] + 1
        region = sublime.Region(0, self.view.size())
        contents = self.view.substr(region)
        syntax = self.view.settings().get("syntax")
        if "HTML" in syntax:
            new_content = "".join(contents.split("\n"))
        else:
            markup = Markup()
            meta, content = markup.get_meta_and_content(contents)
            new_content = markup.to_html("\n".join(content), syntax)
        space = dict(key=space_key)
        version = dict(number=version_number, minorEdit=False)
        body = dict(storage=dict(value=new_content, representation="storage"))
        data = dict(id=content_id, type="page", title=title,
                    space=space, version=version, body=body)
        try:
            self.confluence_api = ConfluenceApi(self.username, self.password, self.base_uri)
            response, mod_content = self.confluence_api.update_content(content_id,
                                                                       data,
                                                                       self.view.file_name())

            if response.ok:
                content_uri = self.confluence_api.get_content_uri(self.content)
                sublime.set_clipboard(content_uri)

                debug_tab(self, mod_content, "Modified")

                sublime.status_message(self.MSG_SUCCESS)
                self.view.settings().set("confluence_content", response.json())
            else:
                print(response.text)

                debug_tab(self, mod_content, "Modified")

                sublime.error_message("Can't update content, reason: {}".format(response.reason))
        except Exception:
            print(response.text)

            debug_tab(self, mod_content, "Modified")

            sublime.error_message("Can't update content, reason: {}".format(response.reason))
 def run(self):
     path = self.extract_path(self.current_file())
     sublime.set_clipboard(path)
     sublime.status_message(path)
Example #37
0
 def copy_to_clipboard_and_inform(self, data):
     sublime.set_clipboard(data)
     lines = len(data.split('\n'))
     self.window.status_message('Copied {} to clipboard'.format(
         '{} lines'.format(lines) if lines > 1 else '"{}"'.format(data)))
Example #38
0
    def on_navigate(self, href):
        """Exceute link callback."""

        params = href.split(':')
        key = params[0]
        index = int(params[1]) if len(params) > 1 else None
        if key == 'reload':
            mdpopups.hide_popup(self.view)
            reinit_plugin()
            self.view.run_command('get_selection_scope')
        if key == 'copy-all':
            sublime.set_clipboard('\n'.join(self.scope_bfr))
            notify('Copied: All')
        elif key == 'copy-scope':
            copy_data(self.scope_bfr, SCOPE_KEY, index,
                      lambda x: x.replace('\n' + ' ' * 31, ' '))
        elif key == 'copy-points':
            copy_data(self.scope_bfr, PTS_KEY, index)
        elif key == 'copy-line-char':
            copy_data(self.scope_bfr, CHAR_LINE_KEY, index)
        elif key == 'copy-fg':
            copy_data(self.scope_bfr, FG_KEY, index)
        elif key == 'copy-fg-sim':
            copy_data(self.scope_bfr, FG_SIM_KEY, index)
        elif key == 'copy-fg-hash':
            copy_data(self.scope_bfr, HASHED_FG_KEY, index)
        elif key == 'copy-fg-hash-sim':
            copy_data(self.scope_bfr, HASHED_FG_SIM_KEY, index)
        elif key == 'copy-bg':
            copy_data(self.scope_bfr, BG_KEY, index)
        elif key == 'copy-bg-sim':
            copy_data(self.scope_bfr, BG_SIM_KEY, index)
        elif key == 'copy-style':
            copy_data(self.scope_bfr, STYLE_KEY, index)
        elif key == 'copy-fg-sel-name':
            copy_data(self.scope_bfr, FG_NAME_KEY, index)
        elif key == 'copy-fg-sel-scope':
            copy_data(self.scope_bfr, FG_SCOPE_KEY, index)
        elif key == 'copy-fg-hash-sel-name':
            copy_data(self.scope_bfr, HASHED_FG_NAME_KEY, index)
        elif key == 'copy-fg-hash-sel-scope':
            copy_data(self.scope_bfr, HASHED_FG_SCOPE_KEY, index)
        elif key == 'copy-bg-sel-name':
            copy_data(self.scope_bfr, BG_NAME_KEY, index)
        elif key == 'copy-bg-sel-scope':
            copy_data(self.scope_bfr, BG_SCOPE_KEY, index)
        elif key == 'copy-bold-sel-name':
            copy_data(self.scope_bfr, BOLD_NAME_KEY, index)
        elif key == 'copy-bold-sel-scope':
            copy_data(self.scope_bfr, BOLD_SCOPE_KEY, index)
        elif key == 'copy-italic-sel-name':
            copy_data(self.scope_bfr, ITALIC_NAME_KEY, index)
        elif key == 'copy-italic-sel-scope':
            copy_data(self.scope_bfr, ITALIC_SCOPE_KEY, index)
        elif key == 'copy-scheme':
            copy_data(self.scope_bfr, SCHEME_KEY, index)
        elif key == 'copy-syntax':
            copy_data(self.scope_bfr, SYNTAX_KEY, index)
        elif key == 'copy-overrides':
            copy_data(self.scope_bfr, OVERRIDE_SCHEME_KEY, index,
                      lambda text: self.overrides[int(params[2]) - 1])
        elif key == 'scheme' and self.scheme_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file', {
                    "file":
                    "${packages}/%s" % self.scheme_file.replace(
                        '\\', '/').replace('Packages/', '', 1)
                })
        elif key == 'syntax' and self.syntax_file is not None:
            window = self.view.window()
            window.run_command(
                'open_file', {
                    "file":
                    "${packages}/%s" % self.syntax_file.replace(
                        '\\', '/').replace('Packages/', '', 1)
                })
        elif key == 'override':
            window = self.view.window()
            window.run_command(
                'open_file', {
                    "file":
                    "${packages}/%s" %
                    self.overrides[int(params[2]) - 1].replace(
                        'Packages/', '', 1)
                })
Example #39
0
    def rest(self):

        link = self.contactAPI(self.locationParams, self.content)

        sublime.set_clipboard(link)
        self.displayOutput(link)
Example #40
0
    def run(self, v):
        """Run ScopeHunter and display in the approriate way."""

        self.view = v
        self.window = self.view.window()
        view = self.window.create_output_panel('scopehunter.results',
                                               unlisted=True)
        self.scope_bfr = []
        self.scope_bfr_tool = []
        self.clips = []
        self.status = ""
        self.popup_template = sublime.load_resource(
            'Packages/ScopeHunter/popup.j2')
        self.scheme_file = None
        self.syntax_file = None
        self.show_statusbar = bool(sh_settings.get("show_statusbar", False))
        self.show_panel = bool(sh_settings.get("show_panel", False))
        if TOOLTIP_SUPPORT:
            self.show_popup = bool(sh_settings.get("show_popup", False))
        else:
            self.show_popup = False
        self.clipboard = bool(sh_settings.get("clipboard", False))
        self.multiselect = bool(sh_settings.get("multiselect", False))
        self.console_log = bool(sh_settings.get("console_log", False))
        self.highlight_extent = bool(sh_settings.get("highlight_extent",
                                                     False))
        self.highlight_scope = sh_settings.get("highlight_scope", 'invalid')
        self.highlight_style = sh_settings.get("highlight_style", 'outline')
        self.highlight_max_size = int(
            sh_settings.get("highlight_max_size", 100))
        self.rowcol_info = bool(sh_settings.get("extent_line_char", False))
        self.points_info = bool(sh_settings.get("extent_points", False))
        self.appearance_info = bool(sh_settings.get("styling", False))
        self.show_simulated = bool(
            sh_settings.get("show_simulated_alpha_colors", False))
        self.file_path_info = bool(sh_settings.get("file_paths", False))
        self.selector_info = bool(sh_settings.get("selectors", False))
        self.scheme_info = self.appearance_info or self.selector_info
        self.first = True
        self.extents = []

        # Get scope info for each selection wanted
        self.index = -1
        if len(self.view.sel()):
            if self.multiselect:
                count = 0
                for sel in self.view.sel():
                    if count > 0 and self.show_popup:
                        self.scope_bfr_tool.append('\n---\n')
                    self.init_template_vars()
                    self.get_info(sel.b)
                    count += 1
            else:
                self.init_template_vars()
                self.get_info(self.view.sel()[0].b)

        # Copy scopes to clipboard
        if self.clipboard:
            sublime.set_clipboard('\n'.join(self.clips))

        # Display in status bar
        if self.show_statusbar:
            sublime.status_message(self.status)

        # Show panel
        if self.show_panel:
            ScopeHunterEditCommand.bfr = '\n'.join(self.scope_bfr)
            ScopeHunterEditCommand.pt = 0
            view.run_command('scope_hunter_edit')
            ScopeHunterEditCommand.clear()
            self.window.run_command("show_panel",
                                    {"panel": "output.scopehunter.results"})

        if self.console_log:
            print('\n'.join(["Scope Hunter"] + self.scope_bfr))

        if self.highlight_extent:
            style = extent_style(self.highlight_style)
            if style == 'underline':
                self.extents = underline(self.extents)
            self.view.add_regions('scope_hunter', self.extents,
                                  self.highlight_scope, '', style)

        if self.show_popup:
            if self.scheme_info or self.rowcol_info or self.points_info or self.file_path_info:
                tail = mdpopups.md2html(self.view, COPY_ALL)
            else:
                tail = mdpopups.md2html(self.view, RELOAD)

            mdpopups.show_popup(
                self.view,
                ''.join(self.scope_bfr_tool) + tail,
                md=False,
                css=ADD_CSS,
                wrapper_class=('scope-hunter'),
                max_width=1000,
                on_navigate=self.on_navigate,
            )
Example #41
0
def copy(el):
    return sublime.set_clipboard(el)
Example #42
0
 def run(self, edit):
     sublime.set_clipboard(self.gist_html_url())
 def on_done(i):
     if i != -1:
         sublime.set_clipboard(dotted_paths[i])
         sublime.status_message("CFML: copied cfc dotted path")
Example #44
0
 def copy():
     ui.InputList([
         ui.InputListItem(
             lambda: sublime.set_clipboard(value),
             "Copy")
     ], value).run()
Example #45
0
 def Append(self):
     cb = sublime.get_clipboard()
     #    print("before " + self.Clipboards[self.Current])
     self.Clipboards[self.Current] = self.Clipboards[self.Current] + cb
     sublime.set_clipboard(self.Clipboards[self.Current])
Example #46
0
 def copy_sha(self):
     sublime.set_clipboard(self.git("rev-parse", self._commit_hash).strip())
Example #47
0
 def process(self, func):
     t = self.getText()
     set_clipboard(func(t))
     self.view.window().status_message('data copied to clipboard')
Example #48
0
    def run(self,
            edit,
            copyonly=False,
            permalink=False,
            mode="blob",
            branch=None):
        self.load_config()

        if not self.view.file_name():
            return

        # The current file
        full_name = os.path.realpath(self.view.file_name())
        folder_name, file_name = os.path.split(full_name)

        # Try to find a git directory
        git_path = self.recurse_dir(folder_name, ".git")
        if not git_path:
            sublime.status_message("Could not find .git directory.")
            return

        new_git_path = folder_name[len(git_path):]

        # path names normalize for UNC styling
        if os.name == "nt":
            new_git_path = new_git_path.replace("\\", "/")
            file_name = file_name.replace("\\", "/")

        # Read the config file in .git
        git_config_path = os.path.join(git_path, ".git", "config")
        with open(git_config_path, "r") as git_config_file:
            config = git_config_file.read()

        # Figure out the host
        scheme = "https"
        result = re.search(r"url.*?=.*?((https?)://([^/]*)/)|(git@([^:]*):)",
                           config)
        if result:
            matches = result.groups()
            if matches[0]:
                scheme = matches[1]
                self.default_host = matches[2]
            else:
                self.default_host = matches[4]

        re_host = re.escape(self.default_host)

        sha, current_branch = self.get_git_status(git_path)
        if not branch:
            branch = current_branch

        target = sha if permalink else branch
        target = quote_plus(target)

        detected_remote = None
        regex = r".*\s.*(?:remote = )(\w+?)\r?\n"
        result = re.search(branch + regex, config)

        if result:
            matches = result.groups()
            detected_remote = [matches[0]]

        for remote in (detected_remote or self.default_remote):

            regex = r".*\s.*(?:https?://%s/|%s:|git://%s/)(.*)/(.*?)(?:\.git)?\r?\n" % (
                re_host, re_host, re_host)
            result = re.search(remote + regex, config)
            if not result:
                continue

            matches = result.groups()
            username = matches[0]
            project = matches[1]

            lines = self.get_selected_line_nums()

            if "bitbucket" in self.default_host:
                lines = ":".join([str(l) for l in lines])
                full_link = scheme + "://%s/%s/%s/src/%s%s/%s?at=%s#cl-%s" % \
                    (self.default_host, username, project, sha, new_git_path,
                        file_name, branch, lines)
            else:
                lines = "-".join("L%s" % line for line in lines)
                full_link = scheme + "://%s/%s/%s/%s/%s%s/%s#%s" % \
                    (self.default_host, username, project, mode, target, new_git_path,
                        file_name, lines)

            sublime.set_clipboard(full_link)
            sublime.status_message("Copied %s to clipboard." % full_link)

            if not copyonly:
                self.view.window().run_command("open_url", {"url": full_link})

            break
Example #49
0
    def navigate(href):
        if href == "hide":
            view.hide_popup()
        elif href == "revert":
            new_text = "\n".join(deleted_lines)
            # (removed) if there is no text to remove, set the
            # region to the end of the line, where the hunk starts
            # and add a new line to the start of the text
            if is_removed:
                if start != 0:
                    # set the start and the end to the end of the start line
                    start_point = end_point = view.text_point(start, 0) - 1
                    # add a leading newline before inserting the text
                    new_text = "\n" + new_text
                else:
                    # (special handling for deleted at the start of the file)
                    # if we are before the start we need to set the start
                    # to 0 and add the newline behind the text
                    start_point = end_point = 0
                    new_text = new_text + "\n"
            # (modified/added)
            # set the start point to the start of the hunk
            # and the end point to the end of the hunk
            else:
                start_point = view.text_point(start - 1, 0)
                end_point = view.text_point(start + size - 1, 0)
                # (modified) if there is text to insert, we
                # don't want to capture the trailing newline,
                # because we insert lines without a trailing newline
                if is_modified and end_point != view.size():
                    end_point -= 1
            replace_param = {
                "a": start_point,
                "b": end_point,
                "text": new_text
            }
            view.run_command("git_gutter_replace_text", replace_param)
            # hide the popup and update the gutter
            view.hide_popup()
            view.run_command("git_gutter")
        elif href in ["disable_hl_diff", "enable_hl_diff"]:
            do_diff = {
                "disable_hl_diff": False,
                "enable_hl_diff": True
            }.get(href)
            # show a diff popup with the same diff info
            _show_diff_popup_impl(view,
                                  point,
                                  highlight_diff=do_diff,
                                  flags=0,
                                  diff_info=diff_info)
        elif href == "copy":
            sublime.set_clipboard("\n".join(deleted_lines))
            copy_message = "  ".join(l.strip() for l in deleted_lines)
            sublime.status_message("Copied: " + copy_message)
        elif href in ["next_change", "prev_change", "first_change"]:
            next_line = meta.get(href, line)
            pt = view.text_point(next_line - 1, 0)

            def show_new_popup():
                if view.visible_region().contains(pt):
                    popup_kwargs = {
                        'action': 'show_diff_popup',
                        'highlight_diff': highlight_diff,
                        'point': pt,
                        'flags': 0
                    }
                    view.run_command('git_gutter', popup_kwargs)
                else:
                    sublime.set_timeout(show_new_popup, 10)

            view.show_at_center(pt)
            show_new_popup()
Example #50
0
 def Pull(self):
     sublime.set_clipboard(self.Clipboards[self.Current])
Example #51
0
 def _run_build(view, result_queue):
     sublime.set_clipboard('github.com/golang/example/hello')
     notify_user('Paste from the clipboard into the input panel')
     begin_event.set()
     view.window().run_command('golang_build_get',
                               {'flags': ['-v', '-d']})
Example #52
0
 def run(self, edit):
     line_number, column = self.view.rowcol(self.view.sel()[0].begin())
     line_number += 1
     sublime.set_clipboard(self.view.file_name() + ':' + str(line_number))
Example #53
0
    def run(self, *args):
        global last_compiler

        #view = sublime.active_window().active_view()
        view = self.view
        code = view.substr(sublime.Region(0, view.size()))
        filepath = view.file_name()
        if filepath:
            self.base_path = os.path.dirname(filepath)
        else:
            self.base_path = None

        settings = sublime.load_settings("KSP.sublime-settings")

        compact = settings.get('ksp_compact_output', False)
        compactVars = settings.get('ksp_compact_variables', False)
        check = settings.get('ksp_extra_checks', True)
        optimize = settings.get('ksp_optimize_code', False)
        comments_on_expansion = settings.get('ksp_comment_inline_functions',
                                             False)
        check_empty_compound_statements = settings.get(
            'ksp_signal_empty_ifcase', True)
        should_play_sound = settings.get('ksp_play_sound', False)

        error_msg = None
        error_lineno = None
        error_filename = filepath  # path to main script

        sound_utility = CompilerSounds()

        try:
            sublime.status_message('Compiling...')

            self.compiler = ksp_compiler.KSPCompiler(
                code,
                self.base_path,
                compact,
                compactVars,
                comments_on_expansion,
                read_file_func=self.read_file_function,
                extra_syntax_checks=check,
                optimize=optimize and check,
                check_empty_compound_statements=check_empty_compound_statements
            )
            if self.compiler.compile(callback=self.compile_on_progress):
                last_compiler = self.compiler
                code = self.compiler.compiled_code
                code = code.replace('\r', '')
                if self.compiler.output_file:
                    if not os.path.isabs(self.compiler.output_file):
                        self.compiler.output_file = os.path.join(
                            self.base_path, self.compiler.output_file)
                    codecs.open(self.compiler.output_file, 'w',
                                'latin-1').write(code)
                    #codecs.open(self.compiler.output_file, 'w', 'mac-roman').write(code)
                    #codecs.open(self.compiler.output_file, 'w', 'utf-8').write(code)
                    sublime.status_message(
                        "Successfully compiled (compiled code saved to %s)." %
                        self.compiler.output_file)
                else:
                    sublime.status_message(
                        "Successfully compiled (the code is now on the clipboard ready to be pasted into Kontakt)."
                    )
                    sublime.set_clipboard(code)
            else:
                sublime.status_message('Compilation aborted.')
        except ksp_ast.ParseException as e:
            #raise
            #import traceback
            #traceback.print_exc()
            error_msg = unicode(e)
            line_object = self.compiler.lines[
                e.lineno]  # self.compiler.lines.get(e.lineno, None)
            if line_object:  # and not line_object.filename:
                error_lineno = line_object.lineno - 1
                error_filename = line_object.filename
            if line_object:
                error_msg = re.sub(r'line (\d+)',
                                   'line %s' % line_object.lineno, error_msg)
        except ksp_compiler.ParseException as e:
            #raise
            #if e.line.filename is None: # if error in currently edited file
            #print ('exc message is ' + e.message)
            error_lineno = e.line.lineno - 1
            error_filename = e.line.filename
            error_msg = e.message
            #error_msg = unicode(str(e), errors='ignore').replace('__', '.')
        except Exception as e:
            error_msg = str(e)
            error_msg = ''.join(traceback.format_exception(*sys.exc_info()))

        if error_msg:
            self.compile_handle_error(error_msg, error_lineno, error_filename)
            if should_play_sound:
                sound_utility.play(command="error")
        else:
            if should_play_sound:
                sound_utility.play(command="finished")
 def run(self, edit):
     python_path_items, class_items = self.pre_run(edit)
     python_path = '.'.join(python_path_items + class_items)
     sublime.set_clipboard(python_path)
     sublime.status_message('"%s" copied to clipboard' % python_path)
Example #55
0
File: gist.py Project: miharp/Gist
 def run(self, edit):
     GistViewCommand.run(self, edit)
     sublime.set_clipboard(self.gist_html_url())
Example #56
0
    def run(self, edit, **args):
        # Current file path & filename

        # only works on current open file
        path, filename = os.path.split(self.view.file_name())

        # Switch to cwd of file
        os.chdir(path + "/")

        # Find the repo
        git_config_path = self.getoutput("git remote show origin -n")

        # Determine git URL which may be either HTTPS or SSH form
        # (i.e. https://domain/user/repo or git@domain:user/repo)
        #
        # parts[0][2] will contain 'domain/user/repo' or 'domain:user/repo'
        #
        # see https://regex101.com/r/pZ3tN3/2 & https://regex101.com/r/iS5tQ4/2
        p = re.compile(r"(.+: )*([\w\d\.]+)[:|@]/?/?(.*)")
        parts = p.findall(git_config_path)
        git_config = parts[0][2]

        remote_name = 'github'
        if 'bitbucket' in git_config:
            remote_name = 'bitbucket'
        if 'codebasehq.com' in git_config:
            remote_name = 'codebasehq'
        remote = REMOTE_CONFIG[remote_name]

        # need to get username from full url

        # Get username and repository (& also project for codebasehq)
        if ':' in git_config:
            # SSH repository
            if remote_name == 'codebasehq':
                # format is codebasehq.com:{user}/{project}/{repo}.git
                domain, user, project, repo = git_config.replace(
                    ".git", "").replace(":", "/").split("/")
            else:
                # format is {domain}:{user}/{repo}.git
                domain, user, repo = git_config.replace(".git", "").replace(
                    ":", "/").split("/")
        else:
            # HTTP repository
            if remote_name == 'codebasehq':
                # format is {user}.codebasehq.com/{project}/{repo}.git
                domain, project, repo = git_config.replace(".git",
                                                           "").split("/")
                user = domain.split('.',
                                    1)[0]  # user is first segment of domain
            else:
                # format is {domain}/{user}/{repo}.git
                domain, user, repo = git_config.replace(".git", "").split("/")

        # Find top level repo in current dir structure
        remote_path = self.getoutput("git rev-parse --show-prefix")

        # Find the current branch
        branch = self.getoutput("git rev-parse --abbrev-ref HEAD")

        # Build the URL
        if remote_name == 'codebasehq':
            url = remote['url'].format(user, project, repo, branch,
                                       remote_path, filename)
        else:
            url = remote['url'].format(user, repo, branch, remote_path,
                                       filename)

        if (args['line']):
            row = self.view.rowcol(self.view.sel()[0].begin())[0] + 1
            url += "{0}{1}".format(remote['line_param'], row)

        if (args['web']):
            webbrowser.open_new_tab(url)
        else:
            sublime.set_clipboard(url)
            sublime.status_message('GIT url has been copied to clipboard')
Example #57
0
    def run(self, edit, cmd):

        # clean command before sending to R
        cmd = cmd.rstrip('\n')
        if len(re.findall("\n", cmd)) == 0:
            cmd = cmd.lstrip()

        App = RBoxSettings("App", None)
        if App == "SublimeREPL":
            external_id = self.view.scope_name(0).split(" ")[0].split(".", 1)[1]
            self.view.window().run_command("repl_send", {"external_id": external_id, "text": cmd})
            return

        plat = sublime.platform()
        if plat == 'osx':
            App = RBoxSettings("App", "R")

            if App == "RStudio":
                args = ['osascript']
                apple_script = ('tell application "RStudio" to activate\n'
                                'delay 0.25\n'
                                'tell application "System Events"\n'
                                    'keystroke "v" using {command down}\n'
                                    'keystroke return\n'
                                'end tell\n'
                                'tell application "Sublime Text" to activate\n')
                args.extend(['-e', apple_script])
                oldcb = sublime.get_clipboard()
                sublime.set_clipboard(cmd)
                proc = subprocess.Popen(args)
                time.sleep(0.5)
                sublime.set_clipboard(oldcb)

            cmd = escape_dq(cmd)
            if re.match('R[0-9]*$', App):
                args = ['osascript']
                args.extend(['-e', 'tell app "' + App + '" to cmd "' + cmd + '"'])
                subprocess.Popen(args)
            elif App == 'Terminal':
                args = ['osascript']
                args.extend(['-e', 'tell app "Terminal" to do script "' + cmd + '" in front window\n'])
                subprocess.Popen(args)
            elif re.match('iTerm', App):
                    # when cmd ends in a space, iterm does not execute. Thus append a line break.
                    if (cmd[-1:] == ' '):
                        cmd += '\n'
                    args = ['osascript']
                    apple_script = ('tell application "' + App + '"\n'
                                        'tell the first terminal\n'
                                            'tell current session\n'
                                                'write text "' + cmd + '"\n'
                                            'end tell\n'
                                        'end tell\n'
                                    'end tell\n')
                    args.extend(['-e', apple_script])
                    subprocess.Popen(args)

        elif plat == 'windows':
            App = RBoxSettings("App", "R64")
            progpath = RBoxSettings(App, str(1) if App == "R64" else str(0))
            ahk_path = os.path.join(sublime.packages_path(), 'R-Box', 'bin','AutoHotkeyU32')
            ahk_script_path = os.path.join(sublime.packages_path(), 'R-Box', 'bin','Rgui.ahk')
            # manually add "\n" to keep the indentation of first line of block code,
            # "\n" is later removed in AutoHotkey script
            cmd = "\n"+cmd

            args = [ahk_path, ahk_script_path, progpath, cmd ]
            subprocess.Popen(args)

        elif plat == 'linux':
            App = RBoxSettings("App", "tmux")
            if App == "tmux":
                progpath = RBoxSettings("tmux", "tmux")
                subprocess.call([progpath, 'set-buffer', cmd + "\n"])
                subprocess.call([progpath, 'paste-buffer', '-d'])

            elif App == "screen":
                progpath = RBoxSettings("screen", "screen")
                subprocess.call([progpath, '-X', 'stuff', cmd + "\n"])
Example #58
0
 def append(self, content):
     # appends killed data to the current entry.
     # Also updates the windows clipboard with
     # everything in this kill entry
     self.killRing[-1] = self.killRing[-1] + content
     sublime.set_clipboard(self.killRing[-1])
Example #59
0
    def to_clipboard(self, html):
        """Save to clipboard."""

        # clipboard copy the full HTML
        sublime.set_clipboard(html)
        sublime.status_message('Markdown export copied to clipboard')
		def on_post_diff_tool(from_file, to_file):
			self.update_view(self.view, edit, to_file)
			sublime.set_clipboard(self.get_content_from_file(from_file))