Example #1
0
 def _unset_offending_vim_options(self, snippet):
     # Care for textwrapping
     if not snippet.keep_formatoptions_unchanged:
         self._cached_offending_vim_options["fo"] = ''.join(
             c for c in vim.eval("&fo") if c in "ct"
         )
         for c in "ct": vim.command("set fo-=%s" % c)
Example #2
0
def floobits_stop_everything():
    if G.AGENT:
        reactor.stop()
        G.AGENT = None
    floobits_pause()
    # TODO: get this value from vim and reset it
    vim.command('set updatetime=4000')
Example #3
0
def echom(message):
	u"""
	Print a regular message that will be visible to the user, even when
	multiple lines are printed
	"""
	# probably some escaping is needed here
	vim.command((u':echomsg "%s"' % message).encode(u'utf-8'))
 def transform_to_scratchbuffer(self):
     """ transforms the current buffer into a scratchbuffer """
     vim.command("call s:ScratchBuffer()")
     vim.command("setlocal nocursorline")
     vim.command("setlocal buftype=acwrite")
     vim.command("setlocal nomodified")
     vim.command("au! BufWriteCmd <buffer> call s:UpdateNoteFromCurrentBuffer()")
Example #5
0
def __vim_multi_replace(locs, old, new, prompt_level):
    if locs is None:
        return

    pattern = ""

    for line, column, bufname in locs:
        if bufname is None or bufname != vim.current.buffer.name:
            continue

        if pattern:
            pattern += "\|"

        pattern += "\%" + str(line) + "l" + "\%>" + str(
            column - 1) + "c\%<" + str(column + len(old)) + "c" + old

    if not pattern:
        return

    cmd = "%s/" + pattern + "/" + new + "/gI"

    if prompt_level >= 2:
        cmd = cmd + "c"

    vim.command(cmd)
Example #6
0
def coq_raw_query(*args):
    global info_msg
    if coqtop is None:
        print("Error: Coqtop isn't running. Are you sure you called :CoqLaunch?")
        return

    raw_query = ' '.join(args)

    xml = ET.Element('call')
    xml.set('val', 'interp')
    xml.set('raw', 'true')
    xml.text = raw_query

    send_cmd(xml)
    response = get_answer()

    if response is None:
        vim.command("call coquille#KillSession()")
        print('ERROR: the Coq process died')
        return

    if response.get('val') == 'good':
        optionnal_info = response.find('string')
        if optionnal_info is not None:
            info_msg = optionnal_info.text
    elif response.get('val') == 'fail':
        info_msg = response.text
        print("FAIL")
    else:
        print("(ANOMALY) unknown answer: %s" % ET.tostring(response)) # ugly

    show_info()
Example #7
0
def coq_rewind(steps=1):
    if coqtop is None:
        print("Error: Coqtop isn't running. Are you sure you called :CoqLaunch?")
        return

    global encountered_dots, info_msg

    request = ET.Element('call')
    request.set('val', 'rewind')
    request.set('steps', str(steps))

    send_cmd(request)

    response = get_answer()

    if response is None:
        vim.command("call coquille#KillSession()")
        print('ERROR: the Coq process died')
        return

    if response.get('val') == 'good':
        additional_steps = response.find('int') # should never be none
        nb_removed = steps + int(additional_steps.text)
        encountered_dots = encountered_dots[:len(encountered_dots) - nb_removed]
    else:
        info_msg = "[COQUILLE ERROR] Unexpected answer:\n\n%s" % ET.tostring(response)

    refresh()
Example #8
0
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))
Example #9
0
def tern_ensureCompletionCached():
  cached = vim.eval("b:ternLastCompletionPos")
  curRow, curCol = vim.current.window.cursor
  curLine = vim.current.buffer[curRow - 1]

  if (curRow == int(cached["row"]) and curCol >= int(cached["end"]) and
      curLine[0:int(cached["end"])] == cached["word"] and
      (not re.match(".*\\W", curLine[int(cached["end"]):curCol]))):
    return

  data = tern_runCommand({"type": "completions", "types": True, "docs": True},
                         {"line": curRow - 1, "ch": curCol})
  if data is None: return

  completions = []
  for rec in data["completions"]:
    completions.append({"word": rec["name"],
                        "menu": tern_asCompletionIcon(rec.get("type")),
                        "info": tern_typeDoc(rec) })
  vim.command("let b:ternLastCompletion = " + json.dumps(completions))
  start, end = (data["start"]["ch"], data["end"]["ch"])
  vim.command("let b:ternLastCompletionPos = " + json.dumps({
    "row": curRow,
    "start": start,
    "end": end,
    "word": curLine[0:end]
  }))
