Python vim.eval() Examples

The following are 30 code examples of vim.eval(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module vim , or try the search function .
Example #1
Source File: repeater.py    From pappy-proxy with MIT License 6 votes vote down vote up
def update_buffers(req):
    b1_id = int(vim.eval("s:b1"))
    b1 = vim.buffers[b1_id]

    b2_id = int(vim.eval("s:b2"))
    b2 = vim.buffers[b2_id]

    # Set up the buffers
    set_buffer_content(b1, req.full_message())

    if req.response is not None:
        set_buffer_content(b2, req.response.full_message())

    # Save the port, ssl, host setting
    vim.command("let s:dest_port=%d" % req.dest_port)
    vim.command("let s:dest_host='%s'" % escape(req.dest_host))

    if req.use_tls:
        vim.command("let s:use_tls=1")
    else:
        vim.command("let s:use_tls=0") 
Example #2
Source File: repeater.py    From pappy-proxy with MIT License 6 votes vote down vote up
def set_up_windows():
    reqid = vim.eval("a:2")
    storage_id = vim.eval("a:3")
    msg_addr = vim.eval("a:4")

    vim.command("let s:storage_id=%d" % int(storage_id))
    
    # Get the left buffer
    vim.command("new")
    vim.command("only")
    b2 = vim.current.buffer
    vim.command("let s:b2=bufnr('$')")

    # Vsplit new file
    vim.command("vnew")
    b1 = vim.current.buffer
    vim.command("let s:b1=bufnr('$')")

    print msg_addr
    comm_type, comm_addr = msg_addr.split(":", 1)
    set_conn(comm_type, comm_addr)
    with ProxyConnection(kind=comm_type, addr=comm_addr) as conn:
        # Get the request
        req = conn.req_by_id(reqid, int(storage_id))
        update_buffers(req) 
Example #3
Source File: tq_common_lib.py    From thesaurus_query.vim with Apache License 2.0 6 votes vote down vote up
def get_variable(v_name, default=None):
    ''' get variable from Vim
    return:
        vim_variable  # buffer variable tried first, global variable second
        default       # if no variable exists, or module used independently
                      # from Vim session.
    '''
    if independent_session:
        return default
    if vim.eval("exists('b:'.'{0}')".format(v_name))=='0':
        if vim.eval("exists('g:'.'{0}')".format(v_name))=='0':
            if vim.eval("exists('{0}')".format(v_name))=='0':
                return default
            else:
                return vim.eval(v_name)
        else:
            return vim.eval('g:'+v_name)
    else:
        return vim.eval('b:'+v_name) 
Example #4
Source File: do.py    From vim-do with MIT License 6 votes vote down vote up
def check_now(self):
        log("Checking background threads output")
        outputs = self.__process_pool.get_outputs()
        changed_processes = set()
        for output in outputs:
            if output[1] is not None:
                log("Process %s has finished with exit status %s"
                    %(output[0], output[1]))
            process = self.__processes.update(*output)
            changed_processes.add(process)

        for process in changed_processes:
            self.__process_renderer.update_process(process)

        self.__process_pool.cleanup()
        if self.__processes.all_finished():
            log("All background threads completed")
            self.__unassign_autocommands()
        else:
            s = 'feedkeys("\\%s")' % Options.refresh_key()
            log(s)
            vim.eval(s) 
Example #5
Source File: roast.py    From roast.vim with MIT License 6 votes vote down vote up
def highlight_line(group, buf_number, line_number):
    match_id = int(vim.buffers[buf_number].vars.get('_roast_match_id', 0))

    if match_id:
        win = None
        for win in vim.windows:
            if win.buffer.number == buf_number:
                break

        try:
            vim.eval(f'matchdelete({match_id})' if win is None else f'matchdelete({match_id}, {win.number})')
        except vim.error:
            # TODO: Only hide E803 error, which is thrown if this match_id has already been deleted.
            pass

    vim.buffers[buf_number].vars['_roast_match_id'] = vim.eval(
        fr"matchadd('{group}', '\V' . escape(getbufline({buf_number}, {line_number + 1})[0], '\') . '\$')"
    ) 
Example #6
Source File: vimplayer.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def remove_player(session=None):
    global players, controllers, current
    if session is None:
        session = int(vim.eval("v:count"))
    print "removing session %d..." % (session,),
    apc = controllers.get(session, None)
    if apc is not None:
        try:
            apc.quit()
        except:
            pass
        del controllers[session]
    timelib.sleep(2)
    p = players.get(session, None)
    if p:
        rv = p.wait()
        del players[session]
    if controllers:
        current = controllers.values()[0]
    else:
        current = None
    print rv 
Example #7
Source File: util.py    From vim-gdscript3 with MIT License 6 votes vote down vote up
def get_project_dir():
    global _project_dir
    if not _project_dir:
        cwd = os.getcwd()
        os.chdir(vim.eval("expand('%:p:h')")) # Directory of current file.
        try:
            while not os.path.isfile("project.godot"):
                os.chdir("..")
                if os.getcwd() == "/":
                    return
            _project_dir = os.getcwd()
        except:
            pass
        finally:
            os.chdir(cwd)
    return _project_dir 
Example #8
Source File: ipython_cell.py    From vim-ipython-cell with GNU General Public License v3.0 6 votes vote down vote up
def _get_cell_boundaries():
    """Return a list of rows (1-indexed) for all cell boundaries."""
    buffer = vim.current.buffer
    delimiter = vim.eval('g:ipython_cell_delimit_cells_by').strip()

    if delimiter == 'marks':
        valid_marks = vim.eval('g:ipython_cell_valid_marks').strip()
        cell_boundaries = _get_rows_with_marks(buffer, valid_marks)
    elif delimiter == 'tags':
        tag = vim.eval('g:ipython_cell_tag')
        cell_boundaries = _get_rows_with_tag(buffer, tag)
    else:
        _error("Invalid option value for g:ipython_cell_valid_marks: {}"
               .format(delimiter))
        return

    # Include beginning of file as a cell boundary
    cell_boundaries.append(1)

    return sorted(set(cell_boundaries)) 
Example #9
Source File: cpsm.py    From cpsm with Apache License 2.0 6 votes vote down vote up
def ctrlp_match():
    """
    Deprecated interface that gets arguments by calling vim.eval() and returns
    outputs by calling vim.command(). Kept for Denite. Use ctrlp_match_with()
    or cpsm_py.ctrlp_match() in new code.
    """
    # TODO: a:regex is unimplemented.
    results, regexes = ctrlp_match_with(
            items=_vim_eval("a:items"), query=_vim_eval("a:str"),
            limit=int(_vim_eval("a:limit")), mmode=_vim_eval("a:mmode"),
            ispath=int(_vim_eval("a:ispath")), crfile=_vim_eval("a:crfile"),
            highlight_mode=_vim_eval("g:cpsm_highlight_mode"),
            match_crfile=int(_vim_eval("s:match_crfile")),
            max_threads=int(_vim_eval("g:cpsm_max_threads")),
            query_inverting_delimiter=_vim_eval("g:cpsm_query_inverting_delimiter"),
            regex_line_prefix=_vim_eval("s:regex_line_prefix"),
            unicode=int(_vim_eval("g:cpsm_unicode")))
    vim.command("let s:results = [%s]" % ",".join(
            map(_escape_and_quote, results)))
    vim.command("let s:regexes = [%s]" % ",".join(
            map(_escape_and_quote, regexes))) 
Example #10
Source File: tq_common_lib.py    From thesaurus_query.vim with Apache License 2.0 5 votes vote down vote up
def vim_eval(command):
    """ wrapper for Vim eval, return None if session is Vim independent """
    if independent_session:
        return None
    return vim.eval(command) 
Example #11
Source File: vim_ipython.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def vim_variable(name, default=None):
    exists = int(vim.eval("exists('%s')" % name))
    return vim.eval(name) if exists else default 
Example #12
Source File: thesaurus_query.py    From thesaurus_query.vim with Apache License 2.0 5 votes vote down vote up
def tq_word_form_reverse(target_word):
    ''' adjust candidate to match trimmed word's case(upper/lower/mixed) '''
    if independent_session:     # this module don't work in Vim independent session
        return None
    wordOriginal = decode_utf_8(vim.eval('l:trimmed_word'))
    if wordOriginal.isupper():
        return target_word.upper()
    elif wordOriginal[0].isupper():
        return target_word[0].upper()+target_word[1:]
    return target_word 
Example #13
Source File: vimconda.py    From vim-conda with MIT License 5 votes vote down vote up
def condaactivate():
    """ function! s:CondaActivate(envname, envpath, envsroot) """
    # It turns out that `os.environ` is loaded only once. Therefore it
    # doesn't see the changes we just made above to the vim process env,
    # and so we will need to set these
    os.environ['CONDA_DEFAULT_ENV'] = vim.eval('a:envname')
    os.environ['PATH'] = vim.eval('$PATH') 
Example #14
Source File: sourcetrail.py    From vim-sourcetrail with MIT License 5 votes vote down vote up
def __init__(self):
        self.port_vim_to_sourcetrail = int(vim.eval('sourcetrail#get("vim_to_sourcetrail_port")'))
        self.port_sourcetrail_to_vim = int(vim.eval('sourcetrail#get("sourcetrail_to_vim_port")'))
        self.ip_addr = vim.eval('sourcetrail#get("sourcetrail_ip")') 
Example #15
Source File: mediawiki_editor.py    From vim-mediawiki-editor with MIT License 5 votes vote down vote up
def var_exists(var):
    return bool(
        int(vim.eval("exists('%s')" % sq_escape(var)))
    ) 
Example #16
Source File: token.py    From DyeVim with MIT License 5 votes vote down vote up
def AddMatch( self, wid ):
        if wid not in self._matchIds:
            self._matchIds[ wid ] = vim.eval( self._create ) 
Example #17
Source File: mediawiki_editor.py    From vim-mediawiki-editor with MIT License 5 votes vote down vote up
def fn_escape(s):
    return vim.eval("fnameescape('%s')" % sq_escape(s)) 
Example #18
Source File: mediawiki_editor.py    From vim-mediawiki-editor with MIT License 5 votes vote down vote up
def input(prompt, text="", password=False):
    vim.command("call inputsave()")
    vim.command(
        "let i = %s('%s', '%s')"
        % (
            ("inputsecret" if password else "input"),
            sq_escape(prompt),
            sq_escape(text),
        )
    )
    vim.command("call inputrestore()")
    return vim.eval("i") 
Example #19
Source File: _vim.py    From completor.vim with MIT License 5 votes vote down vote up
def _patch_nvim(vim):
    class Bindeval(object):
        def __init__(self, data):
            self.data = data

        def __getitem__(self, key):
            return _bytes(self.data[key])

    def function(name):
        def inner(*args, **kwargs):
            ret = vim.call(name, *args, **kwargs)
            return _bytes(ret)
        return inner

    def bindeval(value):
        data = vim.eval(value)
        return Bindeval(data)

    vim_vars = vim.vars

    class vars_wrapper(object):
        def get(self, *args, **kwargs):
            item = vim_vars.get(*args, **kwargs)
            return _bytes(item)

    vim.Function = function
    vim.bindeval = bindeval
    vim.List = list
    vim.Dictionary = dict
    vim.vars = vars_wrapper() 
Example #20
Source File: vimconda.py    From vim-conda with MIT License 5 votes vote down vote up
def condadeactivate():
    """ function! s:CondaDeactivate() """
    # It turns out that `os.environ` is loaded only once. Therefore it
    # doesn't see the changes we just made above to the vim process env,
    # and so we will need to update the embedded Python's version of
    # `os.environ` manually.
    if 'CONDA_DEFAULT_ENV' in os.environ:
        del os.environ['CONDA_DEFAULT_ENV']
    os.environ['PATH'] = vim.eval('$PATH') 
Example #21
Source File: pfp_plugin.py    From pfp-vim with MIT License 5 votes vote down vote up
def pfp_getline(line=None):
    this_buffer = vim.current.buffer.number
    if line is None:
        line, _ = vim.current.window.cursor
    res = vim.eval("getbufline({}, {})".format(this_buffer, line))
    if len(res) == 0:
        return None
    else:
        return res[0] 
Example #22
Source File: pfp_plugin.py    From pfp-vim with MIT License 5 votes vote down vote up
def move_to(line, column):
    vim.eval("setpos('.', [0,{},{}])".format(line, column))


# --------------------------------------- 
Example #23
Source File: pfp_plugin.py    From pfp-vim with MIT License 5 votes vote down vote up
def buffwinnr(name):
    """
    """
    return int(vim.eval("bufwinnr('" + name + "')")) 
Example #24
Source File: pfp_plugin.py    From pfp-vim with MIT License 5 votes vote down vote up
def winnr():
    """
    """
    return int(vim.eval("winnr()")) 
Example #25
Source File: pfp_plugin.py    From pfp-vim with MIT License 5 votes vote down vote up
def _input(message="input"):
    vim.command("call inputsave()")
    vim.command("let user_input = input('" + message + ": ')")
    vim.command("call inputrestore()")
    return vim.eval("user_input") 
Example #26
Source File: repeater.py    From pappy-proxy with MIT License 5 votes vote down vote up
def submit_current_buffer():
    curbuf = vim.current.buffer
    b2_id = int(vim.eval("s:b2"))
    b2 = vim.buffers[b2_id]
    vim.command("let s:b1=bufnr('$')")
    vim.command("only")
    vim.command("rightbelow vertical new")
    vim.command("b %d" % b2_id)
    vim.command("wincmd h")
    full_request = '\n'.join(curbuf)

    req = parse_request(full_request)
    dest_host, dest_port, use_tls, storage_id = dest_loc()
    req.dest_host = dest_host
    req.dest_port = dest_port
    req.use_tls = use_tls

    comm_type, comm_addr = get_conn_addr()
    with ProxyConnection(kind=comm_type, addr=comm_addr) as conn:
        new_req = conn.submit(req, storage=storage_id)
        conn.add_tag(new_req.db_id, "repeater", storage_id)
        update_buffers(new_req)
    
# (left, right) = set_up_windows()
# set_buffer_content(left, 'Hello\nWorld')
# set_buffer_content(right, 'Hello\nOther\nWorld')
#print "Arg is %s" % vim.eval("a:arg") 
Example #27
Source File: repeater.py    From pappy-proxy with MIT License 5 votes vote down vote up
def dest_loc():
    dest_host = vim.eval("s:dest_host")
    dest_port = int(vim.eval("s:dest_port"))
    tls_num = vim.eval("s:use_tls")
    storage_id = int(vim.eval("s:storage_id"))
    if tls_num == "1":
        use_tls = True
    else:
        use_tls = False
    return (dest_host, dest_port, use_tls, storage_id) 
Example #28
Source File: vimconda.py    From vim-conda with MIT License 5 votes vote down vote up
def conda_startup_env():
    """ Get conda startup env

     This is happening at script startup. It looks like a conda env
     was already activated before launching vim, so we need to make
     the required changes internally.
     """
    envname = vim.eval('g:conda_startup_env')
    # Need to get the root "envs" dir in order to build the
    # complete path the to env.
    roots = [os.path.dirname(x) for x in get_envs()
             if envname == os.path.split(x)[-1]]

    if len(roots) > 1:
        print('Found more than one matching env, '
              'this should never happen.')
    elif len(roots) == 0:
        print('\nCould not find a matching env in the list. '
              '\nThis probably means that you are using a local '
              '\n(prefix) Conda env.'
              '\n '
              '\nThis should be fine, but changing to a named env '
              '\nmay make it difficult to reactivate the prefix env.'
              '\n ')
        vim.command('let g:conda_startup_was_prefix = 1')
    else:
        root = roots[0]
        envpath = os.path.join(root, envname)
        # Reset the env paths back to root
        # (This will also modify sys.path to include the site-packages
        # folder of the Python on the system $PATH)
        conda_deactivate()
        # Re-activate.
        conda_activate(envname, envpath, root) 
Example #29
Source File: repeater.py    From pappy-proxy with MIT License 5 votes vote down vote up
def get_conn_addr():
    conn_type = vim.eval("s:conn_type")
    conn_addr = vim.eval("s:conn_addr")
    return (conn_type, conn_addr) 
Example #30
Source File: vimconda.py    From vim-conda with MIT License 5 votes vote down vote up
def python_input(message='input'):
    vim.command('call inputsave()')
    vim.command("let user_input = input('" + message + "', '	', 'custom,Conda_env_input_callback')")
    vim.command('call inputrestore()')
    return vim.eval('user_input')