def moved(): now = time() w = vim.current.window lastbuf = w.vars.get(VLAST, None) if not lastbuf or now - lastbuf[1] > 0.1: w.vars[VLAST] = 0 vim.command('echo "" | au! vial_bufhist_wait_action')
def open_module(name): syspath = env.get().eval('import sys\nreturn sys.path') syspath = env.get_sources() + syspath mname = name.split('.') pkgname = mname[:] + ['__init__.py'] mname[-1] += '.py' foundpath = None for p in syspath: n = os.path.join(p, *mname) if os.path.exists(n): foundpath = n break n = os.path.join(p, *pkgname) if os.path.exists(n): foundpath = n break if foundpath: mark() vim.command('edit {}'.format(foundpath)) else: print >> sys.stderr, "Can't find {}".format(name)
def open_module(name): syspath = env.get().eval('import sys\nreturn sys.path') syspath = env.get_sources() + syspath mname = name.split('.') pkgname = mname[:] + ['__init__.py'] mname[-1] += '.py' foundpath = None for p in syspath: n = os.path.join(p, *mname) if os.path.exists(n): foundpath = n break n = os.path.join(p, *pkgname) if os.path.exists(n): foundpath = n break if foundpath: mark() vim.command('edit {}'.format(foundpath)) else: print >>sys.stderr, "Can't find {}".format(name)
def omnifunc(findstart, base): if findstart in (0, b'0'): q = unidecode(base.decode('utf-8')).lower() book = cached_book() return [r[1] for r in book if q in r[0]] else: vim.command('norm! b') return vim.current.window.cursor[1]
def grep(query): matcher = re.compile(re.escape(query)) t = time() - 1 result = [] for r in get_projects(): for name, path, root, top, fullpath in get_files(r): if time() - t >= 1: redraw() print fullpath t = time() try: if os.stat(fullpath).st_size > MAX_FILESIZE: continue with open(fullpath) as f: source = f.read() matches = matcher.finditer(source) lines = source.splitlines() except OSError: continue for m in matches: start = m.start() line = source.count('\n', 0, start) + 1 offset = start - source.rfind('\n', 0, start) text = lines[line - 1] if len(text) > 100: offstart = max(0, offset - 30) text = text[offstart:offstart+60] + '...' if offstart: text = '...' + text result.append({ 'bufnr': '', 'filename': fullpath, 'pattern': '', 'valid': 1, 'nr': -1, 'lnum': line, 'vcol': 0, 'col': offset, 'text': text.replace('\x00', ' '), 'type': '' }) vfunc.setqflist(result) if result: vim.command('cw') redraw() print '{} matches found'.format(len(result))
def grep(query): matcher = re.compile(re.escape(query)) t = time() - 1 result = [] for r in get_projects(): for name, path, root, top, fullpath in get_files(r): if time() - t >= 1: redraw() print fullpath t = time() try: if os.stat(fullpath).st_size > MAX_FILESIZE: continue with open(fullpath) as f: source = f.read() matches = matcher.finditer(source) lines = source.splitlines() except OSError: continue for m in matches: start = m.start() line = source.count('\n', 0, start) + 1 offset = start - source.rfind('\n', 0, start) text = lines[line - 1] if len(text) > 100: offstart = max(0, offset - 30) text = text[offstart:offstart + 60] + '...' if offstart: text = '...' + text result.append({ 'bufnr': '', 'filename': fullpath, 'pattern': '', 'valid': 1, 'nr': -1, 'lnum': line, 'vcol': 0, 'col': offset, 'text': text.replace('\x00', ' '), 'type': '' }) vfunc.setqflist(result) if result: vim.command('cw') redraw() print '{} matches found'.format(len(result))
def on_select(self, item, cursor): focus_window(self.last_window) mark() item = item[0] if 'offset' in item: line = vfunc.byte2line(item['offset'] + 1) else: line = item['line'] vim.command('normal! {}Gzz'.format(line))
def show_lint_result(errors, warns, append=False): result = errors + warns if not result: vim.command('cclose') redraw() print 'Good job!' return vfunc.setqflist(errors + warns, 'a' if append else ' ') if errors: vim.command('copen') redraw() print '{} error(s) and {} warning(s) found'.format(len(errors), len(warns))
def goto_definition(): source = get_content() pos = vim.current.window.cursor dpos, fname = env.get().location(source, pos, vim.current.buffer.name) if dpos: mark() if fname and fname != vim.current.buffer.name: vim.command(':edit {}'.format(vfunc.fnameescape(fname))) vim.current.window.cursor = dpos else: vim.current.window.cursor = dpos else: print 'Location not found'
def goto_definition(): source = get_content() pos = vim.current.window.cursor locs = env.get().location(source, pos, vim.current.buffer.name) if locs: mark() last = locs[-1] if isinstance(last, dict): head = locs[:-1] tail = [last] else: tail = last last = tail[0] head = locs[:-1] locs = head + tail if len(locs) > 1: llist = [{ 'bufnr': '', 'filename': loc['file'], 'pattern': '', 'valid': 1, 'nr': -1, 'lnum': loc['loc'][0], 'vcol': 0, 'col': loc['loc'][1] + 1, } for loc in locs] vfunc.setloclist(0, llist, ' ') vim.command(':ll {}'.format(len(head) + 1)) redraw() if len(tail) > 1: print 'Multiple locations' else: print 'Chained locations' else: fname = last['file'] dpos = last['loc'] if fname and fname != vim.current.buffer.name: vim.command(':edit {}'.format(vfunc.fnameescape(fname))) vim.current.window.cursor = dpos else: vim.current.window.cursor = dpos else: redraw() print 'Location not found'
def grepop(type): old = vfunc.getreg('"') if type == 'v': vim.command('normal! `<v`>y') elif type == 'char': vim.command('normal! `[v`]y') else: return query = vfunc.getreg('"') if query.strip(): grep(query) else: redraw() print 'Search for nothing?' vfunc.setreg('"', old)
def escape(): if len(vim.windows) < 2: return cur = vfunc.winnr() for n, w in reversed(list(enumerate(vim.windows, 1))): if not buffer_with_file(w.buffer): if not '[Command Line]'in w.buffer.name: focus_window(n) vim.command('q') if n != cur: if cur > n: cur -= 1 focus_window(cur) return
def escape(): if len(vim.windows) < 2: return cur = vfunc.winnr() for n, w in reversed(list(enumerate(vim.windows, 1))): if not buffer_with_file(w.buffer): if not '[Command Line]' in w.buffer.name: focus_window(n) vim.command('q') if n != cur: if cur > n: cur -= 1 focus_window(cur) return
def create_module(name): parts = name.split('.') pkg = parts[:-1] module = parts[-1] root = env.get_sources()[0] for r in pkg: path = os.path.join(root, r) if not os.path.exists(path): os.mkdir(path) init = os.path.join(path, '__init__.py') if not os.path.exists(init): with open(init, 'w') as f: f.write('') root = path mark() vim.command('edit {}'.format(os.path.join(root, module + '.py')))
def execute(mode): cbuf = vim.current.buffer cwin = vim.current.window if mode == 0: # paragraph start = cbuf.mark('{')[0] stop = cbuf.mark('}')[0] elif mode == 1: # visual start = max(0, cbuf.mark('<')[0] - 1) stop = cbuf.mark('>')[0] else: # whole buffer start = 0 stop = len(cbuf) input = '\n'.join(cbuf[start:stop]) executable = cbuf[0].lstrip('#! ') with open('/tmp/vial-pipe-result.txt', 'wb') as f: Popen(executable, shell=True, stderr=f, stdout=f, stdin=PIPE).communicate(input) make_scratch('vial-pipe', title='Result') vim.command('norm! ggdG') vim.command('0read /tmp/vial-pipe-result.txt') focus_window(cwin)
def new(fname): dname = os.path.dirname(fname) if not os.path.exists(dname): os.makedirs(dname) vim.command('e {}'.format(fname))
def init(self, win, buf): vim.command('setlocal syntax=vialpytest') vim.command('nnoremap <buffer> gf :python {}()<cr>'.format(goto_file.ref))
def reset(self): cwin = vim.current.window _, self.buf = make_scratch('__vial_pytest__', self.init, 'pytest') vim.command('normal! ggdG') focus_window(cwin) redraw()
def jump(dir): w = vim.current.window check_history(w) history = list(w.vars[VHIST]) bufnr = vim.current.buffer.number now = time() lastbuf = w.vars.get(VLAST, None) if not lastbuf or (bufnr == lastbuf[0] and now - lastbuf[1] > vim.vars['vial_bufhist_timeout']): history = add_to_history(w, bufnr) if bufnr not in history: history = add_to_history(w, bufnr) names = { r.number: (split(r.name) if r.name else ['', '[buf-{}]'.format(r.number)]) for r in vim.buffers if vfunc.buflisted(r.number) } history[:] = filter(lambda r: r in names, history) dups = True while dups: dups = False for name, g in groupby(sorted(names.iteritems(), key=skey), skey): g = list(g) if len(g) > 1: dups = True for nr, (path, _) in g: p, n = split(path) names[nr] = p, n + '/' + name width = vim.vars['vial_bufhist_width'] if width < 0: width += int(vim.eval('&columns')) - 1 try: idx = history.index(bufnr) except ValueError: return idx += dir if idx < 0: idx = 0 elif idx >= len(history): idx = len(history) - 1 anr = history[idx] active = names[anr][1] before = ' '.join(names[r][1] for r in history[:idx]) after = ' '.join(names[r][1] for r in history[idx + 1:]) half = (width - len(active) - 4) / 2 if len(before) < len(after): blen = min(half, len(before)) alen = width - len(active) - blen - 4 else: alen = min(half, len(after)) blen = width - len(active) - alen - 4 if len(before) > blen: before = '...' + before[3 - blen:] if len(after) > alen: after = after[:alen - 3] + '...' if before: before += ' ' if after: after = ' ' + after vim.command('let x=&ruler | let y=&showcmd') vim.command('set noruler noshowcmd') redraw() echon(before) vim.command('echohl CursorLine') echon(active) vim.command('echohl None') echon(after) vim.command('let &ruler=x | let &showcmd=y') if anr != bufnr: w.vars['vial_bufhist_switch'] = 1 vim.command('silent b {}'.format(anr)) w.vars['vial_bufhist_switch'] = 0 vim.command('augroup vial_bufhist_wait_action') vim.command('au!') vim.command('au CursorMoved,CursorHold <buffer> python %s()' % moved.ref) vim.command('augroup END')
def jump(dir): w = vim.current.window check_history(w) history = list(w.vars[VHIST]) bufnr = vim.current.buffer.number now = time() lastbuf = w.vars.get(VLAST, None) if not lastbuf or (bufnr == lastbuf[0] and now - lastbuf[1] > vim.vars['vial_bufhist_timeout']): history = add_to_history(w, bufnr) if bufnr not in history: history = add_to_history(w, bufnr) names = {r.number: (split(r.name) if r.name else ['', '[buf-{}]'.format(r.number)]) for r in vim.buffers if vfunc.buflisted(r.number)} history[:] = filter(lambda r: r in names, history) dups = True while dups: dups = False for name, g in groupby(sorted(names.iteritems(), key=skey), skey): g = list(g) if len(g) > 1: dups = True for nr, (path, _) in g: p, n = split(path) names[nr] = p, n + '/' + name width = vim.vars['vial_bufhist_width'] if width < 0: width += int(vim.eval('&columns')) - 1 try: idx = history.index(bufnr) except ValueError: return idx += dir if idx < 0: idx = 0 elif idx >= len(history): idx = len(history) - 1 anr = history[idx] active = names[anr][1] before = ' '.join(names[r][1] for r in history[:idx]) after = ' '.join(names[r][1] for r in history[idx+1:]) half = (width - len(active) - 4) / 2 if len(before) < len(after): blen = min(half, len(before)) alen = width - len(active) - blen - 4 else: alen = min(half, len(after)) blen = width - len(active) - alen - 4 if len(before) > blen: before = '...' + before[3-blen:] if len(after) > alen: after = after[:alen-3] + '...' if before: before += ' ' if after: after = ' ' + after vim.command('let x=&ruler | let y=&showcmd') vim.command('set noruler noshowcmd') redraw() echon(before) vim.command('echohl CursorLine') echon(active) vim.command('echohl None') echon(after) vim.command('let &ruler=x | let &showcmd=y') if anr != bufnr: w.vars['vial_bufhist_switch'] = 1 vim.command('silent b {}'.format(anr)) w.vars['vial_bufhist_switch'] = 0 vim.command('augroup vial_bufhist_wait_action') vim.command('au!') vim.command('au CursorMoved,CursorHold <buffer> python %s()' % moved.ref) vim.command('augroup END')
def http(): lines = vim.current.buffer[:] line, _ = vim.current.window.cursor line -= 1 headers, templates = get_headers_and_templates(lines, line) pwd_func = lambda p: vfunc.inputsecret('{}: '.format(p)) input_func = lambda p: vfunc.input('{}: '.format(p)) try: method, url, query, body, tlist, rend = prepare_request(lines, line, headers, input_func, pwd_func) except PrepareException as e: echoerr(str(e)) return rctx = RequestContext() rctx.request(method, url, query, body, headers) cwin = vim.current.window win, buf = make_scratch('__vial_http_req__', title='Request') rlines = rctx.raw_request.splitlines() hlines = [] for r in rctx.history[:-1]: hlines.append(bstr('Redirect {} from {}'.format( r.status, r.request[1]), 'utf-8')) if hlines: hlines.append(b'----------------') buf[:] = hlines + rlines win.cursor = 1, 0 win, buf = make_scratch('__vial_http_hdr__', title='Response headers') if PY2: buf[:] = [r.rstrip('\r\n') for r in rctx.response.msg.headers] else: buf[:] = ['{}: {}'.format(*r).encode('utf-8') for r in rctx.response.msg._headers] win.cursor = 1, 0 size = len(rctx.content) win, buf = make_scratch('__vial_http_raw__', title='Raw Response') buf[:] = rctx.content.splitlines() win.cursor = 1, 0 if PY2: rcontent_type = rctx.response.msg.gettype() else: rcontent_type = rctx.response.msg.get_content_type() content, ctype, jdata = format_content(rcontent_type, rctx.content) win, buf = make_scratch('__vial_http__') win.options['statusline'] = 'Response: {} {} {}ms {}ms {}'.format( rctx.response.status, rctx.response.reason, rctx.ctime, rctx.rtime, sizeof_fmt(size)) vim.command('set filetype={}'.format(ctype)) buf[:] = content.splitlines(False) win.cursor = 1, 0 focus_window(cwin) def set_cookies(*args): cookies = rctx.cookies args = args or sorted(cookies.keys()) return 'Cookie: ' + ';'.join('{}={}'.format(k, cookies[k]) for k in args) ctx = {'body': content, 'json': jdata, 'headers': Headers(rctx.response.getheaders()), 'cookies': rctx.cookies, 'rcookies': rctx.rcookies, 'set_cookies': set_cookies} for t in tlist: if t in templates: lines = render_template(templates[t], **ctx).splitlines() else: lines = ['ERROR: template {} not found'.format(t)] vfunc.append(rend + 1, [''] + lines) rend += 1 + len(lines)
def on_select(self, item, cursor): focus_window(self.last_window) mark() vim.command('normal! {}Gzz^'.format(item[1]))
def init(): vim.vars['vial_bufhist_timeout'] = 2 # seconds vim.vars['vial_bufhist_width'] = -20 vim.command('noremap <silent> <Plug>VialBufHistPrev :python %s(1)<cr>' % jump) vim.command('noremap <silent> <Plug>VialBufHistNext :python %s(-1)<cr>' % jump) vim.command('augroup VialBufHist') vim.command('autocmd!') vim.command('autocmd BufWinEnter * python %s()' % win_buf_enter) vim.command('augroup END')
def http(): lines = vim.current.buffer[:] line, _ = vim.current.window.cursor line -= 1 headers, templates = get_headers_and_templates(lines, line) pwd_func = lambda p: vfunc.inputsecret('{}: '.format(p)) input_func = lambda p: vfunc.input('{}: '.format(p)) try: method, url, query, body, tlist, rend = prepare_request( lines, line, headers, input_func, pwd_func) except PrepareException as e: echoerr(str(e)) return rctx = RequestContext() rctx.request(method, url, query, body, headers) cwin = vim.current.window win, buf = make_scratch('__vial_http_req__', title='Request') rlines = rctx.raw_request.splitlines() hlines = [] for r in rctx.history[:-1]: hlines.append( bstr('Redirect {} from {}'.format(r.status, r.request[1]), 'utf-8')) if hlines: hlines.append(b'----------------') buf[:] = hlines + rlines win.cursor = 1, 0 win, buf = make_scratch('__vial_http_hdr__', title='Response headers') if PY2: buf[:] = [r.rstrip('\r\n') for r in rctx.response.msg.headers] else: buf[:] = [ '{}: {}'.format(*r).encode('utf-8') for r in rctx.response.msg._headers ] win.cursor = 1, 0 size = len(rctx.content) win, buf = make_scratch('__vial_http_raw__', title='Raw Response') buf[:] = rctx.content.splitlines() win.cursor = 1, 0 if PY2: rcontent_type = rctx.response.msg.gettype() else: rcontent_type = rctx.response.msg.get_content_type() content, ctype, jdata = format_content(rcontent_type, rctx.content) win, buf = make_scratch('__vial_http__') win.options['statusline'] = 'Response: {} {} {}ms {}ms {}'.format( rctx.response.status, rctx.response.reason, rctx.ctime, rctx.rtime, sizeof_fmt(size)) vim.command('set filetype={}'.format(ctype)) buf[:] = content.splitlines(False) win.cursor = 1, 0 focus_window(cwin) def set_cookies(*args): cookies = rctx.cookies args = args or sorted(cookies.keys()) return 'Cookie: ' + ';'.join('{}={}'.format(k, cookies[k]) for k in args) ctx = { 'body': content, 'json': jdata, 'headers': Headers(rctx.response.getheaders()), 'cookies': rctx.cookies, 'rcookies': rctx.rcookies, 'set_cookies': set_cookies } for t in tlist: if t in templates: lines = render_template(templates[t], **ctx).splitlines() else: lines = ['ERROR: template {} not found'.format(t)] vfunc.append(rend + 1, [''] + lines) rend += 1 + len(lines)
def on_select(self, item, cursor): focus_window(self.last_window) mark() vim.command('e {}'.format(item[2]))
def goto_file(): filename, line = vfunc.expand('<cWORD>').split(':')[:2] for win in vim.windows: if vfunc.buflisted(win.buffer.number): focus_window(win) vim.command('e +{} {}'.format(line, filename))
def init(): register_function('<SID>BS()', backspace) register_function('<SID>CR()', cr) register_function('<SID>OpenClose(start)', open_close) vim.command('inoremap <Plug>VialCrampLeave <esc>') vim.command('inoremap <Plug>VialCrampSkip <c-g>U<right>') vim.command('inoremap <bs> <c-r>=<SID>BS()<cr><bs>') vim.command('inoremap <cr> <cr><c-r>=<SID>CR()<cr>') for s, e in BRACKETS: ss = s.replace('"', '\\"') ee = e.replace('"', '\\"') if s == e: vim.command( 'inoremap {0} {0}<c-r>=<SID>OpenClose("{1}")<cr>{0}<c-g>U<left>' .format(s, ss)) else: vim.command('inoremap {0} {0}{1}<c-g>U<left>'.format(s, e)) vim.command( 'inoremap {0} {0}<c-r>=<SID>OpenClose("{1}")<cr>'.format( e, ee))
def http(): lines = vim.current.buffer[:] line, _ = vim.current.window.cursor line -= 1 headers, templates = get_headers_and_templates(lines, line) pwd_func = lambda p: vfunc.inputsecret('{}: '.format(p)) input_func = lambda p: vfunc.input('{}: '.format(p)) try: method, url, query, body, tlist, rend = prepare_request( lines, line, headers, input_func, pwd_func) except PrepareException as e: echoerr(str(e)) return u = urlparse.urlsplit(url) if not u.hostname: host = headers.pop('host', '') if not host.startswith('http://') and not host.startswith('https://'): host = 'http://' + host u = urlparse.urlsplit(host + url) path = u.path if u.query: path += '?' + u.query if query: path += ('&' if u.query else '?') + urllib.urlencode(query) if u.scheme == 'https': import ssl cn = httplib.HTTPSConnection(u.hostname, u.port or 443, timeout=CONNECT_TIMEOUT, context=ssl._create_unverified_context()) else: cn = httplib.HTTPConnection(u.hostname, u.port or 80, timeout=CONNECT_TIMEOUT) cn = send_collector(cn) start = time.time() cn.connect() ctime = int((time.time() - start) * 1000) cn.sock.settimeout(READ_TIMEOUT) cn.request(method, path, body, headers) response = cn.getresponse() rtime = int((time.time() - start) * 1000) cwin = vim.current.window win, buf = make_scratch('__vial_http_req__', title='Request') buf[:] = cn._sdata.splitlines() win.cursor = 1, 0 win, buf = make_scratch('__vial_http_hdr__', title='Response headers') if PY2: buf[:] = [r.rstrip('\r\n') for r in response.msg.headers] else: buf[:] = [ '{}: {}'.format(*r).encode('utf-8') for r in response.msg._headers ] win.cursor = 1, 0 content = response.read() size = len(content) win, buf = make_scratch('__vial_http_raw__', title='Raw Response') buf[:] = content.splitlines() win.cursor = 1, 0 if PY2: rcontent_type = response.msg.gettype() else: rcontent_type = response.msg.get_content_type() content, ctype, jdata = format_content(rcontent_type, content) win, buf = make_scratch('__vial_http__') win.options['statusline'] = 'Response: {} {} {}ms {}ms {}'.format( response.status, response.reason, ctime, rtime, sizeof_fmt(size)) vim.command('set filetype={}'.format(ctype)) buf[:] = content.splitlines(False) win.cursor = 1, 0 focus_window(cwin) cj = Cookie.SimpleCookie() if PY2: cheaders = response.msg.getheaders('set-cookie') else: cheaders = response.msg.get_all('set-cookie') for h in cheaders or []: cj.load(h) rcookies = {k: v.value for k, v in iteritems(cj)} cookies = {k: v.coded_value for k, v in iteritems(cj)} def set_cookies(*args): args = args or sorted(cookies.keys()) return 'Cookie: ' + ';'.join('{}={}'.format(k, cookies[k]) for k in args) ctx = { 'body': content, 'json': jdata, 'headers': Headers(response.getheaders()), 'cookies': cookies, 'rcookies': rcookies, 'set_cookies': set_cookies } for t in tlist: if t in templates: lines = render_template(templates[t], **ctx).splitlines() else: lines = ['ERROR: template {} not found'.format(t)] vfunc.append(rend + 1, [''] + lines) rend += 1 + len(lines)