Example #10
0
def try_print_error(e, msg=None):
    try:
        raise e
    except Error as e:
        if msg:
            print(msg)
        else:
            print(e.value["message"])
    except Exception as e:
        # Always print to stdout
        # vim try to be 'smart' and prepend a backtrace when writing to stderr
        # WTF?!
        if msg:
            print(msg)
        else:
            msg = str(e)
            if re.search("Not_found", msg):
                print("error: Not found")
                return None
            elif re.search("Cmi_format.Error", msg):
                if vim.eval('exists("b:merlin_incompatible_version")') == "0":
                    vim.command("let b:merlin_incompatible_version = 1")
                    print("The version of merlin you're using doesn't support this version of ocaml")
                return None
            print(msg)
Example #11
0
def replace_buffer_portion(start, end, txt):
    encoding = vim_encoding()

    start_line = start["line"] - 1
    b = vim.current.buffer

    fst_line = b[start_line]
    lst_line = b[end["line"] - 1]

    prefix = fst_line[0 : start["col"]]
    suffix = lst_line[end["col"] : len(lst_line)]

    del b[start_line : end["line"]]

    txt = prefix.decode(encoding) + txt + suffix.decode(encoding)
    lines = txt.split("\n")
    lines.reverse()
    nb_lines = 0
    for line in lines:
        nb_lines += 1
        b[start_line:0] = [line.encode(encoding)]

    # Properly reindent the modified lines
    vim.current.window.cursor = (start["line"], 0)
    vim.command("call feedkeys('%d==', 'n')" % nb_lines)
Example #12
0
def dirty(repo, filepath):
    if not hasattr(repo, '__getitem__'):
        vim_throw('statuns', repo.path)
    m=match.match(None, None, [filepath], exact=True)
    status=repo.status(match=m, unknown=True)
    if any(status[:-2]):
        vim.command('let r=1')
Example #13
0
    def csi_clear_line(self, csi):
        """ Process the line clear escape sequence. """


        # this escape defaults to 0
        if len(csi['vals']) == 0:
            csi['val'] = 0




        # 0 means cursor right
        if csi['val'] == 0:
            self.screen[self.l] = self.screen[self.l][0:self.c - 1]

        # 1 means cursor left
        elif csi['val'] == 1:
            self.screen[self.l] = ' ' * (self.c) + self.screen[self.l][self.c:]

        # clear entire line
        elif csi['val'] == 2:
            self.screen[self.l] = ''

        # clear colors
        if csi['val'] == 2 or (csi['val'] == 0 and self.c == 1):
            buffer_line = self.get_buffer_line(self.l)
            if buffer_line in self.color_history:
                for syn in self.color_history[buffer_line]:
                    vim.command('syn clear ' + syn['name'])
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")
Example #15
0
def diffToBuffer(*args, **kwargs):
    ui=CaptureToBuf()
    dodiff(ui, *args, **kwargs)
    if len(vim.current.buffer)>1 and vim.current.buffer[-1] == '':
        vim.current.buffer[-1:]=[]
    else:
        vim.command('setlocal binary noendofline')
Example #16
0
  def __init__(self, port=9000, max_children='32', max_data='1024', max_depth='1', minibufexpl='0', debug=0, proxy_host='localhost', proxy_port=None, proxy_key=None):
    """ initialize Debugger """
    socket.setdefaulttimeout(5)
    self.port       = port
    self.proxy_host = proxy_host
    self.proxy_port = proxy_port
    self.proxy_key  = proxy_key
    self.debug      = debug

    self.current    = None
    self.file       = None
    self.lasterror  = None
    self.msgid      = 0
    self.running    = 0
    self.stacks     = []
    self.curstack   = 0
    self.laststack  = 0
    self.bptsetlst  = {} 

    self.status        = None
    self.max_children  = max_children
    self.max_data      = max_data
    self.max_depth     = max_depth

    self.protocol   = DbgProtocol(self.port, self.proxy_host, self.proxy_port, self.proxy_key)

    self.ui         = DebugUI(minibufexpl)
    self.breakpt    = BreakPoint()

    self.file_mapping = list(vim.eval('debuggerFileMapping'))
    self.mapped_files = {}

    vim.command('sign unplace *')
