コード例 #1
0
def show_docstring():
    '''Attempts to find the docstring for a definition and disply it in a
    preview window.'''
    # TODO: Syntax highlighting would be cool
    definitions = createScript().goto_definitions()

    if not definitions:
        return

    definition = definitions[0]
    if len(definitions) > 1:
        definition = _choose_definition(definitions)

    vim.command('let s:docstring=[]')
    vim.bindeval('s:docstring').extend([definition.docstring()])

    vim_docstring_cmds = '''
split Doc
setlocal noswapfile
setlocal buftype=nofile
setlocal modifiable
silent $put=s:docstring[0]
silent normal! ggdd
setlocal nomodifiable
setlocal nomodified
noremap <buffer> q :q<CR>
highlight Midi_Chlorian_Docstring ctermfg=blue
match Midi_Chlorian_Docstring /./
'''

    for cmd in vim_docstring_cmds.split('\n')[1:]:
        vim.command(cmd)
コード例 #2
0
def get_command_for_file(filename):
    """
    Get the command for the given file

    :param filename: The name of the file
    :returns: The command to run for compilation
    """

    if not _config_exists():
        return
    else:
        with open(CONFIG_FILE_NAME) as json_file:
            data = json.load(json_file)

            if filename not in data.keys():

                try:
                    vim.bindeval("g:CurSyntaxCommand")
                    command_str = "unlet g:CurSyntaxCommand"
                except Exception as e:
                    command_str = ""
            else:
                command_str = "let g:CurSyntaxCommand = \""\
                        + data[filename] + "\""

            vim.command(command_str)
コード例 #3
0
ファイル: command.py プロジェクト: ehamberg/vim-pantondoc
    def on_done(self, should_open, returncode):
        if self._run_command and self._output_file_path:
            if vim.bindeval("g:pantondoc_use_message_buffers") and returncode != '0':
                vim.command("let split = &splitbelow")
                vim.command("set splitbelow")

                vim.command("5new pandoc\ output")
                vim.command("let &splitbelow = split")
                vim.command("setlocal wrap")
                vim.command("setlocal linebreak")
                vim.current.buffer[0] = "# Press <Esc> to close this"
                vim.current.buffer.append("▶ " + self._run_command)
                vim.command("normal! G")
                if vim.bindeval('filereadable("pandoc.out")'):
                    vim.command("silent r pandoc.out")
                vim.command("setlocal buftype=nofile")
                vim.command("setlocal nobuflisted")
                # pressing <esc> on the buffer will delete it
                vim.command("map <buffer> <esc> :bd<cr>")
                # we will highlight some elements in the buffer
                vim.command("syn match PandocOutputMarks /^>>/")
                vim.command("syn match PandocCommand /^▶.*$/hs=s+1")
                vim.command("syn match PandocInstructions /^#.*$/")
                vim.command("hi! link PandocOutputMarks Operator")
                vim.command("hi! link PandocCommand Statement")
                vim.command("hi! link PandocInstructions Comment")

            if os.path.exists("pandoc.out"):
                os.remove("pandoc.out")
            vim.command("echohl Statement")
            vim.command("echom 'pantondoc:execute:" + self._run_command + "'")
            vim.command("echohl None")

            # open file if needed
            if os.path.exists(self._output_file_path) and should_open:
                if sys.platform == "darwin":
                    pandoc_open_command = "open" #OSX
                elif sys.platform.startswith("linux"):
                    pandoc_open_command = "xdg-open" # freedesktop/linux
                elif sys.platform.startswith("win"):
                    pandoc_open_command = 'cmd /c \"start' # Windows
                # On windows, we pass commands as an argument to `start`,
                # which is a cmd.exe builtin, so we have to quote it
                if sys.platform.startswith("win"):
                    pandoc_open_command_tail = '"'
                else:
                    pandoc_open_command_tail = ''

                pid = Popen([pandoc_open_command,  self._output_file_path + pandoc_open_command_tail])

            # we reset this
            self._output_file_path = None
            self._run_command = None
コード例 #4
0
ファイル: fbvimtypeahead.py プロジェクト: volkhin/vimrc
 def run(self):
     while not self.stopped:
         try:
             available = vim.bindeval('getchar(1)')
             if available == 0:
                 try:
                     callback = self.thunkQueue.get(False)
                     callback()
                 except Queue.Empty:
                     time.sleep(0.01)
             else:
                     char = vim.bindeval('getchar()')
                     self.charCallback(char)
         except KeyboardInterrupt:
             self.charCallback(key_val('<C-c>'))
コード例 #5
0
	def getSetting(self, setting_name):
		name = '__tab_' + setting_name

		if name in vim.current.tabpage.vars:
			return vim.current.tabpage.vars[name]
		else:
			return vim.bindeval('g:IB_' + setting_name)
コード例 #6
0
ファイル: refactor.py プロジェクト: borman/clighter
def __search_usr_and_rename_refs(tu, usr, new_name):
    if tu is None:
        return

    symbols = []
    clighter_helper.find_cursors_by_usr(tu.cursor, usr, symbols)

    if not symbols:
        return

    # all symbols with the same name
    old_name = clighter_helper.get_spelling_or_displayname(symbols[0])

    locs = set()
    for sym in symbols:
        clighter_helper.search_ref_tokens(tu, sym, locs)

    if len(locs):
        if vim.vars['clighter_rename_prompt_level'] >= 1:
            if vim.bindeval(
                "confirm(\"found symbols in {0}, rename them?\", \"&Yes\n&No\", 1)".format(
                    vim.current.buffer.name)) == 2:
                return

        __vim_multi_replace(
            locs,
            old_name,
            new_name,
            vim.vars['clighter_rename_prompt_level'])
