Browse files

Added ternjs and played around a little.

  • Loading branch information...
1 parent f3a7013 commit 7eafc2e3e7ebbb79c160e60f3a1d43f32dd479ab @romainl committed Dec 11, 2013
View
77 autoload/functions.vim
@@ -14,7 +14,6 @@ function functions#ListRecentFiles(ArgLead, CmdLine, CursorPos)
endfunction
function functions#MRU(command, arg)
-
execute "" . a:command . " " . a:arg
endfunction
@@ -67,13 +66,14 @@ endfunction
" ===========================================================================
" experimental search/replace across project
-function functions#ReplaceThat()
- call functions#Replace(expand(input("Replace: ")))
+function functions#ReplaceThis(visual)
+ if a:visual == 1
+ call functions#Replace(functions#GetVisualSelection())
-endfunction
+ else
+ call functions#Replace(expand(input("Replace: ")))
-function functions#ReplaceThis()
- call functions#Replace(functions#GetVisualSelection())
+ endif
endfunction
@@ -92,64 +92,30 @@ function functions#Replace(search_pattern)
return
elseif user_choice == 1
- let file_pattern = "%"
+ execute "%s/" . a:search_pattern . "/" . replacement_pattern . "/ec"
+
+ else
+ tabedit %
+ if user_choice == 2
+ let file_pattern = "**/*." . expand("%:e")
- elseif user_choice == 2
- let file_pattern = "**/*." . expand("%:e")
+ elseif user_choice == 3
+ let file_pattern = "**/*"
- elseif user_choice == 3
- let file_pattern = "**/*"
+ elseif user_choice == 4
+ let file_pattern = substitute(input("\nCustom file pattern:\n"), "\n", "", "g")
- elseif user_choice == 4
- let file_pattern = substitute(input("\nCustom file pattern:\n"), "\n", "", "g")
+ endif
+ silent execute "vimgrep " . a:search_pattern . " " . file_pattern
+ execute "Qfdo s/" . a:search_pattern . "/" . replacement_pattern . "/ec"
endif
- tabedit %
- silent execute "vimgrep " . a:search_pattern . " " . file_pattern
- cwindow
- execute "Qfdo s/" . a:search_pattern . "/" . replacement_pattern . "/ec"
-
endfunction
-" function functions#ReplaceThis()
-" let search_pattern = functions#GetVisualSelection()
-" let replacement_pattern = expand(input("Replace " . search_pattern . " with: "))
-" echo "\n"
-" let file_pattern = ""
-" let user_choice = inputlist([
-" \ 'In...',
-" \ '1. the current file only',
-" \ '2. every ' . &filetype . ' file in ' . getcwd(),
-" \ '3. every file (except &wildignore) in ' . getcwd(),
-" \ '4. custom file pattern...'])
-
-" if user_choice == 0
-" return
-
-" elseif user_choice == 1
-" let file_pattern = "%"
-
-" elseif user_choice == 2
-" let file_pattern = "**/*." . expand("%:e")
-
-" elseif user_choice == 3
-" let file_pattern = "**/*"
-
-" elseif user_choice == 4
-" let file_pattern = substitute(input("\nCustom file pattern:\n"), "\n", "", "g")
-
-" endif
-
-" silent execute "vimgrep " . search_pattern . " " . file_pattern
-" tabnew
-" cwindow
-" execute "Qfdo s/" . search_pattern . "/" . replacement_pattern . "/ec"
-
-" endfunction
" ===========================================================================
-" :tag /foo but limited to the current buffer
+" like :tag /foo but the completion is limited to the current buffer
function functions#ListBufTags(ArgLead, CmdLine, CursorPos)
" absolute paths are machine/user-dependent
" Tagit() now uses relative paths so we can
@@ -479,6 +445,8 @@ endfunction
" ===========================================================================
" normal characters --> HTML entities
+function functions#Entities()
+ mark `
silent s/Á/\Á/e
silent s/á/\á/e
@@ -960,6 +928,7 @@ function functions#ReverseEntities()
silent s/ÿ/ÿ/e
silent s/Ÿ/Ÿ/e
silent s/Ζ/Ζ/e
+ silent s/ζ/ζ/e
endfunction
View
7 bundle/lang/after/ftplugin/html.vim
@@ -2,9 +2,10 @@ xnoremap <buffer> ?? <Esc>'<yyP"_C<!--<Esc>'>yyp"_C--><Esc>
xnoremap <buffer> !! <Esc>'<"_dd'>"_dd'<
nnoremap <buffer> <leader>& :call functions#Entities()<CR>
-nnoremap <buffer> <leader>é :call functions#ReverseEntities()<CR>
+nnoremap <buffer> <leader>é :call functions#ReverseEntities()<CR>
xnoremap <buffer> <leader>& :call functions#Entities()<CR>
-xnoremap <buffer> <leader>é :call functions#ReverseEntities()<CR>
+xnoremap <buffer> <leader>é :call functions#ReverseEntities()<CR>
+command! -buffer Entities :%call functions#Entities()
command! -buffer UA :call functions#UpdateAnchor()
@@ -15,7 +16,7 @@ nnoremap <buffer> dia /\v"\ze[ >/]<CR>di"
nnoremap <buffer> yia /\v"\ze[ >/]<CR>yi"
nnoremap <buffer> via /\v"\ze[ >/]<CR>vi"
-" à revoir
+" à revoir
" nnoremap <buffer> caa /\v"[ >/]/e<CR>vF=bc
" nnoremap <buffer> daa /\v"[ >/]/e<CR>vF=bd
" nnoremap <buffer> yaa /\v"[ >/]/e<CR>vF=by
View
2 bundle/tern/.gitignore
@@ -0,0 +1,2 @@
+/node_modules
+/doc/tags
View
53 bundle/tern/README.md
@@ -0,0 +1,53 @@
+# Tern for Vim
+
+This is a [Vim][vim] plugin that provides [Tern][tern]-based
+JavaScript editing support.
+
+[vim]: http://www.vim.org/
+[tern]: http://ternjs.net
+
+In JavaScript files, the package will hook into
+[omni completion][omni] to handle autocompletion, and provide the
+following commands:
+
+[omni]: http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion
+
+`TernDef`: Jump to the definition of the thing under the cursor.
+
+`TernDoc`: Look up the documentation of something.
+
+`TernType`: Find the type of the thing under the cursor.
+
+`TernRefs`: Show all references to the variable or property under the
+cursor.
+
+`TernRename`: Rename the variable under the cursor.
+
+## Installation
+
+If you use [Pathogen][path] or something similar, you can clone this
+repository to your `~/.vim/bundle` (or equivalent) directory. Make
+sure you have [node.js][node] and [npm][npm] installed (Tern is a
+JavaScript program), and install the tern server by running `npm
+install` in the `bundle/tern_for_vim` directory.
+
+## Configuration
+
+The command used to start the Tern server can be overridden by setting
+`tern#command` to an array of strings (the binary and its arguments,
+if any). You might need this if your node is installed somewhere
+that's not in the default path, or if you want to install Tern in some
+custom location.
+
+The variable `tern#is_show_argument_hints_enabled` can be set to
+something truthy to make the plugin display the arguments to the
+current function at the bottom of the screen. This feature is
+currently not very mature, and likely to make your editing laggy.
+
+Tern uses `.tern-project` files to configure loading libraries and
+plugins for a project. See the [Tern docs][docs] for details.
+
+[docs]: http://ternjs.net/doc/manual.html#configuration
+[path]: https://github.com/tpope/vim-pathogen
+[node]: http://nodejs.org/
+[npm]: https://npmjs.org/
View
8 bundle/tern/after/ftplugin/javascript_tern.vim
@@ -0,0 +1,8 @@
+call tern#Enable()
+
+" Menu
+menu <silent> Tern.Jump\ To\ Defintion :TernDef<CR>
+menu <silent> Tern.See\ Documentation :TernDoc<CR>
+menu <silent> Tern.DataType :TernType <CR>
+menu <silent> Tern.Show\ all\ References :TernRefs<CR>
+menu <silent> Tern.Rename :TernRename <CR>
View
534 bundle/tern/autoload/tern.vim
@@ -0,0 +1,534 @@
+if !has('python')
+ echo 'tern requires python support'
+ finish
+endif
+
+py << endpy
+
+import vim, os, platform, subprocess, urllib2, webbrowser, json, re, string, time
+from itertools import groupby
+
+def tern_displayError(err):
+ vim.command("echo " + json.dumps(str(err)))
+
+def tern_makeRequest(port, doc):
+ try:
+ req = urllib2.urlopen("http://localhost:" + str(port) + "/", json.dumps(doc),
+ float(vim.eval("g:tern_request_timeout")));
+ return json.loads(req.read())
+ except urllib2.HTTPError, error:
+ tern_displayError(error.read())
+ return None
+
+# Prefixed with _ to influence destruction order. See
+# http://docs.python.org/2/reference/datamodel.html#object.__del__
+_tern_projects = {}
+
+class Project(object):
+ def __init__(self, dir):
+ self.dir = dir
+ self.port = None
+ self.proc = None
+ self.last_failed = 0
+
+ def __del__(self):
+ tern_killServer(self)
+
+def tern_projectDir():
+ cur = vim.eval("b:ternProjectDir")
+ if cur: return cur
+
+ projectdir = ""
+ mydir = vim.eval("expand('%:p:h')")
+ if not os.path.isdir(mydir): return ""
+
+ if mydir:
+ projectdir = mydir
+ while True:
+ parent = os.path.dirname(mydir[:-1])
+ if not parent:
+ break
+ if os.path.isfile(os.path.join(mydir, ".tern-project")):
+ projectdir = mydir
+ break
+ mydir = parent
+
+ vim.command("let b:ternProjectDir = " + json.dumps(projectdir))
+ return projectdir
+
+def tern_findServer(ignorePort=False):
+ dir = tern_projectDir()
+ if not dir: return (None, False)
+ project = _tern_projects.get(dir, None)
+ if project is None:
+ project = Project(dir)
+ _tern_projects[dir] = project
+ if project.port is not None and project.port != ignorePort:
+ return (project.port, True)
+
+ portFile = os.path.join(dir, ".tern-port")
+ if os.path.isfile(portFile):
+ port = int(open(portFile, "r").read())
+ if port != ignorePort:
+ project.port = port
+ return (port, True)
+ return (tern_startServer(project), False)
+
+def tern_startServer(project):
+ if time.time() - project.last_failed < 30: return None
+
+ win = platform.system() == "Windows"
+ env = None
+ if platform.system() == "Darwin":
+ env = os.environ.copy()
+ env["PATH"] += ":/usr/local/bin"
+ proc = subprocess.Popen(vim.eval("g:tern#command") + vim.eval("g:tern#arguments"),
+ cwd=project.dir, env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, shell=win)
+ output = ""
+ while True:
+ line = proc.stdout.readline()
+ if not line:
+ tern_displayError("Failed to start server" + (output and ":\n" + output))
+ project.last_failed = time.time()
+ return None
+ match = re.match("Listening on port (\\d+)", line)
+ if match:
+ port = int(match.group(1))
+ project.port = port
+ project.proc = proc
+ return port
+ else:
+ output += line
+
+def tern_killServer(project):
+ if project.proc is None: return
+ project.proc.stdin.close()
+ project.proc.wait()
+ project.proc = None
+
+def tern_killServers():
+ for project in _tern_projects.values():
+ tern_killServer(project)
+
+def tern_relativeFile():
+ filename = vim.eval("expand('%:p')")
+ return filename[len(tern_projectDir()) + 1:]
+
+def tern_bufferSlice(buf, pos, end):
+ text = ""
+ while pos < end:
+ text += buf[pos] + "\n"
+ pos += 1
+ return text
+
+def tern_fullBuffer():
+ return {"type": "full",
+ "name": tern_relativeFile(),
+ "text": tern_bufferSlice(vim.current.buffer, 0, len(vim.current.buffer))}
+
+def tern_bufferFragment():
+ curRow, curCol = vim.current.window.cursor
+ line = curRow - 1
+ buf = vim.current.buffer
+ minIndent = None
+ start = None
+
+ for i in range(max(0, line - 50), line):
+ if not re.match(".*\\bfunction\\b", buf[i]): continue
+ indent = len(re.match("^\\s*", buf[i]).group(0))
+ if minIndent is None or indent <= minIndent:
+ minIndent = indent
+ start = i
+
+ if start is None: start = max(0, line - 50)
+ end = min(len(buf) - 1, line + 20)
+ return {"type": "part",
+ "name": tern_relativeFile(),
+ "text": tern_bufferSlice(buf, start, end),
+ "offsetLines": start}
+
+def tern_runCommand(query, pos=None, fragments=True):
+ if isinstance(query, str): query = {"type": query}
+ if (pos is None):
+ curRow, curCol = vim.current.window.cursor
+ pos = {"line": curRow - 1, "ch": curCol}
+ port, portIsOld = tern_findServer()
+ if port is None: return
+ curSeq = vim.eval("undotree()['seq_cur']")
+
+ doc = {"query": query, "files": []}
+ if curSeq == vim.eval("b:ternBufferSentAt"):
+ fname, sendingFile = (tern_relativeFile(), False)
+ elif len(vim.current.buffer) > 250 and fragments:
+ f = tern_bufferFragment()
+ doc["files"].append(f)
+ pos = {"line": pos["line"] - f["offsetLines"], "ch": pos["ch"]}
+ fname, sendingFile = ("#0", False)
+ else:
+ doc["files"].append(tern_fullBuffer())
+ fname, sendingFile = ("#0", True)
+ query["file"] = fname
+ query["end"] = pos
+ query["lineCharPositions"] = True
+
+ data = None
+ try:
+ data = tern_makeRequest(port, doc)
+ if data is None: return None
+ except:
+ pass
+
+ if data is None and portIsOld:
+ try:
+ port, portIsOld = tern_findServer(port)
+ if port is None: return
+ data = tern_makeRequest(port, doc)
+ if data is None: return None
+ except Exception as e:
+ tern_displayError(e)
+
+ if sendingFile and vim.eval("b:ternInsertActive") == "0":
+ vim.command("let b:ternBufferSentAt = " + str(curSeq))
+ return data
+
+def tern_sendBuffer(files=None):
+ port, _portIsOld = tern_findServer()
+ if port is None: return False
+ try:
+ tern_makeRequest(port, {"files": files or [tern_fullBuffer()]})
+ return True
+ except:
+ return False
+
+def tern_sendBufferIfDirty():
+ if (vim.eval("exists('b:ternInsertActive')") == "1" and
+ vim.eval("b:ternInsertActive") == "0"):
+ curSeq = vim.eval("undotree()['seq_cur']")
+ if curSeq > vim.eval("b:ternBufferSentAt") and tern_sendBuffer():
+ vim.command("let b:ternBufferSentAt = " + str(curSeq))
+
+def tern_asCompletionIcon(type):
+ if type is None or type == "?": return "(?)"
+ if type.startswith("fn("): return "(fn)"
+ if type.startswith("["): return "([])"
+ if type == "number": return "(num)"
+ if type == "string": return "(str)"
+ if type == "bool": return "(bool)"
+ return "(obj)"
+
+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[int(cached["start"]):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[start:end]
+ }))
+
+def tern_typeDoc(rec):
+ tp = rec.get("type")
+ result = rec.get("doc", " ")
+ if tp and tp != "?":
+ result = tp + "\n" + result
+ return result
+
+def tern_lookupDocumentation(browse=False):
+ data = tern_runCommand("documentation")
+ if data is None: return
+
+ doc = data.get("doc")
+ url = data.get("url")
+ if url:
+ if browse: return webbrowser.open(url)
+ doc = ((doc and doc + "\n\n") or "") + "See " + url
+ if doc:
+ vim.command("call tern#PreviewInfo(" + json.dumps(doc) + ")")
+ else:
+ vim.command("echo 'no documentation found'")
+
+def tern_echoWrap(data, name=""):
+ text = data
+ if len(name) > 0:
+ text = name+": " + text
+ col = int(vim.eval("&columns"))-23
+ if len(text) > col:
+ text = text[0:col]+"..."
+ vim.command("echo '{0}'".format(text))
+
+def tern_lookupType():
+ data = tern_runCommand("type")
+ if data: tern_echoWrap(data.get("type", ""))
+
+def tern_lookupArgumentHints(fname, apos):
+ curRow, curCol = vim.current.window.cursor
+ data = tern_runCommand({"type": "type", "preferFunction": True},
+ {"line": curRow - 1, "ch": apos})
+ if data: tern_echoWrap(data.get("type", ""),name=fname)
+
+def tern_lookupDefinition(cmd):
+ data = tern_runCommand("definition")
+ if data is None: return
+
+ if "file" in data:
+ lnum = data["start"]["line"] + 1
+ col = data["start"]["ch"] + 1
+ filename = data["file"]
+
+ if cmd == "edit" and filename == tern_relativeFile():
+ vim.command("normal! m`")
+ vim.command("call cursor(" + str(lnum) + "," + str(col) + ")")
+ else:
+ vim.command(cmd + " +call\ cursor(" + str(lnum) + "," + str(col) + ") " +
+ tern_projectFilePath(filename).replace(" ", "\\ "))
+ elif "url" in data:
+ vim.command("echo " + json.dumps("see " + data["url"]))
+ else:
+ vim.command("echo 'no definition found'")
+
+def tern_projectFilePath(path):
+ return os.path.join(tern_projectDir(), path)
+
+def tern_refs():
+ data = tern_runCommand("refs", fragments=False)
+ if data is None: return
+
+ refs = []
+ for ref in data["refs"]:
+ lnum = ref["start"]["line"] + 1
+ col = ref["start"]["ch"] + 1
+ filename = tern_projectFilePath(ref["file"])
+ name = data["name"]
+ text = vim.eval("getbufline('" + filename + "'," + str(lnum) + ")")
+ refs.append({"lnum": lnum,
+ "col": col,
+ "filename": filename,
+ "text": name + " (file not loaded)" if len(text)==0 else text[0]})
+ vim.command("call setloclist(0," + json.dumps(refs) + ") | lopen")
+
+# Copied here because Python 2.6 and lower don't have it built in, and
+# python 3.0 and higher don't support old-style cmp= args to the sort
+# method. There's probably a better way to do this...
+def tern_cmp_to_key(mycmp):
+ class K(object):
+ def __init__(self, obj, *args):
+ self.obj = obj
+ def __lt__(self, other):
+ return mycmp(self.obj, other.obj) < 0
+ def __gt__(self, other):
+ return mycmp(self.obj, other.obj) > 0
+ def __eq__(self, other):
+ return mycmp(self.obj, other.obj) == 0
+ def __le__(self, other):
+ return mycmp(self.obj, other.obj) <= 0
+ def __ge__(self, other):
+ return mycmp(self.obj, other.obj) >= 0
+ def __ne__(self, other):
+ return mycmp(self.obj, other.obj) != 0
+ return K
+
+def tern_rename(newName):
+ data = tern_runCommand({"type": "rename", "newName": newName}, fragments=False)
+ if data is None: return
+
+ def mycmp(a,b):
+ return (cmp(a["file"], b["file"]) or
+ cmp(a["start"]["line"], b["start"]["line"]) or
+ cmp(a["start"]["ch"], b["start"]["ch"]))
+ data["changes"].sort(key=tern_cmp_to_key(mycmp))
+ changes_byfile = groupby(data["changes"]
+ ,key=lambda c: tern_projectFilePath(c["file"]))
+
+ name = data["name"]
+ changes, external = ([], [])
+ for file, filechanges in changes_byfile:
+
+ buffer = None
+ for buf in vim.buffers:
+ if buf.name == file:
+ buffer = buf
+
+ if buffer is not None:
+ lines = buffer
+ else:
+ with open(file, "r") as f:
+ lines = f.readlines()
+ for linenr, linechanges in groupby(filechanges, key=lambda c: c["start"]["line"]):
+ text = lines[linenr]
+ offset = 0
+ changed = []
+ for change in linechanges:
+ colStart = change["start"]["ch"]
+ colEnd = change["end"]["ch"]
+ text = text[0:colStart + offset] + newName + text[colEnd + offset:]
+ offset += len(newName) - len(name)
+ changed.append({"lnum": linenr + 1,
+ "col": colStart + 1 + offset,
+ "filename": file})
+ for change in changed:
+ if buffer is not None:
+ lines[linenr] = change["text"] = text
+ else:
+ change["text"] = "[not loaded] " + text
+ lines[linenr] = text
+ changes.extend(changed)
+ if buffer is None:
+ with open(file, "w") as f:
+ f.writelines(lines)
+ external.append({"name": file, "text": string.join(lines, ""), "type": "full"})
+ if len(external):
+ tern_sendBuffer(external)
+ vim.command("call setloclist(0," + json.dumps(changes) + ") | lopen")
+
+endpy
+
+if !exists('g:tern#command')
+ let g:tern#command = ["node", expand('<sfile>:h') . '/../node_modules/tern/bin/tern', '--no-port-file']
+endif
+
+if !exists('g:tern#arguments')
+ let g:tern#arguments = []
+endif
+
+function! tern#PreviewInfo(info)
+ pclose
+ new +setlocal\ previewwindow|setlocal\ buftype=nofile|setlocal\ noswapfile
+ exe "normal z" . &previewheight . "\<cr>"
+ call append(0, type(a:info)==type("") ? split(a:info, "\n") : a:info)
+ wincmd p
+endfunction
+
+function! tern#Complete(findstart, complWord)
+ if a:findstart
+ python tern_ensureCompletionCached()
+ return b:ternLastCompletionPos['start']
+ elseif b:ternLastCompletionPos['end'] - b:ternLastCompletionPos['start'] == len(a:complWord)
+ return b:ternLastCompletion
+ else
+ let rest = []
+ for entry in b:ternLastCompletion
+ if stridx(entry["word"], a:complWord) == 0
+ call add(rest, entry)
+ endif
+ endfor
+ return rest
+ endif
+endfunction
+
+function! tern#LookupType()
+ python tern_lookupType()
+ return ''
+endfunction
+
+function! tern#LookupArgumentHints()
+ if g:tern_show_argument_hints == 'no'
+ return
+ endif
+ let fname = get(matchlist(getline('.')[:col('.')-2],'\([a-zA-Z0-9_]*\)([^()]*$'),1)
+ let pos = match(getline('.')[:col('.')-2],'[a-zA-Z0-9_]*([^()]*$')
+ if pos >= 0
+ python tern_lookupArgumentHints(vim.eval('fname'),int(vim.eval('pos')))
+ else
+ python tern_lookupType()
+ endif
+ return ''
+endfunction
+
+command! TernDoc py tern_lookupDocumentation()
+command! TernDocBrowse py tern_lookupDocumentation(browse=True)
+command! TernType py tern_lookupType()
+command! TernDef py tern_lookupDefinition("edit")
+command! TernDefPreview py tern_lookupDefinition("pedit")
+command! TernDefSplit py tern_lookupDefinition("split")
+command! TernDefTab py tern_lookupDefinition("tabe")
+command! TernRefs py tern_refs()
+command! TernRename exe 'py tern_rename("'.input("new name? ",expand("<cword>")).'")'
+
+if !exists('g:tern_show_argument_hints')
+ let g:tern_show_argument_hints = 'no'
+endif
+
+if !exists('g:tern_map_keys')
+ let g:tern_map_keys = 0
+endif
+
+if !exists('g:tern_map_prefix')
+ let g:tern_map_prefix = '<LocalLeader>'
+endif
+
+if !exists('g:tern_request_timeout')
+ let g:tern_request_timeout = 1
+endif
+
+function! tern#DefaultKeyMap(...)
+ let prefix = len(a:000)==1 ? a:1 : "<LocalLeader>"
+ execute 'nnoremap <buffer> '.prefix.'td' ':TernDoc<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tb' ':TernDocBrowse<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tt' ':TernType<CR>'
+ execute 'nnoremap <buffer> '.prefix.'td' ':TernDef<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tpd' ':TernDefPreview<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tsd' ':TernDefSplit<CR>'
+ execute 'nnoremap <buffer> '.prefix.'ttd' ':TernDefTab<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tr' ':TernRefs<CR>'
+ execute 'nnoremap <buffer> '.prefix.'tR' ':TernRename<CR>'
+endfunction
+
+function! tern#Enable()
+ if stridx(&buftype, "nofile") > -1 || stridx(&buftype, "nowrite") > -1
+ return
+ endif
+ let b:ternProjectDir = ''
+ let b:ternLastCompletion = []
+ let b:ternLastCompletionPos = {'row': -1, 'start': 0, 'end': 0}
+ let b:ternBufferSentAt = -1
+ let b:ternInsertActive = 0
+ setlocal omnifunc=tern#Complete
+ if g:tern_map_keys
+ call tern#DefaultKeyMap(g:tern_map_prefix)
+ endif
+ augroup TernAutoCmd
+ autocmd! * <buffer>
+ autocmd BufLeave <buffer> :py tern_sendBufferIfDirty()
+ if g:tern_show_argument_hints == 'on_move'
+ autocmd CursorMoved,CursorMovedI <buffer> call tern#LookupArgumentHints()
+ elseif g:tern_show_argument_hints == 'on_hold'
+ autocmd CursorHold,CursorHoldI <buffer> call tern#LookupArgumentHints()
+ endif
+ autocmd InsertEnter <buffer> let b:ternInsertActive = 1
+ autocmd InsertLeave <buffer> let b:ternInsertActive = 0
+ augroup END
+endfunction
+
+augroup TernShutDown
+ autocmd VimLeavePre * call tern#Shutdown()
+augroup END
+
+function! tern#Disable()
+ augroup TernAutoCmd
+ autocmd! * <buffer>
+ augroup END
+endfunction
+
+function! tern#Shutdown()
+ py tern_killServers()
+endfunction
View
135 bundle/tern/doc/tern.txt
@@ -0,0 +1,135 @@
+*tern.txt* a plugin for the javascript code analysis engine tern.
+
+==============================================================================
+CONTENTS *tern-contents*
+
+ 1. Intro........................................|tern-intro|
+ 2. Installation.................................|tern-install|
+ 3. Usage........................................|tern-usage|
+ 4. Commands.....................................|tern-commands|
+ 5. Options......................................|tern-options|
+
+==============================================================================
+INTRO *tern-intro*
+
+This plugin integrates features of the tern (http://ternjs.net) code analysis
+engine into vim. It provides features such as semantic code completion and
+intelligent renaming.
+
+==============================================================================
+INSTALLATION *tern-install*
+
+Install the plugin using your prefered plugin manager or copy the files
+to your ~/.vim directory manually. Make sure you have npm and node installed
+and run the following from the root path of the plugin (the same directory
+in which the file package.json is located): >
+
+ $ npm install
+>
+This will install the tern server and all required dependencies.
+Note : This plugin requires vim 7.3+ and builtin python support to work.
+
+==============================================================================
+USAGE *tern-usage*
+
+After installation vim will use the tern supplied omnifunc to handle
+omnicomplete calls for javascript files. In order to set up tern for
+use with your project you should create a '.tern-project' file in the root
+directory of your project. The following is just an example:
+>
+ {
+ "libs": [
+ "browser",
+ "jquery"
+ ],
+ "loadEagerly": [
+ "importantfile.js"
+ ],
+ "plugins": {
+ "requirejs": {
+ "baseURL": "./",
+ "paths": {}
+ }
+ }
+ }
+>
+
+This will tell the tern server to load definitions for jquery and the
+browser environment. Furthermore it will parse 'importantfile.js' on start up
+and register the requirejs plugin.
+
+For more detailed description of this configuration please refer to the online
+documentation of tern which can be found at http://ternjs.net/doc/manual.html
+
+==============================================================================
+COMMANDS *tern-commands*
+
+The following commands are available:
+
+ |TernDoc|....................... Look up Documentation
+ |TernDocBrowse|................. Browse the Documentation
+ |TernType|...................... Perform a type look up
+ |TernDef|....................... Look up definition
+ |TernDefPreview|................ Look up definition in preview
+ |TernDefSplit|.................. Look up definition in new split
+ |TernDefTab|.................... Look up definition in new tab
+ |TernRefs|...................... Look up references
+ |TernRename|.................... Rename identifier
+
+------------------------------------------------------------------------------
+ *TernDoc*
+Look up the documentation of something.
+
+------------------------------------------------------------------------------
+ *TernDocBrowse*
+Open the documentation in an external browser.
+
+------------------------------------------------------------------------------
+ *TernType*
+Find the type of the identifier under the cursor.
+
+------------------------------------------------------------------------------
+ *TernDef*
+Jump to the definition of the identifier under the cursor.
+
+------------------------------------------------------------------------------
+ *TernDefPreview*
+Jump to the definition of the identifier under the cursor inside
+the preview window.
+
+------------------------------------------------------------------------------
+ *TernDefSplit*
+Jump to the definition of the identifier under the cursor in a new split.
+
+------------------------------------------------------------------------------
+ *TernDefTab*
+Jump to the definition of the identifier under the cursor in a new tab.
+
+------------------------------------------------------------------------------
+ *TernRefs*
+List all references of the identifier under the cursor.
+
+------------------------------------------------------------------------------
+ *TernRename*
+Rename the variable under the cursor.
+
+==============================================================================
+OPTIONS *tern-options*
+
+The following options are available:
+
+ |tern_show_argument_hints|....... Configure argument hints display.
+
+-------------------------------------------------------------------------------
+ *tern_show_argument_hints*
+
+Defaults to |'no'|. Can be set to |'on_move'| to update the argument
+hints whenever the cursor moves, or |'on_hold'| to do it whenever the
+cursor is held still for a period that depends on the |updatetime|
+setting. |'on_move'| can reduce responsiveness on slow systems or big
+codebases. |'on_hold'| probably requires you to set |updatetime| to
+something smaller than the default of 4 seconds.
+
+If you do not see argument hints while in insert mode you might
+have to disable the mode indication (:set noshowmode). For more
+information see |'noshowmode'|.
View
1 bundle/tern/ftdetect/tern.vim
@@ -0,0 +1 @@
+au BufNewFile,BufRead .tern-project setf json
View
14 bundle/tern/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "tern_for_vim",
+ "license": "MIT",
+ "version": "0.4.0",
+ "author": "Marijn Haverbeke <marijnh@gmail.com>",
+ "description": "Sublime Text package for Vim",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/marijnh/tern_for_vim.git"
+ },
+ "dependencies": {
+ "tern": ">=0.5"
+ }
+}
View
10 bundle/tmp_moustache_handlebars/ftplugin/mustache.vim
@@ -16,16 +16,6 @@ if exists("loaded_matchit") && exists("b:match_words")
\ . '\%({{\)\@<=/\s*\1\s*}}'
endif
-inoremap <buffer> {{{ {{{}}}<left><left><left>
-inoremap <buffer> {{ {{}}<left><left>
-inoremap <buffer> {{! {{!}}<left><left>
-inoremap <buffer> {{< {{<}}<left><left>
-inoremap <buffer> {{> {{>}}<left><left>
-inoremap <buffer> {{# {{#}}<cr>{{/}}<up><left><left>
-inoremap <buffer> {{if {{#if }}<cr>{{/if}}<up><left>
-inoremap <buffer> {{ife {{#if }}<cr>{{else}}<cr>{{/if}}<up><up><left>
-
-
" Section movement
" Adapted from vim-ruby - many thanks to the maintainers of that plugin
View
34 snippets/html.snippets
@@ -473,14 +473,14 @@ snippet & Æ
# HTML5
snippet article
<article>
- ${0}
+ ${1}
</article>
snippet aside
<aside>
- ${0}
+ ${1}
</aside>
snippet audio
- <audio src="${1}>${0}</audio>
+ <audio src="${1}>
snippet html5
<!DOCTYPE html>
<html>
@@ -490,6 +490,32 @@ snippet html5
${2}
</head>
<body>
- ${0}
+ ${3}
</body>
</html>
+#
+# mustache/handlebars
+snippet {{{
+ {{{${1}}}}
+snippet {{
+ {{${1}}}
+snippet {{!
+ {{! ${1} }}
+snippet {{<
+ {{< ${1}}}
+snippet {{>
+ {{> ${1}}}
+snippet {{#
+ {{#${1}}}
+ ${2}
+ {{/$1}}
+snippet {{if
+ {{#if ${1}}}
+ ${2}
+ {{/if}}
+snippet {{ife
+ {{#if ${1}}}
+ ${2}
+ {{else}}
+ ${3}
+ {{/if}}
View
6 vimrc
@@ -99,7 +99,7 @@ if has('gui_running')
set columns=140
if os == 'Darwin'
- set guifont=Inconsolata-g:h13
+ set guifont=Inconsolata-g:h12
set fuoptions=maxvert,maxhorz
set clipboard^=unnamed
@@ -210,8 +210,8 @@ xnoremap <leader>o <Esc>:let @/ = functions#GetVisualSelection()<CR>
xnoremap <leader>q :s/<C-r>=@/<CR>/
-nnoremap <leader>Q :call functions#ReplaceThat()<CR>
-xnoremap <leader>Q :call functions#ReplaceThis()<CR>
+nnoremap <leader>Q :call functions#ReplaceThis(0)<CR>
+xnoremap <leader>Q :call functions#ReplaceThis(1)<CR>
nnoremap <leader>x *``cgn
nnoremap <leader>X #``cgN

0 comments on commit 7eafc2e

Please sign in to comment.