Example #17
0
    def set_cursor(self, line, column):
        """ Update cursor position in Vim buffer """

        logging.debug('setting cursor at line ' + str(line) + ' column ' + str(column))

        # handle offset
        line += self.offset

        # shift cursor position to handle concealed text
        if self.enable_colors and self.color_mode == 'conceal':
            if line - 1 in self.color_conceals:
                for c in self.color_conceals[line - 1]:
                    if c < column:
                        column += 7
                    else:
                        break

        logging.debug('column is now ' + str(column))

        # figure out line
        buffer_line = line
        if buffer_line > len(self.buffer):
            for l in range(len(self.buffer) - 1, buffer_line):
                self.buffer.append('')

        # figure out column
        real_column = column
        if len(self.buffer[buffer_line - 1]) < real_column:
            self.buffer[buffer_line - 1] = self.buffer[buffer_line - 1] + ' ' * (real_column - len(self.buffer[buffer_line - 1]))

        # python version is occasionally grumpy
        try:
            vim.current.window.cursor = (buffer_line, real_column - 1)
        except:
            vim.command('call cursor(' + str(buffer_line) + ', ' + str(real_column) + ')')
Example #18
0
    def wrapper(wrapped):
        global functions

        code = wrapped.func_code
        name = wrapped.func_name
        args_names = code.co_varnames[:code.co_argcount]
        args_string = ', '.join(args_names)
        functions[name] = wrapped

        if scope == 'local':
            vim_name = 's:' + name
        elif scope == 'global':
            vim_name = name[0].upper() + name[1:]
        else:
            raise Exception('Unrecognized scope option')

        code = []
        code.append('function! ' + vim_name + '(' + args_string + ')')
        code.append('python << EOF')
        code.append('from pyunite.decorators import functions, vim_cast')

        eval_arg_commands = map(lambda x: 'vim.eval("a:{}")'.format(x), args_names)
        retvalue_string = 'vim_cast(functions["' + name + '"](' + ', '.join(eval_arg_commands) + '))'

        code.append('vim.command("return " + ' + retvalue_string + ')')
        code.append('EOF')
        code.append('endfunction')
        vim.command('\n'.join(code))

        return wrapped
Example #19
0
 def command(self, cmd):
   """ go to my window & execute command """
   self.prepare()
   winnr = self.getwinnr()
   if winnr != int(vim.eval("winnr()")):
     vim.command(str(winnr) + 'wincmd w')
   vim.command(cmd)
Example #20
0
	def _switch_to(cls, bufname, vim_commands=None):
		u"""
		Swicht to the buffer with bufname.

		A list of vim.commands (if given) gets executed as well.

		TODO: this should be extracted and imporved to create an easy to use
		way to create buffers/jump to buffers. Otherwise there are going to be
		quite a few ways to open buffers in vimorgmode.
		"""
		cmds = [u'botright split org:%s' % bufname,
				u'setlocal buftype=nofile',
				u'setlocal modifiable',
				u'setlocal nonumber',
				# call opendoc() on enter the original todo item
				u'nnoremap <silent> <buffer> <CR> :exec "py ORGMODE.plugins[u\'Agenda\'].opendoc()"<CR>',
				u'nnoremap <silent> <buffer> <TAB> :exec "py ORGMODE.plugins[u\'Agenda\'].opendoc(switch=True)"<CR>',
				u'nnoremap <silent> <buffer> <S-CR> :exec "py ORGMODE.plugins[u\'Agenda\'].opendoc(split=True)"<CR>',
				# statusline
				u'setlocal statusline=Org\\ %s' % bufname
				]
		if vim_commands:
			cmds.extend(vim_commands)
		for cmd in cmds:
			vim.command(cmd.encode(u'utf-8'))
Example #21
0
	def _get_agendadocuments(self):
		u"""
		Return the org documents of the agenda files; return None if no
		agenda documents are defined.

		TODO: maybe turn this into an decorator?
		"""
		# load org files of agenda
		agenda_files = settings.get(u'org_agenda_files', u',')
		if not agenda_files or agenda_files == ',':
			echoe((u"No org_agenda_files defined. Use :let "
				   u"g:org_agenda_files=['~/org/index.org'] to add "
				   u"files to the agenda view."))
			return

		# glob for files in agenda_files
		resolved_files = []
		for f in agenda_files:
			f = glob.glob(os.path.join(os.path.expanduser(os.path.dirname(f)),
				          os.path.basename(f)))
			resolved_files.extend(f)

		agenda_files = [os.path.realpath(f) for f in resolved_files]

		# load the agenda files into buffers
		for agenda_file in agenda_files:
			vim.command((u'badd %s' % agenda_file.replace(" ", "\ ")).encode(u'utf-8'))

		# determine the buffer nr of the agenda files
		agenda_nums = [get_bufnumber(fn) for fn in agenda_files]

		# collect all documents of the agenda files and create the agenda
		return [ORGMODE.get_document(i) for i in agenda_nums if i is not None]