コード例 #7
0
ファイル: refactor.py プロジェクト: borman/clighter
def __search_usr_and_rename_refs(tu, usr, new_name):
    if tu is None:
        return

    symbols = []
    clighter_helper.find_cursors_by_usr(tu.cursor, usr, symbols)

    if not symbols:
        return

    # all symbols with the same name
    old_name = clighter_helper.get_spelling_or_displayname(symbols[0])

    locs = set()
    for sym in symbols:
        clighter_helper.search_ref_tokens(tu, sym, locs)

    if len(locs):
        if vim.vars['clighter_rename_prompt_level'] >= 1:
            if vim.bindeval(
                    "confirm(\"found symbols in {0}, rename them?\", \"&Yes\n&No\", 1)"
                    .format(vim.current.buffer.name)) == 2:
                return

        __vim_multi_replace(locs, old_name, new_name,
                            vim.vars['clighter_rename_prompt_level'])
コード例 #8
0
ファイル: auutils.py プロジェクト: skeept/dotvim
 def vim_extend(val, var='d', utf=True, list=False):
     d_vim = vim.bindeval(var)
     if list:
         d_vim.extend(val)
     else:
         for key in val:
             d_vim[key] = val[key]
コード例 #9
0
ファイル: maktabajson.py プロジェクト: noscripter/vim-maktaba
def parse():
    """
    Python implementation of maktaba#json#Parse().

    Arguments and return values are passed using a Vim list named 'l:buffer',
    as follows:

    l:buffer[0] - the mapping of null/true/false to the (possibly-custom) Vim
                  values.
    l:buffer[1] - the Vim string to parse.
    l:buffer[2] - (out) the Vim value result.
    l:buffer[3] - (out) the error message, if there is an error.
    """
    buffer = vim.bindeval('l:buffer')

    custom_values = buffer[0]
    json_str = buffer[1]
    try:
        value = [json.loads(json_str)]
    except ValueError as e:
        buffer[3] = e.message
        return

    # Now mutate the resulting Python object to something that can be stored
    # in a Vim value (i.e. has no None values, which Vim won't accept).
    _py2vim_list_inplace(
        value,
        custom_values['null'], custom_values['true'], custom_values['false'])

    buffer[2] = value[0]
コード例 #10
0
	def openSideWindow(self, name, keylist):
		buf_num = int(vim.bindeval("bufnr('" + name + "',1)"))
		vim.command("silent topleft 40 vsplit")
		vim.command("set winfixwidth")

		try:
			vim.command("set winwidth=40")
			vim.command("set winminwidth=40")

			vim.command("silent exe 'buffer! ' . " + str(buf_num))
			vim.command("setlocal buftype=nofile bufhidden=wipe nobuflisted noswapfile nowrap")

			vim.current.buffer.vars['__ib_marker__'] = 1
			vim.current.buffer.vars['__ib_side_window__'] = 1
		except vim.error:
			print("Failed to open side window - don't know why?", name)

		self.buffer_list.append(buf_num)

		for item in keylist:
			vim.command(":map <buffer> <silent> " + item.key_value + " :py3 tab_control.keyPressed(" + str(item.action) + ", vim.eval('getcurpos()'))<cr>")

		self.setSideWindowKeys()

		vim.command(":map <buffer> <silent> <LeftRelease> :py3 tab_control.onMouseClickHandler()<cr>")

		return (vim.current.window, buf_num)
コード例 #11
0
 def vim_extend(val, var='d', utf=True, list=False):
     d_vim = vim.bindeval(var)
     if list:
         d_vim.extend(val)
     else:
         for key in val:
             d_vim[key] = val[key]
コード例 #12
0
def parse():
    """
    Python implementation of maktaba#json#Parse().

    Arguments and return values are passed using a Vim list named 'l:buffer',
    as follows:

    l:buffer[0] - the mapping of null/true/false to the (possibly-custom) Vim
                  values.
    l:buffer[1] - the Vim string to parse.
    l:buffer[2] - (out) the Vim value result.
    l:buffer[3] - (out) the error message, if there is an error.
    """
    buffer = vim.bindeval('l:buffer')

    custom_values = buffer[0]
    json_str = buffer[1]
    try:
        value = [json.loads(json_str)]
    except ValueError as e:
        buffer[3] = e.message
        return

    # Now mutate the resulting Python object to something that can be stored
    # in a Vim value (i.e. has no None values, which Vim won't accept).
    _py2vim_list_inplace(
        value,
        custom_values['null'], custom_values['true'], custom_values['false'])

    buffer[2] = value[0]
コード例 #13
0
	def closeWindow(self, window):
		try:
			if vim.bindeval('winnr("$")') == 2:
				# create a spare empty window so the layout does not break
				vim.command("vnew")

			if type(window) == str or type(window) == str:
				wind_name = window.replace('#', '\\#')
				wind_name = wind_name.replace(':', '\\:')
				window = vim.bindeval('bufwinnr("' + wind_name + '")')

			if window != -1:
				vim.command("sign unplace * buffer=" + str(vim.current.window.buffer.number))
				vim.command(str(window) + "wincmd w")
				vim.command("q")
		except vim.error:
			pass
コード例 #14
0
ファイル: __init__.py プロジェクト: 13768324554/powerline
	def vim_get_func(f, rettype=None):
		'''Return a vim function binding.'''
		try:
			func = vim.bindeval('function("' + f + '")')
		except vim.error:
			return None
		else:
			return rettype_func[rettype](func)
コード例 #15
0
	def setPosition(self, window, position):
		if type(window) == type(vim.current.window):
			buf_num = window.number
		else:
			buf_num = vim.bindeval('winbufnr(' + str(window) + ')')

		if buf_num != -1:
			vim.command('call setpos(".", [' + str(buf_num) + ',' + str(position[0]) + ',' + str(position[1]) + ',0])')
