def input_list(prompt, options): take_from = 0 while take_from < len(options): take_this_time = int(vim.eval('&lines')) - 2 more_items_remaining = take_from + take_this_time < len(options) if more_items_remaining: take_this_time -= 1 options_slice = options[take_from:(take_from + take_this_time)] take_from += take_this_time number_length = len(str(len(options_slice))) def iteration_items_generator(): for option in options_slice: yield option if more_items_remaining: yield '*MORE*' def list_for_input_query_generator(): yield prompt for index, option in enumerate(iteration_items_generator()): index_text = str(index + 1) yield '%s)%s %s' % (index_text, ' ' * (number_length - len(index_text)), option) list_for_input_query = list(list_for_input_query_generator()) chosen_option_number = int(vim.eval("inputlist(%s)" % vim_repr(list_for_input_query))) if more_items_remaining and chosen_option_number == len(options_slice) + 1: print(' ') elif chosen_option_number < 1 or len(options_slice) < chosen_option_number: return None else: return options_slice[chosen_option_number - 1]
def start_event_loop(): global ticker if G.TIMERS: msg.debug('Your Vim was compiled with +timer support. Awesome!') return if not bool(int(vim.eval('has("clientserver")'))): return fallback_to_feedkeys('This VIM was not compiled with clientserver support. You should consider using a different vim!') exe = getattr(G, 'VIM_EXECUTABLE', None) if not exe: return fallback_to_feedkeys('Your vim was compiled with clientserver, but I don\'t know the name of the vim executable.' 'Please define it in your ~/.floorc using the vim_executable directive. e.g. \'vim_executable mvim\'.') servername = vim.eval('v:servername') if not servername: return fallback_to_feedkeys('I can not identify the servername of this vim. You may need to pass --servername to vim at startup.') evaler = ticker_python.format(binary=exe, servername=servername, sleep='1.0') ticker = subprocess.Popen(['python', '-c', evaler], stderr=subprocess.PIPE, stdout=subprocess.PIPE) ticker.poll() utils.set_timeout(ticker_watcher, 500, ticker)
def reset_color(): global error_at # Clear current coloring (dirty) if int(vim.eval('b:checked')) != -1: vim.command('call matchdelete(b:checked)') vim.command('let b:checked = -1') if int(vim.eval('b:sent')) != -1: vim.command('call matchdelete(b:sent)') vim.command('let b:sent = -1') if int(vim.eval('b:errors')) != -1: vim.command('call matchdelete(b:errors)') vim.command('let b:errors = -1') # Recolor if encountered_dots: (line, col) = encountered_dots[-1] start = { 'line': 0 , 'col': 0 } stop = { 'line': line + 1, 'col': col } zone = _make_matcher(start, stop) vim.command("let b:checked = matchadd('CheckedByCoq', '%s')" % zone) if len(send_queue) > 0: (l, c) = encountered_dots[-1] if encountered_dots else (0,-1) r = send_queue.pop() send_queue.append(r) (line, col) = r['stop'] start = { 'line': l , 'col': c + 1 } stop = { 'line': line + 1, 'col': col } zone = _make_matcher(start, stop) vim.command("let b:sent = matchadd('SentToCoq', '%s')" % zone) if error_at: ((sline, scol), (eline, ecol)) = error_at start = { 'line': sline + 1, 'col': scol } stop = { 'line': eline + 1, 'col': ecol } zone = _make_matcher(start, stop) vim.command("let b:errors = matchadd('CoqError', '%s')" % zone) error_at = None
def tabnew(path): "Open a file in a new tab or switch to an existing one" path = os.path.abspath(path) if vim.eval('has("gui")') == '1': vim.command('tab drop %s' % path) return for tab_nr in range(int(vim.eval("tabpagenr('$')"))): for buf_nr in vim.eval("tabpagebuflist(%i + 1)" % tab_nr): buf_nr = int(buf_nr) - 1 try: buf_path = vim.buffers[buf_nr].name except IndexError: # Just do good old asking for forgiveness. # don't know why this happens :-) pass else: if buf_path == path: # tab exists, just switch to that tab vim.command('tabfirst | tabnext %i' % (tab_nr + 1)) break else: continue break else: # tab doesn't exist, add a new one. vim.command('tabnew %s' % path)
def LoadDictIntoVimGlobals( new_globals, overwrite = True ): extend_option = '"force"' if overwrite else '"keep"' # We need to use json.dumps because that won't use the 'u' prefix on strings # which Vim would bork on. vim.eval( 'extend( g:, {0}, {1})'.format( json.dumps( new_globals ), extend_option ) )
def vim_selectphrase(l1, c1, l2, c2): # In some context, vim set column of '> to 2147483647 (2^31 - 1) # This cause the merlin json parser on 32 bit platforms to overflow bound = 2147483647 - 1 vl1 = min(bound, int(vim.eval(l1))) vc1 = min(bound, int(vim.eval(c1))) vl2 = min(bound, int(vim.eval(l2))) vc2 = min(bound, int(vim.eval(c2))) sync_buffer_to(vl2, vc2) loc2 = command("boundary", "at", {"line": vl2, "col": vc2}) if vl2 != vl1 or vc2 != vc1: loc1 = command("boundary", "at", {"line": vl1, "col": vc1}) else: loc1 = None if loc2 == None: return fst = loc2[0] snd = loc2[1] if loc1 != None: fst = min_pos(loc1[0], loc2[0]) snd = max_pos(loc1[1], loc2[1]) for (var, val) in [(l1, fst["line"]), (l2, snd["line"]), (c1, fst["col"]), (c2, snd["col"])]: vim.command("let %s = %d" % (var, val))
def tern_startServer(project): if time.time() - project.last_failed < 30: return None win = platform.system() == "Windows" env = None if platform.system() == "Darwin": env = os.environ.copy() env["PATH"] += ":/usr/local/bin" command = vim.eval("g:tern#command") + vim.eval("g:tern#arguments") try: proc = subprocess.Popen(command, cwd=project.dir, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=win) except Exception as e: tern_displayError("Failed to start server: " + str(e)) return None output = "" while True: line = proc.stdout.readline().decode('utf8') if not line: tern_displayError("Failed to start server" + (output and ":\n" + output)) project.last_failed = time.time() return None match = re.match("Listening on port (\\d+)", line) if match: port = int(match.group(1)) project.port = port project.proc = proc return port else: output += line
def SetQuickFixList( quickfix_list, focus = False, autoclose = False ): """Populate the quickfix list and open it. List should be in qflist format: see ":h setqflist" for details. When focus is set to True, the quickfix window becomes the active window. When autoclose is set to True, the quickfix window is automatically closed after an entry is selected.""" vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) ) OpenQuickFixList( focus, autoclose )
def main(): binary = 'clang-rename' if vim.eval('exists("g:clang_rename_path")') == "1": binary = vim.eval('g:clang_rename') # Get arguments for clang-rename binary. offset = int(vim.eval('line2byte(line("."))+col(".")')) - 2 if offset < 0: print >> sys.stderr, '''Couldn\'t determine cursor position. Is your file empty?''' return filename = vim.current.buffer.name new_name_request_message = 'type new name:' new_name = vim.eval("input('{}\n')".format(new_name_request_message)) # Call clang-rename. command = [binary, filename, '-i', '-offset', str(offset), '-new-name', str(new_name)] # FIXME: make it possible to run the tool on unsaved file. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if stderr: print stderr # Reload all buffers in Vim. vim.command("bufdo edit")
def _JumpToLocation( self, definition_list ): if len( definition_list ) == 1: definition = definition_list[ 0 ] if definition.in_builtin_module(): if isinstance( definition.definition, jedi.keywords.Keyword ): vimsupport.PostVimMessage( "Cannot get the definition of Python keywords." ) else: vimsupport.PostVimMessage( "Builtin modules cannot be displayed." ) else: vimsupport.JumpToLocation( definition.module_path, definition.line_nr, definition.column + 1 ) else: # multiple definitions defs = [] for definition in definition_list: if definition.in_builtin_module(): defs.append( {'text': 'Builtin ' + \ definition.description.encode( 'utf-8' ) } ) else: defs.append( {'filename': definition.module_path.encode( 'utf-8' ), 'lnum': definition.line_nr, 'col': definition.column + 1, 'text': definition.description.encode( 'utf-8' ) } ) vim.eval( 'setqflist( %s )' % repr( defs ) ) vim.eval( 'youcompleteme#OpenGoToList()' )
def fold_text(allow_dirty=False): u""" Set the fold text :setlocal foldtext=Method-which-calls-foldtext :allow_dirty: Perform a query without (re)building the DOM if True :returns: None """ line = int(vim.eval(u_encode(u'v:foldstart'))) d = ORGMODE.get_document(allow_dirty=allow_dirty) heading = None if allow_dirty: heading = d.find_current_heading(line - 1) else: heading = d.current_heading(line - 1) if heading: str_heading = unicode(heading) # expand tabs ts = int(vim.eval(u_encode(u'&ts'))) idx = str_heading.find(u'\t') if idx != -1: tabs, spaces = divmod(idx, ts) str_heading = str_heading.replace(u'\t', u' ' * (ts - spaces), 1) str_heading = str_heading.replace(u'\t', u' ' * ts) # Workaround for vim.command seems to break the completion menu vim.eval(u_encode(u'SetOrgFoldtext("%s...")' % (re.sub(r'\[\[([^[\]]*\]\[)?([^[\]]+)\]\]', r'\2', str_heading).replace( u'\\', u'\\\\').replace(u'"', u'\\"'), )))
def _handle_failure(self, trigger): """ Mainly make sure that we play well with SuperTab """ if trigger.lower() == "<tab>": feedkey = "\\" + trigger else: feedkey = None mode = "n" if not self._supertab_keys: if vim.eval("exists('g:SuperTabMappingForward')") != "0": self._supertab_keys = ( vim.eval("g:SuperTabMappingForward"), vim.eval("g:SuperTabMappingBackward"), ) else: self._supertab_keys = [ '', '' ] for idx, sttrig in enumerate(self._supertab_keys): if trigger.lower() == sttrig.lower(): if idx == 0: feedkey= r"\<c-n>" elif idx == 1: feedkey = r"\<c-p>" # Use remap mode so SuperTab mappings will be invoked. mode = "m" break if feedkey: feedkeys(feedkey, mode)
def create_new_note_from_current_buffer(self): """ get content of the current buffer and create new note """ content = "\n".join(str(line) for line in vim.current.buffer[:]) markdown = (vim.eval("&filetype") == "markdown") if markdown: note, status = self.simplenote.update_note({"content": content, "systemtags": ["markdown"]}) else: note, status = self.simplenote.update_note({"content": content}) if status == 0: self.note_version[note["key"]] = note["version"] self.transform_to_scratchbuffer() # Replace any non alphanumeric characters to play safe with valid vim buffer names # otherwise vim will happily add them, but will fail to switch to them regex = re.compile("[^a-zA-Z0-9]") firstline = regex.sub("_", vim.current.buffer[0]) buffertitle = "SN_%s" % firstline self.set_current_note(buffertitle, note["key"]) self.bufnum_to_noteid[vim.current.buffer.number] = note["key"] vim.command("doautocmd BufReadPost") # BufReadPost can cause auto-selection of filetype based on file content so reset filetype after this if int(vim.eval("exists('g:SimplenoteFiletype')")) == 1: vim.command("setlocal filetype="+vim.eval("g:SimplenoteFiletype")) # But let simplenote markdown flag override the above if markdown: vim.command("setlocal filetype=markdown") print("New note created.") else: print("Update failed.: %s" % note["key"])
def set_srcview(self, file, line): """ set srcview windows to file:line and replace current sign """ if '0' != vim.eval('exists("g:debuggerPathMap")'): import re map_sep = re.compile(',\s*') path_sep = re.compile('\s*:\s*') mappings = map_sep.split(vim.eval('g:debuggerPathMap')) #print mappings if mappings: for mapping in mappings: (remote_path, local_path) = path_sep.split(mapping) path_map = re.compile('(' + remote_path + ')') file = path_map.sub(local_path, file) if file == self.file and self.line == line: return nextsign = self.next_sign() if file != self.file: self.file = file self.go_srcview() vim.command('silent edit ' + file) vim.command('sign place ' + nextsign + ' name=current line='+str(line)+' file='+file) vim.command('sign unplace ' + self.cursign) vim.command('sign jump ' + nextsign + ' file='+file) #vim.command('normal z.') self.line = line self.cursign = nextsign
def base_snippet_files_for(self, ft, default=True): """ Returns a list of snippet files matching the given filetype (ft). If default is set to false, it doesn't include shipped files. Searches through each path in 'runtimepath' in reverse order, in each of these, it searches each directory name listed in 'g:UltiSnipsSnippetDirectories' in order, then looks for files in these directories called 'ft.snippets' or '*_ft.snippets' replacing ft with the filetype. """ snippet_dirs = vim.eval("g:UltiSnipsSnippetDirectories") base_snippets = os.path.realpath(os.path.join(__file__, "../../../UltiSnips")) ret = [] paths = vim.eval("&runtimepath").split(',') if vim.eval("exists('g:UltiSnipsDontReverseSearchPath')") == "0" or \ vim.eval("g:UltiSnipsDontReverseSearchPath") == "0": paths = paths[::-1] for rtp in paths: for snippet_dir in snippet_dirs: pth = os.path.realpath(os.path.expanduser(os.path.join(rtp, snippet_dir))) patterns = ["%s.snippets", "*_%s.snippets"] if not default and pth == base_snippets: patterns.remove("%s.snippets") for pattern in patterns: for fn in glob.glob(os.path.join(pth, pattern % ft)): if fn not in ret: ret.append(fn) return ret
def complete_all_buffer_matches(): """ Return a completion result for a:keyword_base searched in all buffers """ encoding = vim.eval("&encoding") keyword_base = vim.eval("a:keyword_base").decode(encoding) min_length_keyword_base = int(vim.eval( "localcomplete#getAllBufferMinPrefixLength()")) if len(keyword_base) < min_length_keyword_base: transmit_all_buffer_result_to_vim([]) return punctuation_chars = get_additional_keyword_chars().decode(encoding) casematch_flag = get_casematch_flag(CASEMATCH_CONFIG_LOCAL) # Note: theoretically there could be a non-alphanumerical character at the # leftmost position. needle = re.compile(r'\b%s[\w%s]+' % (keyword_base, punctuation_chars), re.UNICODE|casematch_flag) found_matches = [] for buffer_line in generate_all_buffer_lines(): found_matches.extend(needle.findall(buffer_line.decode(encoding))) found_matches = apply_infercase_to_matches_cond( keyword_base, found_matches) transmit_all_buffer_result_to_vim(found_matches)
def debugger_init(debug = 0): global debugger # get needed vim variables # port that the engine will connect on port = int(vim.eval('debuggerPort')) if port == 0: port = 9000 # the max_depth variable to set in the engine max_children = vim.eval('debuggerMaxChildren') if max_children == '': max_children = '32' max_data = vim.eval('debuggerMaxData') if max_data == '': max_data = '1024' max_depth = vim.eval('debuggerMaxDepth') if max_depth == '': max_depth = '1' minibufexpl = int(vim.eval('debuggerMiniBufExpl')) if minibufexpl == 0: minibufexpl = 0 debugger = Debugger(port, max_children, max_data, max_depth, minibufexpl, debug)
def complete_local_matches(): """ Return a local completion result for a:keyword_base """ encoding = vim.eval("&encoding") keyword_base = vim.eval("a:keyword_base").decode(encoding) min_length_keyword_base = int(vim.eval( "localcomplete#getLocalMinPrefixLength()")) if len(keyword_base) < min_length_keyword_base: transmit_local_matches_result_to_vim([]) return punctuation_chars = get_additional_keyword_chars().decode(encoding) casematch_flag = get_casematch_flag(CASEMATCH_CONFIG_LOCAL) # Note: theoretically there could be a non-alphanumerical character at the # leftmost position. needle = re.compile(r'\b%s[\w%s]+' % (keyword_base, punctuation_chars), re.UNICODE|casematch_flag) found_matches = [] for buffer_line in generate_haystack(): found_matches.extend(needle.findall(buffer_line.decode(encoding))) found_matches = apply_infercase_to_matches_cond( keyword_base, found_matches) if os.environ.get("LOCALCOMPLETE_DEBUG") is not None: fake_matches = found_matches[:] fake_matches.append(keyword_base) found_matches = fake_matches transmit_local_matches_result_to_vim(found_matches)
def complete_dictionary_matches(): """ Return a dictionary completion result for a:keyword_base """ encoding = vim.eval("&encoding") keyword_base = vim.eval("a:keyword_base").decode(encoding) dictionary_file = vim.eval("&dictionary") if dictionary_file: casematch_flag = get_casematch_flag(CASEMATCH_CONFIG_DICT) needle = re.compile(r'^%s\w+' % keyword_base, re.UNICODE|re.MULTILINE|casematch_flag) try: haystack = read_file_contents(dictionary_file) except IOError as err: vim.command('echoerr "Error reading dictionary: %s"' % str(err)) haystack = u'' found_matches = needle.findall(haystack) else: found_matches = [] found_matches = apply_infercase_to_matches_cond( keyword_base, found_matches) origin_note = vim.eval("g:localcomplete#OriginNoteDictionary") vim.command(VIM_COMMAND_DICTCOMPLETE % repr(produce_result_value( found_matches, origin_note)))
def ub_get_blog_settings(): '''Get the blog settings from vimrc and raise exception if none found ''' class UBConfiguration: homepage = 'http://0x3f.org/blog/ultrablog-as-an-ultimate-vim-blogging-plugin/' def __init__(self, rawSettings): self.loginName = rawSettings['login_name'].strip() self.password = rawSettings['password'].strip() self.dbf = rawSettings['db'].strip() self.url = rawSettings['url'].strip() self.url = self.url.endswith('/') and self.url or self.url+'/' self.xmlrpc = self.url+'xmlrpc.php' if vim.eval('exists("ub_blog")') == '0': return None settings = vim.eval('ub_blog') cfg = UBConfiguration(settings) # Manipulate db file path editor_mode = ub_get_option('ub_editor_mode') if editor_mode is not None and editor_mode.isdigit() and int(editor_mode) == 1: cfg.dbf = '' elif cfg.dbf is None or cfg.dbf=='': cfg.dbf = os.path.normpath(os.path.expanduser('~')+'/.vim/UltraBlog.db') else: cfg.dbf = os.path.abspath(vim.eval("expand('%s')" % cfg.dbf)) return cfg
def get_buffer_ranges(): """ Calculate the (above_indexes, current_index, below_indexes) index and index-lists of buffer lines requested through the configuration and return that tuple. """ prev_line_count = int(vim.eval("localcomplete#getLinesAboveCount()")) ahead_line_count = int(vim.eval("localcomplete#getLinesBelowCount()")) current_index = int(vim.eval("line('.')")) - 1 last_line_index = int(vim.eval("line('$')")) - 1 if prev_line_count < 0: first_index = 0 else: first_index = max(0, current_index - prev_line_count) if ahead_line_count < 0: last_index = last_line_index else: last_index = min(last_line_index, current_index + ahead_line_count) return (range(first_index, current_index), current_index, range(current_index + 1, last_index + 1))
def bufvar_exists(buffer, varname): if not buffer or buffer.number == vim.current.buffer.number: return int(vim.eval('exists("b:{0}")'.format(varname))) else: return int(vim.eval( 'has_key(getbufvar({0}, ""), {1})'.format(buffer.number, varname) ))
def _get_preview_url(self): wiki_repo_defined = int(vim.eval("exists('g:ghwiki_preview_repo')")) if not wiki_repo_defined: self._err = "please set ghwiki_preview_repo in your ~/.vimrc" return wiki_repo = vim.eval("g:ghwiki_preview_repo") if len(wiki_repo.split('/')) != 2: self._err = "invalid ghwiki_preview_repo set, " self._err += "must have the form: 'user/repo'" return user, repo = wiki_repo.split('/') gh = github.GitHub() try: repo_exists = gh.repos.show(user, repo) if not repo_exists.has_wiki: self._err = "repo %s does not have a git-backed wiki enabled" self._err = self._err % repo return except urllib2.HTTPError: self._err = "repo %s does not exist" % wiki_repo return except urllib2.URLError: self._err = "no internet connection available" return return 'https://github.com/%s/%s/wiki/_preview' % (user, repo)
def getCurrentCompletions(base): priority = vim.eval("g:clang_sort_algo") == "priority" line = int(vim.eval("line('.')")) column = int(vim.eval("b:col")) t = CompleteThread(line, column, getCurrentFile(), vim.current.buffer.name) t.start() while t.isAlive(): t.join(0.01) cancel = int(vim.eval("complete_check()")) if cancel != 0: return [] cr = t.result if cr is None: return [] regexp = re.compile("^" + base) filteredResult = filter(lambda x: regexp.match(getAbbr(x.string)), cr.results) getPriority = lambda x: x.string.priority getAbbrevation = lambda x: getAbbr(x.string).lower() if priority: key = getPriority else: key = getAbbrevation sortedResult = sorted(filteredResult, None, key) return map(formatResult, sortedResult)
def debugger_init(debug=0): global debugger # get needed vim variables # port that the engine will connect on port = int(vim.eval("debuggerPort")) if port == 0: port = 9000 # the max_depth variable to set in the engine max_children = vim.eval("debuggerMaxChildren") if max_children == "": max_children = "32" max_data = vim.eval("debuggerMaxData") if max_data == "": max_data = "1024" max_depth = vim.eval("debuggerMaxDepth") if max_depth == "": max_depth = "1" minibufexpl = int(vim.eval("debuggerMiniBufExpl")) if minibufexpl == 0: minibufexpl = 0 debugger = Debugger(port, max_children, max_data, max_depth, minibufexpl, debug)
def CandidatesForQueryAsyncInner( self, query, unused_start_column ): if not self.omnifunc: self.stored_candidates = None return try: return_value = int( vim.eval( self.omnifunc + '(1,"")' ) ) if return_value < 0: self.stored_candidates = None return omnifunc_call = [ self.omnifunc, "(0,'", vimsupport.EscapeForVim( query ), "')" ] items = vim.eval( ''.join( omnifunc_call ) ) if 'words' in items: items = items['words'] if not hasattr( items, '__iter__' ): raise TypeError( OMNIFUNC_NOT_LIST ) self.stored_candidates = filter( bool, items ) except (TypeError, ValueError) as error: vimsupport.PostVimMessage( OMNIFUNC_RETURNED_BAD_VALUE + ' ' + str( error ) ) self.stored_candidates = None return
def updateCurrentDiagnostics(): global debug debug = int(vim.eval("g:clang_debug")) == 1 userOptionsGlobal = splitOptions(vim.eval("g:clang_user_options")) userOptionsLocal = splitOptions(vim.eval("b:clang_user_options")) args = userOptionsGlobal + userOptionsLocal getCurrentTranslationUnit(args, getCurrentFile(), vim.current.buffer.name, update=True)
def set_tags(cls): u""" Set tags for current heading """ d = ORGMODE.get_document() heading = d.current_heading() if not heading: return # retrieve tags res = None if heading.tags: res = vim.eval(u'input("Tags: ", ":%s:", "customlist,Org_complete_tags")' % u':'.join(heading.tags)) else: res = vim.eval(u'input("Tags: ", "", "customlist,Org_complete_tags")') if res is None: # user pressed <Esc> abort any further processing return # remove empty tags heading.tags = filter(lambda x: x.strip() != u'', res.decode(u'utf-8').strip().strip(u':').split(u':')) d.write() return u'OrgSetTags'
def execute(self, should_open): with open("pandoc.out", 'w') as tmp: if vim.eval("has('clientserver')") == '1' and \ vim.eval("v:servername") != "" and \ vim.eval("executable('python')") == '1': async_runner = '"' + os.path.join(os.path.dirname(__file__), "async.py") + '"' servername_arg = "--servername=" + vim.eval("v:servername") open_arg = "--open" if should_open else "--noopen" async_command = " ".join(["python", async_runner, servername_arg, open_arg, self._run_command]) try: Popen(shlex.split(async_command), stdout=tmp, stderr=tmp) except: vim.command('echoe "vim-pandoc: could not execute pandoc asynchronously"') elif vim.eval("has('nvim')") == '1': vim.command("call jobstart("+ \ str(['pandoc'] + shlex.split(self._run_command)[1:]) + \ ", extend({'should_open': '" + str(int(should_open)) + \ "'}, {'on_exit': 'pandoc#command#JobHandler'}))") #vim.command('call jobstart(["pandoc", ' + str(shlex.split(self._run_command)[1:]) + '])') else: try: com = Popen(shlex.split(self._run_command), stdout=tmp, stderr=tmp) com.wait() except: vim.command('echoe "vim-pandoc: could not execute pandoc"') return self.on_done(should_open, com.returncode)
def ub_get_meta(item, buf=None): '''Get value of the given item from meta data in the current buffer ''' def __get_value(item, line): tmp = line.split(':') val = ':'.join(tmp[1:]).strip() if item.endswith('id'): if val.isdigit(): val = int(val) if val<=0: return None else: return None return val nr = ub_get_bufnr(buf) if nr is None: nr = int(vim.eval("bufnr('%')")) regex_meta_end = re.compile('^\s*-->') regex_item = re.compile('^\$'+item+':\s*') for line in vim.eval("getbufline(%d,0,'$')" % nr): if regex_meta_end.match(line): break if regex_item.match(line): return __get_value(item, line) return None
def GetTagFiles(): tag_files = vim.eval('tagfiles()') current_working_directory = os.getcwd() return [ os.path.join(current_working_directory, x) for x in tag_files ]
# # It operates on the current, potentially unsaved buffer and does not create # or save any files. To revert a formatting, just undo. from __future__ import absolute_import, division, print_function import difflib import json import platform import subprocess import sys import vim # set g:clang_format_path to the path to clang-format if it is not on the path # Change this to the full path if clang-format is not on the path. binary = 'clang-format' if vim.eval('exists("g:clang_format_path")') == "1": binary = vim.eval('g:clang_format_path') # Change this to format according to other formatting styles. See the output of # 'clang-format --help' for a list of supported styles. The default looks for # a '.clang-format' or '_clang-format' file to indicate the style that should be # used. style = None fallback_style = None if vim.eval('exists("g:clang_format_fallback_style")') == "1": fallback_style = vim.eval('g:clang_format_fallback_style') def get_buffer(encoding): if platform.python_version_tuple()[0] == '3': return vim.current.buffer return [ line.decode(encoding) for line in vim.current.buffer ]
def init_org_todo(cls): u""" Initialize org todo selection window. """ bufnr = int(vim.current.buffer.name.split('/')[-1]) all_states = ORGTODOSTATES.get(bufnr, None) # because timeoutlen can only be set globally it needs to be stored and restored later vim.command(u'let g:org_sav_timeoutlen=&timeoutlen'.encode(u'utf-8')) vim.command( u'au orgmode BufEnter <buffer> :if ! exists("g:org_sav_timeoutlen")|let g:org_sav_timeoutlen=&timeoutlen|set timeoutlen=1|endif' .encode(u'utf-8')) vim.command( u'au orgmode BufLeave <buffer> :if exists("g:org_sav_timeoutlen")|let &timeoutlen=g:org_sav_timeoutlen|unlet g:org_sav_timeoutlen|endif' .encode(u'utf-8')) # make window a scratch window and set the statusline differently vim.command( u'setlocal nolist tabstop=16 buftype=nofile timeout timeoutlen=1 winfixheight' .encode(u'utf-8')) vim.command((u'setlocal statusline=Org\\ todo\\ (%s)' % vim.eval( (u'fnameescape(fnamemodify(bufname(%d), ":t"))' % bufnr).encode(u'utf-8'))).encode(u'utf-8')) vim.command( (u'nnoremap <silent> <buffer> <Esc> :%sbw<CR>' % (vim.eval(u'bufnr("%")'.encode(u'utf-8')), )).encode(u'utf-8')) vim.command( u'nnoremap <silent> <buffer> <CR> :let g:org_state = fnameescape(expand("<cword>"))<Bar>bw<Bar>exec "py ORGMODE.plugins[u\'Todo\'].set_todo_state(\'".g:org_state."\')"<Bar>unlet! g:org_state<CR>' .encode(u'utf-8')) if all_states is None: vim.command(u'bw'.encode(u'utf-8')) echom(u'No todo states avaiable for buffer %s' % vim.current.buffer.name) for l in xrange(0, len(all_states)): res = u'' for j in xrange(0, 2): if j < len(all_states[l]): for i in all_states[l][j]: if type(i) != unicode: continue v, k = split_access_key(i) if k: res += (u'\t' if res else u'') + u'[%s] %s' % (k, v) # map access keys to callback that updates current heading # map selection keys vim.command(( u'nnoremap <silent> <buffer> %s :bw<Bar>py ORGMODE.plugins[u"Todo"].set_todo_state("%s".decode(u"utf-8"))<CR>' % (k, v)).encode(u'utf-8')) elif v: res += (u'\t' if res else u'') + v if res: if l == 0: # WORKAROUND: the cursor can not be positioned properly on # the first line. Another line is just inserted and it # works great vim.current.buffer[0] = u''.encode(u'utf-8') vim.current.buffer.append(res.encode(u'utf-8')) # position the cursor of the current todo item vim.command(u'normal! G'.encode(u'utf-8')) current_state = settings.unset(u'org_current_state_%d' % bufnr) found = False if current_state is not None and current_state != '': for i in xrange(0, len(vim.current.buffer)): idx = vim.current.buffer[i].find(current_state) if idx != -1: vim.current.window.cursor = (i + 1, idx) found = True break if not found: vim.current.window.cursor = (2, 4) # finally make buffer non modifiable vim.command(u'setfiletype orgtodo'.encode(u'utf-8')) vim.command(u'setlocal nomodifiable'.encode(u'utf-8')) # remove temporary todo states for the current buffer del ORGTODOSTATES[bufnr]
def toggle_todo_state(cls, direction=Direction.FORWARD, interactive=False, next_set=False): u""" Toggle state of TODO item :returns: The changed heading """ d = ORGMODE.get_document(allow_dirty=True) # get heading heading = d.find_current_heading() if not heading: vim.eval(u'feedkeys("^", "n")') return todo_states = d.get_todo_states(strip_access_key=False) # get todo states if not todo_states: echom(u'No todo keywords configured.') return current_state = heading.todo # get new state interactively if interactive: # determine position of the interactive prompt prompt_pos = settings.get(u'org_todo_prompt_position', u'botright') if prompt_pos not in [u'botright', u'topleft']: prompt_pos = u'botright' # pass todo states to new window ORGTODOSTATES[d.bufnr] = todo_states settings.set(u'org_current_state_%d' % d.bufnr, current_state if current_state is not None else u'', overwrite=True) todo_buffer_exists = bool( int( vim.eval((u'bufexists("org:todo/%d")' % (d.bufnr, )).encode(u'utf-8')))) if todo_buffer_exists: # if the buffer already exists, reuse it vim.command((u'%s sbuffer org:todo/%d' % ( prompt_pos, d.bufnr, )).encode(u'utf-8')) else: # create a new window vim.command( (u'keepalt %s %dsplit org:todo/%d' % (prompt_pos, len(todo_states), d.bufnr)).encode(u'utf-8')) else: new_state = Todo._get_next_state(current_state, todo_states, direction=direction, interactive=interactive, next_set=next_set) cls.set_todo_state(new_state) # plug plug = u'OrgTodoForward' if direction == Direction.BACKWARD: plug = u'OrgTodoBackward' return plug
def __init__(self): # {{{ self.extension = vim.eval('g:NVIM_extension') self.database = vim.eval('g:NVIM_database') self.language = vim.eval('g:NVIM_language') self.reload_database()
vim.command("redraw") #}}} def load_from_selection(): # {{{ ''' Handle loading from a link in the text. ''' # make sure the buffer is cleared vim.command("let @n=''") vim.command('normal "nyi]') name = vim.eval('@n') if not name: return filename = nvimdb.get_filename(name) load_note(filename) # TODO - remove if/when we put it in an onload handler set_entry_line(name) # }}} # Python initialisation code buf_results = vim.current.buffer win_results = vim.current.window win_results_nr = vim.eval('winnr()') nvim_debug = True nvimdb = Nvimdb() populate_initial_buffer()
def current_full_file_path(): return vim.eval("expand('%:p')")
def get_current_path(): ''' returns the current file's full path without its name ''' try: return vim.eval('expand("%:p:h")') except AttributeError: return ''
def update_presence(): """Update presence in Discord """ global ignored_file_types global ignored_directories if (ignored_file_types == -1): # Lazy init if (vim.eval("exists('{}')".format("g:vimsence_ignored_file_types")) == "1"): ignored_file_types = vim.eval("g:vimsence_ignored_file_types") else: ignored_file_types = [] if (vim.eval("exists('{}')".format("g:vimsence_ignored_directories")) == "1"): ignored_directories = vim.eval("g:vimsence_ignored_directories") else: ignored_directories = [] activity = base_activity large_image = "" large_text = "" details = "" state = "" filename = get_filename() directory = get_directory() filetype = get_filetype() if (u.contains(ignored_file_types, filetype) or u.contains(ignored_directories, directory)): # Priority #1: if the file type or folder is ignored, use the default activity to avoid exposing # the folder or file. rpc_obj.set_activity(base_activity) return elif filetype and filetype in has_thumbnail: # Check for files with thumbnail support large_text = 'Editing a {} file'.format(filetype) if (filetype in remap): filetype = remap[filetype] large_image = filetype details = 'Editing {}'.format(filename) state = 'Workspace: {}'.format(directory) elif filetype in file_explorers or u.contains_fuzzy(file_explorer_names, filename): # Special case: file explorers. These have a separate icon and description. large_image = 'file-explorer' large_text = 'In the file explorer' details = 'Searching for files' state = 'Workspace: {}'.format(directory) elif (is_writeable() and filename): # if none of the other match, check if the buffer is writeable. If it is, # assume it's a file and continue. large_image = 'none' large_text = 'Editing a {} file'.format(filetype if filetype else "Unknown" if not get_extension() else get_extension()) details = 'Editing {}'.format(filename) state = 'Workspace: {}'.format(directory) else: large_image = 'none' large_text = 'Nothing' details = 'Nothing' # Update the activity activity['assets']['large_image'] = large_image activity['assets']['large_text'] = large_text activity['details'] = details activity['state'] = state try: rpc_obj.set_activity(activity) except BrokenPipeError as e: # Connection to Discord is lost pass except NameError as e: # Discord is not running pass except OSError as e: # IO-related issues (possibly disconnected) pass
def show_status_message(message): if int(vim.eval('g:VimpairShowStatusMessages')) != 0: print('Vimpair:', message)
def get_filetype(): """Get the filetype for file that is being edited :returns: string """ return vim.eval('&filetype')
def get_current_filename(): ''' returns name and extension of the current file ''' try: return vim.eval('expand("%:t")') except AttributeError: return ''
def is_writeable(): """Returns whether the buffer is writeable or not :returns: string """ return vim.eval('&modifiable')
def get_directory(): """Get current directory :returns: string """ return re.split(r"[\\/]", vim.eval('getcwd()'))[-1]
def eval(text): """Wraps vim.eval.""" rv = vim.eval(as_vimencoding(text)) if not isinstance(rv, (dict, list)): return as_unicode(rv) return rv
def get_filename(): """Get current filename that is being edited :returns: string """ return vim.eval('expand("%:t")')
def updateminimap(): minimap = getmmwindow() if not minimap: return src = vim.current.window if not hasattr(src, 'buffer'): return # Ignore NERD_tree Buffers # TODO make configurable if "NERD_tree" in src.buffer.name: return if src.buffer == minimap.buffer: return HORIZ_SCALE = 0.5 mode = vim.eval("mode()") cursor = src.cursor vim.command("normal! H") topline = src.cursor[0] bottomline = topline + src.height - 1 vim.current.window = minimap highlight_group = vim.eval("g:minimap_highlight") mmheight = 4 * minimap.height line_infos = [{ 'count': 0.0, 'weight': [0.0] * 2 * WIDTH } for _ in range(mmheight)] def char_weight(c): if c == ' ' or c == '\t': return 0.0 if c == '.' or c == ',' or c == '\'': return 0.2 if c == '|' or c == '-' or c == '#': return 2.0 return 1.0 heightrat = max(1.0, len(src.buffer) / mmheight) for y, line in enumerate(src.buffer): ymm = int(y / heightrat) line_infos[ymm]['count'] += 1.0 / HORIZ_SCALE for x, c in enumerate(line): xmm = int(x * HORIZ_SCALE) if xmm >= len(line_infos[ymm]['weight']): continue line_infos[ymm]['weight'][xmm] += char_weight(c) def draw(line_infos): c = Canvas() for y, info in enumerate(line_infos): for x in range(len(info['weight'])): if info['count'] == 0: continue if info['weight'][x] / info['count'] >= 0.5: c.set(x, y) # pad with spaces to ensure uniform block highlighting if PY3: return [line.ljust(WIDTH, u'\u00A0') for line in c.rows()] else: return [unicode(line).ljust(WIDTH, u'\u00A0') for line in c.rows()] vim.command(":setlocal modifiable") minimap.buffer[:] = draw(line_infos) # Highlight the current visible zone tmp = len(minimap.buffer) / len(src.buffer) top = min(len(minimap.buffer) - 1, int(topline * tmp)) bottom = top + math.ceil(src.height * tmp) vim.command("match {0} /\\%>0v\\%<{1}v\\%>{2}l\\%<{3}l./".format( highlight_group, WIDTH + 1, top, bottom)) # center the highlighted zone height = int(vim.eval("winheight(0)")) # first, put the cursor at the top of the buffer vim.command("normal! gg") # then, jump so that the active zone is centered if (top + (bottom - top) / 2) > height / 2: jump = min(top + (bottom - top) / 2 + height / 2, len(minimap.buffer)) vim.command("normal! %dgg" % jump) # prevent any further modification vim.command(":setlocal nomodifiable") vim.current.window = src # restore the current selection if we were in visual mode. if mode in ('v', 'V', '\026'): vim.command("normal! gv") src.cursor = cursor
def filetypes(self): return [ft for ft in vim.eval('&filetype').split('.') if ft]
def vim_fnameescape(s): return vim.eval("fnameescape('%s')" % s.replace("'", "''"))
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # File: todo.py # Description: Todo.txt overdue date syntax script # License: Vim license # Website: http://github.com/freitass/todo.txt-vim # Version: 0.1 import vim import os import sys from datetime import date from datetime import timedelta dateregex_dir = os.path.join(vim.eval('s:script_dir'), 'dateregex') if os.path.isdir(dateregex_dir): sys.path.insert(0, dateregex_dir) def add_due_date_syntax_highlight(): try: from dateregex import regex_date_before except ImportError: print("dateregex module not found. Overdue dates won't be highlighted") return #regex = regex_date_before(date.today()) regex = regex_date_before(date.today() + timedelta(days=1)) regex = r'(^|<)due:%s(>|$)' % regex vim.command("syntax match OverDueDate '\\v%s'" % regex)
def vim_list_if_set(name): return vim.eval('exists("{0}") ? {0} : []'.format(name))
# # You should have received a copy of the GNU Affero General Public License # along with vim-minimap. If not, see < http://www.gnu.org/licenses/ >. # # (C) 2014- by Séverin Lemaignan for the VIM integration, <*****@*****.**> # (C) 2014- by Adam Tauber for the Drawille part, <*****@*****.**> import os import sys import math PY3 = sys.version_info[0] == 3 import vim # Add the library to the Python path. for p in vim.eval("&runtimepath").split(','): plugin_dir = os.path.join(p, "autoload", "drawille") if os.path.exists(plugin_dir): if plugin_dir not in sys.path: sys.path.append(plugin_dir) break from drawille import * WIDTH = 20 MINIMAP = "vim-minimap" def getmmwindow(): for b in vim.buffers: if b.name.endswith(MINIMAP):
def current_context(): filename = vim.eval("expand('%:p')") content = "\n".join(vim.current.buffer) + "\n" return (filename, content)
def differs_from_current_file(path): buf_path = vim.eval("expand('%:p')") return buf_path != path
import select import time ssl = False try: import ssl except ImportError: pass import vim import msg import sublime import shared as G CERT = os.path.join(vim.eval("g:floobits_plugin_dir"), 'startssl-ca.pem') msg.debug("CERT is ", CERT) class AgentConnection(object): ''' Simple chat server using select ''' def __init__(self, owner, room, host=None, port=None, secure=True, on_auth=None, Protocol=None): self.sock_q = Queue.Queue() self.sock = None
def vim_is_set(name, default=False): if not vim.eval('exists("%s")' % name): return default return not (vim.eval(name) in ["", "0", "false"])
def open_file(filename): current_buffer = vim.eval('expand("%:p")') if current_buffer != filename: vim.command(':silent! edit! %s | :silent! :filetype detect' % filename)
import sys import vim sys.path.append(vim.eval('expand("<sfile>:h")')) def open_buffering(buffer_names): vim.command('rightbelow split {0}'.format('buffering')) vim.command('normal! ggdG') vim.command('setlocal buftype=nowrite') vim.command('call append(0, {0})'.format(buffer_names)) vim.command('normal! gg') def get_open_buffers(): buffers = vim.buffers valid_open_buffers = [buffer for buffer in buffers] buffer_names = [] for buffer in valid_open_buffers: buffer_name = vim.eval('bufname("{}")'.format(buffer.name)) buffer_listed = vim.eval('buflisted("{}")'.format(buffer.name)) if buffer_listed == "1" and buffer_name != "buffering": buffer_names.append('{0}'.format(buffer_name)) return buffer_names def delete_buffer(): if vim.eval('bufname("{}")'.format( vim.current.buffer.name)) != "buffering": return
def get_rtags_variable(name): return vim.eval('g:rtags' + name)
def PrepareForTesting(): InstallTestRequestHandler( test_data_dir=vim.eval('g:codesearch_test_data_dir'))