Example #22
0
def lookupAllUserTypes():
    js = getResponse('/lookupalltypes')
    if (js != ''):
        response = json.loads(js)
        if (response != None):
            vim.command("let s:allUserTypes = '%s'" % (response['Types']))
            vim.command("let s:allUserInterfaces = '%s'" % (response['Interfaces']))
Example #23
0
def getResponse(endPoint, additionalParameters=None, timeout=None ):
    parameters = {}
    parameters['line'] = vim.eval('line(".")')
    parameters['column'] = vim.eval('col(".")')
    parameters['buffer'] = '\r\n'.join(vim.eval("getline(1,'$')")[:])
    parameters['filename'] = vim.current.buffer.name
    if(additionalParameters != None):
        parameters.update(additionalParameters)

    if(timeout == None):
        timeout=int(vim.eval('g:OmniSharp_timeout'))

    host = vim.eval('g:OmniSharp_host')

    if vim.eval('exists("b:OmniSharp_host")') == '1':
        host = vim.eval('b:OmniSharp_host')

    target = urlparse.urljoin(host, endPoint)
    parameters = urllib.urlencode(parameters)

    proxy = urllib2.ProxyHandler({})
    opener = urllib2.build_opener(proxy)
    try:
        response = opener.open(target, parameters, timeout)
        vim.command("let g:serverSeenRunning = 1")
        return response.read()
    except Exception as e:
        vim.command("let g:serverSeenRunning = 0")
        return ''
Example #24
0
def echo(message):
	u"""
	Print a regular message that will not be visible to the user when
	multiple lines are printed
	"""
	for m in message.split(u'\n'):
		vim.command(u_encode((u':echo "%s"' % m)))
Example #25
0
def recall_pos():
    marks = vim.eval("g:hackernews_marks")
    m = hex(vim.current.buffer[0])
    if m in marks:
        mark = marks[m]
        vim.current.window.cursor = (int(mark[0]), int(mark[1]))
        vim.command("set syntax=%s" % mark[2])
Example #26
0
def __vim_multi_replace(locs, old, new, prompt):
    if not locs:
        return

    pattern = ""

    for line, column, bufname in locs:
        if not bufname or bufname != vim.current.buffer.name:
            continue

        if pattern:
            pattern += r'\|'

        pattern += r'\%' + str(line) + 'l' + r'\%>' + str(
            column - 1) + r'c\%<' + str(column + len(old)) + 'c' + old

    if not pattern:
        return

    cmd = '%s/' + pattern + '/' + new + '/gI'

    if prompt >= 2:
        cmd = cmd + 'c'

    vim.command(cmd)
Example #27
0
def echoe(message):
	u"""
	Print an error message. This should only be used for serious errors!
	"""
	# probably some escaping is needed here
	for m in message.split(u'\n'):
		vim.command(u_encode(u':echoerr "%s"' % m))
Example #28
0
def getTestCommand():
    mode = vim.eval('a:mode')
    parameters = {}
    parameters['Type'] = mode
    response = json.loads(getResponse('/gettestcontext', parameters))
    testCommand = "let s:testcommand = '%(TestCommand)s'" % response
    vim.command(testCommand)
 def version_of_current_note(self, version=None):
     """ retrieve a specific version of current note """
     note_id = self.get_current_note()
     try:
         current_version = self.note_version[note_id]
         buffer = vim.current.buffer
         if version is None:
             # If no args then just print version of note
             print("Displaying note ID %s version %s" % (note_id, current_version))
         else:
             if (buffer.options["modified"] == False):
                 if version == "0":
                     note, status = self.simplenote.get_note(note_id)
                     if status == 0:
                         buffer[:] = list(map(lambda x: str(x), note["content"].split("\n")))
                         # Need to set as unmodified so can continue to browse through versions
                         vim.command("setlocal nomodified")
                         print("Displaying most recent version of note ID %s" % note_id)
                 else:
                     note, status = self.simplenote.get_note(note_id, version)
                     if status == 0:
                         buffer[:] = list(map(lambda x: str(x), note["content"].split("\n")))
                         # Need to set as unmodified so can continue to browse through versions
                         vim.command("setlocal nomodified")
                         print("Displaying note ID %s version %s. To restore, :Simplenote -u, to revert to most recent, :Simplenote -v" % (note_id, version))
                     else:
                         print("Error fetching note data. Perhaps that version isn't available.")
             else:
                 print("Save changes before trying to show another version")
     except KeyError:
         print("This isn't a Simplenote")