コード例 #16
0
ファイル: vimpy_setup.py プロジェクト: domi91c/vimpy
    def get_ignored_modules(self):
        """ Update the ignored modules list. """

        # Get the ignored modules setting as a string.
        ignored_modules = vim.bindeval('g:vimpy_ignored_modules')
        ignored_modules = ignored_modules.split(',')

        # Remove all empty items from resulting list.
        return filter(None, ignored_modules)
コード例 #17
0
ファイル: __init__.py プロジェクト: sbuys/dotfiles
	def vim_get_func(f, rettype=None):
		'''Return a vim function binding.'''
		try:
			func = vim.bindeval('function("' + f + '")')
			if sys.version_info >= (3,) and rettype is str:
				return (lambda *args, **kwargs: func(*args, **kwargs).decode('utf-8', errors='replace'))
			return func
		except vim.error:
			return None
コード例 #18
0
def sort_unite():
    candidates = vim.bindeval('a:candidates')
    is_file = vim.eval('is_file')
    pattern = vim.eval('a:context.input')

    for candidate in candidates:
        word = candidate['word']
        rank = abbrev_matcher.rank(pattern, word, is_file=is_file)
        candidate['filter__rank'] = rank
コード例 #19
0
ファイル: vimpy_setup.py プロジェクト: FelikZ/vimpy
    def get_ignored_modules(self):
        """ Update the ignored modules list. """

        # Get the ignored modules setting as a string.
        ignored_modules = vim.bindeval('g:vimpy_ignored_modules')
        ignored_modules = ignored_modules.split(',')

        # Remove all empty items from resulting list.
        return filter(None, ignored_modules)
コード例 #20
0
ファイル: matcher.py プロジェクト: urandom/ctrlp.vim
    def filter(self, items, pat, limit, mmode, ispath, crfile, regexp):
        if not pat:
            self.logger.debug("No pattern, returning original items")
            self.queue.put(self.initialList(items, limit, ispath, crfile), timeout=1)

            self.process(pat)

            return

        self.logger.debug("Filtering {number} items using {pat}".format(number = len(items), pat=pat))

        self.process(pat)

        if self.lastpat == pat and self.lastmmode == mmode \
                and self.lastispath == ispath and self.lastregexp == regexp:
            if self.process(pat) and self.queue.qsize() == 0 and not self.thread.isAlive():
                self.logger.debug("Thread job is processed for {pat}".format(pat=pat))
                self.lastpat = None
            elif self.thread.isAlive() or self.queue.qsize() > 0:
                self.logger.debug("Waiting for thread job for {pat}".format(pat=pat))
                self.forceCursorHold()
            else:
                self.logger.debug("The same pattern '{pat}'".format(pat=pat))
        elif pat:
            self.logger.debug("Starting thread for {pat}".format(pat=pat))
            self.patterns.append(pat)

            mru = vim.bindeval('ctrlp#mrufiles#list()')
            mru = list(mru)[:50] if isinstance(mru, vim.List) else []

            self.thread = Thread(target=thread_worker, args=(
                self.queue, items, pat, limit,
                mmode, ispath, crfile, regexp, mru,
                vim.bindeval('&ic'), vim.bindeval('&scs'), self.logger
            ))
            self.thread.daemon = True
            self.thread.start()

            self.lastpat = pat
            self.lastmmode = mmode
            self.lastispath = ispath
            self.lastregexp = regexp

            self.forceCursorHold()
コード例 #21
0
	def openFileWithContent(self, name, contents, force_new=False, readonly=True, replace=False):
		# escape name - some chars cause problems
		name = name.replace('#', '\\#')

		buf_number = vim.bindeval("bufnr('" + name + "')")
		if int(buf_number) != -1:
			# the buffer exists? Is it in a window?
			wind_num = vim.bindeval("bufwinnr('" + str(buf_number) + "')")
			if wind_num != -1 and not replace:
				# If the buffer is in a window - lets exit.
				return
			else:
				self.setBufferContents(int(buf_number), contents, readonly=readonly)
		else:
			# we need to create the buffer.
			buf_number = vim.eval("bufnr('" + name + "', 1)")
			self.setBufferContents(int(buf_number), contents, readonly=readonly)

		# Ok, we have a buffer we need to put it in a window.
		if force_new:
			# easy, force new - always create a new window.
			vim.command("silent rightbelow vsplit " + name)
			wind_num = vim.bindeval("winnr()")
		else:
			wind_num = self.findNotOurWindow()

			if wind_num == -1:
				# did not find a good window --- create a new one
				vim.command("silent rightbelow vsplit " + name)
				wind_num = vim.bindeval("winnr()")

		# Ok, put the buffer in a window
		vim.command(str(wind_num) + " wincmd w")
		vim.command("silent buffer " + str(buf_number))

		buf = vim.buffers[int(buf_number)]
		if readonly:
			buf.options['buflisted'] = False
			buf.options['modifiable'] = False

		#vim.windows[wind_num].options['wrap'] = False

		return vim.current.window
コード例 #22
0
ファイル: plasmaplace.py プロジェクト: raymond-w-ko/dot
def Cljfmt(code):
    repl = create_or_get_repl()
    job = CljfmtJob(repl, code)
    job.start()
    formatted_code = job.wait()
    if not formatted_code:
        pass
    else:
        vl = vim.bindeval("s:formatted_code")
        vl.extend(formatted_code.split("\n"))