Example #30
0
    def draw(self):
    
        # get current buffer!
        b = utils.get_buffer(self.buffer_name)

        # set to markdown syntax for now
        vim.command("set filetype=markdown")

        # append title
        b.append("## %s" % self.repo)
        b.append("")
        
        for i in self.issues:
            issue_string = "%s. \"%s\" " % (i[0], i[1])

            if len(i[5]) > 0:
                 issue_string += "#%s " % ",".join(i[5])
            
            if not (i[2] == github.user()["login"]):
                issue_string += "@%s " % i[2]
            if not (i[3] == "open"):
                issue_string += i[3]
            
            # add labels if they exist
            b.append(issue_string)

        # delete first line
        vim.command("1delete _")
Example #31
0
def _goto_window_for_buffer(b):
    w = int(vim.eval('bufwinnr(%d)' % int(b)))
    vim.command('%dwincmd w' % w)
Example #32
0
def clear_location_list():
    vim.command("lexpr []")
Example #33
0
def define_command(command_name, fn):
    commands[command_name] = fn
    vim.command("command! {0} python pyglyvim_call_command('{0}')".format(
        command_name))
Example #34
0

def open_location_list():
    vim.command("lwindow")


def close_location_list():
    vim.command("lclose")


# Signs
def clear_signs():
    vim.command("sign unplace * file={0}".format(vim.current.buffer.name))


def define_sign(sign_name, text="*", text_highlight="Error"):
    vim.command("sign define {0} text={1} texthl={2}".format(
        sign_name, text, text_highlight))


def add_sign(sign_id, line_number, sign_name, file_path=None):
    if file_path is None:
        file_path = vim.current.buffer.name
    vim.command('sign place {0} line={1} name={2} file={3}'.format(
        sign_id, line_number, sign_name, file_path))


# handle vim commands defined via pyglyvim
vim.command(
    "python from pyglyvim import call_command as pyglyvim_call_command")
def UnitePyGetMrus():
    global mrus
    vim.command('let s:mrus = %s' % str(mrus))
Example #36
0
server_address = '/tmp/nvim-gdb-python-socket'

# Make sure the socket does not already exist
try:
    os.unlink(server_address)
except OSError:
    if os.path.exists(server_address):
        raise

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
sock.bind(server_address)
sock.settimeout(0.5)

# Let GDB send back the list of sources
vim.command('call nvimgdb#Send("nvim-gdb-info-sources %s")' % server_address)

# Receive the result from GDB
data, addr = sock.recvfrom(65536)
lines = data.decode('utf-8').splitlines()

# What we are going to search for
target = os.path.normpath(sys.argv[0])
target_min_len = len(os.path.basename(target))
target = target[::-1]

def LongestCommonPrefix(a, b):
    n = min(len(a), len(b))
    for i in range(n):
        if a[i] != b[i]:
            return i
Example #37
0
File: _vim.py Project: ravsa/Vgit
def command(cmd):
    """Wraps vim.command."""
    return as_unicode(vim.command(as_vimencoding(cmd)))
Example #38
0
def no_jedi_warning(error=None):
    vim.command('echohl WarningMsg')
    vim.command('echom "Please install Jedi if you want to use jedi-vim."')
    if error:
        vim.command('echom "The error was: {0}"'.format(error))
    vim.command('echohl None')
Example #39
0
 def on_create(self):
     self.command('setlocal syntax=debugger_log')
     if self.creation_count == 1:
         vim.command('silent! au BufWinLeave %s :silent! bdelete %s' %
                     (self.name, self.name))
Example #40
0
 def echo_status_vim(indicator):
     vim.command('redraw | echo "%s"' % indicator)
Example #41
0
 def remove_pointer(self):
     vim.command('sign unplace %s' % self.pointer_sign_id)
Example #42
0
def goto(mode="goto", no_output=False):
    """
    :param str mode: "related_name", "definition", "assignment", "auto"
    :return: list of definitions/assignments
    :rtype: list
    """
    script = get_script()
    if mode == "goto":
        definitions = [x for x in script.goto_definitions()
                       if not x.in_builtin_module()]
        if not definitions:
            definitions = script.goto_assignments()
    elif mode == "related_name":
        definitions = script.usages()
    elif mode == "definition":
        definitions = script.goto_definitions()
    elif mode == "assignment":
        definitions = script.goto_assignments(follow_imports=True)

    if no_output:
        return definitions
    if not definitions:
        echo_highlight("Couldn't find any definitions for this.")
    elif len(definitions) == 1 and mode != "related_name":
        d = list(definitions)[0]
        if d.in_builtin_module():
            if d.is_keyword:
                echo_highlight("Cannot get the definition of Python keywords.")
            else:
                echo_highlight("Builtin modules cannot be displayed (%s)."
                               % d.desc_with_module)
        else:
            using_tagstack = int(vim_eval('g:jedi#use_tag_stack')) == 1
            if (d.module_path or '') != vim.current.buffer.name:
                result = new_buffer(d.module_path,
                                    using_tagstack=using_tagstack)
                if not result:
                    return []
            if (using_tagstack and d.module_path and
                    os.path.exists(d.module_path)):
                tagname = d.name
                with tempfile('{0}\t{1}\t{2}'.format(
                        tagname, d.module_path, 'call cursor({0}, {1})'.format(
                            d.line, d.column + 1))) as f:
                    old_tags = vim.eval('&tags')
                    old_wildignore = vim.eval('&wildignore')
                    try:
                        # Clear wildignore to ensure tag file isn't ignored
                        vim.command('set wildignore=')
                        vim.command('let &tags = %s' %
                                    repr(PythonToVimStr(f.name)))
                        vim.command('tjump %s' % tagname)
                    finally:
                        vim.command('let &tags = %s' %
                                    repr(PythonToVimStr(old_tags)))
                        vim.command('let &wildignore = %s' %
                                    repr(PythonToVimStr(old_wildignore)))
            vim.current.window.cursor = d.line, d.column
    else:
        # multiple solutions
        lst = []
        for d in definitions:
            if d.in_builtin_module():
                lst.append(dict(text=PythonToVimStr('Builtin ' + d.description)))
            elif d.module_path is None:
                # Typically a namespace, in the future maybe other things as
                # well.
                lst.append(dict(text=PythonToVimStr(d.description)))
            else:
                lst.append(dict(filename=PythonToVimStr(d.module_path),
                                lnum=d.line, col=d.column + 1,
                                text=PythonToVimStr(d.description)))
        vim_eval('setqflist(%s)' % repr(lst))
        vim_eval('jedi#add_goto_window(' + str(len(lst)) + ')')
    return definitions
Example #43
0
 def set_line(self, lineno):
     self.focus()
     vim.command("normal %sgg" % str(lineno))
Example #44
0
 def command(self, cmd):
     """ go to my window & execute command """
     winnr = self.getwinnr()
     if winnr != int(vim.eval("winnr()")):
         vim.command(str(winnr) + 'wincmd w')
     vim.command(cmd)
Example #45
0
 def focus(self):
     vim.command(self.winno + "wincmd w")
Example #46
0
 def clear_signs(self):
     vim.command('sign unplace *')
Example #47
0
 def command(self, cmd):
     vim.command('redir => _tmp')
     vim.command('silent %s' % cmd)
     vim.command('redir END')
     return vim.eval('_tmp')
Example #48
0
 def command(self, cmd, silent=True):
     self.focus()
     prepend = "silent " if silent else ""
     command_str = prepend + self.winno + "wincmd " + cmd
     vim.command(command_str)
Example #49
0
 def place_breakpoint(self, sign_id, file, line):
     vim.command('sign place '+str(sign_id)+\
             ' name=breakpt line='+str(line)+\
             ' file='+file.as_local())
Example #50
0
 def error(self, string):
     vim.command('echohl Error | echo "'+\
             str(string).replace('"','\\"')+\
             '" | echohl None')
     vdebug.log.Log(string, vdebug.log.Logger.ERROR)
Example #51
0
def command(cmd):
    """Wraps vim.command."""
    return vim.command(cmd)