コード例 #23
0
ファイル: command.py プロジェクト: ehamberg/vim-pantondoc
    def execute(self, should_open):
        with open("pandoc.out", 'w') as tmp:
            if vim.bindeval("has('clientserver')"):
                async_runner = os.path.join(os.path.dirname(__file__), "async.py")
                servername_arg = "--servername=" + vim.bindeval("v:servername")
                open_arg  = "--open" if should_open else "--noopen"
                async_command = " ".join([async_runner, servername_arg, open_arg, self._run_command])
                try:
                    pid = Popen(shlex.split(async_command), stdout=tmp, stderr=tmp)
                except:
                    vim.command('echoe "pantondoc: could not execute pandoc asynchronously"')
            else:
                try:
                    com = Popen(shlex.split(self._run_command), stdout=tmp, stderr=tmp)
                    com.wait()
                except:
                    vim.command('echoe "pantondoc: could not execute pandoc"')
                    return

                self.on_done(should_open, com.returncode)
コード例 #24
0
	def openBottomWindow(self, name, contents=None):
		buf_num = int(vim.bindeval("bufnr('" + name + "',1)"))
		vim.command("bot new")
		vim.command("silent buffer " + str(buf_num))
		vim.command("setlocal bufhidden=wipe nobuflisted noswapfile nowrap")

		if contents is not None:
			vim.buffers[buf_num-1][:] = contents

		vim.current.buffer.vars['__ib_marker__'] = 1
		return vim.current.window
コード例 #25
0
    def initialize(self, path):
        if path == self.path:
            return
        else:
            self.flush()  # flush previous
            self.dirty = False
            vim.command("let " + self.vim_cfg_name + " = {}")
            self.vim_cfg = vim.bindeval(self.vim_cfg_name)
            self.path = path
            if os.path.isfile(path):
                with open(path) as f:
                    try:
                        cfg = json.load(f)
                        self.vim_cfg.update(cfg)
                    except BaseException:
                        vim.command("let " + self.vim_cfg_name + " = {}")
                        # re-bindeval due to new dictionary created
                        self.vim_cfg = vim.bindeval(self.vim_cfg_name)

            self.fill_with_boilerplate()
コード例 #26
0
	def findSyntaxRegionEnd(self, start_line, column, hightlight):
		next_line = start_line
		last_line = vim.bindeval('line("$")') - 1

		while next_line < last_line:
			if self.findSyntaxGroup(next_line, column, hightlight):
				next_line += 1
			else:
				next_line -= 1
				break

		return next_line
コード例 #27
0
ファイル: hubr_vim.py プロジェクト: dhleong/hubr
def _vimify(obj):
    """Convert a dict, list, etc. into a vim-consumable format"""
    if isinstance(obj, dict):
        d = vim.bindeval("{}")
        for key, val in obj.iteritems():
            key = str(key)
            try: 
                d[key] = _vimify(val)
            except TypeError, e:
                print "Failed to convert ", val
                raise e
        return d
コード例 #28
0
def filter_unite():
    pattern = vim.eval('input')
    candidates = vim.bindeval('a:candidates')
    regex = abbrev_matcher.make_regex(pattern)

    def candidate_word(candidate):
        return (candidate['word']
                if isinstance(candidate, vim.Dictionary) else candidate)

    candidate_words = map(candidate_word, candidates)

    line_nums = filter_grep_exc_handling(regex, candidate_words)
    filter_by_indices(candidates, line_nums)
コード例 #29
0
def rename(clang_service):
    clang_service.update_buffers(__get_bufctx_list(), False)
    clang_service.parse_all(
        string.atoi(vim.eval('g:clighter_heuristic_compile_args')),
        vim.bindeval('g:clighter_compile_args'))

    cc = clang_service.get_cc(vim.current.buffer.name)
    if not cc:
        return

    tu = cc.current_tu
    if not tu:
        return

    symbol = clighter_helper.get_vim_symbol(
        clighter_helper.get_vim_cursor(tu, tu.get_file(cc.name)))

    if not symbol:
        return

    old_name = clighter_helper.get_spelling_or_displayname(symbol)
    vim.command("echohl WildMenu")
    new_name = vim.eval("input(' Rename {0} : ', '{1}')".format(
        old_name, old_name))
    vim.command("echohl None")

    if not new_name or old_name == new_name:
        return

    print ' '

    pos = vim.current.window.cursor

    locs = set()
    locs.add((symbol.location.line, symbol.location.column,
              symbol.location.file.name))
    clighter_helper.search_referenced_tokens(tu, symbol, locs)

    prompt = string.atoi(vim.eval('g:clighter_rename_prompt_level'))

    __vim_multi_replace(locs, old_name, new_name, prompt)

    if clighter_helper.is_global_symbol(symbol) and vim.eval(
            'g:clighter_enable_cross_rename') == '1':
        __cross_buffer_rename(clang_service, symbol.get_usr(), new_name,
                              prompt)

    vim.current.window.cursor = pos

    clang_service.update_buffers(__get_bufctx_list(), True)
コード例 #30
0
	def getUsefullWindow(self):
		wind_num = vim.bindeval("winnr('#')") - 1

		if "__ib_marker__" in vim.current.tabpage.windows[wind_num].buffer.vars:
			# ok, we are not going to use this - it is special, so search for another.
			if len(vim.current.tabpage.windows) == 2:
				if wind_num == 0:
					wind_num = 1
				else:
					wind_num = 0
			else:
				wind_num = -1
				for index, window in enumerate(vim.current.tabpage.windows):
					if "__ib_marker__" not in window.buffer.vars:
						# we have a winner!
						wind_num = index
						break
				else:
					# Ok, did not find one - so give up and create a new window.
					vim.command("silent rightbelow vsplit")
					wind_num = vim.bindeval("winnr()") - 1

		return wind_num + 1