Example #52
0
 def remove_breakpoint(self, breakpoint):
     id = breakpoint.id
     vim.command('sign unplace %i' % id)
     if self.breakpointwin.is_open:
         self.breakpointwin.remove_breakpoint(id)
Example #53
0
def PostVimMessage(message):
    vim.command('echohl WarningMsg | echomsg "{0}" | echohl None'.format(
        message.replace('"', '\\"')))
Example #54
0
def highlightRange(range, hlGroup):
    pattern = '/\%' + str(range.start.line) + 'l' + '\%' \
        + str(range.start.column) + 'c' + '.*' \
        + '\%' + str(range.end.column) + 'c/'
    command = "exe 'syntax match' . ' " + hlGroup + ' ' + pattern + "'"
    vim.command(command)
Example #55
0
 def unregister_menu(self):
     vim.command(u'silent! aunmenu Org'.encode(u'utf-8'))
Example #56
0
def EchoText(text):
    vim.command("echom '{0}'".format(text.replace("'", r"''")))
Example #57
0
def completions():
    jedi.settings.case_insensitive_completion = \
        bool(int(vim_eval("get(b:, 'jedi_case_insensitive_completion', "
                          "g:jedi#case_insensitive_completion)")))

    row, column = vim.current.window.cursor
    # Clear call signatures in the buffer so they aren't seen by the completer.
    # Call signatures in the command line can stay.
    if int(vim_eval("g:jedi#show_call_signatures")) == 1:
        clear_call_signatures()
    if vim.eval('a:findstart') == '1':
        count = 0
        for char in reversed(vim.current.line[:column]):
            if not re.match(r'[\w\d]', char):
                break
            count += 1
        vim.command('return %i' % (column - count))
    else:
        base = vim.eval('a:base')
        source = ''
        for i, line in enumerate(vim.current.buffer):
            # enter this path again, otherwise source would be incomplete
            if i == row - 1:
                source += line[:column] + base + line[column:]
            else:
                source += line
            source += '\n'
        # here again hacks, because jedi has a different interface than vim
        column += len(base)
        try:
            script = get_script(source=source)
            completions = script.complete(*get_pos(column))
            signatures = script.get_signatures(*get_pos(column))

            add_info = "preview" in vim.eval("&completeopt").split(",")
            out = []
            for c in completions:
                d = dict(
                    word=PythonToVimStr(c.name[:len(base)] + c.complete),
                    abbr=PythonToVimStr(c.name_with_symbols),
                    # stuff directly behind the completion
                    menu=PythonToVimStr(c.description),
                    icase=1,  # case insensitive
                    dup=1  # allow duplicates (maybe later remove this)
                )
                if add_info:
                    try:
                        d["info"] = PythonToVimStr(c.docstring())
                    except Exception:
                        print("jedi-vim: error with docstring for %r: %s" %
                              (c, traceback.format_exc()))
                out.append(d)

            strout = str(out)
        except Exception:
            # print to stdout, will be in :messages
            print(traceback.format_exc())
            strout = ''
            completions = []
            signatures = []

        show_call_signatures(signatures)
        vim.command('return ' + strout)
Example #58
0
 def r(*args, **kwargs):
     res = f(*args, **kwargs)
     if REPEAT_EXISTS and isinstance(res, basestring):
         vim.command((u'silent! call repeat#set("\\<Plug>%s")' %
                      res).encode(u'utf-8'))
     return res
Example #59
0
    def new_checkbox(cls, below=None, plain=None):
        '''
		if below is:
			True -> create new list below current line
			False/None -> create new list above current line
		if plain is:
			True -> create a plainlist item
			False/None -> create an empty checkbox
		'''
        d = ORGMODE.get_document()
        h = d.current_heading()
        if h is None:
            return
        # init checkboxes for current heading
        h.init_checkboxes()
        c = h.current_checkbox()

        nc = Checkbox()
        nc._heading = h

        # default checkbox level
        level = h.level + 1
        start = vim.current.window.cursor[0] - 1
        # if no checkbox is found, insert at current line with indent level=1
        if c is None:
            h.checkboxes.append(nc)
        else:
            l = c.get_parent_list()
            idx = c.get_index_in_parent_list()
            if l is not None and idx is not None:
                l.insert(idx + (1 if below else 0), nc)
                # workaround for broken associations, Issue #165
                nc._parent = c.parent
                if below:
                    if c.next_sibling:
                        c.next_sibling._previous_sibling = nc
                    nc._next_sibling = c.next_sibling
                    c._next_sibling = nc
                    nc._previous_sibling = c
                else:
                    if c.previous_sibling:
                        c.previous_sibling._next_sibling = nc
                    nc._next_sibling = c
                    nc._previous_sibling = c.previous_sibling
                    c._previous_sibling = nc

            t = c.type
            # increase key for ordered lists
            if t[-1] in OrderListType:
                try:
                    num = int(t[:-1]) + (1 if below else -1)
                    if num < 0:
                        # don't decrease to numbers below zero
                        echom(u"Can't decrement further than '0'")
                        return
                    t = '%d%s' % (num, t[-1])
                except ValueError:
                    try:
                        char = ord(t[:-1]) + (1 if below else -1)
                        if below:
                            if char == 91:
                                # stop incrementing at Z (90)
                                echom(u"Can't increment further than 'Z'")
                                return
                            elif char == 123:
                                # increment from z (122) to A
                                char = 65
                        else:
                            if char == 96:
                                # stop decrementing at a (97)
                                echom(u"Can't decrement further than 'a'")
                                return
                            elif char == 64:
                                # decrement from A (65) to z
                                char = 122
                        t = u'%s%s' % (chr(char), t[-1])
                    except ValueError:
                        pass
            nc.type = t
            level = c.level

            if below:
                start = c.end_of_last_child
            else:
                start = c.start

        if plain:  # only create plainlist item when requested
            nc.status = None
        nc.level = level

        if below:
            start += 1
        # vim's buffer behave just opposite to Python's list when inserting a
        # new item.  The new entry is appended in vim put prepended in Python!
        vim.current.buffer.append("")  # workaround for neovim
        vim.current.buffer[start:start] = [unicode(nc)]
        del vim.current.buffer[-1]  # restore from workaround for neovim

        # update checkboxes status
        cls.update_checkboxes_status()

        vim.command((u'exe "normal %dgg"|startinsert!' %
                     (start + 1, )).encode(u'utf-8'))
Example #60
0
def JiraVimIssueOpen(sessionStorage, isSplit=False):
    issueKey = str(sys.argv[0])
    connection = sessionStorage.connection
    # Carry on the board name from the previous buffer

    buf, new = sessionStorage.getBuff(objName=issueKey)
    if isSplit:
        vim.command("sbuffer " + str(buf.number))
    else:
        vim.command("buffer " + str(buf.number))
    vim.command("set modifiable")
    if new:
        issue = Issue(issueKey, connection)
        project = str(issue.getField("project"))
        issue_type = str(issue.getField("issuetype"))
        DrawUtil.set_filetype(issue)

        sessionStorage.assignIssue(issue, buf)

        ##### DRAW THE HEADER
        line = DrawUtil.draw_header(buf, issue, "%s %s" %
                                    (issueKey, project)) + 2
        buf.append(issue_type, 2)

        ##### DRAW BASIC INFORMATION
        basic_info_category = ("Basic Information", [
            (field.title(), issue.getField(field)) for field in issue.basicInfo
        ])
        line = DrawUtil.draw_category(buf,
                                      issue,
                                      basic_info_category,
                                      line=line,
                                      str_generator=': '.join) + 1
        buf.append("")

        ##### DRAW DISPLAY FIELDS
        categories = [(field.title(), [("", issue.getField(field))])
                      for field in issue.displayFields]
        for c in categories:
            line = DrawUtil.draw_category(
                buf,
                issue,
                c,
                line=line,
                formatter=Formatters.DISPLAY_FIELDS_FORMATTER,
                str_generator=''.join) + 1
            buf.append("")

        ##### DRAW COMMENTS
        comments = issue.getComments()
        comments = ("Comments", [
            (str(c.author) + "[" + (str(c.author.name) if hasattr(
                c.author, "name") else str(c.author.accountId)) + "] " +
             datetime.strptime(
                 c.created, "%Y-%m-%dT%H:%M:%S.%f%z").strftime("%c"), c.body)
            for c in comments
        ])
        # This is just a very long way of telling the computer to format each comment as <author> <date>: <body>
        # The %c in strftime is to format the date in a human readable way
        comment_formatter = FormatterFactory.get_comment_formatter(
            len(comments[1]))
        line = DrawUtil.draw_category(buf,
                                      issue,
                                      comments,
                                      line=line,
                                      formatter=comment_formatter,
                                      str_generator=": ".join) + 1
        buf.append("")

    vim.command("set nomodifiable")
    vim.command("normal! gg")