コード例 #31
0
ファイル: utils.py プロジェクト: chetgurevitch/vimspector
def SetUpCommandBuffer( cmd, name ):
  bufs = vim.bindeval(
    'vimspector#internal#job#StartCommandWithLog( {}, "{}" )'.format(
      json.dumps( cmd ),
      name ) )

  if bufs is None:
    raise RuntimeError( "Unable to start job {}: {}".format( cmd, name ) )
  elif not all( b > 0 for b in bufs ):
    raise RuntimeError( "Unable to get all streams for job {}: {}".format(
      name,
      cmd ) )

  return [ vim.buffers[ b ] for b in bufs ]
コード例 #32
0
ファイル: hubr_vim.py プロジェクト: dhleong/hubr
def hubr_to_vim(bindName, result):
    """Called from vim to copy the method result
       back into vim-space
    """
    if type(result) == HubrResult:
        result = {
            'status': result.get_status(),
            'next': result.next(),
            'json': result.json()
        }

    d = vim.bindeval(bindName)
    vimified = _vimify(result)
    d['result'] = vimified
コード例 #33
0
ファイル: fbvimutils.py プロジェクト: volkhin/vimrc
def vimfunc(funcname, *args):
    countermap = localstate.cache('vimfunc_countermap', lambda: {})
    counter = countermap.setdefault('count', 0)
    countermap['count'] = counter + 1

    vim_arg_list_name = 'g:__vimfunc__arg_map_' + str(counter)
    vc('let %s = []' % (vim_arg_list_name))
    arg_list = vim.bindeval(vim_arg_list_name)
    arg_list.extend(args)

    arg_expr = ', '.join(['%s[%s]' %(vim_arg_list_name, i) for i in range(len(args))])
    expr = '%s(%s)' % (funcname, arg_expr)

    vim.eval(expr)

    vc('unlet %s' % (vim_arg_list_name))
コード例 #34
0
ファイル: refactor.py プロジェクト: borman/clighter
def rename(clang_service):
    tu_ctx = clang_service.get_tu_ctx(vim.current.buffer.name)
    if tu_ctx is None:
        return

    clang_service.update_unsaved_dict(__get_buffer_dict(), False)
    clang_service.parse_all()

    vim_cursor, def_cursor = clighter_helper.get_vim_cursor_and_def(tu_ctx)

    if vim_cursor is None or def_cursor is None:
        return

    old_name = clighter_helper.get_spelling_or_displayname(def_cursor)
    vim.command("echohl WildMenu")
    new_name = vim.bindeval(
        "input(' Rename {0} : ', '{1}')".format(old_name, old_name))
    vim.command("echohl None")

    if not new_name or old_name == new_name:
        return

    print ' '

    pos = vim.current.window.cursor

    locs = set()
    locs.add((def_cursor.location.line, def_cursor.location.column,
              def_cursor.location.file.name))
    clighter_helper.search_ref_tokens(
        tu_ctx.translation_unit,
        def_cursor,
        locs)
    __vim_multi_replace(
        locs,
        old_name,
        new_name,
        vim.vars['clighter_rename_prompt_level'])

    if clighter_helper.is_symbol_cursor(
            def_cursor) and vim.vars['clighter_enable_cross_rename'] == 1:
        __cross_buffer_rename(clang_service, def_cursor.get_usr(), new_name)

    vim.current.window.cursor = pos

    clang_service.update_unsaved_dict(__get_buffer_dict(), True)
コード例 #35
0
ファイル: fbvimtypeahead.py プロジェクト: volkhin/vimrc
    def setupWindow(self):
        # save current window
        self.current_winnr = vim.bindeval('winnr()')

        # setup our typeahead buffer
        vc('botright 1new "File Search"',
            'setlocal buftype=nofile',
            'nohlsearch',
            'setlocal noswapfile winfixheight',
            'setlocal nocursorcolumn',
            'setlocal nocursorline',
            'setlocal nonumber',
            'setlocal nowrap',
            'setlocal bufhidden=wipe',
            'resize %s' % (self.win_size),
            'normal "10oggzt"'
        )
コード例 #36
0
ファイル: __init__.py プロジェクト: 21gunnns/powerline
def trailing_whitespace(pl, segment_info):
	'''Return the line number for trailing whitespaces

	It is advised not to use this segment in insert mode: in Insert mode it will 
	iterate over all lines in buffer each time you happen to type a character 
	which may cause lags. It will also show you whitespace warning each time you 
	happen to type space.

	Highlight groups used: ``trailing_whitespace`` or ``warning``.
	'''
	global trailing_whitespace_cache
	if trailing_whitespace_cache is None:
		trailing_whitespace_cache = register_buffer_cache(defaultdict(lambda: (0, None)))
	bufnr = segment_info['bufnr']
	changedtick = getbufvar(bufnr, 'changedtick')
	if trailing_whitespace_cache[bufnr][0] == changedtick:
		return trailing_whitespace_cache[bufnr][1]
	else:
		buf = segment_info['buffer']
		bws = b' \t'
		sws = str(bws)
		for i in range(len(buf)):
			try:
				line = buf[i]
			except UnicodeDecodeError:  # May happen in Python 3
				if hasattr(vim, 'bindeval'):
					line = vim.bindeval('getbufline({0}, {1})'.format(
						bufnr, i + 1))
					has_trailing_ws = (line[-1] in bws)
				else:
					line = vim.eval('strtrans(getbufline({0}, {1}))'.format(
						bufnr, i + 1))
					has_trailing_ws = (line[-1] in bws)
			else:
				has_trailing_ws = (line and line[-1] in sws)
			if has_trailing_ws:
				break
		if has_trailing_ws:
			ret = [{
				'contents': str(i + 1),
				'highlight_groups': ['trailing_whitespace', 'warning'],
			}]
		else:
			ret = None
		trailing_whitespace_cache[bufnr] = (changedtick, ret)
		return ret
コード例 #37
0
ファイル: atcoder.py プロジェクト: ringo9971/vim-atcoder
def getText(url):
    session = requests.session()

    res = session.get(ATCODER_LOGIN)
    page = BeautifulSoup(res.text, 'lxml')
    csrf_token = page.find(attrs={'name': 'csrf_token'}).get('value')
    login_info = {
        "csrf_token": csrf_token,
        "username": vim.eval('g:atcoder_name'),
        "password": vim.eval('g:atcoder_pass'),
    }
    session.post(ATCODER_LOGIN, data=login_info)

    page = session.get(url)

    page = BeautifulSoup(page.text, 'lxml').find_all(class_="part")
    s = vim.bindeval('s:')
    s['text'] = str(page)
コード例 #38
0
    def _StartDebugAdapter(self):
        self._logger.info('Starting debug adapter with: {0}'.format(
            json.dumps(self._adapter)))

        channel_send_func = vim.bindeval(
            "vimspector#internal#job#StartDebugSession( {0} )".format(
                json.dumps(self._adapter)))

        self._connection = debug_adapter_connection.DebugAdapterConnection(
            self, channel_send_func)

        self._logger.info('Debug Adapter Started')

        vim.command('augroup vimspector_cleanup')
        vim.command('autocmd!')
        vim.command(
            'autocmd VimLeavePre * py3 _vimspector_session.CloseDown()')
        vim.command('augroup END')
コード例 #39
0
  def _StartDebugAdapter( self ):
    if self._connection:
      utils.UserMessage( 'The connection is already created. Please try again',
                         persist = True )
      return

    self._logger.info( 'Starting debug adapter with: %s',
                       json.dumps( self._adapter ) )

    self._init_complete = False
    self._on_init_complete_handlers = []
    self._launch_complete = False
    self._run_on_server_exit = None

    self._connection_type = 'job'
    if 'port' in self._adapter:
      self._connection_type = 'channel'

      if self._adapter[ 'port' ] == 'ask':
        port = utils.AskForInput( 'Enter port to connect to: ' )
        self._adapter[ 'port' ] = port

    # TODO: Do we actually need to copy and update or does Vim do that?
    env = os.environ.copy()
    if 'env' in self._adapter:
      env.update( self._adapter[ 'env' ] )
    self._adapter[ 'env' ] = env

    if 'cwd' not in self._adapter:
      self._adapter[ 'cwd' ] = os.getcwd()

    channel_send_func = vim.bindeval(
      "vimspector#internal#{}#StartDebugSession( {} )".format(
        self._connection_type,
        json.dumps( self._adapter ) ) )

    if channel_send_func is None:
      self._logger.error( "Unable to start debug server" )
    else:
      self._connection = debug_adapter_connection.DebugAdapterConnection(
        self,
        channel_send_func )

      self._logger.info( 'Debug Adapter Started' )
コード例 #40
0
ファイル: matcher.py プロジェクト: urandom/ctrlp.vim
    def process(self, pat):
        queue = []
        while True:
            try:
                queue.append(self.queue.get(False))
                self.queue.task_done()
            except Empty:
                break

        if not queue:
            self.logger.debug("Empty queue")
            return False

        data = None

        for d in queue:
            if d["pat"]:
                try:
                    index = self.patterns.index(d["pat"])
                    self.patterns = self.patterns[index+1:]
                    data = d
                except ValueError:
                    continue
            else:
                data = d
                self.lastpat = None
                self.patterns = []
                break

        if not data:
            self.logger.debug("No valid data entry")
            return False

        callback = vim.bindeval('function("ctrlp#process")')
        lines = vim.List(data["items"])
        subitems = vim.List(data["subitems"])

        callback(lines, pat, 1, subitems)

        if data["pat"] == pat:
            self.queue = Queue()

        return True
コード例 #41
0
ファイル: run.py プロジェクト: yannicklm/vimpytest
def run_pytest():
    """ Main entry point

    If current file is a test file, run it and store its name,
    Otherwise, run the latest stored test.

    """
    cur_filename = vim.current.buffer.name
    if not cur_filename:
        return
    basename = os.path.basename(cur_filename)
    if basename.startswith("test"):
        to_run = cur_filename
    else:
        to_run = vim.bindeval("t:pytest_latest_test")
        if not to_run:
            return
    vim.command("!py.test %s" % to_run)
    vim.command('let t:pytest_latest_test="%s"' % to_run)
コード例 #42
0
ファイル: jupiter_wrapper.py プロジェクト: francisjsun/moon
def get_boilerplate():
    current_file = vim.eval('g:moon_current_file_path')
    current_file = current_file.replace(moon.moon_project_dir, '')
    prefix = get_prefix()

    bd = boilerplate.get(
        moon.moon_project_dir, current_file, get_author(),
        moon.moon_project_cfg.get_value('macro_ignored_dir'), prefix)
    vim_bd = vim.bindeval('g:moon_boilerplate')
    if 'copyright_declaration' in bd:
        vim_bd.extend([get_vim_let_string(bd['copyright_declaration']),
                       ""])
    if 'include_guard' in bd:
        include_guard_lines = bd['include_guard']
        vim_bd.extend([include_guard_lines[0],
                       include_guard_lines[1],
                       "", "",
                       include_guard_lines[2]])
    if 'cpp_include_header' in bd:
        vim_bd.extend([bd['cpp_include_header']])
コード例 #43
0
ファイル: refactor.py プロジェクト: borman/clighter
def rename(clang_service):
    tu_ctx = clang_service.get_tu_ctx(vim.current.buffer.name)
    if tu_ctx is None:
        return

    clang_service.update_unsaved_dict(__get_buffer_dict(), False)
    clang_service.parse_all()

    vim_cursor, def_cursor = clighter_helper.get_vim_cursor_and_def(tu_ctx)

    if vim_cursor is None or def_cursor is None:
        return

    old_name = clighter_helper.get_spelling_or_displayname(def_cursor)
    vim.command("echohl WildMenu")
    new_name = vim.bindeval("input(' Rename {0} : ', '{1}')".format(
        old_name, old_name))
    vim.command("echohl None")

    if not new_name or old_name == new_name:
        return

    print ' '

    pos = vim.current.window.cursor

    locs = set()
    locs.add((def_cursor.location.line, def_cursor.location.column,
              def_cursor.location.file.name))
    clighter_helper.search_ref_tokens(tu_ctx.translation_unit, def_cursor,
                                      locs)
    __vim_multi_replace(locs, old_name, new_name,
                        vim.vars['clighter_rename_prompt_level'])

    if clighter_helper.is_symbol_cursor(
            def_cursor) and vim.vars['clighter_enable_cross_rename'] == 1:
        __cross_buffer_rename(clang_service, def_cursor.get_usr(), new_name)

    vim.current.window.cursor = pos

    clang_service.update_unsaved_dict(__get_buffer_dict(), True)
コード例 #44
0
ファイル: matcher.py プロジェクト: urandom/ctrlp.vim
    def initialList(self, items, limit, ispath, crfile):
        mru = None
        if ispath:
            mru = vim.bindeval('ctrlp#mrufiles#list()')

        if isinstance(mru, vim.List) and mru:
            mrudict = {}
            mrucount = len(mru)
            index = 0
            for f in mru:
                mrudict[f] = index
                index += 1

            recentCount = 0
            restCount = 0

            recent = []
            rest = []
            for item in items:
                if item == crfile:
                    continue

                if mrudict.get(item, -1) != -1:
                    recent.append(item)
                    recentCount += 1
                    mrucount -= 1

                elif restCount + recentCount < limit:
                    rest.append(item)
                    restCount += 1

                if recentCount == limit or not mrucount and restCount + recentCount >= limit:
                    break

            recent = sorted(recent, cmp=lambda a, b: mrudict.get(a, -1) - mrudict.get(b, -1))
            return {"items": recent + rest[:limit - restCount], "subitems": items[recentCount-1:], "pat": ""}

        else:
            return {"items": items[:limit], "subitems": items[limit-1:], "pat": ""}
コード例 #45
0
ファイル: maktabajson.py プロジェクト: noscripter/vim-maktaba
def format():
    """
    Python implementation of maktaba#json#Format().

    Arguments and return values are passed using a Vim list named 'l:buffer',
    as follows:

    l:buffer[0] - the mapping of null/true/false to the default Vim sentinels.
    l:buffer[1] - the Vim value to format.
    l:buffer[2] - (out) the string result.
    l:buffer[3] - (out) the error message, if there is an error.
    """

    buffer = vim.bindeval('l:buffer')
    custom_values = buffer[0]
    value = buffer[1]
    # Now translate the Vim value to something that uses Python types (e.g.
    # None, True, False), based on the custom values we're using.  Note that
    # this must return a copy of the input, as we cannot store None (or True
    # or False) in a Vim value.  (Doing this also avoids needing to tell
    # json.dumps() how to serialize a vim.List or vim.Dictionary.)

    # Note that to do this we need to check our custom values for equality,
    # which we also can't do if they're a vim.List or vim.Dictionary.
    # Fortunately, there's an easy way to fix that.
    custom_values = _vim2py_deepcopy(custom_values, None, None, None)

    # Now we can use those custom values to translate the real value.
    value = _vim2py_deepcopy(
        value,
        custom_values['null'], custom_values['true'], custom_values['false'])

    try:
        buffer[2] = json.dumps(value, allow_nan=False)
    except ValueError as e:  # e.g. attempting to format NaN
        buffer[3] = e.message
    except TypeError as e:  # e.g. attempting to format a Function
        buffer[3] = e.message
コード例 #46
0
ファイル: api.py プロジェクト: sagargp/shdw
 def wrapper():
     return func(vim.bindeval('a:'))
コード例 #47
0
ファイル: __init__.py プロジェクト: Tukeke/powerline
			r = vim.eval(self.f + '(' + json.dumps(args)[1:-1] + ')')
			if self.rettype:
				return self.rettype(r)
			return r

	vim_get_func = VimFunc


_getbufvar = vim_get_func('getbufvar')


# It may crash on some old vim versions and I do not remember in which patch 
# I fixed this crash.
if hasattr(vim, 'vvars') and vim.vvars['version'] > 703:
	_vim_to_python_types = {
		getattr(vim, 'Dictionary', None) or type(vim.bindeval('{}')):
			lambda value: dict(((key, _vim_to_python(value[key])) for key in value.keys())),
		getattr(vim, 'List', None) or type(vim.bindeval('[]')):
			lambda value: [_vim_to_python(item) for item in value],
		getattr(vim, 'Function', None) or type(vim.bindeval('function("mode")')):
			lambda _: None,
	}

	def vim_getvar(varname):
		return _vim_to_python(vim.vars[str(varname)])

	def bufvar_exists(buffer, varname):
		buffer = buffer or vim.current.buffer
		return varname in buffer.vars

	def vim_getwinvar(segment_info, varname):
コード例 #48
0
ファイル: highlight.py プロジェクト: borman/clighter
def highlight_window(clang_service, extend=50):
    tu_ctx = clang_service.get_tu_ctx(vim.current.buffer.name)
    if tu_ctx is None:
        clear_highlight()
        return

    tu = tu_ctx.translation_unit
    if tu is None:
        clear_highlight()
        return

    (top, bottom) = (vim.bindeval("line('w0')"), vim.bindeval("line('w$')"))

    draw_syntax = False
    draw_def_ref = False

    if highlight_window.hl_tick < clang_service.parse_tick or highlight_window.syntactic_range is None or top < highlight_window.syntactic_range[
            0] or bottom > highlight_window.syntactic_range[1]:
        draw_syntax = True
        vim.command("call s:clear_match_pri([{0}])".format(SYNTAX_PRI))
        highlight_window.hl_tick = clang_service.parse_tick

    if vim.vars["ClighterCursorHL"] == 1:
        vim_cursor, def_cursor = clighter_helper.get_vim_cursor_and_def(tu_ctx)

        if highlight_window.highlighted_define_cur is not None and(
                def_cursor is None or highlight_window.highlighted_define_cur !=
                def_cursor):
            vim.command("call s:clear_match_pri([{0}])".format(DEF_REF_PRI))

        if def_cursor is not None and(
                highlight_window.
                highlighted_define_cur
                is None or highlight_window.highlighted_define_cur != def_cursor):
            draw_def_ref = True

            # special case for preprocessor
            if def_cursor.kind.is_preprocessing(
            ) and def_cursor.location.file.name == vim.current.buffer.name:
                __vim_matchaddpos(
                    'clighterCursorDefRef', def_cursor.location.line, def_cursor.location.column, len(
                        clighter_helper.get_spelling_or_displayname(def_cursor)), DEF_REF_PRI)

        highlight_window.highlighted_define_cur = def_cursor

    if not draw_syntax and not draw_def_ref:
        return

    target_range = [top, bottom]

    if draw_syntax:
        buflinenr = len(vim.current.buffer)
        target_range = [max(top - extend, 1), min(bottom + extend, buflinenr)]
        highlight_window.syntactic_range = target_range

    file = tu.get_file(tu_ctx.bufname)
    tokens = tu.get_tokens(
        extent=cindex.SourceRange.from_locations(
            cindex.SourceLocation.from_position(
                tu, file, target_range[0], 1), cindex.SourceLocation.from_position(
                tu, file, target_range[1] + 1, 1)))

    for t in tokens:
        """ Do semantic highlighting'
        """
        if t.kind.value != 2:
            continue

        t_cursor = cindex.Cursor.from_location(
            tu,
            cindex.SourceLocation.from_position(
                tu,
                file,
                t.location.line,
                t.location.column))  # cursor under vim

        if draw_syntax:
            __draw_token(t.location.line, t.location.column, len(
                t.spelling), t_cursor.kind, t_cursor.type.kind)

        """ Do definition/reference highlighting'
        """
        if draw_def_ref:
            t_def_cursor = clighter_helper.get_semantic_definition(t_cursor)
            if t_def_cursor is not None and t_def_cursor == highlight_window.highlighted_define_cur:
                __vim_matchaddpos(
                    'clighterCursorDefRef', t.location.line, t.location.column, len(
                        t.spelling), DEF_REF_PRI)
コード例 #49
0
ファイル: powerline.py プロジェクト: andreiglingeanu/dotvim
    def status(fname):
        return funcs.status(path, fname)
    def branch():
        return funcs.branch(path)
    return Funcs(status=status, branch=branch)

funcs_cache = {}
fname_cache = {}

def plugin_eval(expr):
    global plugin_eval
    plugin_eval = vim_get_func('<SNR>'+sid+'_Eval')
    return plugin_eval(expr)

if hasattr(vim, 'bindeval'):
    self_dict = vim.bindeval('{}')

    def get_repo(path):
        global get_repo
        vim_get_repo = plugin_eval('s:_r.repo.get')
        get_repo = lambda path: vim_get_repo(path, self=self_dict)
        return get_repo(path)

    def get_interval(key):
        global get_interval
        vim_get_interval = plugin_eval('s:_r.cache.getinterval')
        get_interval = lambda key: vim_get_interval(key, self=self_dict)
        return get_interval(key)

    rf_dict = vim.bindeval('{"repo": ":"}')
コード例 #50
0
ファイル: matcher.py プロジェクト: urandom/ctrlp.vim
 def forceCursorHold(self):
     vim.bindeval('function("ctrlp#forcecursorhold")')()
コード例 #51
0
ファイル: __init__.py プロジェクト: jimrhoskins/dotconfig
	def vim_get_func(f, rettype=None):
		'''Return a vim function binding.'''
		try:
			return vim.bindeval('function("' + f + '")')
		except vim.error:
			return None
コード例 #52
0
ファイル: __init__.py プロジェクト: jimrhoskins/dotconfig

def source_plugin():
	import sys
	import os
	if sys.version_info[:2] == (3, 3):
		vim.command('let g:powerline_pycmd = "python3"')
		vim.command('let g:powerline_pyeval = "py3eval"')
	else:
		vim.command('let g:powerline_pycmd = "python"')
		vim.command('let g:powerline_pyeval = "pyeval"')
	fnameescape = vim_get_func('fnameescape')
	vim.command('source ' + fnameescape(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'powerline.vim')).decode('utf-8'))

try:
	_vim_globals = vim.bindeval('g:')

	def vim_set_global_var(var, val):
		'''Set a global var in vim using bindeval().'''
		_vim_globals[var] = val

	def vim_get_func(f, rettype=None):
		'''Return a vim function binding.'''
		try:
			return vim.bindeval('function("' + f + '")')
		except vim.error:
			return None
except AttributeError:
	import json

	def vim_set_global_var(var, val):  # NOQA