diff --git a/.gitignore b/.gitignore index d04c760e2e..5aac7e02db 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1 @@ -vim/.netrwhist -vim/.VimballRecord \ No newline at end of file +vim/.vim/.netrwhist \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..e69de29bb2 diff --git a/LICENSE b/LICENSE index b6c091399c..f686812ba1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2009 Ryan Bates +Copyright (c) 2011 Sebastian Marr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md new file mode 100644 index 0000000000..a55fd2c441 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# Sebastian Marr dotfiles + +These are config files to set up a command line environment the way I like it. + +## Prerequisites + +The dotfiles are installed via [GNU stow](http://www.gnu.org/software/stow). Install it with the package manager of your choice. +Use of zsh heavily recommended. + +## Installation + + git clone git://github.com/sebastianmarr/dotfiles ~/.dotfiles + cd ~/.dotfiles + +The simple way: + + ./install.sh + +The manual way: + + git submodule init + git submodule update + stow zsh + stow tmux + # etc... + +Just stow every configuration you need. diff --git a/README.rdoc b/README.rdoc deleted file mode 100644 index 375a9c2d95..0000000000 --- a/README.rdoc +++ /dev/null @@ -1,74 +0,0 @@ -= Ryan Bates Dot Files - -These are config files to set up a system the way I like it. - - -== Installation - - git clone git://github.com/ryanb/dotfiles ~/.dotfiles - cd ~/.dotfiles - rake install - - -== Environment - -I am running on Mac OS X, but it will likely work on Linux as well with -minor fiddling. I primarily use zsh, but this includes some older bash -files as well. If you would like to switch to zsh, you can do so with -the following command. - - chsh -s /bin/zsh - - -== Features - -I normally place all of my coding projects in ~/code, so this directory -can easily be accessed (and tab completed) with the "c" command. - - c railsca - -There is also an "h" command which behaves similar, but acts on the -home path. - - h doc - -Tab completion is also added to rake and cap commands: - - rake db:mi - cap de - -To speed things up, the results are cached in local .rake_tasks~ and -.cap_tasks~. It is smart enough to expire the cache automatically in -most cases, but you can simply remove the files to flush the cache. - -There are a few key bindings set. Many of these require option to be -set as the meta key. Option-left/right arrow will move cursor by word, -and control-left/right will move to beginning and end of line. -Control-option-N will open a new tab with the current directory under -Mac OS X Terminal. - -If you're using git, you'll notice the current branch name shows up in -the prompt while in a git repository. - -If you're using Rails, you'll find some handy aliases (below). You can -also use show_log and hide_log in script/console to show the log inline. - - ss # script/server - sc # script/console - sg # script/generate - a # autotest - tlog # tail -f log/development.log - rst # touch tmp/restart.txt - migrate # rake db:migrate db:test:clone - scaffold # script/generate nifty_scaffold - -See the other aliases in ~/.zsh/aliases - -If there are some shell configuration settings which you want secure or -specific to one system, place it into a ~/.localrc file. This will be -loaded automatically if it exists. - -There are several features enabled in Ruby's irb including history and -completion. Many convenience methods are added as well such as "ri" -which can be used to get inline documentation in IRB. See irbrc and -railsrc files for details. diff --git a/Rakefile b/Rakefile deleted file mode 100644 index ab5af7fa6c..0000000000 --- a/Rakefile +++ /dev/null @@ -1,50 +0,0 @@ -require 'rake' -require 'erb' - -desc "install the dot files into user's home directory" -task :install do - replace_all = false - Dir['*'].each do |file| - next if %w[Rakefile README.rdoc LICENSE].include? file - - if File.exist?(File.join(ENV['HOME'], ".#{file.sub('.erb', '')}")) - if File.identical? file, File.join(ENV['HOME'], ".#{file.sub('.erb', '')}") - puts "identical ~/.#{file.sub('.erb', '')}" - elsif replace_all - replace_file(file) - else - print "overwrite ~/.#{file.sub('.erb', '')}? [ynaq] " - case $stdin.gets.chomp - when 'a' - replace_all = true - replace_file(file) - when 'y' - replace_file(file) - when 'q' - exit - else - puts "skipping ~/.#{file.sub('.erb', '')}" - end - end - else - link_file(file) - end - end -end - -def replace_file(file) - system %Q{rm -rf "$HOME/.#{file.sub('.erb', '')}"} - link_file(file) -end - -def link_file(file) - if file =~ /.erb$/ - puts "generating ~/.#{file.sub('.erb', '')}" - File.open(File.join(ENV['HOME'], ".#{file.sub('.erb', '')}"), 'w') do |new_file| - new_file.write ERB.new(File.read(file)).result(binding) - end - else - puts "linking ~/.#{file}" - system %Q{ln -s "$PWD/#{file}" "$HOME/.#{file}"} - end -end diff --git a/bash/aliases b/bash/aliases deleted file mode 100644 index 8da1e09f4e..0000000000 --- a/bash/aliases +++ /dev/null @@ -1,15 +0,0 @@ -. ~/.zsh/aliases - -# changing directory to code project -function c { cd ~/code/$1; } - -# alternative to "rails" command to use templates -function railsapp { - template=$1 - appname=$2 - shift 2 - rails $appname -m http://github.com/ryanb/rails-templates/raw/master/$template.rb $@ -} - -# misc -alias reload='. ~/.bash_profile' diff --git a/bash/completion_scripts/capistrano_completion b/bash/completion_scripts/capistrano_completion deleted file mode 100755 index d1d0967572..0000000000 --- a/bash/completion_scripts/capistrano_completion +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env ruby - -# to install, add the following line to your .bash_profile or .bashrc -# complete -C path/to/capistrano_completion -o default capistrano - -# Capistrano completion will return matching capistrano tasks given typed text. This -# way you can auto-complete tasks as you are typing them by hitting [tab] or [tab][tab] -# This also caches the capistrano tasks for optimium speed -class CapistranoCompletion - CACHE_FILE_NAME = '.cap_tasks~' - - def initialize(command) - @command = command - end - - def matches - exit 0 if capfile.nil? - matching_tasks.map do |task| - task.sub(typed_before_colon, '') - end - end - - private - - def typed - @command[/\s(.+?)$/, 1] || '' - end - - def typed_before_colon - typed[/.+\:/] || '' - end - - def matching_tasks - all_tasks.select do |task| - task[0, typed.length] == typed - end - end - - def all_tasks - cache_current? ? tasks_from_cache : generate_tasks - end - - def cache_current? - File.exist?(cache_file) && File.mtime(cache_file) >= File.mtime(capfile) - end - - def capfile - ['capfile', 'Capfile', 'capfile.rb', 'Capfile.rb'].detect do |file| - File.file? File.join(Dir.pwd, file) - end - end - - def cache_file - File.join(Dir.pwd, CACHE_FILE_NAME) - end - - def tasks_from_cache - IO.read(cache_file).split - end - - def generate_tasks - tasks = `cap --tasks`.split("\n")[1..-8].collect {|line| line.split[1]} - File.open(cache_file, 'w') { |f| f.write tasks.join("\n") } - tasks - end -end - -puts CapistranoCompletion.new(ENV["COMP_LINE"]).matches -exit 0 diff --git a/bash/completion_scripts/git_completion b/bash/completion_scripts/git_completion deleted file mode 100755 index 0d33f9a3dc..0000000000 --- a/bash/completion_scripts/git_completion +++ /dev/null @@ -1,1265 +0,0 @@ -# -# bash completion support for core Git. -# -# Copyright (C) 2006,2007 Shawn O. Pearce -# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/). -# Distributed under the GNU General Public License, version 2.0. -# -# The contained completion routines provide support for completing: -# -# *) local and remote branch names -# *) local and remote tag names -# *) .git/remotes file names -# *) git 'subcommands' -# *) tree paths within 'ref:path/to/file' expressions -# *) common --long-options -# -# To use these routines: -# -# 1) Copy this file to somewhere (e.g. ~/.git-completion.sh). -# 2) Added the following line to your .bashrc: -# source ~/.git-completion.sh -# -# 3) You may want to make sure the git executable is available -# in your PATH before this script is sourced, as some caching -# is performed while the script loads. If git isn't found -# at source time then all lookups will be done on demand, -# which may be slightly slower. -# -# 4) Consider changing your PS1 to also show the current branch: -# PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ ' -# -# The argument to __git_ps1 will be displayed only if you -# are currently in a git repository. The %s token will be -# the name of the current branch. -# -# To submit patches: -# -# *) Read Documentation/SubmittingPatches -# *) Send all patches to the current maintainer: -# -# "Shawn O. Pearce" -# -# *) Always CC the Git mailing list: -# -# git@vger.kernel.org -# - -__gitdir () -{ - if [ -z "$1" ]; then - if [ -n "$__git_dir" ]; then - echo "$__git_dir" - elif [ -d .git ]; then - echo .git - else - git rev-parse --git-dir 2>/dev/null - fi - elif [ -d "$1/.git" ]; then - echo "$1/.git" - else - echo "$1" - fi -} - -__git_ps1 () -{ - local b="$(git symbolic-ref HEAD 2>/dev/null)" - if [ -n "$b" ]; then - if [ -n "$1" ]; then - printf "$1" "${b##refs/heads/}" - else - printf " (%s)" "${b##refs/heads/}" - fi - fi -} - -__gitcomp () -{ - local all c s=$'\n' IFS=' '$'\t'$'\n' - local cur="${COMP_WORDS[COMP_CWORD]}" - if [ $# -gt 2 ]; then - cur="$3" - fi - for c in $1; do - case "$c$4" in - --*=*) all="$all$c$4$s" ;; - *.) all="$all$c$4$s" ;; - *) all="$all$c$4 $s" ;; - esac - done - IFS=$s - COMPREPLY=($(compgen -P "$2" -W "$all" -- "$cur")) - return -} - -__git_heads () -{ - local cmd i is_hash=y dir="$(__gitdir "$1")" - if [ -d "$dir" ]; then - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/heads ); do - echo "${i#refs/heads/}" - done - return - fi - for i in $(git-ls-remote "$1" 2>/dev/null); do - case "$is_hash,$i" in - y,*) is_hash=n ;; - n,*^{}) is_hash=y ;; - n,refs/heads/*) is_hash=y; echo "${i#refs/heads/}" ;; - n,*) is_hash=y; echo "$i" ;; - esac - done -} - -__git_tags () -{ - local cmd i is_hash=y dir="$(__gitdir "$1")" - if [ -d "$dir" ]; then - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/tags ); do - echo "${i#refs/tags/}" - done - return - fi - for i in $(git-ls-remote "$1" 2>/dev/null); do - case "$is_hash,$i" in - y,*) is_hash=n ;; - n,*^{}) is_hash=y ;; - n,refs/tags/*) is_hash=y; echo "${i#refs/tags/}" ;; - n,*) is_hash=y; echo "$i" ;; - esac - done -} - -__git_refs () -{ - local cmd i is_hash=y dir="$(__gitdir "$1")" - if [ -d "$dir" ]; then - if [ -e "$dir/HEAD" ]; then echo HEAD; fi - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/tags refs/heads refs/remotes); do - case "$i" in - refs/tags/*) echo "${i#refs/tags/}" ;; - refs/heads/*) echo "${i#refs/heads/}" ;; - refs/remotes/*) echo "${i#refs/remotes/}" ;; - *) echo "$i" ;; - esac - done - return - fi - for i in $(git-ls-remote "$dir" 2>/dev/null); do - case "$is_hash,$i" in - y,*) is_hash=n ;; - n,*^{}) is_hash=y ;; - n,refs/tags/*) is_hash=y; echo "${i#refs/tags/}" ;; - n,refs/heads/*) is_hash=y; echo "${i#refs/heads/}" ;; - n,refs/remotes/*) is_hash=y; echo "${i#refs/remotes/}" ;; - n,*) is_hash=y; echo "$i" ;; - esac - done -} - -__git_refs2 () -{ - local i - for i in $(__git_refs "$1"); do - echo "$i:$i" - done -} - -__git_refs_remotes () -{ - local cmd i is_hash=y - for i in $(git-ls-remote "$1" 2>/dev/null); do - case "$is_hash,$i" in - n,refs/heads/*) - is_hash=y - echo "$i:refs/remotes/$1/${i#refs/heads/}" - ;; - y,*) is_hash=n ;; - n,*^{}) is_hash=y ;; - n,refs/tags/*) is_hash=y;; - n,*) is_hash=y; ;; - esac - done -} - -__git_remotes () -{ - local i ngoff IFS=$'\n' d="$(__gitdir)" - shopt -q nullglob || ngoff=1 - shopt -s nullglob - for i in "$d/remotes"/*; do - echo ${i#$d/remotes/} - done - [ "$ngoff" ] && shopt -u nullglob - for i in $(git --git-dir="$d" config --list); do - case "$i" in - remote.*.url=*) - i="${i#remote.}" - echo "${i/.url=*/}" - ;; - esac - done -} - -__git_merge_strategies () -{ - if [ -n "$__git_merge_strategylist" ]; then - echo "$__git_merge_strategylist" - return - fi - sed -n "/^all_strategies='/{ - s/^all_strategies='// - s/'// - p - q - }" "$(git --exec-path)/git-merge" -} -__git_merge_strategylist= -__git_merge_strategylist="$(__git_merge_strategies 2>/dev/null)" - -__git_complete_file () -{ - local pfx ls ref cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - ?*:*) - ref="${cur%%:*}" - cur="${cur#*:}" - case "$cur" in - ?*/*) - pfx="${cur%/*}" - cur="${cur##*/}" - ls="$ref:$pfx" - pfx="$pfx/" - ;; - *) - ls="$ref" - ;; - esac - COMPREPLY=($(compgen -P "$pfx" \ - -W "$(git --git-dir="$(__gitdir)" ls-tree "$ls" \ - | sed '/^100... blob /s,^.* ,, - /^040000 tree /{ - s,^.* ,, - s,$,/, - } - s/^.* //')" \ - -- "$cur")) - ;; - *) - __gitcomp "$(__git_refs)" - ;; - esac -} - -__git_complete_revlist () -{ - local pfx cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - *...*) - pfx="${cur%...*}..." - cur="${cur#*...}" - __gitcomp "$(__git_refs)" "$pfx" "$cur" - ;; - *..*) - pfx="${cur%..*}.." - cur="${cur#*..}" - __gitcomp "$(__git_refs)" "$pfx" "$cur" - ;; - *.) - __gitcomp "$cur." - ;; - *) - __gitcomp "$(__git_refs)" - ;; - esac -} - -__git_commands () -{ - if [ -n "$__git_commandlist" ]; then - echo "$__git_commandlist" - return - fi - local i IFS=" "$'\n' - for i in $(git help -a|egrep '^ ') - do - case $i in - *--*) : helper pattern;; - applymbox) : ask gittus;; - applypatch) : ask gittus;; - archimport) : import;; - cat-file) : plumbing;; - check-attr) : plumbing;; - check-ref-format) : plumbing;; - commit-tree) : plumbing;; - cvsexportcommit) : export;; - cvsimport) : import;; - cvsserver) : daemon;; - daemon) : daemon;; - diff-files) : plumbing;; - diff-index) : plumbing;; - diff-tree) : plumbing;; - fast-import) : import;; - fsck-objects) : plumbing;; - fetch-pack) : plumbing;; - fmt-merge-msg) : plumbing;; - for-each-ref) : plumbing;; - hash-object) : plumbing;; - http-*) : transport;; - index-pack) : plumbing;; - init-db) : deprecated;; - local-fetch) : plumbing;; - mailinfo) : plumbing;; - mailsplit) : plumbing;; - merge-*) : plumbing;; - mktree) : plumbing;; - mktag) : plumbing;; - pack-objects) : plumbing;; - pack-redundant) : plumbing;; - pack-refs) : plumbing;; - parse-remote) : plumbing;; - patch-id) : plumbing;; - peek-remote) : plumbing;; - prune) : plumbing;; - prune-packed) : plumbing;; - quiltimport) : import;; - read-tree) : plumbing;; - receive-pack) : plumbing;; - reflog) : plumbing;; - repo-config) : deprecated;; - rerere) : plumbing;; - rev-list) : plumbing;; - rev-parse) : plumbing;; - runstatus) : plumbing;; - sh-setup) : internal;; - shell) : daemon;; - send-pack) : plumbing;; - show-index) : plumbing;; - ssh-*) : transport;; - stripspace) : plumbing;; - svn) : import export;; - symbolic-ref) : plumbing;; - tar-tree) : deprecated;; - unpack-file) : plumbing;; - unpack-objects) : plumbing;; - update-index) : plumbing;; - update-ref) : plumbing;; - update-server-info) : daemon;; - upload-archive) : plumbing;; - upload-pack) : plumbing;; - write-tree) : plumbing;; - verify-tag) : plumbing;; - *) echo $i;; - esac - done -} -__git_commandlist= -__git_commandlist="$(__git_commands 2>/dev/null)" - -__git_aliases () -{ - local i IFS=$'\n' - for i in $(git --git-dir="$(__gitdir)" config --list); do - case "$i" in - alias.*) - i="${i#alias.}" - echo "${i/=*/}" - ;; - esac - done -} - -__git_aliased_command () -{ - local word cmdline=$(git --git-dir="$(__gitdir)" \ - config --get "alias.$1") - for word in $cmdline; do - if [ "${word##-*}" ]; then - echo $word - return - fi - done -} - -__git_whitespacelist="nowarn warn error error-all strip" - -_git_am () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - if [ -d .dotest ]; then - __gitcomp "--skip --resolved" - return - fi - case "$cur" in - --whitespace=*) - __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" - return - ;; - --*) - __gitcomp " - --signoff --utf8 --binary --3way --interactive - --whitespace= - " - return - esac - COMPREPLY=() -} - -_git_apply () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --whitespace=*) - __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" - return - ;; - --*) - __gitcomp " - --stat --numstat --summary --check --index - --cached --index-info --reverse --reject --unidiff-zero - --apply --no-add --exclude= - --whitespace= --inaccurate-eof --verbose - " - return - esac - COMPREPLY=() -} - -_git_add () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--interactive --refresh" - return - esac - COMPREPLY=() -} - -_git_bisect () -{ - local i c=1 command - while [ $c -lt $COMP_CWORD ]; do - i="${COMP_WORDS[c]}" - case "$i" in - start|bad|good|reset|visualize|replay|log) - command="$i" - break - ;; - esac - c=$((++c)) - done - - if [ $c -eq $COMP_CWORD -a -z "$command" ]; then - __gitcomp "start bad good reset visualize replay log" - return - fi - - case "$command" in - bad|good|reset) - __gitcomp "$(__git_refs)" - ;; - *) - COMPREPLY=() - ;; - esac -} - -_git_branch () -{ - __gitcomp "$(__git_refs)" -} - -_git_bundle () -{ - local mycword="$COMP_CWORD" - case "${COMP_WORDS[0]}" in - git) - local cmd="${COMP_WORDS[2]}" - mycword="$((mycword-1))" - ;; - git-bundle*) - local cmd="${COMP_WORDS[1]}" - ;; - esac - case "$mycword" in - 1) - __gitcomp "create list-heads verify unbundle" - ;; - 2) - # looking for a file - ;; - *) - case "$cmd" in - create) - __git_complete_revlist - ;; - esac - ;; - esac -} - -_git_checkout () -{ - __gitcomp "$(__git_refs)" -} - -_git_cherry () -{ - __gitcomp "$(__git_refs)" -} - -_git_cherry_pick () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--edit --no-commit" - ;; - *) - __gitcomp "$(__git_refs)" - ;; - esac -} - -_git_commit () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp " - --all --author= --signoff --verify --no-verify - --edit --amend --include --only - " - return - esac - COMPREPLY=() -} - -_git_describe () -{ - __gitcomp "$(__git_refs)" -} - -_git_diff () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--cached --stat --numstat --shortstat --summary - --patch-with-stat --name-only --name-status --color - --no-color --color-words --no-renames --check - --full-index --binary --abbrev --diff-filter - --find-copies-harder --pickaxe-all --pickaxe-regex - --text --ignore-space-at-eol --ignore-space-change - --ignore-all-space --exit-code --quiet --ext-diff - --no-ext-diff" - return - ;; - esac - __git_complete_file -} - -_git_diff_tree () -{ - __gitcomp "$(__git_refs)" -} - -_git_fetch () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-fetch*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) - __gitcomp "$(__git_remotes)" - ;; - *) - case "$cur" in - *:*) - __gitcomp "$(__git_refs)" "" "${cur#*:}" - ;; - *) - local remote - case "${COMP_WORDS[0]}" in - git-fetch) remote="${COMP_WORDS[1]}" ;; - git) remote="${COMP_WORDS[2]}" ;; - esac - __gitcomp "$(__git_refs2 "$remote")" - ;; - esac - ;; - esac -} - -_git_format_patch () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp " - --stdout --attach --thread - --output-directory - --numbered --start-number - --numbered-files - --keep-subject - --signoff - --in-reply-to= - --full-index --binary - --not --all - " - return - ;; - esac - __git_complete_revlist -} - -_git_gc () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--prune --aggressive" - return - ;; - esac - COMPREPLY=() -} - -_git_ls_remote () -{ - __gitcomp "$(__git_remotes)" -} - -_git_ls_tree () -{ - __git_complete_file -} - -_git_log () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --pretty=*) - __gitcomp " - oneline short medium full fuller email raw - " "" "${cur##--pretty=}" - return - ;; - --date=*) - __gitcomp " - relative iso8601 rfc2822 short local default - " "" "${cur##--date=}" - return - ;; - --*) - __gitcomp " - --max-count= --max-age= --since= --after= - --min-age= --before= --until= - --root --topo-order --date-order --reverse - --no-merges --follow - --abbrev-commit --abbrev= - --relative-date --date= - --author= --committer= --grep= - --all-match - --pretty= --name-status --name-only --raw - --not --all - --left-right --cherry-pick - " - return - ;; - esac - __git_complete_revlist -} - -_git_merge () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "${COMP_WORDS[COMP_CWORD-1]}" in - -s|--strategy) - __gitcomp "$(__git_merge_strategies)" - return - esac - case "$cur" in - --strategy=*) - __gitcomp "$(__git_merge_strategies)" "" "${cur##--strategy=}" - return - ;; - --*) - __gitcomp " - --no-commit --no-summary --squash --strategy - " - return - esac - __gitcomp "$(__git_refs)" -} - -_git_merge_base () -{ - __gitcomp "$(__git_refs)" -} - -_git_name_rev () -{ - __gitcomp "--tags --all --stdin" -} - -_git_pull () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-pull*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) - __gitcomp "$(__git_remotes)" - ;; - *) - local remote - case "${COMP_WORDS[0]}" in - git-pull) remote="${COMP_WORDS[1]}" ;; - git) remote="${COMP_WORDS[2]}" ;; - esac - __gitcomp "$(__git_refs "$remote")" - ;; - esac -} - -_git_push () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-push*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) - __gitcomp "$(__git_remotes)" - ;; - *) - case "$cur" in - *:*) - local remote - case "${COMP_WORDS[0]}" in - git-push) remote="${COMP_WORDS[1]}" ;; - git) remote="${COMP_WORDS[2]}" ;; - esac - __gitcomp "$(__git_refs "$remote")" "" "${cur#*:}" - ;; - +*) - __gitcomp "$(__git_refs)" + "${cur#+}" - ;; - *) - __gitcomp "$(__git_refs)" - ;; - esac - ;; - esac -} - -_git_rebase () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - if [ -d .dotest ] || [ -d .git/.dotest-merge ]; then - __gitcomp "--continue --skip --abort" - return - fi - case "${COMP_WORDS[COMP_CWORD-1]}" in - -s|--strategy) - __gitcomp "$(__git_merge_strategies)" - return - esac - case "$cur" in - --strategy=*) - __gitcomp "$(__git_merge_strategies)" "" "${cur##--strategy=}" - return - ;; - --*) - __gitcomp "--onto --merge --strategy" - return - esac - __gitcomp "$(__git_refs)" -} - -_git_config () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - local prv="${COMP_WORDS[COMP_CWORD-1]}" - case "$prv" in - branch.*.remote) - __gitcomp "$(__git_remotes)" - return - ;; - branch.*.merge) - __gitcomp "$(__git_refs)" - return - ;; - remote.*.fetch) - local remote="${prv#remote.}" - remote="${remote%.fetch}" - __gitcomp "$(__git_refs_remotes "$remote")" - return - ;; - remote.*.push) - local remote="${prv#remote.}" - remote="${remote%.push}" - __gitcomp "$(git --git-dir="$(__gitdir)" \ - for-each-ref --format='%(refname):%(refname)' \ - refs/heads)" - return - ;; - pull.twohead|pull.octopus) - __gitcomp "$(__git_merge_strategies)" - return - ;; - color.branch|color.diff|color.status) - __gitcomp "always never auto" - return - ;; - color.*.*) - __gitcomp " - black red green yellow blue magenta cyan white - bold dim ul blink reverse - " - return - ;; - *.*) - COMPREPLY=() - return - ;; - esac - case "$cur" in - --*) - __gitcomp " - --global --system --file= - --list --replace-all - --get --get-all --get-regexp - --add --unset --unset-all - --remove-section --rename-section - " - return - ;; - branch.*.*) - local pfx="${cur%.*}." - cur="${cur##*.}" - __gitcomp "remote merge" "$pfx" "$cur" - return - ;; - branch.*) - local pfx="${cur%.*}." - cur="${cur#*.}" - __gitcomp "$(__git_heads)" "$pfx" "$cur" "." - return - ;; - remote.*.*) - local pfx="${cur%.*}." - cur="${cur##*.}" - __gitcomp " - url fetch push skipDefaultUpdate - receivepack uploadpack tagopt - " "$pfx" "$cur" - return - ;; - remote.*) - local pfx="${cur%.*}." - cur="${cur#*.}" - __gitcomp "$(__git_remotes)" "$pfx" "$cur" "." - return - ;; - esac - __gitcomp " - apply.whitespace - core.fileMode - core.gitProxy - core.ignoreStat - core.preferSymlinkRefs - core.logAllRefUpdates - core.loosecompression - core.repositoryFormatVersion - core.sharedRepository - core.warnAmbiguousRefs - core.compression - core.legacyHeaders - core.packedGitWindowSize - core.packedGitLimit - clean.requireForce - color.branch - color.branch.current - color.branch.local - color.branch.remote - color.branch.plain - color.diff - color.diff.plain - color.diff.meta - color.diff.frag - color.diff.old - color.diff.new - color.diff.commit - color.diff.whitespace - color.pager - color.status - color.status.header - color.status.added - color.status.changed - color.status.untracked - diff.renameLimit - diff.renames - fetch.unpackLimit - format.headers - format.subjectprefix - gitcvs.enabled - gitcvs.logfile - gitcvs.allbinary - gitcvs.dbname gitcvs.dbdriver gitcvs.dbuser gitcvs.dvpass - gc.packrefs - gc.reflogexpire - gc.reflogexpireunreachable - gc.rerereresolved - gc.rerereunresolved - http.sslVerify - http.sslCert - http.sslKey - http.sslCAInfo - http.sslCAPath - http.maxRequests - http.lowSpeedLimit - http.lowSpeedTime - http.noEPSV - i18n.commitEncoding - i18n.logOutputEncoding - log.showroot - merge.tool - merge.summary - merge.verbosity - pack.window - pack.depth - pack.windowMemory - pack.compression - pack.deltaCacheSize - pack.deltaCacheLimit - pull.octopus - pull.twohead - repack.useDeltaBaseOffset - show.difftree - showbranch.default - tar.umask - transfer.unpackLimit - receive.unpackLimit - receive.denyNonFastForwards - user.name - user.email - user.signingkey - whatchanged.difftree - branch. remote. - " -} - -_git_remote () -{ - local i c=1 command - while [ $c -lt $COMP_CWORD ]; do - i="${COMP_WORDS[c]}" - case "$i" in - add|rm|show|prune|update) command="$i"; break ;; - esac - c=$((++c)) - done - - if [ $c -eq $COMP_CWORD -a -z "$command" ]; then - __gitcomp "add rm show prune update" - return - fi - - case "$command" in - rm|show|prune) - __gitcomp "$(__git_remotes)" - ;; - update) - local i c='' IFS=$'\n' - for i in $(git --git-dir="$(__gitdir)" config --list); do - case "$i" in - remotes.*) - i="${i#remotes.}" - c="$c ${i/=*/}" - ;; - esac - done - __gitcomp "$c" - ;; - *) - COMPREPLY=() - ;; - esac -} - -_git_reset () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--mixed --hard --soft" - return - ;; - esac - __gitcomp "$(__git_refs)" -} - -_git_shortlog () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp " - --max-count= --max-age= --since= --after= - --min-age= --before= --until= - --no-merges - --author= --committer= --grep= - --all-match - --not --all - --numbered --summary - " - return - ;; - esac - __git_complete_revlist -} - -_git_show () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --pretty=*) - __gitcomp " - oneline short medium full fuller email raw - " "" "${cur##--pretty=}" - return - ;; - --*) - __gitcomp "--pretty=" - return - ;; - esac - __git_complete_file -} - -_git_stash () -{ - __gitcomp 'list show apply clear' -} - -_git_submodule () -{ - local i c=1 command - while [ $c -lt $COMP_CWORD ]; do - i="${COMP_WORDS[c]}" - case "$i" in - add|status|init|update) command="$i"; break ;; - esac - c=$((++c)) - done - - if [ $c -eq $COMP_CWORD -a -z "$command" ]; then - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--quiet --cached" - ;; - *) - __gitcomp "add status init update" - ;; - esac - return - fi -} - -_git_tag () -{ - local i c=1 f=0 - while [ $c -lt $COMP_CWORD ]; do - i="${COMP_WORDS[c]}" - case "$i" in - -d|-v) - __gitcomp "$(__git_tags)" - return - ;; - -f) - f=1 - ;; - esac - c=$((++c)) - done - - case "${COMP_WORDS[COMP_CWORD-1]}" in - -m|-F) - COMPREPLY=() - ;; - -*|tag|git-tag) - if [ $f = 1 ]; then - __gitcomp "$(__git_tags)" - else - COMPREPLY=() - fi - ;; - *) - __gitcomp "$(__git_refs)" - ;; - esac -} - -_git () -{ - local i c=1 command __git_dir - - while [ $c -lt $COMP_CWORD ]; do - i="${COMP_WORDS[c]}" - case "$i" in - --git-dir=*) __git_dir="${i#--git-dir=}" ;; - --bare) __git_dir="." ;; - --version|--help|-p|--paginate) ;; - *) command="$i"; break ;; - esac - c=$((++c)) - done - - if [ $c -eq $COMP_CWORD -a -z "$command" ]; then - case "${COMP_WORDS[COMP_CWORD]}" in - --*=*) COMPREPLY=() ;; - --*) __gitcomp " - --no-pager - --git-dir= - --bare - --version - --exec-path - " - ;; - *) __gitcomp "$(__git_commands) $(__git_aliases)" ;; - esac - return - fi - - local expansion=$(__git_aliased_command "$command") - [ "$expansion" ] && command="$expansion" - - case "$command" in - am) _git_am ;; - add) _git_add ;; - apply) _git_apply ;; - bisect) _git_bisect ;; - bundle) _git_bundle ;; - branch) _git_branch ;; - checkout) _git_checkout ;; - cherry) _git_cherry ;; - cherry-pick) _git_cherry_pick ;; - commit) _git_commit ;; - config) _git_config ;; - describe) _git_describe ;; - diff) _git_diff ;; - fetch) _git_fetch ;; - format-patch) _git_format_patch ;; - gc) _git_gc ;; - log) _git_log ;; - ls-remote) _git_ls_remote ;; - ls-tree) _git_ls_tree ;; - merge) _git_merge;; - merge-base) _git_merge_base ;; - name-rev) _git_name_rev ;; - pull) _git_pull ;; - push) _git_push ;; - rebase) _git_rebase ;; - remote) _git_remote ;; - reset) _git_reset ;; - shortlog) _git_shortlog ;; - show) _git_show ;; - show-branch) _git_log ;; - stash) _git_stash ;; - submodule) _git_submodule ;; - tag) _git_tag ;; - whatchanged) _git_log ;; - *) COMPREPLY=() ;; - esac -} - -_gitk () -{ - local cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - --*) - __gitcomp "--not --all" - return - ;; - esac - __git_complete_revlist -} - -complete -o default -o nospace -F _git git -complete -o default -o nospace -F _gitk gitk -complete -o default -o nospace -F _git_am git-am -complete -o default -o nospace -F _git_apply git-apply -complete -o default -o nospace -F _git_bisect git-bisect -complete -o default -o nospace -F _git_branch git-branch -complete -o default -o nospace -F _git_bundle git-bundle -complete -o default -o nospace -F _git_checkout git-checkout -complete -o default -o nospace -F _git_cherry git-cherry -complete -o default -o nospace -F _git_cherry_pick git-cherry-pick -complete -o default -o nospace -F _git_commit git-commit -complete -o default -o nospace -F _git_describe git-describe -complete -o default -o nospace -F _git_diff git-diff -complete -o default -o nospace -F _git_fetch git-fetch -complete -o default -o nospace -F _git_format_patch git-format-patch -complete -o default -o nospace -F _git_gc git-gc -complete -o default -o nospace -F _git_log git-log -complete -o default -o nospace -F _git_ls_remote git-ls-remote -complete -o default -o nospace -F _git_ls_tree git-ls-tree -complete -o default -o nospace -F _git_merge git-merge -complete -o default -o nospace -F _git_merge_base git-merge-base -complete -o default -o nospace -F _git_name_rev git-name-rev -complete -o default -o nospace -F _git_pull git-pull -complete -o default -o nospace -F _git_push git-push -complete -o default -o nospace -F _git_rebase git-rebase -complete -o default -o nospace -F _git_config git-config -complete -o default -o nospace -F _git_remote git-remote -complete -o default -o nospace -F _git_reset git-reset -complete -o default -o nospace -F _git_shortlog git-shortlog -complete -o default -o nospace -F _git_show git-show -complete -o default -o nospace -F _git_stash git-stash -complete -o default -o nospace -F _git_submodule git-submodule -complete -o default -o nospace -F _git_log git-show-branch -complete -o default -o nospace -F _git_tag git-tag -complete -o default -o nospace -F _git_log git-whatchanged - -# The following are necessary only for Cygwin, and only are needed -# when the user has tab-completed the executable name and consequently -# included the '.exe' suffix. -# -if [ Cygwin = "$(uname -o 2>/dev/null)" ]; then -complete -o default -o nospace -F _git_add git-add.exe -complete -o default -o nospace -F _git_apply git-apply.exe -complete -o default -o nospace -F _git git.exe -complete -o default -o nospace -F _git_branch git-branch.exe -complete -o default -o nospace -F _git_bundle git-bundle.exe -complete -o default -o nospace -F _git_cherry git-cherry.exe -complete -o default -o nospace -F _git_describe git-describe.exe -complete -o default -o nospace -F _git_diff git-diff.exe -complete -o default -o nospace -F _git_format_patch git-format-patch.exe -complete -o default -o nospace -F _git_log git-log.exe -complete -o default -o nospace -F _git_ls_tree git-ls-tree.exe -complete -o default -o nospace -F _git_merge_base git-merge-base.exe -complete -o default -o nospace -F _git_name_rev git-name-rev.exe -complete -o default -o nospace -F _git_push git-push.exe -complete -o default -o nospace -F _git_config git-config -complete -o default -o nospace -F _git_shortlog git-shortlog.exe -complete -o default -o nospace -F _git_show git-show.exe -complete -o default -o nospace -F _git_log git-show-branch.exe -complete -o default -o nospace -F _git_tag git-tag.exe -complete -o default -o nospace -F _git_log git-whatchanged.exe -fi diff --git a/bash/completion_scripts/project_completion b/bash/completion_scripts/project_completion deleted file mode 100755 index a1f1c1eeb4..0000000000 --- a/bash/completion_scripts/project_completion +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env ruby - -class ProjectCompletion - def initialize(command) - @command = command - end - - def matches - projects.select do |task| - task[0, typed.length] == typed - end - end - - def typed - @command[/\s(.+?)$/, 1] || '' - end - - def projects - `ls ~/code/`.split - end -end - -puts ProjectCompletion.new(ENV["COMP_LINE"]).matches -exit 0 diff --git a/bash/completion_scripts/rake_completion b/bash/completion_scripts/rake_completion deleted file mode 100755 index f72cb7df9b..0000000000 --- a/bash/completion_scripts/rake_completion +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env ruby - -# to install, add the following line to your .bash_profile or .bashrc -# complete -C path/to/rake_completion -o default rake - -# Rake completion will return matching rake tasks given typed text. This way -# you can auto-complete tasks as you are typing them by hitting [tab] or [tab][tab] -# This also caches the rake tasks for optimium speed -class RakeCompletion - CACHE_FILE_NAME = '.rake_tasks~' - - def initialize(command) - @command = command - end - - def matches - exit 0 if rakefile.nil? - matching_tasks.map do |task| - task.sub(typed_before_colon, '') - end - end - - private - - def typed - @command[/\s(.+?)$/, 1] || '' - end - - def typed_before_colon - typed[/.+\:/] || '' - end - - def matching_tasks - all_tasks.select do |task| - task[0, typed.length] == typed - end - end - - def all_tasks - cache_current? ? tasks_from_cache : generate_tasks - end - - def cache_current? - File.exist?(cache_file) && File.mtime(cache_file) >= File.mtime(rakefile) - end - - def rakefile - ['rakefile', 'Rakefile', 'rakefile.rb', 'Rakefile.rb'].detect do |file| - File.file? File.join(Dir.pwd, file) - end - end - - def cache_file - File.join(Dir.pwd, CACHE_FILE_NAME) - end - - def tasks_from_cache - IO.read(cache_file).split - end - - def generate_tasks - tasks = `rake --tasks`.split("\n")[1..-1].collect {|line| line.split[1]} - File.open(cache_file, 'w') { |f| f.write tasks.join("\n") } - tasks - end -end - -puts RakeCompletion.new(ENV["COMP_LINE"]).matches -exit 0 diff --git a/bash/completions b/bash/completions deleted file mode 100644 index ad63d01905..0000000000 --- a/bash/completions +++ /dev/null @@ -1,4 +0,0 @@ -source ~/.bash/completion_scripts/git_completion -complete -C ~/.bash/completion_scripts/rake_completion -o default rake -complete -C ~/.bash/completion_scripts/project_completion -o default c -complete -C ~/.bash/completion_scripts/capistrano_completion -o default cap diff --git a/bash/config b/bash/config deleted file mode 100644 index 5b9ec8298e..0000000000 --- a/bash/config +++ /dev/null @@ -1,2 +0,0 @@ -export PS1="\w$ " -export EDITOR="mate_wait" diff --git a/bash/paths b/bash/paths deleted file mode 100644 index 74da8d4fc5..0000000000 --- a/bash/paths +++ /dev/null @@ -1,2 +0,0 @@ -export PATH="~/bin:~/.bin:/usr/local/homebrew/bin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:/usr/local/git/bin:$PATH" -export MANPATH="/usr/local/man:/usr/local/mysql/man:/usr/local/git/man:$MANPATH" diff --git a/bash_profile b/bash_profile deleted file mode 100644 index b76e61b0ab..0000000000 --- a/bash_profile +++ /dev/null @@ -1,3 +0,0 @@ -if [ -f ~/.bashrc ]; then - source ~/.bashrc -fi diff --git a/bashrc b/bashrc deleted file mode 100644 index 28235cd419..0000000000 --- a/bashrc +++ /dev/null @@ -1,9 +0,0 @@ -source ~/.bash/aliases -source ~/.bash/completions -source ~/.bash/paths -source ~/.bash/config - -# use .localrc for settings specific to one system -if [ -f ~/.localrc ]; then - source ~/.localrc -fi diff --git a/bin/mate_wait b/bin/mate_wait deleted file mode 100755 index 78bd9fecac..0000000000 --- a/bin/mate_wait +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -mate -w diff --git a/bin/tagversions b/bin/tagversions deleted file mode 100755 index 4c0cb83956..0000000000 --- a/bin/tagversions +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env ruby -w - -class TagVersions - def initialize(args) - print_help if args.empty? - @regexp = nil - @preview = false - args.each do |argument| - case argument - when '-a', '--all' then @regexp = ".*" - when '-p', '--preview' then @preview = true - when '-h', '--help' then print_help - else @regexp = argument - end - end - end - - def print_help - puts <<-HELP -Usage: tagversions [OPTIONS] [REGEXP] - Look through the git commits for messages with the given regular expression and tag what looks like verisons. - - Options: - -a, --all Search all commits, not just the ones matching the regular expression. - -p, --preview Don't do actual branching, instead print out what will be tagged. - -h, --help Display this help page. -HELP - exit - end - - def run - tags = `git tag`.split("\n") - `git log --pretty="%H %s" | grep "#{@regexp}"`.split("\n").each do |line| - version = line[/\bv?(\d\.[\d\.]*)\b/, 1] - sha = line[/^\w+/] - if version && !version.empty? && !tags.include?(version) - puts "Tagging #{version} on #{sha}" - tags << version - `git tag -a "#{version}" -m "version #{version}" "#{sha}"` unless @preview - end - end - end -end - -TagVersions.new($*).run diff --git a/gemrc b/gemrc deleted file mode 100644 index 79434593bb..0000000000 --- a/gemrc +++ /dev/null @@ -1,10 +0,0 @@ ---- -:verbose: true -gem: --no-ri --no-rdoc -:update_sources: true -:sources: -- http://gems.rubyforge.org -- http://gems.github.com -:backtrace: false -:bulk_threshold: 1000 -:benchmark: false diff --git a/git/.gitconfig b/git/.gitconfig new file mode 100644 index 0000000000..e21856646a --- /dev/null +++ b/git/.gitconfig @@ -0,0 +1,43 @@ +[user] + name = Sebastian Marr +[alias] + a = add + u = checkout + c = commit + s = status -sb + b = branch + d = diff + pl = pull + ps = push + work = config user.email "sebastian@ulysses.app" + private = config user.email "mail@sebastianmarr.de" + l = log --pretty=format:'%C(blue)%h%Creset%C(yellow)%d%Creset %s %C(green)%cr %C(cyan)%an%Creset' --abbrev-commit + lg = log --pretty=format:'%C(blue)%h%Creset%C(yellow)%d%Creset %s %C(green)%cr %C(cyan)%an%Creset' --abbrev-commit --all --graph + dt = difftool + mt = mergetool +[color] + diff = auto + status = auto + branch = auto +[core] + excludesfile = ~/.gitignore_global + editor = vim +[apply] + whitespace = nowarn +[push] + default = current +[help] + autocorrect = 1 +[clean] + requireForce = false +[branch] + autosetuprebase = always +[filter "media"] + clean = git-media-clean %f + smudge = git-media-smudge %f +[rebase] + autoStash = true +[advice] + detachedHead = false +[init] + defaultBranch = main diff --git a/git/.gitignore_global b/git/.gitignore_global new file mode 100755 index 0000000000..9cc115775d --- /dev/null +++ b/git/.gitignore_global @@ -0,0 +1,10 @@ +.DS_Store +.svn +*~ +.*.swp +*.iml +*.ipr +*.iws +.idea/ +.elixir_ls/ +.vscode/ diff --git a/gitconfig.erb b/gitconfig.erb deleted file mode 100644 index c4daf6527d..0000000000 --- a/gitconfig.erb +++ /dev/null @@ -1,20 +0,0 @@ -[user] - name = <%= print("Your Name: "); STDOUT.flush; STDIN.gets.chomp %> - email = <%= print("Your Email: "); STDOUT.flush; STDIN.gets.chomp %> -[alias] - co = checkout -[color] - diff = auto - status = auto - branch = auto -[core] - excludesfile = <%= ENV['HOME'] %>/.gitignore - editor = mate_wait - autocrlf = input -[apply] - whitespace = nowarn -[format] - pretty = %C(yellow)%h%Creset %s %C(red)(%an, %cr)%Creset -[github] - user = <%= print("GitHub Username: "); STDOUT.flush; STDIN.gets.chomp %> - token = <%= print("GitHub API Token: "); STDOUT.flush; STDIN.gets.chomp %> diff --git a/gitignore b/gitignore deleted file mode 100755 index c5582434d0..0000000000 --- a/gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -.svn -*~ -.*.swp diff --git a/gvimrc b/gvimrc deleted file mode 100644 index 8a5f9e43d9..0000000000 --- a/gvimrc +++ /dev/null @@ -1,6 +0,0 @@ -set guioptions-=T " hide toolbar -set lines=55 columns=100 - -colorscheme railscasts - -set guifont=DejaVu\ Sans\ Mono:h13 diff --git a/install.sh b/install.sh new file mode 100755 index 0000000000..2292d5982c --- /dev/null +++ b/install.sh @@ -0,0 +1,15 @@ +#! /bin/sh + +if ! type "git" > /dev/null; then + echo "Please install git first." + exit 1 +fi + +if ! type "stow" > /dev/null; then + echo "Please install stow first." + exit 1 +fi + +git submodule init +git submodule update +stow tmux zsh git irb vim diff --git a/irb/.irbrc b/irb/.irbrc new file mode 100644 index 0000000000..4178dc3f85 --- /dev/null +++ b/irb/.irbrc @@ -0,0 +1 @@ +require 'irb/completion' \ No newline at end of file diff --git a/irbrc b/irbrc deleted file mode 100644 index 33670180b6..0000000000 --- a/irbrc +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/ruby -require 'irb/completion' -require 'irb/ext/save-history' - -IRB.conf[:SAVE_HISTORY] = 1000 -IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb_history" - -IRB.conf[:PROMPT_MODE] = :SIMPLE - -%w[rubygems looksee/shortcuts wirble].each do |gem| - begin - require gem - rescue LoadError - end -end - -class Object - # list methods which aren't in superclass - def local_methods(obj = self) - (obj.methods - obj.class.superclass.instance_methods).sort - end - - # print documentation - # - # ri 'Array#pop' - # Array.ri - # Array.ri :pop - # arr.ri :pop - def ri(method = nil) - unless method && method =~ /^[A-Z]/ # if class isn't specified - klass = self.kind_of?(Class) ? name : self.class.name - method = [klass, method].compact.join('#') - end - system 'ri', method.to_s - end -end - -def copy(str) - IO.popen('pbcopy', 'w') { |f| f << str.to_s } -end - -def copy_history - history = Readline::HISTORY.entries - index = history.rindex("exit") || -1 - content = history[(index+1)..-2].join("\n") - puts content - copy content -end - -def paste - `pbpaste` -end - -load File.dirname(__FILE__) + '/.railsrc' if ($0 == 'irb' && ENV['RAILS_ENV']) || ($0 == 'script/rails' && Rails.env) diff --git a/railsrc b/railsrc deleted file mode 100644 index 2ed96731cc..0000000000 --- a/railsrc +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/ruby - -begin - require 'hirb' # sudo gem install cldwalker-hirb --source http://gems.github.com - Hirb.enable -rescue LoadError -end - -def change_log(stream) - ActiveRecord::Base.logger = Logger.new(stream) - ActiveRecord::Base.clear_active_connections! -end - -def show_log - change_log(STDOUT) -end - -def hide_log - change_log(nil) -end diff --git a/tmux/.tmux.conf b/tmux/.tmux.conf new file mode 100644 index 0000000000..0e36fc7ab8 --- /dev/null +++ b/tmux/.tmux.conf @@ -0,0 +1,37 @@ +# needed or stuff breaks on mac os +set -g default-terminal screen-256color + +# nested tmux sessions +bind-key b send-prefix +# bigger scroll buffer +set -g history-limit 20000 + +# start window indexing at 1 +set -g base-index 1 + +# use current directory as path for new windows and panes +bind '"' split-window -c "#{pane_current_path}" +bind % split-window -h -c "#{pane_current_path}" +bind c new-window -c "#{pane_current_path}" + +# use current directory as window name +set-option -g status-interval 5 +set-option -g automatic-rename on +set-option -g automatic-rename-format '#{b:pane_current_path}' + +# automatically reorder windows +set -g renumber-windows on + +# This toggles the synchronize-panes feature +bind-key a set-window-option synchronize-panes +# This allows killing the whole session with a simple short cut: +bind-key X kill-session + +# Enable mouse mode +set -g mouse on +bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'" +bind -n WheelDownPane select-pane -t= \; send-keys -M + +# Various Copy Mode magic +setw -g mode-keys vi +bind-key -T copy-mode-vi y send -X copy-pipe-and-cancel "pbcopy" diff --git a/vim/.vimrc b/vim/.vimrc new file mode 100644 index 0000000000..10a33b982c --- /dev/null +++ b/vim/.vimrc @@ -0,0 +1,12 @@ +set nocompatible +syntax enable +filetype plugin indent on +set showmode +set hidden +set number +set ruler +set incsearch +set hlsearch +set nobackup +set nowritebackup + diff --git a/vim/after/plugin/TabularMaps.vim b/vim/after/plugin/TabularMaps.vim deleted file mode 100755 index 20f7141410..0000000000 --- a/vim/after/plugin/TabularMaps.vim +++ /dev/null @@ -1,48 +0,0 @@ -if !exists(':Tabularize') - finish " Tabular.vim wasn't loaded -endif - -let s:save_cpo = &cpo -set cpo&vim - -AddTabularPattern! assignment /[|&+*/%<>=!~-]\@!=]=\|=\~\)\@![|&+*/%<>=!~-]*=/l1r1 -AddTabularPattern! two_spaces / /l0 - -AddTabularPipeline! multiple_spaces / / map(a:lines, "substitute(v:val, ' *', ' ', 'g')") | tabular#TabularizeStrings(a:lines, ' ', 'l0') - -AddTabularPipeline! argument_list /(.*)/ map(a:lines, 'substitute(v:val, ''\s*\([(,)]\)\s*'', ''\1'', ''g'')') - \ | tabular#TabularizeStrings(a:lines, '[(,)]', 'l0') - \ | map(a:lines, 'substitute(v:val, ''\(\s*\),'', '',\1 '', "g")') - \ | map(a:lines, 'substitute(v:val, ''\s*)'', ")", "g")') - -function! SplitCDeclarations(lines) - let rv = [] - for line in a:lines - " split the line into declaractions - let split = split(line, '\s*[,;]\s*') - " separate the type from the first declaration - let type = substitute(split[0], '\%(\%([&*]\s*\)*\)\=\k\+$', '', '') - " add the ; back on every declaration - call map(split, 'v:val . ";"') - " add the first element to the return as-is, and remove it from the list - let rv += [ remove(split, 0) ] - " transform the other elements by adding the type on at the beginning - call map(split, 'type . v:val') - " and add them all to the return - let rv += split - endfor - return rv -endfunction - -AddTabularPipeline! split_declarations /,.*;/ SplitCDeclarations(a:lines) - -AddTabularPattern! ternary_operator /^.\{-}\zs?\|:/l1 - -AddTabularPattern! cpp_io /<<\|>>/l1 - -AddTabularPattern! pascal_assign /:=/l1 - -AddTabularPattern! trailing_c_comments /\/\*\|\*\/\|\/\//l1 - -let &cpo = s:save_cpo -unlet s:save_cpo diff --git a/vim/after/plugin/snipMate.vim b/vim/after/plugin/snipMate.vim deleted file mode 100644 index 03e79ae296..0000000000 --- a/vim/after/plugin/snipMate.vim +++ /dev/null @@ -1,35 +0,0 @@ -" These are the mappings for snipMate.vim. Putting it here ensures that it -" will be mapped after other plugins such as supertab.vim. -if !exists('loaded_snips') || exists('s:did_snips_mappings') - finish -endif -let s:did_snips_mappings = 1 - -ino =TriggerSnippet() -snor i=TriggerSnippet() -ino =BackwardsSnippet() -snor i=BackwardsSnippet() -ino =ShowAvailableSnips() - -" The default mappings for these are annoying & sometimes break snipMate. -" You can change them back if you want, I've put them here for convenience. -snor b -snor a -snor bi -snor ' b' -snor ` b` -snor % b% -snor U bU -snor ^ b^ -snor \ b\ -snor b - -" By default load snippets in snippets_dir -if empty(snippets_dir) - finish -endif - -call GetSnippets(snippets_dir, '_') " Get global snippets - -au FileType * if &ft != 'help' | call GetSnippets(snippets_dir, &ft) | endif -" vim:noet:sw=4:ts=4:ft=vim diff --git a/vim/autoload/fuf.vim b/vim/autoload/fuf.vim deleted file mode 100644 index 0a91d3a506..0000000000 --- a/vim/autoload/fuf.vim +++ /dev/null @@ -1,1155 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - - - -function fuf#getPathSeparator() - return (!&shellslash && (has('win32') || has('win64')) ? '\' : '/') -endfunction - -" Removes duplicates -" this function doesn't change list of argument. -function fuf#unique(items) - let sorted = sort(a:items) - if len(sorted) < 2 - return sorted - endif - let last = remove(sorted, 0) - let result = [last] - for item in sorted - if item != last - call add(result, item) - let last = item - endif - endfor - return result -endfunction - -" [ [0], [1,2], [3] ] -> [ 0, 1, 2, 3 ] -" this function doesn't change list of argument. -function fuf#concat(items) - let result = [] - for l in a:items - let result += l - endfor - return result -endfunction - -" filter() with the maximum number of items -" this function doesn't change list of argument. -function fuf#filterWithLimit(items, expr, limit) - if a:limit <= 0 - return filter(copy(a:items), a:expr) - endif - let result = [] - let stride = a:limit * 3 / 2 " x1.5 - for i in range(0, len(a:items) - 1, stride) - let result += filter(a:items[i : i + stride - 1], a:expr) - if len(result) >= a:limit - return remove(result, 0, a:limit - 1) - endif - endfor - return result -endfunction - -" -function fuf#countModifiedFiles(files, time) - return len(filter(copy(a:files), 'getftime(v:val) > a:time')) -endfunction - -" -function fuf#getCurrentTagFiles() - return sort(filter(map(tagfiles(), 'fnamemodify(v:val, '':p'')'), 'filereadable(v:val)')) -endfunction - -" -function fuf#mapToSetSerialIndex(in, offset) - for i in range(len(a:in)) - let a:in[i].index = i + a:offset - endfor - return a:in -endfunction - -" -function fuf#updateMruList(mrulist, newItem, maxItem, exclude) - let result = copy(a:mrulist) - let result = filter(result,'v:val.word != a:newItem.word') - let result = insert(result, a:newItem) - let result = filter(result, 'v:val.word !~ a:exclude') - return result[0 : a:maxItem - 1] -endfunction - -" takes suffix number. if no digits, returns -1 -function fuf#suffixNumber(str) - let s = matchstr(a:str, '\d\+$') - return (len(s) ? str2nr(s) : -1) -endfunction - -" "foo/bar/buz/hoge" -> { head: "foo/bar/buz/", tail: "hoge" } -function fuf#splitPath(path) - let head = matchstr(a:path, '^.*[/\\]') - return { - \ 'head' : head, - \ 'tail' : a:path[strlen(head):] - \ } -endfunction - -" "foo/.../bar/...hoge" -> "foo/.../bar/../../hoge" -function fuf#expandTailDotSequenceToParentDir(pattern) - return substitute(a:pattern, '^\(.*[/\\]\)\?\zs\.\(\.\+\)\ze[^/\\]*$', - \ '\=repeat(".." . fuf#getPathSeparator(), len(submatch(2)))', '') -endfunction - -" -function fuf#hash224(str) - let a = 0x00000800 " shift 11 bit - let b = 0x001fffff " extract 11 bit - let nHash = 7 - let hashes = repeat([0], nHash) - for i in range(len(a:str)) - let iHash = i % nHash - let hashes[iHash] = hashes[iHash] * a + hashes[iHash] / b - let hashes[iHash] += char2nr(a:str[i]) - endfor - return join(map(hashes, 'printf("%08x", v:val)'), '') -endfunction - -" -function fuf#formatPrompt(prompt, partialMatching) - let indicator = (a:partialMatching ? '!' : '') - return substitute(a:prompt, '[]', indicator, 'g') -endfunction - -" -function fuf#getFileLines(file) - let bufnr = (type(a:file) ==# type(0) ? a:file : bufnr('^' . a:file . '$')) - let lines = getbufline(bufnr, 1, '$') - if !empty(lines) - return lines - endif - try - return readfile(expand(a:file)) - catch /.*/ - endtry - return [] -endfunction - -" -function fuf#makePreviewLinesAround(lines, indices, page, maxHeight) - let index = ((empty(a:indices) ? 0 : a:indices[0]) - \ + a:page * a:maxHeight) % len(a:lines) - if empty(a:lines) || a:maxHeight <= 0 - return [] - endif - let beg = max([0, index - a:maxHeight / 2]) - let end = min([beg + a:maxHeight, len(a:lines)]) - let beg = max([0, end - a:maxHeight]) - let lines = [] - for i in range(beg, end - 1) - let mark = (count(a:indices, i) ? '>' : ' ') - call add(lines, printf('%s%4d ', mark, i + 1) . a:lines[i]) - endfor - return lines -endfunction - -" a:file: a path string or a buffer number -function fuf#makePreviewLinesForFile(file, count, maxHeight) - let lines = fuf#getFileLines(a:file) - if empty(lines) - return [] - endif - let bufnr = (type(a:file) ==# type(0) ? a:file : bufnr('^' . a:file . '$')) - if exists('s:bufferCursorPosMap[bufnr]') - let indices = [s:bufferCursorPosMap[bufnr][1] - 1] - else - let indices = [] - endif - return fuf#makePreviewLinesAround( - \ lines, indices, a:count, a:maxHeight) -endfunction - -" -function fuf#echoWithHl(msg, hl) - execute "echohl " . a:hl - echo a:msg - echohl None -endfunction - -" -function fuf#inputHl(prompt, text, hl) - execute "echohl " . a:hl - let s = input(a:prompt, a:text) - echohl None - return s -endfunction - -" -function fuf#openBuffer(bufNr, mode, reuse) - if a:reuse && ((a:mode == s:OPEN_TYPE_SPLIT && - \ s:moveToWindowOfBufferInCurrentTabPage(a:bufNr)) || - \ (a:mode == s:OPEN_TYPE_VSPLIT && - \ s:moveToWindowOfBufferInCurrentTabPage(a:bufNr)) || - \ (a:mode == s:OPEN_TYPE_TAB && - \ s:moveToWindowOfBufferInOtherTabPage(a:bufNr))) - return - endif - execute printf({ - \ s:OPEN_TYPE_CURRENT : '%sbuffer' , - \ s:OPEN_TYPE_SPLIT : '%ssbuffer' , - \ s:OPEN_TYPE_VSPLIT : 'vertical %ssbuffer', - \ s:OPEN_TYPE_TAB : 'tab %ssbuffer' , - \ }[a:mode], a:bufNr) -endfunction - -" -function fuf#openFile(path, mode, reuse) - let bufNr = bufnr('^' . a:path . '$') - if bufNr > -1 - call fuf#openBuffer(bufNr, a:mode, a:reuse) - else - execute { - \ s:OPEN_TYPE_CURRENT : 'edit ' , - \ s:OPEN_TYPE_SPLIT : 'split ' , - \ s:OPEN_TYPE_VSPLIT : 'vsplit ' , - \ s:OPEN_TYPE_TAB : 'tabedit ', - \ }[a:mode] . fnameescape(fnamemodify(a:path, ':~:.')) - endif -endfunction - -" -function fuf#openTag(tag, mode) - execute { - \ s:OPEN_TYPE_CURRENT : 'tjump ' , - \ s:OPEN_TYPE_SPLIT : 'stjump ' , - \ s:OPEN_TYPE_VSPLIT : 'vertical stjump ', - \ s:OPEN_TYPE_TAB : 'tab stjump ' , - \ }[a:mode] . a:tag -endfunction - -" -function fuf#openHelp(tag, mode) - execute { - \ s:OPEN_TYPE_CURRENT : 'help ' , - \ s:OPEN_TYPE_SPLIT : 'help ' , - \ s:OPEN_TYPE_VSPLIT : 'vertical help ', - \ s:OPEN_TYPE_TAB : 'tab help ' , - \ }[a:mode] . a:tag -endfunction - -" -function fuf#prejump(mode) - execute { - \ s:OPEN_TYPE_CURRENT : '' , - \ s:OPEN_TYPE_SPLIT : 'split' , - \ s:OPEN_TYPE_VSPLIT : 'vsplit' , - \ s:OPEN_TYPE_TAB : 'tab split', - \ }[a:mode] -endfunction - -" -function fuf#compareRanks(i1, i2) - if exists('a:i1.ranks') && exists('a:i2.ranks') - for i in range(min([len(a:i1.ranks), len(a:i2.ranks)])) - if a:i1.ranks[i] > a:i2.ranks[i] - return +1 - elseif a:i1.ranks[i] < a:i2.ranks[i] - return -1 - endif - endfor - endif - return 0 -endfunction - -" -function fuf#makePathItem(fname, menu, appendsDirSuffix) - let pathPair = fuf#splitPath(a:fname) - let dirSuffix = (a:appendsDirSuffix && isdirectory(a:fname) - \ ? fuf#getPathSeparator() - \ : '') - return { - \ 'word' : a:fname . dirSuffix, - \ 'wordForPrimaryHead': s:toLowerForIgnoringCase(pathPair.head), - \ 'wordForPrimaryTail': s:toLowerForIgnoringCase(pathPair.tail), - \ 'wordForBoundary' : s:toLowerForIgnoringCase(s:getWordBoundaries(pathPair.tail)), - \ 'wordForRefining' : s:toLowerForIgnoringCase(a:fname . dirSuffix), - \ 'wordForRank' : s:toLowerForIgnoringCase(pathPair.tail), - \ 'menu' : a:menu, - \ } -endfunction - -" -function fuf#makeNonPathItem(word, menu) - let wordL = s:toLowerForIgnoringCase(a:word) - return { - \ 'word' : a:word, - \ 'wordForPrimary' : wordL, - \ 'wordForBoundary': s:toLowerForIgnoringCase(s:getWordBoundaries(a:word)), - \ 'wordForRefining': wordL, - \ 'wordForRank' : wordL, - \ 'menu' : a:menu, - \ } -endfunction - -" -function s:interpretPrimaryPatternForPathTail(pattern) - let pattern = fuf#expandTailDotSequenceToParentDir(a:pattern) - let pairL = fuf#splitPath(s:toLowerForIgnoringCase(pattern)) - return { - \ 'primary' : pattern, - \ 'primaryForRank': pairL.tail, - \ 'matchingPairs' : [['v:val.wordForPrimaryTail', pairL.tail],], - \ } -endfunction - -" -function s:interpretPrimaryPatternForPath(pattern) - let pattern = fuf#expandTailDotSequenceToParentDir(a:pattern) - let patternL = s:toLowerForIgnoringCase(pattern) - let pairL = fuf#splitPath(patternL) - if g:fuf_splitPathMatching - let matches = [ - \ ['v:val.wordForPrimaryHead', pairL.head], - \ ['v:val.wordForPrimaryTail', pairL.tail], - \ ] - else - let matches = [ - \ ['v:val.wordForPrimaryHead . v:val.wordForPrimaryTail', patternL], - \ ] - endif - return { - \ 'primary' : pattern, - \ 'primaryForRank': pairL.tail, - \ 'matchingPairs' : matches, - \ } -endfunction - -" -function s:interpretPrimaryPatternForNonPath(pattern) - let patternL = s:toLowerForIgnoringCase(a:pattern) - return { - \ 'primary' : a:pattern, - \ 'primaryForRank': patternL, - \ 'matchingPairs' : [['v:val.wordForPrimary', patternL],], - \ } -endfunction - -" -function fuf#makePatternSet(patternBase, interpreter, partialMatching) - let MakeMatchingExpr = function(a:partialMatching - \ ? 's:makePartialMatchingExpr' - \ : 's:makeFuzzyMatchingExpr') - let [primary; refinings] = split(a:patternBase, g:fuf_patternSeparator, 1) - let elements = call(a:interpreter, [primary]) - let primaryExprs = map(elements.matchingPairs, 'MakeMatchingExpr(v:val[0], v:val[1])') - let refiningExprs = map(refinings, 's:makeRefiningExpr(v:val)') - return { - \ 'primary' : elements.primary, - \ 'primaryForRank': elements.primaryForRank, - \ 'filteringExpr' : join(primaryExprs + refiningExprs, ' && '), - \ } -endfunction - -" -function fuf#enumExpandedDirsEntries(dir, exclude) - " Substitutes "\" because on Windows, "**\" doesn't include ".\", - " but "**/" include "./". I don't know why. - let dirNormalized = substitute(a:dir, '\', '/', 'g') - let entries = split(glob(dirNormalized . "*" ), "\n") + - \ split(glob(dirNormalized . ".*"), "\n") - " removes "*/." and "*/.." - call filter(entries, 'v:val !~ ''\v(^|[/\\])\.\.?$''') - call map(entries, 'fuf#makePathItem(v:val, "", 1)') - if len(a:exclude) - call filter(entries, 'v:val.word !~ a:exclude') - endif - return entries -endfunction - -" -function fuf#mapToSetAbbrWithSnippedWordAsPath(items) - let maxLenStats = {} - call map(a:items, 's:makeFileAbbrInfo(v:val, maxLenStats)') - let snippedHeads = - \ map(maxLenStats, 's:getSnippedHead(v:key[: -2], v:val)') - return map(a:items, 's:setAbbrWithFileAbbrData(v:val, snippedHeads)') -endfunction - -" -function fuf#setAbbrWithFormattedWord(item, abbrIndex) - let lenMenu = (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - let abbrPrefix = (exists('a:item.abbrPrefix') ? a:item.abbrPrefix : '') - let a:item.abbr = abbrPrefix . a:item.word - if a:abbrIndex - let a:item.abbr = printf('%4d: ', a:item.index) . a:item.abbr - endif - let a:item.abbr = s:snipTail(a:item.abbr, g:fuf_maxMenuWidth - lenMenu, s:ABBR_SNIP_MASK) - return a:item -endfunction - -" -function fuf#defineLaunchCommand(CmdName, modeName, prefixInitialPattern) - execute printf('command! -bang -narg=? %s call fuf#launch(%s, %s . , len())', - \ a:CmdName, string(a:modeName), a:prefixInitialPattern) -endfunction - -" -function fuf#defineKeyMappingInHandler(key, func) - " hacks to be able to use feedkeys(). - execute printf( - \ 'inoremap %s =fuf#getRunningHandler().%s ? "" : ""', - \ a:key, a:func) -endfunction - -" -function fuf#launch(modeName, initialPattern, partialMatching) - if exists('s:runningHandler') - call fuf#echoWithHl('FuzzyFinder is running.', 'WarningMsg') - endif - if count(g:fuf_modes, a:modeName) == 0 - echoerr 'This mode is not available: ' . a:modeName - return - endif - let s:runningHandler = fuf#{a:modeName}#createHandler(copy(s:handlerBase)) - let s:runningHandler.info = fuf#loadInfoFile(s:runningHandler.getModeName()) - let s:runningHandler.partialMatching = a:partialMatching - let s:runningHandler.bufNrPrev = bufnr('%') - let s:runningHandler.lastCol = -1 - call s:runningHandler.onModeEnterPre() - call s:setTemporaryGlobalOption('completeopt', 'menuone') - call s:setTemporaryGlobalOption('ignorecase', 0) - if s:runningHandler.getPreviewHeight() > 0 - call s:setTemporaryGlobalOption( - \ 'cmdheight', s:runningHandler.getPreviewHeight() + 1) - endif - call s:activateFufBuffer() - augroup FufLocal - autocmd! - autocmd CursorMovedI call s:runningHandler.onCursorMovedI() - autocmd InsertLeave nested call s:runningHandler.onInsertLeave() - augroup END - for [key, func] in [ - \ [ g:fuf_keyOpen , 'onCr(' . s:OPEN_TYPE_CURRENT . ', 0)' ], - \ [ g:fuf_keyOpenSplit , 'onCr(' . s:OPEN_TYPE_SPLIT . ', 0)' ], - \ [ g:fuf_keyOpenVsplit , 'onCr(' . s:OPEN_TYPE_VSPLIT . ', 0)' ], - \ [ g:fuf_keyOpenTabpage , 'onCr(' . s:OPEN_TYPE_TAB . ', 0)' ], - \ [ '' , 'onBs()' ], - \ [ '' , 'onBs()' ], - \ [ g:fuf_keyPreview , 'onPreviewBase()' ], - \ [ g:fuf_keyNextMode , 'onSwitchMode(+1)' ], - \ [ g:fuf_keyPrevMode , 'onSwitchMode(-1)' ], - \ [ g:fuf_keySwitchMatching, 'onSwitchMatching()' ], - \ [ g:fuf_keyPrevPattern , 'onRecallPattern(+1)' ], - \ [ g:fuf_keyNextPattern , 'onRecallPattern(-1)' ], - \ ] - call fuf#defineKeyMappingInHandler(key, func) - endfor - " Starts Insert mode and makes CursorMovedI event now. Command prompt is - " needed to forces a completion menu to update every typing. - call setline(1, s:runningHandler.getPrompt() . a:initialPattern) - call s:runningHandler.onModeEnterPost() - call feedkeys("A", 'n') " startinsert! does not work in InsertLeave event handler - redraw -endfunction - -" -function fuf#loadInfoFile(modeName) - try - let lines = readfile(expand(g:fuf_infoFile)) - " compatibility check - if count(lines, s:INFO_FILE_VERSION_LINE) == 0 - call s:warnOldInfoFile() - let g:fuf_infoFile = '' - throw 1 - endif - catch /.*/ - let lines = [] - endtry - let s:lastInfoMap = s:deserializeInfoMap(lines) - if !exists('s:lastInfoMap[a:modeName]') - let s:lastInfoMap[a:modeName] = {} - endif - return extend(s:lastInfoMap[a:modeName], { 'data': [], 'stats': [] }, 'keep') -endfunction - -" if a:modeName is empty, a:info is treated as a map of information -function fuf#saveInfoFile(modeName, info) - if empty(a:modeName) - let s:lastInfoMap = a:info - else - let s:lastInfoMap[a:modeName] = a:info - endif - let lines = [ s:INFO_FILE_VERSION_LINE ] + s:serializeInfoMap(s:lastInfoMap) - try - call writefile(lines, expand(g:fuf_infoFile)) - catch /.*/ - endtry -endfunction - -" -function fuf#editInfoFile() - new - silent file `='[fuf-info]'` - let s:bufNrInfo = bufnr('%') - setlocal filetype=vim - setlocal bufhidden=delete - setlocal buftype=acwrite - setlocal noswapfile - augroup FufInfo - autocmd! - autocmd BufWriteCmd call s:onBufWriteCmdInfoFile() - augroup END - execute '0read ' . expand(g:fuf_infoFile) - setlocal nomodified -endfunction - -" -function fuf#getRunningHandler() - return s:runningHandler -endfunction - -" -function fuf#onComplete(findstart, base) - return s:runningHandler.onComplete(a:findstart, a:base) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:INFO_FILE_VERSION_LINE = "VERSION\t300" -let s:ABBR_SNIP_MASK = '...' -let s:OPEN_TYPE_CURRENT = 1 -let s:OPEN_TYPE_SPLIT = 2 -let s:OPEN_TYPE_VSPLIT = 3 -let s:OPEN_TYPE_TAB = 4 - -" wildcard -> regexp -function s:convertWildcardToRegexp(expr) - let re = escape(a:expr, '\') - for [pat, sub] in [ [ '*', '\\.\\*' ], [ '?', '\\.' ], [ '[', '\\[' ], ] - let re = substitute(re, pat, sub, 'g') - endfor - return '\V' . re -endfunction - -" a:pattern: 'str' -> '\V\.\*s\.\*t\.\*r\.\*' -function s:makeFuzzyMatchingExpr(target, pattern) - let wi = '' - for c in split(a:pattern, '\zs') - if wi =~# '[^*?]$' && c !~ '[*?]' - let wi .= '*' - endif - let wi .= c - endfor - return s:makePartialMatchingExpr(a:target, wi) -endfunction - -" a:pattern: 'str' -> '\Vstr' -" 'st*r' -> '\Vst\.\*r' -function s:makePartialMatchingExpr(target, pattern) - let patternMigemo = s:makeAdditionalMigemoPattern(a:pattern) - if a:pattern !~ '[*?]' && empty(patternMigemo) - " NOTE: stridx is faster than regexp matching - return 'stridx(' . a:target . ', ' . string(a:pattern) . ') >= 0' - endif - return a:target . ' =~# ' . - \ string(s:convertWildcardToRegexp(a:pattern)) . patternMigemo -endfunction - -" -function s:makeRefiningExpr(pattern) - let expr = s:makePartialMatchingExpr('v:val.wordForRefining', a:pattern) - if a:pattern =~# '\D' - return expr - else - return '(' . expr . ' || v:val.index == ' . string(a:pattern) . ')' - endif -endfunction - -" -function s:makeAdditionalMigemoPattern(pattern) - if !g:fuf_useMigemo || a:pattern =~# '[^\x01-\x7e]' - return '' - endif - return '\|\m' . substitute(migemo(a:pattern), '\\_s\*', '.*', 'g') -endfunction - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function s:snipHead(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - return a:mask . a:str[-a:len + len(a:mask):] -endfunction - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function s:snipTail(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - return a:str[:a:len - 1 - len(a:mask)] . a:mask -endfunction - -" Snips a:str and add a:mask if the length of a:str is more than a:len -function s:snipMid(str, len, mask) - if a:len >= len(a:str) - return a:str - elseif a:len <= len(a:mask) - return a:mask - endif - let len_head = (a:len - len(a:mask)) / 2 - let len_tail = a:len - len(a:mask) - len_head - return (len_head > 0 ? a:str[: len_head - 1] : '') . a:mask . - \ (len_tail > 0 ? a:str[-len_tail :] : '') -endfunction - -" -function s:getWordBoundaries(word) - return substitute(a:word, '\a\zs\l\+\|\zs\A', '', 'g') -endfunction - -" -function s:toLowerForIgnoringCase(str) - return (g:fuf_ignoreCase ? tolower(a:str) : a:str) -endfunction - -" -function s:setRanks(item, pattern, exprBoundary, stats) - "let word2 = substitute(a:eval_word, '\a\zs\l\+\|\zs\A', '', 'g') - let a:item.ranks = [ - \ s:evaluateLearningRank(a:item.word, a:stats), - \ -s:scoreSequentialMatching(a:item.wordForRank, a:pattern), - \ -s:scoreBoundaryMatching(a:item.wordForBoundary, - \ a:pattern, a:exprBoundary), - \ a:item.index, - \ ] - return a:item -endfunction - -" -function s:evaluateLearningRank(word, stats) - for i in range(len(a:stats)) - if a:stats[i].word ==# a:word - return i - endif - endfor - return len(a:stats) -endfunction - -let g:s = "" -" range of return value is [0.0, 1.0] -function s:scoreSequentialMatching(word, pattern) - if empty(a:pattern) - return 0.0 - endif - let pos = stridx(a:word, a:pattern) - if pos < 0 - return 0.0 - endif - let lenRest = len(a:word) - len(a:pattern) - pos - return (pos == 0 ? 0.5 : 0.0) + 0.5 / (lenRest + 1) -endfunction - -" range of return value is [0.0, 1.0] -function s:scoreBoundaryMatching(wordForBoundary, pattern, exprBoundary) - if empty(a:pattern) - return 0.0 - endif - if !eval(a:exprBoundary) - return 0 - endif - return 0.5 + 0.5 * s:scoreSequentialMatching(a:wordForBoundary, a:pattern) -endfunction - -" -function s:highlightPrompt(prompt) - syntax clear - execute printf('syntax match %s /^\V%s/', g:fuf_promptHighlight, escape(a:prompt, '\')) -endfunction - -" -function s:highlightError() - syntax clear - syntax match Error /^.*$/ -endfunction - -" returns 0 if the buffer is not found. -function s:moveToWindowOfBufferInCurrentTabPage(bufNr) - if count(tabpagebuflist(), a:bufNr) == 0 - return 0 - endif - execute bufwinnr(a:bufNr) . 'wincmd w' - return 1 -endfunction - -" returns 0 if the buffer is not found. -function s:moveToOtherTabPageOpeningBuffer(bufNr) - for tabNr in range(1, tabpagenr('$')) - if tabNr != tabpagenr() && count(tabpagebuflist(tabNr), a:bufNr) > 0 - execute 'tabnext ' . tabNr - return 1 - endif - endfor - return 0 -endfunction - -" returns 0 if the buffer is not found. -function s:moveToWindowOfBufferInOtherTabPage(bufNr) - if !s:moveToOtherTabPageOpeningBuffer(a:bufNr) - return 0 - endif - return s:moveToWindowOfBufferInCurrentTabPage(a:bufNr) -endfunction - -" -function s:expandAbbrevMap(pattern, abbrevMap) - let result = [a:pattern] - for [pattern, subs] in items(a:abbrevMap) - let exprs = result - let result = [] - for expr in exprs - let result += map(copy(subs), 'substitute(expr, pattern, escape(v:val, ''\''), "g")') - endfor - endfor - return fuf#unique(result) -endfunction - -" -function s:makeFileAbbrInfo(item, maxLenStats) - let head = matchstr(a:item.word, '^.*[/\\]\ze.') - let a:item.abbr = { 'head' : head, - \ 'tail' : a:item.word[strlen(head):], - \ 'key' : head . '.', - \ 'prefix' : printf('%4d: ', a:item.index), } - if exists('a:item.abbrPrefix') - let a:item.abbr.prefix .= a:item.abbrPrefix - endif - let len = len(a:item.abbr.prefix) + len(a:item.word) + - \ (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - if !exists('a:maxLenStats[a:item.abbr.key]') || len > a:maxLenStats[a:item.abbr.key] - let a:maxLenStats[a:item.abbr.key] = len - endif - return a:item -endfunction - -" -function s:getSnippedHead(head, baseLen) - return s:snipMid(a:head, len(a:head) + g:fuf_maxMenuWidth - a:baseLen, s:ABBR_SNIP_MASK) -endfunction - -" -function s:setAbbrWithFileAbbrData(item, snippedHeads) - let lenMenu = (exists('a:item.menu') ? len(a:item.menu) + 2 : 0) - let abbr = a:item.abbr.prefix . a:snippedHeads[a:item.abbr.key] . a:item.abbr.tail - let a:item.abbr = s:snipTail(abbr, g:fuf_maxMenuWidth - lenMenu, s:ABBR_SNIP_MASK) - return a:item -endfunction - -let s:bufNrFuf = -1 - -" -function s:openFufBuffer() - if !bufexists(s:bufNrFuf) - topleft 1new - silent file `='[fuf]'` - let s:bufNrFuf = bufnr('%') - elseif bufwinnr(s:bufNrFuf) == -1 - topleft 1split - execute 'silent ' . s:bufNrFuf . 'buffer' - delete _ - elseif bufwinnr(s:bufNrFuf) != bufwinnr('%') - execute bufwinnr(s:bufNrFuf) . 'wincmd w' - endif -endfunction - -function s:setLocalOptionsForFufBuffer() - setlocal filetype=fuf - setlocal bufhidden=delete - setlocal buftype=nofile - setlocal noswapfile - setlocal nobuflisted - setlocal modifiable - setlocal nocursorline " for highlighting - setlocal nocursorcolumn " for highlighting - setlocal omnifunc=fuf#onComplete -endfunction - -" -function s:activateFufBuffer() - " lcd . : To avoid the strange behavior that unnamed buffer changes its cwd - " if 'autochdir' was set on. - lcd . - let cwd = getcwd() - call s:openFufBuffer() - " lcd ... : countermeasure against auto-cd script - lcd `=cwd` - call s:setLocalOptionsForFufBuffer() - redraw " for 'lazyredraw' - if exists(':AcpLock') - AcpLock - elseif exists(':AutoComplPopLock') - AutoComplPopLock - endif -endfunction - -" -function s:deactivateFufBuffer() - if exists(':AcpUnlock') - AcpUnlock - elseif exists(':AutoComplPopUnlock') - AutoComplPopUnlock - endif - " must close after returning to previous window - wincmd p - execute s:bufNrFuf . 'bdelete' -endfunction - -let s:originalGlobalOptions = {} - -" -function s:setTemporaryGlobalOption(name, value) - call extend(s:originalGlobalOptions, { a:name : eval('&' . a:name) }, 'keep') - execute printf('let &%s = a:value', a:name) -endfunction - -" -function s:restoreTemporaryGlobalOptions() - for [name, value] in items(s:originalGlobalOptions) - execute printf('let &%s = value', name) - endfor - let s:originalGlobalOptions = {} -endfunction - -" -function s:warnOldInfoFile() - call fuf#echoWithHl(printf("=================================================================\n" . - \ " Sorry, but your information file for FuzzyFinder is no longer \n" . - \ " compatible with this version of FuzzyFinder. Please remove \n" . - \ " %-63s\n" . - \ "=================================================================\n" , - \ '"' . expand(g:fuf_infoFile) . '".'), - \ 'WarningMsg') - echohl Question - call input('Press Enter') - echohl None -endfunction - -" -function s:serializeInfoMap(infoMap) - let lines = [] - for [m, info] in items(a:infoMap) - for [key, value] in items(info) - let lines += map(copy(value), 'm . "\t" . key . "\t" . string(v:val)') - endfor - endfor - return lines -endfunction - -" -function s:deserializeInfoMap(lines) - let infoMap = {} - for e in filter(map(a:lines, 'matchlist(v:val, ''^\v(\S+)\s+(\S+)\s+(.+)$'')'), '!empty(v:val)') - if !exists('infoMap[e[1]]') - let infoMap[e[1]] = {} - endif - if !exists('infoMap[e[1]][e[2]]') - let infoMap[e[1]][e[2]] = [] - endif - call add(infoMap[e[1]][e[2]], eval(e[3])) - endfor - return infoMap -endfunction - -" -function s:onBufWriteCmdInfoFile() - call fuf#saveInfoFile('', s:deserializeInfoMap(getline(1, '$'))) - setlocal nomodified - execute printf('%dbdelete! ', s:bufNrInfo) - echo "Information file updated" -endfunction - -" }}}1 -"============================================================================= -" s:handlerBase {{{1 - -let s:handlerBase = {} - -"----------------------------------------------------------------------------- -" PURE VIRTUAL FUNCTIONS {{{2 -" -" " -" s:handler.getModeName() -" -" " -" s:handler.getPrompt() -" -" " returns true if the mode deals with file paths. -" s:handler.targetsPath() -" -" " -" s:handler.getCompleteItems(patternSet) -" -" " -" s:handler.onOpen(word, mode) -" -" " Before entering FuzzyFinder buffer. This function should return in a short time. -" s:handler.onModeEnterPre() -" -" " After entering FuzzyFinder buffer. -" s:handler.onModeEnterPost() -" -" " After leaving FuzzyFinder buffer. -" s:handler.onModeLeavePost(opened) -" -" }}}2 -"----------------------------------------------------------------------------- - -" -function s:handlerBase.concretize(deriv) - call extend(self, a:deriv, 'error') - return self -endfunction - -" -function s:handlerBase.addStat(pattern, word) - let stat = { 'pattern' : a:pattern, 'word' : a:word } - call filter(self.info.stats, 'v:val !=# stat') - call insert(self.info.stats, stat) - let self.info.stats = self.info.stats[0 : g:fuf_learningLimit - 1] -endfunction - -" -function s:handlerBase.getMatchingCompleteItems(patternBase) - let MakeMatchingExpr = function(self.partialMatching - \ ? 's:makePartialMatchingExpr' - \ : 's:makeFuzzyMatchingExpr') - let patternSet = self.makePatternSet(a:patternBase) - let exprBoundary = s:makeFuzzyMatchingExpr('a:wordForBoundary', patternSet.primaryForRank) - let stats = filter( - \ copy(self.info.stats), 'v:val.pattern ==# patternSet.primaryForRank') - let items = self.getCompleteItems(patternSet.primary) - " NOTE: In order to know an excess, plus 1 to limit number - let items = fuf#filterWithLimit( - \ items, patternSet.filteringExpr, g:fuf_enumeratingLimit + 1) - return map(items, - \ 's:setRanks(v:val, patternSet.primaryForRank, exprBoundary, stats)') -endfunction - -" -function s:handlerBase.onComplete(findstart, base) - if a:findstart - return 0 - elseif !self.existsPrompt(a:base) - return [] - endif - call s:highlightPrompt(self.getPrompt()) - let items = [] - for patternBase in s:expandAbbrevMap(self.removePrompt(a:base), g:fuf_abbrevMap) - let items += self.getMatchingCompleteItems(patternBase) - if len(items) > g:fuf_enumeratingLimit - let items = items[ : g:fuf_enumeratingLimit - 1] - call s:highlightError() - break - endif - endfor - if empty(items) - call s:highlightError() - else - call sort(items, 'fuf#compareRanks') - call feedkeys("\\", 'n') - let self.lastFirstWord = items[0].word - endif - return items -endfunction - -" -function s:handlerBase.existsPrompt(line) - return strlen(a:line) >= strlen(self.getPrompt()) && - \ a:line[:strlen(self.getPrompt()) -1] ==# self.getPrompt() -endfunction - -" -function s:handlerBase.removePrompt(line) - return a:line[(self.existsPrompt(a:line) ? strlen(self.getPrompt()) : 0):] -endfunction - -" -function s:handlerBase.restorePrompt(line) - let i = 0 - while i < len(self.getPrompt()) && i < len(a:line) && self.getPrompt()[i] ==# a:line[i] - let i += 1 - endwhile - return self.getPrompt() . a:line[i : ] -endfunction - -" -function s:handlerBase.onCursorMovedI() - if !self.existsPrompt(getline('.')) - call setline('.', self.restorePrompt(getline('.'))) - call feedkeys("\", 'n') - elseif col('.') <= len(self.getPrompt()) - " if the cursor is moved before command prompt - call feedkeys(repeat("\", len(self.getPrompt()) - col('.') + 1), 'n') - elseif col('.') > strlen(getline('.')) && col('.') != self.lastCol - " if the cursor is placed on the end of the line and has been actually moved. - let self.lastCol = col('.') - let self.lastPattern = self.removePrompt(getline('.')) - call feedkeys("\\", 'n') - endif -endfunction - -" -function s:handlerBase.onInsertLeave() - unlet s:runningHandler - let lastPattern = self.removePrompt(getline('.')) - call s:restoreTemporaryGlobalOptions() - call s:deactivateFufBuffer() - call fuf#saveInfoFile(self.getModeName(), self.info) - let fOpen = exists('s:reservedCommand') - if fOpen - call self.onOpen(s:reservedCommand[0], s:reservedCommand[1]) - unlet s:reservedCommand - endif - call self.onModeLeavePost(fOpen) - if exists('s:reservedMode') - call fuf#launch(s:reservedMode, lastPattern, self.partialMatching) - unlet s:reservedMode - endif -endfunction - -" -function s:handlerBase.onCr(openType, fCheckDir) - if pumvisible() - call feedkeys(printf("\\=fuf#getRunningHandler().onCr(%d, %d) ? '' : ''\", - \ a:openType, self.targetsPath()), 'n') - return - endif - if !empty(self.lastPattern) - call self.addStat(self.lastPattern, self.removePrompt(getline('.'))) - endif - if a:fCheckDir && getline('.') =~# '[/\\]$' - " To clear i_ expression (fuf#getRunningHandler().onCr...) - echo '' - return - endif - let s:reservedCommand = [self.removePrompt(getline('.')), a:openType] - call feedkeys("\", 'n') " stopinsert behavior is strange... -endfunction - -" -function s:handlerBase.onBs() - let pattern = self.removePrompt(getline('.')[ : col('.') - 2]) - if empty(pattern) - let numBs = 0 - elseif !g:fuf_smartBs - let numBs = 1 - elseif pattern[-len(g:fuf_patternSeparator) : ] ==# g:fuf_patternSeparator - let numBs = len(split(pattern, g:fuf_patternSeparator, 1)[-2]) - \ + len(g:fuf_patternSeparator) - elseif self.targetsPath() && pattern[-1 : ] =~# '[/\\]' - let numBs = len(matchstr(pattern, '[^/\\]*.$')) - else - let numBs = 1 - endif - call feedkeys((pumvisible() ? "\" : "") . repeat("\", numBs), 'n') -endfunction - -" -function s:handlerBase.onPreviewBase() - if self.getPreviewHeight() <= 0 - return - elseif !pumvisible() - return - elseif !self.existsPrompt(getline('.')) - let word = self.removePrompt(getline('.')) - elseif !exists('self.lastFirstWord') - return - else - let word = self.lastFirstWord - endif - redraw - if exists('self.lastPreviewInfo') && self.lastPreviewInfo.word ==# word - let self.lastPreviewInfo.count += 1 - else - let self.lastPreviewInfo = {'word': word, 'count': 0} - endif - let lines = self.makePreviewLines(word, self.lastPreviewInfo.count) - let lines = lines[: self.getPreviewHeight() - 1] - call map(lines, 'substitute(v:val, "\t", repeat(" ", &tabstop), "g")') - call map(lines, 's:snipTail(v:val, &columns - 1, s:ABBR_SNIP_MASK)') - echo join(lines, "\n") -endfunction - -" -function s:handlerBase.onSwitchMode(shift) - let modes = copy(g:fuf_modes) - call map(modes, '{ "ranks": [ fuf#{v:val}#getSwitchOrder(), v:val ] }') - call filter(modes, 'v:val.ranks[0] >= 0') - call sort(modes, 'fuf#compareRanks') - let s:reservedMode = self.getModeName() - for i in range(len(modes)) - if modes[i].ranks[1] ==# self.getModeName() - let s:reservedMode = modes[(i + a:shift) % len(modes)].ranks[1] - break - endif - endfor - call feedkeys("\", 'n') " stopinsert doesn't work. -endfunction - -" -function s:handlerBase.onSwitchMatching() - let self.partialMatching = !self.partialMatching - let self.lastCol = -1 - call setline('.', self.restorePrompt(self.lastPattern)) - call feedkeys("\", 'n') - "call self.onCursorMovedI() -endfunction - -" -function s:handlerBase.onRecallPattern(shift) - let patterns = map(copy(self.info.stats), 'v:val.pattern') - if !exists('self.indexRecall') - let self.indexRecall = -1 - endif - let self.indexRecall += a:shift - if self.indexRecall < 0 - let self.indexRecall = -1 - elseif self.indexRecall >= len(patterns) - let self.indexRecall = len(patterns) - 1 - else - call setline('.', self.getPrompt() . patterns[self.indexRecall]) - call feedkeys("\", 'n') - endif -endfunction - -" }}}1 -"============================================================================= -" INITIALIZATION {{{1 - -augroup FufGlobal - autocmd! - autocmd BufLeave * let s:bufferCursorPosMap[bufnr('')] = getpos('.') -augroup END - -let s:bufferCursorPosMap = {} - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/vim/autoload/fuf/bookmark.vim b/vim/autoload/fuf/bookmark.vim deleted file mode 100644 index 59cc13ba90..0000000000 --- a/vim/autoload/fuf/bookmark.vim +++ /dev/null @@ -1,211 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_bookmark') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_bookmark = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#bookmark#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#bookmark#getSwitchOrder() - return g:fuf_bookmark_switchOrder -endfunction - -" -function fuf#bookmark#renewCache() -endfunction - -" -function fuf#bookmark#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#bookmark#onInit() - call fuf#defineLaunchCommand('FufBookmark', s:MODE_NAME, '""') - command! -bang -narg=? FufAddBookmark call s:bookmarkHere() - command! -bang -narg=0 -range FufAddBookmarkAsSelectedText call s:bookmarkHere(s:getSelectedText()) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -" -function s:getSelectedText() - let reg_ = [@", getregtype('"')] - let regA = [@a, getregtype('a')] - if mode() =~# "[vV\]" - silent normal! "aygv - else - let pos = getpos('.') - silent normal! gv"ay - call setpos('.', pos) - endif - let text = @a - call setreg('"', reg_[0], reg_[1]) - call setreg('a', regA[0], regA[1]) - return text -endfunction - -" opens a:path and jumps to the line matching to a:pattern from a:lnum within -" a:range. if not found, jumps to a:lnum. -function s:jumpToBookmark(path, mode, pattern, lnum) - call fuf#openFile(a:path, a:mode, g:fuf_reuseWindow) - call cursor(s:getMatchingLineNumber(getline(1, '$'), a:pattern, a:lnum), 0) - normal! zvzz -endfunction - -" -function s:getMatchingLineNumber(lines, pattern, lnumBegin) - let l = min([a:lnumBegin, len(a:lines)]) - for [l0, l1] in map(range(0, g:fuf_bookmark_searchRange), - \ '[l + v:val, l - v:val]') - if l0 <= len(a:lines) && a:lines[l0 - 1] =~# a:pattern - return l0 - elseif l1 >= 0 && a:lines[l1 - 1] =~# a:pattern - return l1 - endif - endfor - return l -endfunction - -" -function s:getLinePattern(lnum) - return '\C\V\^' . escape(getline(a:lnum), '\') . '\$' -endfunction - -" -function s:bookmarkHere(word) - if !empty(&buftype) || expand('%') !~ '\S' - call fuf#echoWithHl('Can''t bookmark this buffer.', 'WarningMsg') - return - endif - let item = { - \ 'word' : (a:word =~# '\S' ? substitute(a:word, '\n', ' ', 'g') - \ : pathshorten(expand('%:p:~')) . '|' . line('.') . '| ' . getline('.')), - \ 'path' : expand('%:p'), - \ 'lnum' : line('.'), - \ 'pattern' : s:getLinePattern(line('.')), - \ 'time' : localtime(), - \ } - let item.word = fuf#inputHl('Bookmark as:', item.word, 'Question') - if item.word !~ '\S' - call fuf#echoWithHl('Canceled', 'WarningMsg') - return - endif - let info = fuf#loadInfoFile(s:MODE_NAME) - call insert(info.data, item) - call fuf#saveInfoFile(s:MODE_NAME, info) -endfunction - -" -function s:findItem(items, word) - for item in a:items - if item.word ==# a:word - return item - endif - endfor - return {} -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_bookmark_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let item = s:findItem(self.info.data, a:word) - let lines = fuf#getFileLines(item.path) - if empty(lines) - return [] - endif - let index = s:getMatchingLineNumber(lines, item.pattern, item.lnum) - 1 - return fuf#makePreviewLinesAround( - \ lines, [index], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:mode == s:OPEN_TYPE_DELETE - call filter(self.info.data, 'v:val.word !=# a:word') - call fuf#saveInfoFile(s:MODE_NAME, self.info) - call fuf#launch(s:MODE_NAME, self.lastPattern, self.partialMatching) - return - else - let item = s:findItem(self.info.data, a:word) - if !empty(item) - call s:jumpToBookmark(item.path, a:mode, item.pattern, item.lnum) - endif - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - call fuf#defineKeyMappingInHandler(g:fuf_bookmark_keyDelete, - \ 'onCr(' . s:OPEN_TYPE_DELETE . ', 0)') - let self.items = copy(self.info.data) - call map(self.items, 'fuf#makeNonPathItem(v:val.word, strftime(g:fuf_timeFormat, v:val.time))') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/buffer.vim b/vim/autoload/fuf/buffer.vim deleted file mode 100644 index b8e5ee18ec..0000000000 --- a/vim/autoload/fuf/buffer.vim +++ /dev/null @@ -1,176 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_buffer') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_buffer = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#buffer#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#buffer#getSwitchOrder() - return g:fuf_buffer_switchOrder -endfunction - -" -function fuf#buffer#renewCache() -endfunction - -" -function fuf#buffer#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#buffer#onInit() - call fuf#defineLaunchCommand('FufBuffer', s:MODE_NAME, '""') - augroup fuf#buffer - autocmd! - autocmd BufEnter * call s:updateBufTimes() - autocmd BufWritePost * call s:updateBufTimes() - augroup END -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -let s:bufTimes = {} - -" -function s:updateBufTimes() - let s:bufTimes[bufnr('%')] = localtime() -endfunction - -" -function s:makeItem(nr) - let fname = (empty(bufname(a:nr)) - \ ? '[No Name]' - \ : fnamemodify(bufname(a:nr), ':~:.')) - let time = (exists('s:bufTimes[a:nr]') ? s:bufTimes[a:nr] : 0) - let item = fuf#makePathItem(fname, strftime(g:fuf_timeFormat, time), 0) - let item.index = a:nr - let item.bufNr = a:nr - let item.time = time - let item.abbrPrefix = s:getBufIndicator(a:nr) . ' ' - return item -endfunction - -" -function s:getBufIndicator(bufNr) - if !getbufvar(a:bufNr, '&modifiable') - return '[-]' - elseif getbufvar(a:bufNr, '&modified') - return '[+]' - elseif getbufvar(a:bufNr, '&readonly') - return '[R]' - else - return ' ' - endif -endfunction - -" -function s:compareTimeDescending(i1, i2) - return a:i1.time == a:i2.time ? 0 : a:i1.time > a:i2.time ? -1 : +1 -endfunction - -" -function s:findItem(items, word) - for item in a:items - if item.word ==# a:word - return item - endif - endfor - return {} -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_buffer_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let item = s:findItem(self.items, a:word) - if empty(item) - return [] - endif - return fuf#makePreviewLinesForFile(item.bufNr, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - " not use bufnr(a:word) in order to handle unnamed buffer - let item = s:findItem(self.items, a:word) - if !empty(item) - call fuf#openBuffer(item.bufNr, a:mode, g:fuf_reuseWindow) - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = map(filter(range(1, bufnr('$')), - \ 'buflisted(v:val) && v:val != self.bufNrPrev'), - \ 's:makeItem(v:val)') - if g:fuf_buffer_mruOrder - call fuf#mapToSetSerialIndex(sort(self.items, 's:compareTimeDescending'), 1) - endif - let self.items = fuf#mapToSetAbbrWithSnippedWordAsPath(self.items) -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/callbackfile.vim b/vim/autoload/fuf/callbackfile.vim deleted file mode 100644 index 8c6963845e..0000000000 --- a/vim/autoload/fuf/callbackfile.vim +++ /dev/null @@ -1,133 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_callbackfile') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_callbackfile = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#callbackfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#callbackfile#getSwitchOrder() - return -1 -endfunction - -" -function fuf#callbackfile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#callbackfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#callbackfile#onInit() -endfunction - -" -function fuf#callbackfile#launch(initialPattern, partialMatching, prompt, exclude, listener) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:exclude = a:exclude - let s:listener = a:listener - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = getcwd() . s:exclude . "\n" . a:dir - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, s:exclude) - if isdirectory(a:dir) - call insert(s:cache[key], fuf#makePathItem(a:dir . '.', '', 0)) - endif - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - let items = copy(s:enumItems(fuf#splitPath(a:patternPrimary).head)) - return filter(items, 'bufnr("^" . v:val.word . "$") != self.bufNrPrev') -endfunction - -" -function s:handler.onOpen(word, mode) - call s:listener.onComplete(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) - if !a:opened - call s:listener.onAbort() - endif -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/callbackitem.vim b/vim/autoload/fuf/callbackitem.vim deleted file mode 100644 index 3ee072cbd5..0000000000 --- a/vim/autoload/fuf/callbackitem.vim +++ /dev/null @@ -1,135 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_callbackitem') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_callbackitem = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#callbackitem#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#callbackitem#getSwitchOrder() - return -1 -endfunction - -" -function fuf#callbackitem#renewCache() -endfunction - -" -function fuf#callbackitem#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#callbackitem#onInit() -endfunction - -" -function fuf#callbackitem#launch(initialPattern, partialMatching, prompt, listener, items, forPath) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:listener = a:listener - let s:forPath = a:forPath - let s:items = copy(a:items) - if s:forPath - call map(s:items, 'fuf#makePathItem(v:val, "", 1)') - call fuf#mapToSetSerialIndex(s:items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:items) - else - call map(s:items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - endif - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - if s:forPath - return g:fuf_previewHeight - endif - return 0 -endfunction - -" -function s:handler.targetsPath() - return s:forPath -endfunction - -" -function s:handler.makePatternSet(patternBase) - let parser = (s:forPath - \ ? 's:interpretPrimaryPatternForPath' - \ : 's:interpretPrimaryPatternForNonPath') - return fuf#makePatternSet(a:patternBase, parser, self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - if s:forPath - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) - endif - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - call s:listener.onComplete(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) - if !a:opened - call s:listener.onAbort() - endif -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/changelist.vim b/vim/autoload/fuf/changelist.vim deleted file mode 100644 index 40f2d2c5ad..0000000000 --- a/vim/autoload/fuf/changelist.vim +++ /dev/null @@ -1,168 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_changelist') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_changelist = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#changelist#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#changelist#getSwitchOrder() - return g:fuf_changelist_switchOrder -endfunction - -" -function fuf#changelist#renewCache() -endfunction - -" -function fuf#changelist#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#changelist#onInit() - call fuf#defineLaunchCommand('FufChangeList', s:MODE_NAME, '""') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getChangesLines() - redir => result - :silent changes - redir END - return split(result, "\n") -endfunction - -" -function s:parseChangesLine(line) - " return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') - let elements = matchlist(a:line, '\v^(.)\s*(\d+)\s+(\d+)\s+(\d+)\s*(.*)$') - if empty(elements) - return {} - endif - return { - \ 'prefix': elements[1], - \ 'count' : elements[2], - \ 'lnum' : elements[3], - \ 'text' : printf('|%d:%d|%s', elements[3], elements[4], elements[5]), - \ } -endfunction - -" -function s:makeItem(line) - let parsed = s:parseChangesLine(a:line) - if empty(parsed) - return {} - endif - let item = fuf#makeNonPathItem(parsed.text, '') - let item.abbrPrefix = parsed.prefix - let item.lnum = parsed.lnum - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_changelist_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(self.bufNrPrev) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - let older = 0 - for line in reverse(s:getChangesLines()) - if stridx(line, '>') == 0 - let older = 1 - endif - let parsed = s:parseChangesLine(line) - if !empty(parsed) && parsed.text ==# a:word - if parsed.count != 0 - execute 'normal! ' . parsed.count . (older ? 'g;' : 'g,') . 'zvzz' - endif - break - endif - endfor -endfunction - -" -function s:handler.onModeEnterPre() - let self.items = s:getChangesLines() -endfunction - -" -function s:handler.onModeEnterPost() - call map(self.items, 's:makeItem(v:val)') - call filter(self.items, '!empty(v:val)') - call reverse(self.items) - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/vim/autoload/fuf/dir.vim b/vim/autoload/fuf/dir.vim deleted file mode 100644 index 689ba0f817..0000000000 --- a/vim/autoload/fuf/dir.vim +++ /dev/null @@ -1,128 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_dir') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_dir = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#dir#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#dir#getSwitchOrder() - return g:fuf_dir_switchOrder -endfunction - -" -function fuf#dir#renewCache() - let s:cache = {} -endfunction - -" -function fuf#dir#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#dir#onInit() - call fuf#defineLaunchCommand('FufDir' , s:MODE_NAME, '""') - call fuf#defineLaunchCommand('FufDirWithFullCwd' , s:MODE_NAME, 'fnamemodify(getcwd(), '':p'')') - call fuf#defineLaunchCommand('FufDirWithCurrentBufferDir', s:MODE_NAME, 'expand(''%:~:.'')[:-1-len(expand(''%:~:.:t''))]') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = getcwd() . g:fuf_dir_exclude . "\n" . a:dir - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, g:fuf_dir_exclude) - call filter(s:cache[key], 'v:val.word =~# ''[/\\]$''') - if isdirectory(a:dir) - call insert(s:cache[key], fuf#makePathItem(a:dir . '.', '', 0)) - endif - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_dir_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesAround( - \ split(glob(fnamemodify(a:word, ':p') . '*'), "\n"), - \ [], a:count, self.getPreviewHeight()) - return -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumItems(fuf#splitPath(a:patternPrimary).head) -endfunction - -" -function s:handler.onOpen(word, mode) - execute ':cd ' . fnameescape(a:word) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/file.vim b/vim/autoload/fuf/file.vim deleted file mode 100644 index 348b4af430..0000000000 --- a/vim/autoload/fuf/file.vim +++ /dev/null @@ -1,137 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_file') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_file = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#file#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#file#getSwitchOrder() - return g:fuf_file_switchOrder -endfunction - -" -function fuf#file#renewCache() - let s:cache = {} -endfunction - -" -function fuf#file#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#file#onInit() - call fuf#defineLaunchCommand('FufFile' , s:MODE_NAME, '""') - call fuf#defineLaunchCommand('FufFileWithFullCwd' , s:MODE_NAME, 'fnamemodify(getcwd(), '':p'')') - call fuf#defineLaunchCommand('FufFileWithCurrentBufferDir', s:MODE_NAME, 'expand(''%:~:.'')[:-1-len(expand(''%:~:.:t''))]') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:enumItems(dir) - let key = getcwd() . g:fuf_file_exclude . "\n" . a:dir - if !exists('s:cache[key]') - let s:cache[key] = fuf#enumExpandedDirsEntries(a:dir, g:fuf_file_exclude) - call fuf#mapToSetSerialIndex(s:cache[key], 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:cache[key]) - endif - return s:cache[key] -endfunction - -" -function s:enumNonCurrentItems(dir, bufNr, cache) - let key = a:dir . 'AVOIDING EMPTY KEY' - if !exists('a:cache[key]') - " NOTE: filtering should be done with - " 'bufnr("^" . v:val.word . "$") != a:bufNr'. - " But it takes a lot of time! - let bufName = bufname(a:bufNr) - let a:cache[key] = - \ filter(copy(s:enumItems(a:dir)), 'v:val.word != bufName') - endif - return a:cache[key] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_file_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPathTail', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumNonCurrentItems( - \ fuf#splitPath(a:patternPrimary).head, self.bufNrPrev, self.cache) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.cache = {} -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/givencmd.vim b/vim/autoload/fuf/givencmd.vim deleted file mode 100644 index 757282989a..0000000000 --- a/vim/autoload/fuf/givencmd.vim +++ /dev/null @@ -1,119 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_givencmd') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_givencmd = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givencmd#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givencmd#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givencmd#renewCache() -endfunction - -" -function fuf#givencmd#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givencmd#onInit() -endfunction - -" -function fuf#givencmd#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = copy(a:items) - call map(s:items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - if a:word[0] =~# '[:/?]' - call histadd(a:word[0], a:word[1:]) - endif - call feedkeys(a:word . "\", 'n') -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/givendir.vim b/vim/autoload/fuf/givendir.vim deleted file mode 100644 index 10b89efb00..0000000000 --- a/vim/autoload/fuf/givendir.vim +++ /dev/null @@ -1,119 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_givendir') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_givendir = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givendir#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givendir#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givendir#renewCache() -endfunction - -" -function fuf#givendir#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givendir#onInit() -endfunction - -" -function fuf#givendir#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = map(copy(a:items), 'substitute(v:val, ''[/\\]\?$'', "", "")') - let s:items = map(s:items, 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(s:items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(s:items) - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesAround( - \ split(glob(fnamemodify(a:word, ':p') . '*'), "\n"), - \ [], a:count, self.getPreviewHeight()) - return -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - execute ':cd ' . fnameescape(a:word) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/givenfile.vim b/vim/autoload/fuf/givenfile.vim deleted file mode 100644 index 3b726bca05..0000000000 --- a/vim/autoload/fuf/givenfile.vim +++ /dev/null @@ -1,117 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_givenfile') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_givenfile = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#givenfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#givenfile#getSwitchOrder() - return -1 -endfunction - -" -function fuf#givenfile#renewCache() -endfunction - -" -function fuf#givenfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#givenfile#onInit() -endfunction - -" -function fuf#givenfile#launch(initialPattern, partialMatching, prompt, items) - let s:prompt = (empty(a:prompt) ? '>' : a:prompt) - let s:items = map(copy(a:items), 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(s:items, 1) - call map(s:items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - call fuf#launch(s:MODE_NAME, a:initialPattern, a:partialMatching) -endfunction - - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(s:prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/help.vim b/vim/autoload/fuf/help.vim deleted file mode 100644 index b0693d0f92..0000000000 --- a/vim/autoload/fuf/help.vim +++ /dev/null @@ -1,202 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_help') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_help = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#help#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#help#getSwitchOrder() - return g:fuf_help_switchOrder -endfunction - -" -function fuf#help#renewCache() - let s:cache = {} -endfunction - -" -function fuf#help#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#help#onInit() - call fuf#defineLaunchCommand('FufHelp' , s:MODE_NAME, '""') - call fuf#defineLaunchCommand('FufHelpWithCursorWord', s:MODE_NAME, 'expand('''')') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getCurrentHelpTagFiles() - let prefix = 'doc' . fuf#getPathSeparator() - let tagFiles = split(globpath(&runtimepath, prefix . 'tags' ), "\n") - \ + split(globpath(&runtimepath, prefix . 'tags-??'), "\n") - return sort(map(tagFiles, 'fnamemodify(v:val, ":p")')) -endfunction - -" -function s:parseHelpTagEntry(line, tagFile) - let elements = split(a:line, "\t") - if len(elements) != 3 || elements[0][0] ==# '!' - return {} - endif - let suffix = matchstr(a:tagFile, '-\zs..$') - if empty(suffix) - let suffix = '@en' - else - let suffix = '@' . suffix - endif - let dir = fnamemodify(a:tagFile, ':h') . fuf#getPathSeparator() - return { - \ 'word' : elements[0] . suffix, - \ 'path' : dir . elements[1], - \ 'pattern': elements[2][1:], - \ } -endfunction - -" -function s:getHelpTagEntries(tagFile) - let names = map(readfile(a:tagFile), 's:parseHelpTagEntry(v:val, a:tagFile)') - return filter(names, '!empty(v:val)') -endfunction - -" -function s:parseHelpTagFiles(tagFiles) - if !empty(g:fuf_help_cache_dir) - if !isdirectory(expand(g:fuf_help_cache_dir)) - call mkdir(expand(g:fuf_help_cache_dir), 'p') - endif - " NOTE: fnamemodify('a/b', ':p') returns 'a/b/' if the directory exists. - let cacheFile = fnamemodify(g:fuf_help_cache_dir, ':p') - \ . fuf#hash224(join(a:tagFiles, "\n")) - if filereadable(cacheFile) && fuf#countModifiedFiles(a:tagFiles, getftime(cacheFile)) == 0 - return map(readfile(cacheFile), 'eval(v:val)') - endif - endif - let items = fuf#unique(fuf#concat(map(copy(a:tagFiles), 's:getHelpTagEntries(v:val)'))) - let items = map(items, 'extend(v:val, fuf#makeNonPathItem(v:val.word, ""))') - call fuf#mapToSetSerialIndex(items, 1) - let items = map(items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - if !empty(g:fuf_help_cache_dir) - call writefile(map(copy(items), 'string(v:val)'), cacheFile) - endif - return items -endfunction - -" -function s:enumHelpTags(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join(a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseHelpTagFiles(a:tagFiles) - \ } - endif - return s:cache[key].items -endfunction - -" -function s:getMatchingIndex(lines, pattern) - if empty(a:pattern) - return -1 - endif - for i in range(len(a:lines)) - if stridx(a:lines[i], a:pattern) >= 0 - return i - endif - endfor - return -1 -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_help_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(s:enumHelpTags(self.tagFiles)), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].path) - let index = s:getMatchingIndex(lines, items[0].pattern) - return [items[0].path . ':'] + fuf#makePreviewLinesAround( - \ lines, (index < 0 ? [] : [index]), a:count, self.getPreviewHeight() - 1) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumHelpTags(self.tagFiles) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openHelp(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = s:getCurrentHelpTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/jumplist.vim b/vim/autoload/fuf/jumplist.vim deleted file mode 100644 index 72876d9a15..0000000000 --- a/vim/autoload/fuf/jumplist.vim +++ /dev/null @@ -1,178 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_jumplist') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_jumplist = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#jumplist#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#jumplist#getSwitchOrder() - return g:fuf_jumplist_switchOrder -endfunction - -" -function fuf#jumplist#renewCache() -endfunction - -" -function fuf#jumplist#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#jumplist#onInit() - call fuf#defineLaunchCommand('FufJumpList', s:MODE_NAME, '""') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getJumpsLines() - redir => result - :silent jumps - redir END - return split(result, "\n") -endfunction - -" -function s:parseJumpsLine(line, bufnrPrev) - "return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') - let elements = matchlist(a:line, '\v^(.)\s*(\d+)\s+(\d+)\s+(\d+)\s*(.*)$') - if empty(elements) - return {} - endif - let linePrevBuffer = join(getbufline(a:bufnrPrev, elements[3])) - if stridx(linePrevBuffer, elements[5]) >= 0 - let fname = bufname(a:bufnrPrev) - let text = elements[5] - else - let fname = elements[5] - let text = join(getbufline('^' . elements[5] . '$', elements[3])) - endif - return { - \ 'prefix': elements[1], - \ 'count' : elements[2], - \ 'lnum' : elements[3], - \ 'fname' : fname, - \ 'text' : printf('%s|%d:%d|%s', fname, elements[3], elements[4], text), - \ } -endfunction - -" -function s:makeItem(line, bufnrPrev) - let parsed = s:parseJumpsLine(a:line, a:bufnrPrev) - if empty(parsed) - return {} - endif - let item = fuf#makeNonPathItem(parsed.text, '') - let item.abbrPrefix = parsed.prefix - let item.lnum = parsed.lnum - let item.fname = parsed.fname - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_jumplist_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].fname) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - let older = 0 - for line in reverse(s:getJumpsLines()) - if stridx(line, '>') == 0 - let older = 1 - endif - let parsed = s:parseJumpsLine(line, self.bufNrPrev) - if !empty(parsed) && parsed.text ==# a:word - if parsed.count != 0 - execute 'normal! ' . parsed.count . (older ? "\" : "\") . 'zvzz' - endif - break - endif - endfor -endfunction - -" -function s:handler.onModeEnterPre() - let self.items = s:getJumpsLines() -endfunction - -" -function s:handler.onModeEnterPost() - call map(self.items, 's:makeItem(v:val, self.bufNrPrev)') - call filter(self.items, '!empty(v:val)') - call reverse(self.items) - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/vim/autoload/fuf/line.vim b/vim/autoload/fuf/line.vim deleted file mode 100644 index 166c62953e..0000000000 --- a/vim/autoload/fuf/line.vim +++ /dev/null @@ -1,131 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_line') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_line = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#line#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#line#getSwitchOrder() - return g:fuf_line_switchOrder -endfunction - -" -function fuf#line#renewCache() -endfunction - -" -function fuf#line#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#line#onInit() - call fuf#defineLaunchCommand('FufLine', s:MODE_NAME, '""') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') -let s:OPEN_TYPE_DELETE = -1 - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_line_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(self.bufNrPrev) - return fuf#makePreviewLinesAround( - \ lines, [items[0].index - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - call filter(self.items, 'v:val.word ==# a:word') - if empty(self.items) - return - execute 'cc ' . self.items[0].index - endif - call cursor(self.items[0].index, 0) - normal! zvzz -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let tab = repeat(' ', getbufvar(self.bufNrPrev, '&tabstop')) - let self.items = getbufline(self.bufNrPrev, 1, '$') - let lnumFormat = '%' . len(string(len(self.items) + 1)) . 'd|' - for i in range(len(self.items)) - let self.items[i] = printf(lnumFormat, i + 1) - \ . substitute(self.items[i], "\t", tab, 'g') - endfor - call map(self.items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 0)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/mrucmd.vim b/vim/autoload/fuf/mrucmd.vim deleted file mode 100644 index cb3ada33b3..0000000000 --- a/vim/autoload/fuf/mrucmd.vim +++ /dev/null @@ -1,130 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_mrucmd') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_mrucmd = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#mrucmd#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#mrucmd#getSwitchOrder() - return g:fuf_mrucmd_switchOrder -endfunction - -" -function fuf#mrucmd#renewCache() -endfunction - -" -function fuf#mrucmd#requiresOnCommandPre() - return 1 -endfunction - -" -function fuf#mrucmd#onInit() - call fuf#defineLaunchCommand('FufMruCmd', s:MODE_NAME, '""') -endfunction - -" -function fuf#mrucmd#onCommandPre(cmd) - if getcmdtype() =~# '^[:/?]' - call s:updateInfo(a:cmd) - endif -endfunction - - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:updateInfo(cmd) - let info = fuf#loadInfoFile(s:MODE_NAME) - let info.data = fuf#updateMruList( - \ info.data, { 'word' : a:cmd, 'time' : localtime() }, - \ g:fuf_mrucmd_maxItem, g:fuf_mrucmd_exclude) - call fuf#saveInfoFile(s:MODE_NAME, info) -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_mrucmd_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return 0 -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return [] -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call s:updateInfo(a:word) - call histadd(a:word[0], a:word[1:]) - call feedkeys(a:word . "\", 'n') -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = copy(self.info.data) - call map(self.items, 'fuf#makeNonPathItem(v:val.word, strftime(g:fuf_timeFormat, v:val.time))') - call fuf#mapToSetSerialIndex(self.items, 1) - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/mrufile.vim b/vim/autoload/fuf/mrufile.vim deleted file mode 100644 index 9235f03319..0000000000 --- a/vim/autoload/fuf/mrufile.vim +++ /dev/null @@ -1,156 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_mrufile') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_mrufile = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#mrufile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#mrufile#getSwitchOrder() - return g:fuf_mrufile_switchOrder -endfunction - -" -function fuf#mrufile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#mrufile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#mrufile#onInit() - call fuf#defineLaunchCommand('FufMruFile', s:MODE_NAME, '""') - augroup fuf#mrufile - autocmd! - autocmd BufEnter * call s:updateInfo() - autocmd BufWritePost * call s:updateInfo() - augroup END -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:updateInfo() - if !empty(&buftype) || !filereadable(expand('%')) - return - endif - let info = fuf#loadInfoFile(s:MODE_NAME) - let info.data = fuf#updateMruList( - \ info.data, { 'word' : expand('%:p'), 'time' : localtime() }, - \ g:fuf_mrufile_maxItem, g:fuf_mrufile_exclude) - call fuf#saveInfoFile(s:MODE_NAME, info) - call s:removeItemFromCache(expand('%:p')) -endfunction - -" -function s:removeItemFromCache(word) - for items in values(s:cache) - if exists('items[a:word]') - unlet items[a:word] - endif - endfor -endfunction - -" returns empty value if invalid item -function s:formatItemUsingCache(item) - if a:item.word !~ '\S' - return {} - endif - if !exists('s:cache[a:item.word]') - if filereadable(a:item.word) - let s:cache[a:item.word] = fuf#makePathItem( - \ fnamemodify(a:item.word, ':~'), strftime(g:fuf_timeFormat, a:item.time), 0) - else - let s:cache[a:item.word] = {} - endif - endif - return s:cache[a:item.word] -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_mrufile_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = copy(self.info.data) - let self.items = map(self.items, 's:formatItemUsingCache(v:val)') - let self.items = filter(self.items, '!empty(v:val) && bufnr("^" . v:val.word . "$") != self.bufNrPrev') - let self.items = fuf#mapToSetSerialIndex(self.items, 1) - let self.items = fuf#mapToSetAbbrWithSnippedWordAsPath(self.items) -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/quickfix.vim b/vim/autoload/fuf/quickfix.vim deleted file mode 100644 index 1bb4b6457b..0000000000 --- a/vim/autoload/fuf/quickfix.vim +++ /dev/null @@ -1,150 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_quickfix') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_quickfix = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#quickfix#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#quickfix#getSwitchOrder() - return g:fuf_quickfix_switchOrder -endfunction - -" -function fuf#quickfix#renewCache() -endfunction - -" -function fuf#quickfix#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#quickfix#onInit() - call fuf#defineLaunchCommand('FufQuickfix', s:MODE_NAME, '""') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getJumpsLines() - redir => result - :silent jumps - redir END - return split(result, "\n") -endfunction - -" -function s:parseJumpsLine(line) - return matchlist(a:line, '^\(.\)\s\+\(\d\+\)\s\(.*\)$') -endfunction - -" -function s:makeItem(qfItem) - if !a:qfItem.valid - return {} - endif - let item = fuf#makeNonPathItem( - \ printf('%s|%d:%d|%s', bufname(a:qfItem.bufnr), a:qfItem.lnum, - \ a:qfItem.col, matchstr(a:qfItem.text, '\s*\zs.*\S')) - \ , '') - let item.bufnr = a:qfItem.bufnr - let item.lnum = a:qfItem.lnum - return item -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_quickfix_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - let items = filter(copy(self.items), 'v:val.word ==# a:word') - if empty(items) - return [] - endif - let lines = fuf#getFileLines(items[0].bufnr) - return fuf#makePreviewLinesAround( - \ lines, [items[0].lnum - 1], a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#prejump(a:mode) - call filter(self.items, 'v:val.word ==# a:word') - if !empty(self.items) - execute 'cc ' . self.items[0].index - endif -endfunction - -" -function s:handler.onModeEnterPre() -endfunction - -" -function s:handler.onModeEnterPost() - let self.items = getqflist() - call map(self.items, 's:makeItem(v:val)') - call fuf#mapToSetSerialIndex(self.items, 1) - call filter(self.items, 'exists("v:val.word")') - call map(self.items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: - diff --git a/vim/autoload/fuf/tag.vim b/vim/autoload/fuf/tag.vim deleted file mode 100644 index bf566f056e..0000000000 --- a/vim/autoload/fuf/tag.vim +++ /dev/null @@ -1,182 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_tag') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_tag = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#tag#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#tag#getSwitchOrder() - return g:fuf_tag_switchOrder -endfunction - -" -function fuf#tag#renewCache() - let s:cache = {} -endfunction - -" -function fuf#tag#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#tag#onInit() - call fuf#defineLaunchCommand('FufTag' , s:MODE_NAME, '""') - call fuf#defineLaunchCommand('FufTagWithCursorWord', s:MODE_NAME, 'expand('''')') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getTagNames(tagFile) - let names = map(readfile(a:tagFile), 'matchstr(v:val, ''^[^!\t][^\t]*'')') - return filter(names, 'v:val =~# ''\S''') -endfunction - -" -function s:parseTagFiles(tagFiles) - if !empty(g:fuf_tag_cache_dir) - if !isdirectory(expand(g:fuf_tag_cache_dir)) - call mkdir(expand(g:fuf_tag_cache_dir), 'p') - endif - " NOTE: fnamemodify('a/b', ':p') returns 'a/b/' if the directory exists. - let cacheFile = fnamemodify(g:fuf_tag_cache_dir, ':p') - \ . fuf#hash224(join(a:tagFiles, "\n")) - if filereadable(cacheFile) && fuf#countModifiedFiles(a:tagFiles, getftime(cacheFile)) == 0 - return map(readfile(cacheFile), 'eval(v:val)') - endif - endif - let items = fuf#unique(fuf#concat(map(copy(a:tagFiles), 's:getTagNames(v:val)'))) - let items = map(items, 'fuf#makeNonPathItem(v:val, "")') - call fuf#mapToSetSerialIndex(items, 1) - let items = map(items, 'fuf#setAbbrWithFormattedWord(v:val, 1)') - if !empty(g:fuf_tag_cache_dir) - call writefile(map(copy(items), 'string(v:val)'), cacheFile) - endif - return items -endfunction - -" -function s:enumTags(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join(a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseTagFiles(a:tagFiles) - \ } - endif - return s:cache[key].items -endfunction - -" -function s:getMatchingIndex(lines, cmd) - if a:cmd !~# '\D' - return str2nr(a:cmd) - endif - let pattern = matchstr(a:cmd, '^\/\^\zs.*\ze\$\/$') - if empty(pattern) - return -1 - endif - for i in range(len(a:lines)) - if a:lines[i] ==# pattern - return i - endif - endfor - return -1 -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_tag_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 0 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForNonPath', - \ self.partialMatching) -endfunction - -" 'cmd' is '/^hoge hoge$/' or line number -function s:handler.makePreviewLines(word, count) - let tags = taglist('^' . a:word . '$') - if empty(tags) - return [] - endif - let i = a:count % len(tags) - let title = printf('(%d/%d) %s', i + 1, len(tags), tags[i].filename) - let lines = fuf#getFileLines(tags[i].filename) - let index = s:getMatchingIndex(lines, tags[i].cmd) - return [title] + fuf#makePreviewLinesAround( - \ lines, (index < 0 ? [] : [index]), 0, self.getPreviewHeight() - 1) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return s:enumTags(self.tagFiles) -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openTag(a:word, a:mode) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = fuf#getCurrentTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() - let &l:tags = join(self.tagFiles, ',') -endfunction - -" -function s:handler.onModeLeavePost(opened) - let &l:tags = '' -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/fuf/taggedfile.vim b/vim/autoload/fuf/taggedfile.vim deleted file mode 100644 index 30a79b1478..0000000000 --- a/vim/autoload/fuf/taggedfile.vim +++ /dev/null @@ -1,162 +0,0 @@ -"============================================================================= -" Copyright (c) 2007-2009 Takeshi NISHIDA -" -"============================================================================= -" LOAD GUARD {{{1 - -if exists('g:loaded_autoload_fuf_taggedfile') || v:version < 702 - finish -endif -let g:loaded_autoload_fuf_taggedfile = 1 - -" }}}1 -"============================================================================= -" GLOBAL FUNCTIONS {{{1 - -" -function fuf#taggedfile#createHandler(base) - return a:base.concretize(copy(s:handler)) -endfunction - -" -function fuf#taggedfile#getSwitchOrder() - return g:fuf_taggedfile_switchOrder -endfunction - -" -function fuf#taggedfile#renewCache() - let s:cache = {} -endfunction - -" -function fuf#taggedfile#requiresOnCommandPre() - return 0 -endfunction - -" -function fuf#taggedfile#onInit() - call fuf#defineLaunchCommand('FufTaggedFile', s:MODE_NAME, '""') -endfunction - -" }}}1 -"============================================================================= -" LOCAL FUNCTIONS/VARIABLES {{{1 - -let s:MODE_NAME = expand(':t:r') - -" -function s:getTaggedFileList(tagfile) - execute 'cd ' . fnamemodify(a:tagfile, ':h') - let result = map(readfile(a:tagfile), 'matchstr(v:val, ''^[^!\t][^\t]*\t\zs[^\t]\+'')') - call map(readfile(a:tagfile), 'fnamemodify(v:val, ":p")') - cd - - call map(readfile(a:tagfile), 'fnamemodify(v:val, ":~:.")') - return filter(result, 'v:val =~# ''[^/\\ ]$''') -endfunction - -" -function s:parseTagFiles(tagFiles) - if !empty(g:fuf_taggedfile_cache_dir) - if !isdirectory(expand(g:fuf_taggedfile_cache_dir)) - call mkdir(expand(g:fuf_taggedfile_cache_dir), 'p') - endif - " NOTE: fnamemodify('a/b', ':p') returns 'a/b/' if the directory exists. - let cacheFile = fnamemodify(g:fuf_taggedfile_cache_dir, ':p') - \ . fuf#hash224(join(a:tagFiles, "\n")) - if filereadable(cacheFile) && fuf#countModifiedFiles(a:tagFiles, getftime(cacheFile)) == 0 - return map(readfile(cacheFile), 'eval(v:val)') - endif - endif - let items = fuf#unique(fuf#concat(map(copy(a:tagFiles), 's:getTaggedFileList(v:val)'))) - call map(items, 'fuf#makePathItem(v:val, "", 0)') - call fuf#mapToSetSerialIndex(items, 1) - call fuf#mapToSetAbbrWithSnippedWordAsPath(items) - if !empty(g:fuf_taggedfile_cache_dir) - call writefile(map(copy(items), 'string(v:val)'), cacheFile) - endif - return items -endfunction - -" -function s:enumTaggedFiles(tagFiles) - if !len(a:tagFiles) - return [] - endif - let key = join([getcwd()] + a:tagFiles, "\n") - if !exists('s:cache[key]') || fuf#countModifiedFiles(a:tagFiles, s:cache[key].time) - let s:cache[key] = { - \ 'time' : localtime(), - \ 'items' : s:parseTagFiles(a:tagFiles) - \ } - endif - return s:cache[key].items -endfunction - -" }}}1 -"============================================================================= -" s:handler {{{1 - -let s:handler = {} - -" -function s:handler.getModeName() - return s:MODE_NAME -endfunction - -" -function s:handler.getPrompt() - return fuf#formatPrompt(g:fuf_taggedfile_prompt, self.partialMatching) -endfunction - -" -function s:handler.getPreviewHeight() - return g:fuf_previewHeight -endfunction - -" -function s:handler.targetsPath() - return 1 -endfunction - -" -function s:handler.makePatternSet(patternBase) - return fuf#makePatternSet(a:patternBase, 's:interpretPrimaryPatternForPath', - \ self.partialMatching) -endfunction - -" -function s:handler.makePreviewLines(word, count) - return fuf#makePreviewLinesForFile(a:word, a:count, self.getPreviewHeight()) -endfunction - -" -function s:handler.getCompleteItems(patternPrimary) - return self.items -endfunction - -" -function s:handler.onOpen(word, mode) - call fuf#openFile(a:word, a:mode, g:fuf_reuseWindow) -endfunction - -" -function s:handler.onModeEnterPre() - let self.tagFiles = fuf#getCurrentTagFiles() -endfunction - -" -function s:handler.onModeEnterPost() - " NOTE: Don't do this in onModeEnterPre() - " because that should return in a short time. - let self.items = - \ filter(copy(s:enumTaggedFiles(self.tagFiles)), - \ 'bufnr("^" . v:val.word . "$") != self.bufNrPrev') -endfunction - -" -function s:handler.onModeLeavePost(opened) -endfunction - -" }}}1 -"============================================================================= -" vim: set fdm=marker: diff --git a/vim/autoload/rails.vim b/vim/autoload/rails.vim deleted file mode 100644 index 01c984e829..0000000000 --- a/vim/autoload/rails.vim +++ /dev/null @@ -1,4680 +0,0 @@ -" autoload/rails.vim -" Author: Tim Pope - -" Install this file as autoload/rails.vim. - -if exists('g:autoloaded_rails') || &cp - finish -endif -let g:autoloaded_rails = '4.1' - -let s:cpo_save = &cpo -set cpo&vim - -" Utility Functions {{{1 - -let s:app_prototype = {} -let s:file_prototype = {} -let s:buffer_prototype = {} -let s:readable_prototype = {} - -function! s:add_methods(namespace, method_names) - for name in a:method_names - let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name) - endfor -endfunction - -function! s:function(name) - return function(substitute(a:name,'^s:',matchstr(expand(''), '\d\+_'),'')) -endfunction - -function! s:sub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'') -endfunction - -function! s:gsub(str,pat,rep) - return substitute(a:str,'\v\C'.a:pat,a:rep,'g') -endfunction - -function! s:startswith(string,prefix) - return strpart(a:string, 0, strlen(a:prefix)) ==# a:prefix -endfunction - -function! s:compact(ary) - return s:sub(s:sub(s:gsub(a:ary,'\n\n+','\n'),'\n$',''),'^\n','') -endfunction - -function! s:scrub(collection,item) - " Removes item from a newline separated collection - let col = "\n" . a:collection - let idx = stridx(col,"\n".a:item."\n") - let cnt = 0 - while idx != -1 && cnt < 100 - let col = strpart(col,0,idx).strpart(col,idx+strlen(a:item)+1) - let idx = stridx(col,"\n".a:item."\n") - let cnt += 1 - endwhile - return strpart(col,1) -endfunction - -function! s:escarg(p) - return s:gsub(a:p,'[ !%#]','\\&') -endfunction - -function! s:esccmd(p) - return s:gsub(a:p,'[!%#]','\\&') -endfunction - -function! s:rquote(str) - " Imperfect but adequate for Ruby arguments - if a:str =~ '^[A-Za-z0-9_/.:-]\+$' - return a:str - elseif &shell =~? 'cmd' - return '"'.s:gsub(s:gsub(a:str,'\','\\'),'"','\\"').'"' - else - return "'".s:gsub(s:gsub(a:str,'\','\\'),"'","'\\\\''")."'" - endif -endfunction - -function! s:sname() - return fnamemodify(s:file,':t:r') -endfunction - -function! s:pop_command() - if exists("s:command_stack") && len(s:command_stack) > 0 - exe remove(s:command_stack,-1) - endif -endfunction - -function! s:push_chdir(...) - if !exists("s:command_stack") | let s:command_stack = [] | endif - if exists("b:rails_root") && (a:0 ? getcwd() !=# rails#app().path() : !s:startswith(getcwd(), rails#app().path())) - let chdir = exists("*haslocaldir") && haslocaldir() ? "lchdir " : "chdir " - call add(s:command_stack,chdir.s:escarg(getcwd())) - exe chdir.s:escarg(rails#app().path()) - else - call add(s:command_stack,"") - endif -endfunction - -function! s:app_path(...) dict - return join([self.root]+a:000,'/') -endfunction - -function! s:app_has_file(file) dict - return filereadable(self.path(a:file)) -endfunction - -function! s:app_find_file(name, ...) dict abort - let trim = strlen(self.path())+1 - if a:0 - let path = s:pathjoin(map(s:pathsplit(a:1),'self.path(v:val)')) - else - let path = s:pathjoin([self.path()]) - endif - let suffixesadd = s:pathjoin(get(a:000,1,&suffixesadd)) - let default = get(a:000,2,'') - let oldsuffixesadd = &l:suffixesadd - try - let &suffixesadd = suffixesadd - " Versions before 7.1.256 returned directories from findfile - if type(default) == type(0) && (v:version < 702 || default == -1) - let all = findfile(a:name,path,-1) - if v:version < 702 - call filter(all,'!isdirectory(v:val)') - endif - call map(all,'s:gsub(strpart(fnamemodify(v:val,":p"),trim),"\\\\","/")') - return default < 0 ? all : get(all,default-1,'') - elseif type(default) == type(0) - let found = findfile(a:name,path,default) - else - let i = 1 - let found = findfile(a:name,path) - while v:version < 702 && found != "" && isdirectory(found) - let i += 1 - let found = findfile(a:name,path,i) - endwhile - endif - return found == "" ? default : s:gsub(strpart(fnamemodify(found,':p'),trim),'\\','/') - finally - let &l:suffixesadd = oldsuffixesadd - endtry -endfunction - -call s:add_methods('app',['path','has_file','find_file']) - -" Split a path into a list. From pathogen.vim -function! s:pathsplit(path) abort - if type(a:path) == type([]) | return copy(a:path) | endif - let split = split(a:path,'\\\@' - if matchstr(self.getline(a:lnum+1),'^'.spc) && !matchstr(self.getline(a:lnum+1),'^'.spc.endpat) && matchstr(cline,endpat) - return a:lnum - endif - let endl = a:lnum - while endl <= self.line_count() - let endl += 1 - if self.getline(endl) =~ '^'.spc.endpat - return endl - elseif self.getline(endl) =~ '^=begin\>' - while self.getline(endl) !~ '^=end\>' && endl <= self.line_count() - let endl += 1 - endwhile - let endl += 1 - elseif self.getline(endl) !~ '^'.spc && self.getline(endl) !~ '^\s*\%(#.*\)\=$' - return 0 - endif - endwhile - return 0 -endfunction - -function! s:endof(lnum) - return rails#buffer().end_of(a:lnum) -endfunction - -function! s:readable_last_opening_line(start,pattern,limit) dict abort - let line = a:start - while line > a:limit && self.getline(line) !~ a:pattern - let line -= 1 - endwhile - let lend = self.end_of(line) - if line > a:limit && (lend < 0 || lend >= a:start) - return line - else - return -1 - endif -endfunction - -function! s:lastopeningline(pattern,limit,start) - return rails#buffer().last_opening_line(a:start,a:pattern,a:limit) -endfunction - -function! s:readable_define_pattern() dict abort - if self.name() =~ '\.yml$' - return '^\%(\h\k*:\)\@=' - endif - let define = '^\s*def\s\+\(self\.\)\=' - if self.name() =~# '\.rake$' - let define .= "\\\|^\\s*\\%(task\\\|file\\)\\s\\+[:'\"]" - endif - if self.name() =~# '/schema\.rb$' - let define .= "\\\|^\\s*create_table\\s\\+[:'\"]" - endif - return define -endfunction - -function! s:readable_last_method_line(start) dict abort - return self.last_opening_line(a:start,self.define_pattern(),0) -endfunction - -function! s:lastmethodline(start) - return rails#buffer().last_method_line(a:start) -endfunction - -function! s:readable_last_method(start) dict abort - let line = self.last_method_line(a:start) - if line - return s:sub(matchstr(self.getline(line),'\%('.self.define_pattern().'\)\zs\h\%(\k\|[:.]\)*[?!=]\='),':$','') - else - return "" - endif -endfunction - -function! s:lastmethod(...) - return rails#buffer().last_method(a:0 ? a:1 : line(".")) -endfunction - -function! s:readable_last_format(start) dict abort - if self.type_name('view') - let format = fnamemodify(self.path(),':r:e') - if format == '' - return get({'rhtml': 'html', 'rxml': 'xml', 'rjs': 'js', 'haml': 'html'},fnamemodify(self.path(),':e'),'') - else - return format - endif - endif - let rline = self.last_opening_line(a:start,'\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\.*\|respond_to\)\s*\%(\ rline - let match = matchstr(self.getline(line),'\C^\s*'.variable.'\s*\.\s*\zs\h\k*') - if match != '' - return match - endif - let line -= 1 - endwhile - endif - return "" -endfunction - -function! s:lastformat(start) - return rails#buffer().last_format(a:start) -endfunction - -function! s:format(...) - let format = rails#buffer().last_format(a:0 > 1 ? a:2 : line(".")) - return format ==# '' && a:0 ? a:1 : format -endfunction - -call s:add_methods('readable',['end_of','last_opening_line','last_method_line','last_method','last_format','define_pattern']) - -let s:view_types = 'rhtml,erb,rxml,builder,rjs,mab,liquid,haml,dryml,mn' - -function! s:viewspattern() - return '\%('.s:gsub(s:view_types,',','\\|').'\)' -endfunction - -function! s:controller(...) - return rails#buffer().controller_name(a:0 ? a:1 : 0) -endfunction - -function! s:readable_controller_name(...) dict abort - let f = self.name() - if has_key(self,'getvar') && self.getvar('rails_controller') != '' - return self.getvar('rails_controller') - elseif f =~ '\ get(self,last_lines_ftime,0) - let self.last_lines = readfile(self.path()) - let self.last_lines_ftime = ftime - endif - return get(self,'last_lines',[]) -endfunction - -function! s:file_getline(lnum,...) dict abort - if a:0 - return self.lines[lnum-1 : a:1-1] - else - return self.lines[lnum-1] - endif -endfunction - -function! s:buffer_lines() dict abort - return self.getline(1,'$') -endfunction - -function! s:buffer_getline(...) dict abort - if a:0 == 1 - return get(call('getbufline',[self.number()]+a:000),0,'') - else - return call('getbufline',[self.number()]+a:000) - endif -endfunction - -function! s:readable_line_count() dict abort - return len(self.lines()) -endfunction - -function! s:environment() - if exists('$RAILS_ENV') - return $RAILS_ENV - else - return "development" - endif -endfunction - -function! s:Complete_environments(...) - return s:completion_filter(rails#app().environments(),a:0 ? a:1 : "") -endfunction - -function! s:warn(str) - echohl WarningMsg - echomsg a:str - echohl None - " Sometimes required to flush output - echo "" - let v:warningmsg = a:str -endfunction - -function! s:error(str) - echohl ErrorMsg - echomsg a:str - echohl None - let v:errmsg = a:str -endfunction - -function! s:debug(str) - if exists("g:rails_debug") && g:rails_debug - echohl Debug - echomsg a:str - echohl None - endif -endfunction - -function! s:buffer_getvar(varname) dict abort - return getbufvar(self.number(),a:varname) -endfunction - -function! s:buffer_setvar(varname, val) dict abort - return setbufvar(self.number(),a:varname,a:val) -endfunction - -call s:add_methods('buffer',['getvar','setvar']) - -" }}}1 -" "Public" Interface {{{1 - -" RailsRoot() is the only official public function - -function! rails#underscore(str) - let str = s:gsub(a:str,'::','/') - let str = s:gsub(str,'(\u+)(\u\l)','\1_\2') - let str = s:gsub(str,'(\l|\d)(\u)','\1_\2') - let str = tolower(str) - return str -endfunction - -function! rails#camelize(str) - let str = s:gsub(a:str,'/(.=)','::\u\1') - let str = s:gsub(str,'%([_-]|<)(.)','\u\1') - return str -endfunction - -function! rails#singularize(word) - " Probably not worth it to be as comprehensive as Rails but we can - " still hit the common cases. - let word = a:word - if word =~? '\.js$' || word == '' - return word - endif - let word = s:sub(word,'eople$','ersons') - let word = s:sub(word,'[aeio]@ 0 && getbufvar(nr,'rails_file_type') != '' - return getbufvar(nr,'rails_file_type') - elseif f =~ '_controller\.rb$' || f =~ '\' - let r = "controller-api" - else - let r = "controller" - endif - elseif f =~ '_api\.rb' - let r = "api" - elseif f =~ '\') - if class == "ActiveResource::Base" - let class = "ares" - let r = "model-ares" - elseif class == 'ActionMailer::Base' - let r = "mailer" - elseif class != '' - let class = tolower(s:gsub(class,'[^A-Z]','')) - let r = "model-".class - elseif f =~ '_mailer\.rb$' - let r = "mailer" - elseif top =~ '\<\%(validates_\w\+_of\|set_\%(table_name\|primary_key\)\|has_one\|has_many\|belongs_to\)\>' - let r = "model-arb" - else - let r = "model" - endif - elseif f =~ '\.*\.' - let r = "view-layout-" . e - elseif f =~ '\<\%(app/views\|components\)/.*/_\k\+\.\k\+\%(\.\k\+\)\=$' - let r = "view-partial-" . e - elseif f =~ '\.*\.' || f =~ '\' - if e == "yml" - let r = "fixtures-yaml" - else - let r = "fixtures" . (e == "" ? "" : "-" . e) - endif - elseif f =~ '\' || f=~ '\.*\.rb$' - let r = "config-routes" - elseif f =~ '\"')) - else - return a:type - endif -endfunction - -function! s:app_environments() dict - if self.cache.needs('environments') - call self.cache.set('environments',self.relglob('config/environments/','**/*','.rb')) - endif - return copy(self.cache.get('environments')) -endfunction - -function! s:app_default_locale() dict abort - if self.cache.needs('default_locale') - let candidates = map(filter(s:readfile(self.path('config/environment.rb')),'v:val =~ "^ *config.i18n.default_locale = :[\"'']\\=[A-Za-z-]\\+[\"'']\\= *$"'),'matchstr(v:val,"[A-Za-z-]\\+[\"'']\\= *$")') - call self.cache.set('default_locale',get(candidates,0,'en')) - endif - return self.cache.get('default_locale') -endfunction - -function! s:app_has(feature) dict - let map = { - \'test': 'test/', - \'spec': 'spec/', - \'cucumber': 'features/', - \'sass': 'public/stylesheets/sass/'} - if self.cache.needs('features') - call self.cache.set('features',{}) - endif - let features = self.cache.get('features') - if !has_key(features,a:feature) - let path = get(map,a:feature,a:feature.'/') - let features[a:feature] = isdirectory(rails#app().path(path)) - endif - return features[a:feature] -endfunction - -" Returns the subset of ['test', 'spec', 'cucumber'] present on the app. -function! s:app_test_suites() dict - return filter(['test','spec','cucumber'],'self.has(v:val)') -endfunction - -call s:add_methods('app',['default_locale','environments','file','has','test_suites']) -call s:add_methods('file',['path','name','lines','getline']) -call s:add_methods('buffer',['app','number','path','name','lines','getline','type_name']) -call s:add_methods('readable',['app','calculate_file_type','type_name','line_count']) - -" }}}1 -" Ruby Execution {{{1 - -function! s:app_ruby_shell_command(cmd) dict abort - if self.path() =~ '://' - return "ruby ".a:cmd - else - return "ruby -C ".s:rquote(self.path())." ".a:cmd - endif -endfunction - -function! s:app_script_shell_command(cmd) dict abort - if self.has_file('script/rails') && a:cmd !~# '^rails\>' - let cmd = 'script/rails '.a:cmd - else - let cmd = 'script/'.a:cmd - endif - return self.ruby_shell_command(cmd) -endfunction - -function! s:app_background_script_command(cmd) dict abort - let cmd = s:esccmd(self.script_shell_command(a:cmd)) - if has_key(self,'options') && has_key(self.options,'gnu_screen') - let screen = self.options.gnu_screen - else - let screen = g:rails_gnu_screen - endif - if has("gui_win32") - if &shellcmdflag == "-c" && ($PATH . &shell) =~? 'cygwin' - silent exe "!cygstart -d ".s:rquote(self.path())." ruby ".a:cmd - else - exe "!start ".cmd - endif - elseif exists("$STY") && !has("gui_running") && screen && executable("screen") - silent exe "!screen -ln -fn -t ".s:sub(s:sub(a:cmd,'\s.*',''),'^%(script|-rcommand)/','rails-').' '.cmd - else - exe "!".cmd - endif - return v:shell_error -endfunction - -function! s:app_execute_script_command(cmd) dict abort - exe '!'.s:esccmd(self.script_shell_command(a:cmd)) - return v:shell_error -endfunction - -function! s:app_lightweight_ruby_eval(ruby,...) dict abort - let def = a:0 ? a:1 : "" - if !executable("ruby") - return def - endif - let args = '-e '.s:rquote('begin; require %{rubygems}; rescue LoadError; end; begin; require %{active_support}; rescue LoadError; end; '.a:ruby) - let cmd = self.ruby_shell_command(args) - " If the shell is messed up, this command could cause an error message - silent! let results = system(cmd) - return v:shell_error == 0 ? results : def -endfunction - -function! s:app_eval(ruby,...) dict abort - let def = a:0 ? a:1 : "" - if !executable("ruby") - return def - endif - let args = "-r./config/boot -r ".s:rquote(self.path("config/environment"))." -e ".s:rquote(a:ruby) - let cmd = self.ruby_shell_command(args) - " If the shell is messed up, this command could cause an error message - silent! let results = system(cmd) - return v:shell_error == 0 ? results : def -endfunction - -call s:add_methods('app', ['ruby_shell_command','script_shell_command','execute_script_command','background_script_command','lightweight_ruby_eval','eval']) - -" }}}1 -" Commands {{{1 - -function! s:prephelp() - let fn = fnamemodify(s:file,':h:h').'/doc/' - if filereadable(fn.'rails.txt') - if !filereadable(fn.'tags') || getftime(fn.'tags') <= getftime(fn.'rails.txt') - silent! helptags `=fn` - endif - endif -endfunction - -function! RailsHelpCommand(...) - call s:prephelp() - let topic = a:0 ? a:1 : "" - if topic == "" || topic == "-" - return "help rails" - elseif topic =~ '^g:' - return "help ".topic - elseif topic =~ '^-' - return "help rails".topic - else - return "help rails-".topic - endif -endfunction - -function! s:BufCommands() - call s:BufFinderCommands() - call s:BufNavCommands() - call s:BufScriptWrappers() - command! -buffer -bar -nargs=? -bang -count -complete=customlist,s:Complete_rake Rake :call s:Rake(0,! && ? -1 : ,) - command! -buffer -bar -nargs=? -bang -range -complete=customlist,s:Complete_preview Rpreview :call s:Preview(0,,) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_environments Rlog :call s:Log(0,) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_set Rset :call s:Set(0,) - command! -buffer -bar -nargs=0 Rtags :call rails#app().tags_command() - " Embedding all this logic directly into the command makes the error - " messages more concise. - command! -buffer -bar -nargs=? -bang Rdoc : - \ if 0 || =~ "^\\([:'-]\\|g:\\)" | - \ exe RailsHelpCommand() | - \ else | call s:Doc(0,) | endif - command! -buffer -bar -nargs=0 -bang Rrefresh :if 0|unlet! g:autoloaded_rails|source `=s:file`|endif|call s:Refresh(0) - if exists(":NERDTree") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rtree :NERDTree `=rails#app().path()` - elseif exists(":Project") - command! -buffer -bar -nargs=? Rtree :call s:Project(0,) - endif - command! -buffer -bar -nargs=? Rproject :call s:warn("Warning: :Rproject has been deprecated in favor of :Rtree") | Rtree - if exists("g:loaded_dbext") - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_environments Rdbext :call s:BufDatabase(2,)|let b:dbext_buffer_defaulted = 1 - endif - let ext = expand("%:e") - if ext =~ s:viewspattern() - " TODO: complete controller names with trailing slashes here - command! -buffer -bar -nargs=? -range -complete=customlist,s:controllerList Rextract :,call s:Extract(0,) - endif - if RailsFilePath() =~ '\0) - endif -endfunction - -function! s:Doc(bang, string) - if a:string != "" - if exists("g:rails_search_url") - let query = substitute(a:string,'[^A-Za-z0-9_.~-]','\="%".printf("%02X",char2nr(submatch(0)))','g') - let url = printf(g:rails_search_url, query) - else - return s:error("specify a g:rails_search_url with %s for a query placeholder") - endif - elseif isdirectory(rails#app().path("doc/api/classes")) - let url = rails#app().path("/doc/api/index.html") - elseif s:getpidfor("0.0.0.0","8808") > 0 - let url = "http://localhost:8808" - else - let url = "http://api.rubyonrails.org" - endif - call s:initOpenURL() - if exists(":OpenURL") - exe "OpenURL ".s:escarg(url) - else - return s:error("No :OpenURL command found") - endif -endfunction - -function! s:Log(bang,arg) - if a:arg == "" - let lf = "log/".s:environment().".log" - else - let lf = "log/".a:arg.".log" - endif - let size = getfsize(rails#app().path(lf)) - if size >= 1048576 - call s:warn("Log file is ".((size+512)/1024)."KB. Consider :Rake log:clear") - endif - if a:bang - exe "cgetfile ".lf - clast - else - if exists(":Tail") - Tail `=rails#app().path(lf)` - else - pedit `=rails#app().path(lf)` - endif - endif -endfunction - -function! rails#new_app_command(bang,...) - if a:0 == 0 - let msg = "rails.vim ".g:autoloaded_rails - if a:bang && exists('b:rails_root') && RailsFileType() == '' - echo msg." (Rails)" - elseif a:bang && exists('b:rails_root') - echo msg." (Rails-".RailsFileType().")" - elseif a:bang - echo msg - else - !rails - endif - return - endif - let dir = "" - if a:1 !~ '^-' - let dir = a:1 - elseif a:{a:0} =~ '[\/]' - let dir = a:{a:0} - else - let dir = a:1 - endif - let str = "" - let c = 1 - while c <= a:0 - let str .= " " . s:rquote(expand(a:{c})) - let c += 1 - endwhile - let dir = expand(dir) - let append = "" - if a:bang - let append .= " --force" - endif - exe "!rails".append.str - if filereadable(dir."/".g:rails_default_file) - edit `=dir.'/'.g:rails_default_file` - endif -endfunction - -function! s:app_tags_command() dict - if exists("g:Tlist_Ctags_Cmd") - let cmd = g:Tlist_Ctags_Cmd - elseif executable("exuberant-ctags") - let cmd = "exuberant-ctags" - elseif executable("ctags-exuberant") - let cmd = "ctags-exuberant" - elseif executable("ctags") - let cmd = "ctags" - elseif executable("ctags.exe") - let cmd = "ctags.exe" - else - return s:error("ctags not found") - endif - exe '!'.cmd.' -f '.s:escarg(self.path("tmp/tags")).' -R --langmap="ruby:+.rake.builder.rjs" '.g:rails_ctags_arguments.' '.s:escarg(self.path()) -endfunction - -call s:add_methods('app',['tags_command']) - -function! s:Refresh(bang) - if exists("g:rubycomplete_rails") && g:rubycomplete_rails && has("ruby") && exists('g:rubycomplete_completions') - silent! ruby ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) - silent! ruby if defined?(ActiveSupport::Dependencies); ActiveSupport::Dependencies.clear; elsif defined?(Dependencies); Dependencies.clear; end - if a:bang - silent! ruby ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) - endif - endif - call rails#app().cache.clear() - silent doautocmd User BufLeaveRails - if a:bang - for key in keys(s:apps) - if type(s:apps[key]) == type({}) - call s:apps[key].cache.clear() - endif - call extend(s:apps[key],filter(copy(s:app_prototype),'type(v:val) == type(function("tr"))'),'force') - endfor - endif - let i = 1 - let max = bufnr('$') - while i <= max - let rr = getbufvar(i,"rails_root") - if rr != "" - call setbufvar(i,"rails_refresh",1) - endif - let i += 1 - endwhile - silent doautocmd User BufEnterRails -endfunction - -function! s:RefreshBuffer() - if exists("b:rails_refresh") && b:rails_refresh - let oldroot = b:rails_root - unlet! b:rails_root - let b:rails_refresh = 0 - call RailsBufInit(oldroot) - unlet! b:rails_refresh - endif -endfunction - -" }}}1 -" Rake {{{1 - -function! s:app_rake_tasks() dict - if self.cache.needs('rake_tasks') - call s:push_chdir() - try - let lines = split(system("rake -T"),"\n") - finally - call s:pop_command() - endtry - if v:shell_error != 0 - return [] - endif - call map(lines,'matchstr(v:val,"^rake\\s\\+\\zs\\S*")') - call filter(lines,'v:val != ""') - call self.cache.set('rake_tasks',lines) - endif - return self.cache.get('rake_tasks') -endfunction - -call s:add_methods('app', ['rake_tasks']) - -let s:efm_backtrace='%D(in\ %f),' - \.'%\\s%#from\ %f:%l:%m,' - \.'%\\s%#from\ %f:%l:,' - \.'%\\s#{RAILS_ROOT}/%f:%l:\ %#%m,' - \.'%\\s%#[%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:\ %#%m,' - \.'%\\s%#%f:%l:' - -function! s:makewithruby(arg,bang,...) - let old_make = &makeprg - try - let &l:makeprg = rails#app().ruby_shell_command(a:arg) - exe 'make'.(a:bang ? '!' : '') - if !a:bang - cwindow - endif - finally - let &l:makeprg = old_make - endtry -endfunction - -function! s:Rake(bang,lnum,arg) - let self = rails#app() - let lnum = a:lnum < 0 ? 0 : a:lnum - let old_makeprg = &l:makeprg - let old_errorformat = &l:errorformat - try - if &l:makeprg !~# 'rake' - let &l:makeprg = 'rake' - endif - let &l:errorformat = s:efm_backtrace - let t = RailsFileType() - let arg = a:arg - if &filetype == "ruby" && arg == '' && g:rails_modelines - let mnum = s:lastmethodline(lnum) - let str = getline(mnum)."\n".getline(mnum+1)."\n".getline(mnum+2)."\n" - let pat = '\s\+\zs.\{-\}\ze\%(\n\|\s\s\|#{\@!\|$\)' - let mat = matchstr(str,'#\s*rake'.pat) - let mat = s:sub(mat,'\s+$','') - if mat != "" - let arg = mat - endif - endif - if arg == '' - let opt = s:getopt('task','bl') - if opt != '' - let arg = opt - else - let arg = rails#buffer().default_rake_task(lnum) - endif - endif - let withrubyargs = '-r ./config/boot -r '.s:rquote(self.path('config/environment')).' -e "puts \%((in \#{Dir.getwd}))" ' - if arg =~# '^notes\>' - let &l:errorformat = '%-P%f:,\ \ *\ [%*[\ ]%l]\ [%t%*[^]]] %m,\ \ *\ [%*[\ ]%l] %m,%-Q' - " %D to chdir is apparently incompatible with %P multiline messages - call s:push_chdir(1) - exe 'make! '.arg - call s:pop_command() - if !a:bang - cwindow - endif - elseif arg =~# '^\%(stats\|routes\|secret\|time:zones\|db:\%(charset\|collation\|fixtures:identify\>.*\|version\)\)\%([: ]\|$\)' - let &l:errorformat = '%D(in\ %f),%+G%.%#' - exe 'make! '.arg - if !a:bang - copen - endif - elseif arg =~ '^preview\>' - exe (lnum == 0 ? '' : lnum).'R'.s:gsub(arg,':','/') - elseif arg =~ '^runner:' - let arg = s:sub(arg,'^runner:','') - let root = matchstr(arg,'%\%(:\w\)*') - let file = expand(root).matchstr(arg,'%\%(:\w\)*\zs.*') - if file =~ '#.*$' - let extra = " -- -n ".matchstr(file,'#\zs.*') - let file = s:sub(file,'#.*','') - else - let extra = '' - endif - if self.has_file(file) || self.has_file(file.'.rb') - call s:makewithruby(withrubyargs.'-r"'.file.'"'.extra,a:bang,file !~# '_\%(spec\|test\)\%(\.rb\)\=$') - else - call s:makewithruby(withrubyargs.'-e '.s:esccmd(s:rquote(arg)),a:bang) - endif - elseif arg == 'run' || arg == 'runner' - call s:makewithruby(withrubyargs.'-r"'.RailsFilePath().'"',a:bang,RailsFilePath() !~# '_\%(spec\|test\)\%(\.rb\)\=$') - elseif arg =~ '^run:' - let arg = s:sub(arg,'^run:','') - let arg = s:sub(arg,'^\%:h',expand('%:h')) - let arg = s:sub(arg,'^%(\%|$|#@=)',expand('%')) - let arg = s:sub(arg,'#(\w+[?!=]=)$',' -- -n\1') - call s:makewithruby(withrubyargs.'-r'.arg,a:bang,arg !~# '_\%(spec\|test\)\.rb$') - else - exe 'make! '.arg - if !a:bang - cwindow - endif - endif - finally - let &l:errorformat = old_errorformat - let &l:makeprg = old_makeprg - endtry -endfunction - -function! s:readable_default_rake_task(lnum) dict abort - let app = self.app() - let t = self.type_name() - let lnum = a:lnum < 0 ? 0 : a:lnum - if self.getline(lnum) =~# '# rake ' - return matchstr(self.getline(lnum),'\C# rake \zs.*') - elseif self.getline(self.last_method_line(lnum)-1) =~# '# rake ' - return matchstr(self.getline(self.last_method_line(lnum)-1),'\C# rake \zs.*') - elseif self.getline(self.last_method_line(lnum)) =~# '# rake ' - return matchstr(self.getline(self.last_method_line(lnum)),'\C# rake \zs.*') - elseif self.getline(1) =~# '# rake ' && !lnum - return matchstr(self.getline(1),'\C# rake \zs.*') - elseif t =~ '^config-routes\>' - return 'routes' - elseif t =~ '^fixtures-yaml\>' && lnum - return "db:fixtures:identify LABEL=".self.last_method(lnum) - elseif t =~ '^fixtures\>' && lnum == 0 - return "db:fixtures:load FIXTURES=".s:sub(fnamemodify(self.name(),':r'),'^.{-}/fixtures/','') - elseif t =~ '^task\>' - let mnum = self.last_method_line(lnum) - let line = getline(mnum) - " We can't grab the namespace so only run tasks at the start of the line - if line =~# '^\%(task\|file\)\>' - return self.last_method(a:lnum) - else - return matchstr(self.getline(1),'\C# rake \zs.*') - endif - elseif t =~ '^spec\>' - if self.name() =~# '\ 0 - return 'spec SPEC="%:p":'.lnum - else - return 'spec SPEC="%:p"' - endif - elseif t =~ '^test\>' - let meth = self.last_method(lnum) - if meth =~ '^test_' - let call = " -n".meth."" - else - let call = "" - endif - if t =~ '^test-\%(unit\|functional\|integration\)$' - return s:sub(s:gsub(t,'-',':'),'unit$|functional$','&s')." TEST=\"%:p\"".s:sub(call,'^ ',' TESTOPTS=') - elseif self.name() =~# '\' && self.name() !~# '\' - return 'test:units TEST="%:p:r:s?[\/]app[\/]models[\/]?/test/unit/?_test.rb"' - elseif t=~ '^api\>' - return 'test:units TEST="%:p:r:s?[\/]app[\/]apis[\/]?/test/functional/?_test.rb"' - elseif t=~ '^\<\%(controller\|helper\|view\)\>' - if self.name() =~ '\' - if lnum > 0 - return 'cucumber FEATURE="%:p":'.lnum - else - return 'cucumber FEATURE="%:p"' - endif - elseif t =~ '^cucumber\>' - return 'cucumber' - else - return '' - endif -endfunction - -function! s:Complete_rake(A,L,P) - return s:completion_filter(rails#app().rake_tasks(),a:A) -endfunction - -call s:add_methods('readable',['default_rake_task']) - -" }}}1 -" Preview {{{1 - -function! s:initOpenURL() - if !exists(":OpenURL") - if has("gui_mac") || has("gui_macvim") || exists("$SECURITYSESSIONID") - command -bar -nargs=1 OpenURL :!open - elseif has("gui_win32") - command -bar -nargs=1 OpenURL :!start cmd /cstart /b - elseif executable("sensible-browser") - command -bar -nargs=1 OpenURL :!sensible-browser - endif - endif -endfunction - -function! s:scanlineforuris(line) - let url = matchstr(a:line,"\\v\\C%(%(GET|PUT|POST|DELETE)\\s+|\w+:/)/[^ \n\r\t<>\"]*[^] .,;\n\r\t<>\":]") - if url =~ '\C^\u\+\s\+' - let method = matchstr(url,'^\u\+') - let url = matchstr(url,'\s\+\zs.*') - if method !=? "GET" - let url .= (url =~ '?' ? '&' : '?') . '_method='.tolower(method) - endif - endif - if url != "" - return [url] - else - return [] - endif -endfunction - -function! s:readable_preview_urls(lnum) dict abort - let urls = [] - let start = self.last_method_line(a:lnum) - 1 - while start > 0 && self.getline(start) =~ '^\s*\%(\%(-\=\|<%\)#.*\)\=$' - let urls = s:scanlineforuris(self.getline(start)) + urls - let start -= 1 - endwhile - let start = 1 - while start < self.line_count() && self.getline(start) =~ '^\s*\%(\%(-\=\|<%\)#.*\)\=$' - let urls += s:scanlineforuris(self.getline(start)) - let start += 1 - endwhile - if has_key(self,'getvar') && self.getvar('rails_preview') != '' - let url += [self.getvar('rails_preview')] - end - if self.name() =~ '^public/stylesheets/sass/' - let urls = urls + [s:sub(s:sub(self.name(),'^public/stylesheets/sass/','/stylesheets/'),'\.sass$','.css')] - elseif self.name() =~ '^public/' - let urls = urls + [s:sub(self.name(),'^public','')] - elseif self.controller_name() != '' && self.controller_name() != 'application' - if self.type_name('controller') && self.last_method(a:lnum) != '' - let urls += ['/'.self.controller_name().'/'.self.last_method(a:lnum).'/'] - elseif self.type_name('controller','view-layout','view-partial') - let urls += ['/'.self.controller_name().'/'] - elseif self.type_name('view') - let urls += ['/'.s:controller().'/'.fnamemodify(self.name(),':t:r:r').'/'] - endif - endif - return urls -endfunction - -call s:add_methods('readable',['preview_urls']) - -function! s:Preview(bang,lnum,arg) - let root = s:getopt("root_url") - if root == '' - let root = s:getopt("url") - endif - let root = s:sub(root,'/$','') - if a:arg =~ '://' - let uri = a:arg - elseif a:arg != '' - let uri = root.'/'.s:sub(a:arg,'^/','') - else - let uri = get(rails#buffer().preview_urls(a:lnum),0,'') - let uri = root.'/'.s:sub(s:sub(uri,'^/',''),'/$','') - endif - call s:initOpenURL() - if exists(':OpenURL') && !a:bang - exe 'OpenURL '.uri - else - " Work around bug where URLs ending in / get handled as FTP - let url = uri.(uri =~ '/$' ? '?' : '') - silent exe 'pedit '.url - wincmd w - if &filetype == '' - if uri =~ '\.css$' - setlocal filetype=css - elseif uri =~ '\.js$' - setlocal filetype=javascript - elseif getline(1) =~ '^\s*<' - setlocal filetype=xhtml - endif - endif - call RailsBufInit(rails#app().path()) - map q :bwipe - wincmd p - if !a:bang - call s:warn("Define a :OpenURL command to use a browser") - endif - endif -endfunction - -function! s:Complete_preview(A,L,P) - return rails#buffer().preview_urls(a:L =~ '^\d' ? matchstr(a:L,'^\d\+') : line('.')) -endfunction - -" }}}1 -" Script Wrappers {{{1 - -function! s:BufScriptWrappers() - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_script Rscript :call rails#app().script_command(0,) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_generate Rgenerate :call rails#app().generate_command(0,) - command! -buffer -bar -nargs=* -complete=customlist,s:Complete_destroy Rdestroy :call rails#app().destroy_command(0,) - command! -buffer -bar -nargs=? -bang -complete=customlist,s:Complete_server Rserver :call rails#app().server_command(0,) - command! -buffer -bang -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rrunner :call rails#app().runner_command(0 ? -2 : (==?:-1),) - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rp :call rails#app().runner_command(==?:-1,'p begin '..' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Rpp :call rails#app().runner_command(==?:-1,'require %{pp}; pp begin '..' end') - command! -buffer -nargs=1 -range=0 -complete=customlist,s:Complete_ruby Ry :call rails#app().runner_command(==?:-1,'y begin '..' end') -endfunction - -function! s:app_generators() dict - if self.cache.needs('generators') - let generators = self.relglob("vendor/plugins/","*/generators/*") - let generators += self.relglob("","lib/generators/*") - call filter(generators,'v:val =~ "/$"') - let generators += split(glob(expand("~/.rails/generators")."/*"),"\n") - call map(generators,'s:sub(v:val,"^.*[\\\\/]generators[\\\\/]\\ze.","")') - call map(generators,'s:sub(v:val,"[\\\\/]$","")') - call self.cache.set('generators',generators) - endif - return sort(split(g:rails_generators,"\n") + self.cache.get('generators')) -endfunction - -function! s:app_script_command(bang,...) dict - let str = "" - let cmd = a:0 ? a:1 : "console" - let c = 2 - while c <= a:0 - let str .= " " . s:rquote(a:{c}) - let c += 1 - endwhile - if cmd ==# "plugin" - call self.cache.clear('generators') - endif - if a:bang || cmd =~# 'console' - return self.background_script_command(cmd.str) - else - return self.execute_script_command(cmd.str) - endif -endfunction - -function! s:app_runner_command(count,args) dict - if a:count == -2 - return self.script_command(a:bang,"runner",a:args) - else - let str = self.ruby_shell_command('-r./config/boot -e "require '."'commands/runner'".'" '.s:rquote(a:args)) - let res = s:sub(system(str),'\n$','') - if a:count < 0 - echo res - else - exe a:count.'put =res' - endif - endif -endfunction - -function! s:getpidfor(bind,port) - if has("win32") || has("win64") - let netstat = system("netstat -anop tcp") - let pid = matchstr(netstat,'\<'.a:bind.':'.a:port.'\>.\{-\}LISTENING\s\+\zs\d\+') - elseif executable('lsof') - let pid = system("lsof -i 4tcp@".a:bind.':'.a:port."|grep LISTEN|awk '{print $2}'") - let pid = s:sub(pid,'\n','') - else - let pid = "" - endif - return pid -endfunction - -function! s:app_server_command(bang,arg) dict - let port = matchstr(a:arg,'\%(-p\|--port=\=\)\s*\zs\d\+') - if port == '' - let port = "3000" - endif - " TODO: Extract bind argument - let bind = "0.0.0.0" - if a:bang && executable("ruby") - let pid = s:getpidfor(bind,port) - if pid =~ '^\d\+$' - echo "Killing server with pid ".pid - if !has("win32") - call system("ruby -e 'Process.kill(:TERM,".pid.")'") - sleep 100m - endif - call system("ruby -e 'Process.kill(9,".pid.")'") - sleep 100m - endif - if a:arg == "-" - return - endif - endif - if has_key(self,'options') && has_key(self.options,'gnu_screen') - let screen = self.options.gnu_screen - else - let screen = g:rails_gnu_screen - endif - if has("win32") || has("win64") || (exists("$STY") && !has("gui_running") && screen && executable("screen")) - call self.background_script_command('server '.a:arg) - else - " --daemon would be more descriptive but lighttpd does not support it - call self.execute_script_command('server '.a:arg." -d") - endif - call s:setopt('a:root_url','http://'.(bind=='0.0.0.0'?'localhost': bind).':'.port.'/') -endfunction - -function! s:app_destroy_command(bang,...) dict - if a:0 == 0 - return self.execute_script_command('destroy') - elseif a:0 == 1 - return self.execute_script_command('destroy '.s:rquote(a:1)) - endif - let str = "" - let c = 1 - while c <= a:0 - let str .= " " . s:rquote(a:{c}) - let c += 1 - endwhile - call self.execute_script_command('destroy'.str) - call self.cache.clear('user_classes') -endfunction - -function! s:app_generate_command(bang,...) dict - if a:0 == 0 - return self.execute_script_command('generate') - elseif a:0 == 1 - return self.execute_script_command('generate '.s:rquote(a:1)) - endif - let cmd = join(map(copy(a:000),'s:rquote(v:val)'),' ') - if cmd !~ '-p\>' && cmd !~ '--pretend\>' - let execstr = self.script_shell_command('generate '.cmd.' -p -f') - let res = system(execstr) - let g:res = res - let junk = '\%(\e\[[0-9;]*m\)\=' - let file = matchstr(res,junk.'\s\+\%(create\|force\)'.junk.'\s\+\zs\f\+\.rb\ze\n') - if file == "" - let file = matchstr(res,junk.'\s\+\%(identical\)'.junk.'\s\+\zs\f\+\.rb\ze\n') - endif - else - let file = "" - endif - if !self.execute_script_command('generate '.cmd) && file != '' - call self.cache.clear('user_classes') - call self.cache.clear('features') - if file =~ '^db/migrate/\d\d\d\d' - let file = get(self.relglob('',s:sub(file,'\d+','[0-9]*[0-9]')),-1,file) - endif - edit `=self.path(file)` - endif -endfunction - -call s:add_methods('app', ['generators','script_command','runner_command','server_command','destroy_command','generate_command']) - -function! s:Complete_script(ArgLead,CmdLine,P) - let cmd = s:sub(a:CmdLine,'^\u\w*\s+','') - if cmd !~ '^[ A-Za-z0-9_=:-]*$' - return [] - elseif cmd =~# '^\w*$' - return s:completion_filter(rails#app().relglob("script/","**/*"),a:ArgLead) - elseif cmd =~# '^\%(plugin\)\s\+'.a:ArgLead.'$' - return s:completion_filter(["discover","list","install","update","remove","source","unsource","sources"],a:ArgLead) - elseif cmd =~# '\%(plugin\)\s\+\%(install\|remove\)\s\+'.a:ArgLead.'$' || cmd =~ '\%(generate\|destroy\)\s\+plugin\s\+'.a:ArgLead.'$' - return s:pluginList(a:ArgLead,a:CmdLine,a:P) - elseif cmd =~# '^\%(generate\|destroy\)\s\+'.a:ArgLead.'$' - return s:completion_filter(rails#app().generators(),a:ArgLead) - elseif cmd =~# '^\%(generate\|destroy\)\s\+\w\+\s\+'.a:ArgLead.'$' - let target = matchstr(cmd,'^\w\+\s\+\%(\w\+:\)\=\zs\w\+\ze\s\+') - if target =~# '^\w*controller$' - return filter(s:controllerList(a:ArgLead,"",""),'v:val !=# "application"') - elseif target ==# 'generator' - return s:completion_filter(map(rails#app().relglob('lib/generators/','*'),'s:sub(v:val,"/$","")')) - elseif target ==# 'helper' - return s:helperList(a:ArgLead,"","") - elseif target ==# 'integration_test' || target ==# 'integration_spec' || target ==# 'feature' - return s:integrationtestList(a:ArgLead,"","") - elseif target ==# 'metal' - return s:metalList(a:ArgLead,"","") - elseif target ==# 'migration' || target ==# 'session_migration' - return s:migrationList(a:ArgLead,"","") - elseif target =~# '^\w*\%(model\|resource\)$' || target =~# '\w*scaffold\%(_controller\)\=$' || target ==# 'mailer' - return s:modelList(a:ArgLead,"","") - elseif target ==# 'observer' - let observers = s:observerList("","","") - let models = s:modelList("","","") - if cmd =~# '^destroy\>' - let models = [] - endif - call filter(models,'index(observers,v:val) < 0') - return s:completion_filter(observers + models,a:ArgLead) - else - return [] - endif - elseif cmd =~# '^\%(generate\|destroy\)\s\+scaffold\s\+\w\+\s\+'.a:ArgLead.'$' - return filter(s:controllerList(a:ArgLead,"",""),'v:val !=# "application"') - return s:completion_filter(rails#app().environments()) - elseif cmd =~# '^\%(console\)\s\+\(--\=\w\+\s\+\)\='.a:ArgLead."$" - return s:completion_filter(rails#app().environments()+["-s","--sandbox"],a:ArgLead) - elseif cmd =~# '^\%(server\)\s\+.*-e\s\+'.a:ArgLead."$" - return s:completion_filter(rails#app().environments(),a:ArgLead) - elseif cmd =~# '^\%(server\)\s\+' - if a:ArgLead =~# '^--environment=' - return s:completion_filter(map(copy(rails#app().environments()),'"--environment=".v:val'),a:ArgLead) - else - return filter(["-p","-b","-e","-m","-d","-u","-c","-h","--port=","--binding=","--environment=","--mime-types=","--daemon","--debugger","--charset=","--help"],'s:startswith(v:val,a:ArgLead)') - endif - endif - return "" -endfunction - -function! s:CustomComplete(A,L,P,cmd) - let L = "Rscript ".a:cmd." ".s:sub(a:L,'^\h\w*\s+','') - let P = a:P - strlen(a:L) + strlen(L) - return s:Complete_script(a:A,L,P) -endfunction - -function! s:Complete_server(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"server") -endfunction - -function! s:Complete_console(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"console") -endfunction - -function! s:Complete_generate(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"generate") -endfunction - -function! s:Complete_destroy(A,L,P) - return s:CustomComplete(a:A,a:L,a:P,"destroy") -endfunction - -function! s:Complete_ruby(A,L,P) - return s:completion_filter(rails#app().user_classes()+["ActiveRecord::Base"],a:A) -endfunction - -" }}}1 -" Navigation {{{1 - -function! s:BufNavCommands() - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rcd :cd `=rails#app().path()` - command! -buffer -bar -nargs=? -complete=customlist,s:Complete_cd Rlcd :lcd `=rails#app().path()` - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rfind :call s:Find(,'' ,) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find REfind :call s:Find(,'E',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RSfind :call s:Find(,'S',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RVfind :call s:Find(,'V',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find RTfind :call s:Find(,'T',) - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rsfind :RSfind - command! -buffer -bar -nargs=* -count=1 -complete=customlist,s:Complete_find Rtabfind :RTfind - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit Redit :call s:Edit(,'' ,) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit REedit :call s:Edit(,'E',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RSedit :call s:Edit(,'S',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RVedit :call s:Edit(,'V',) - command! -buffer -bar -nargs=* -bang -complete=customlist,s:Complete_edit RTedit :call s:Edit(,'T',) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_edit RDedit :call s:Edit(,'D',) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related A :call s:Alternate('', ,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AE :call s:Alternate('E',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AS :call s:Alternate('S',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AV :call s:Alternate('V',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AT :call s:Alternate('T',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AD :call s:Alternate('D',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related AN :call s:Related('' ,,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related R :call s:Related('' ,,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RE :call s:Related('E',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RS :call s:Related('S',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RV :call s:Related('V',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RT :call s:Related('T',,,,) - command! -buffer -bar -nargs=* -range=0 -complete=customlist,s:Complete_related RD :call s:Related('D',,,,) -endfunction - -function! s:djump(def) - let def = s:sub(a:def,'^[#:]','') - if def =~ '^\d\+$' - exe def - elseif def =~ '^!' - if expand('%') !~ '://' && !isdirectory(expand('%:p:h')) - call mkdir(expand('%:p:h'),'p') - endif - elseif def != '' - let ext = matchstr(def,'\.\zs.*') - let def = matchstr(def,'[^.]*') - let v:errmsg = '' - silent! exe "djump ".def - if ext != '' && (v:errmsg == '' || v:errmsg =~ '^E387') - let rpat = '\C^\s*\%(mail\>.*\|respond_to\)\s*\%(\ 0 - let variable = matchstr(getline(rline),rpat) - let success = search('\C^\s*'.variable.'\s*\.\s*\zs'.ext.'\>','',end) - if !success - silent! exe "djump ".def - endif - endif - endif - endif -endfunction - -function! s:Find(count,cmd,...) - let str = "" - if a:0 - let i = 1 - while i < a:0 - let str .= s:escarg(a:{i}) . " " - let i += 1 - endwhile - let file = a:{i} - let tail = matchstr(file,'[#!].*$\|:\d*\%(:in\>.*\)\=$') - if tail != "" - let file = s:sub(file,'[#!].*$|:\d*%(:in>.*)=$','') - endif - if file != "" - let file = s:RailsIncludefind(file) - endif - else - let file = s:RailsFind() - let tail = "" - endif - call s:findedit((a:count==1?'' : a:count).a:cmd,file.tail,str) -endfunction - -function! s:Edit(count,cmd,...) - if a:0 - let str = "" - let i = 1 - while i < a:0 - let str .= "`=a:".i."` " - let i += 1 - endwhile - let file = a:{i} - call s:findedit(s:editcmdfor(a:cmd),file,str) - else - exe s:editcmdfor(a:cmd) - endif -endfunction - -function! s:fuzzyglob(arg) - return s:gsub(s:gsub(a:arg,'[^/.]','[&]*'),'%(/|^)\.@!|\.','&*') -endfunction - -function! s:Complete_find(ArgLead, CmdLine, CursorPos) - let paths = s:pathsplit(&l:path) - let seen = {} - for path in paths - if s:startswith(path,rails#app().path()) && path !~ '[][*]' - let path = path[strlen(rails#app().path()) + 1 : ] - for file in rails#app().relglob(path == '' ? '' : path.'/',s:fuzzyglob(rails#underscore(a:ArgLead)), a:ArgLead =~# '\u' ? '.rb' : '') - let seen[file] = 1 - endfor - endif - endfor - let results = sort(map(keys(seen),'s:sub(v:val,"[.]rb$","")')) - return s:autocamelize(results,a:ArgLead) -endfunction - -function! s:Complete_edit(ArgLead, CmdLine, CursorPos) - return s:completion_filter(rails#app().relglob("",s:fuzzyglob(a:ArgLead)),a:ArgLead) -endfunction - -function! s:Complete_cd(ArgLead, CmdLine, CursorPos) - let all = rails#app().relglob("",a:ArgLead."*") - call filter(all,'v:val =~ "/$"') - return filter(all,'s:startswith(v:val,a:ArgLead)') -endfunction - -function! RailsIncludeexpr() - " Is this foolproof? - if mode() =~ '[iR]' || expand("") != v:fname - return s:RailsIncludefind(v:fname) - else - return s:RailsIncludefind(v:fname,1) - endif -endfunction - -function! s:linepeak() - let line = getline(line(".")) - let line = s:sub(line,'^(.{'.col(".").'}).*','\1') - let line = s:sub(line,'([:"'."'".']|\%[qQ]=[[({<])=\f*$','') - return line -endfunction - -function! s:matchcursor(pat) - let line = getline(".") - let lastend = 0 - while lastend >= 0 - let beg = match(line,'\C'.a:pat,lastend) - let end = matchend(line,'\C'.a:pat,lastend) - if beg < col(".") && end >= col(".") - return matchstr(line,'\C'.a:pat,lastend) - endif - let lastend = end - endwhile - return "" -endfunction - -function! s:findit(pat,repl) - let res = s:matchcursor(a:pat) - if res != "" - return substitute(res,'\C'.a:pat,a:repl,'') - else - return "" - endif -endfunction - -function! s:findamethod(func,repl) - return s:findit('\s*\<\%('.a:func.'\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>.\=',a:repl) -endfunction - -function! s:findasymbol(sym,repl) - return s:findit('\s*:\%('.a:sym.'\)\s*=>\s*(\=\s*[@:'."'".'"]\(\f\+\)\>.\=',a:repl) -endfunction - -function! s:findfromview(func,repl) - " ( ) ( ) ( \1 ) ( ) - return s:findit('\s*\%(<%\)\==\=\s*\<\%('.a:func.'\)\s*(\=\s*[@:'."'".'"]\(\f\+\)\>['."'".'"]\=\s*\%(%>\s*\)\=',a:repl) -endfunction - -function! s:RailsFind() - if filereadable(expand("")) - return expand("") - endif - - " UGH - let format = s:format('html') - - let res = s:findit('\v\s*.=',expand('%:h').'/\1') - if res != ""|return res.(fnamemodify(res,':e') == '' ? '.rb' : '')|endif - - let res = s:findit('\v['."'".'"]=',expand('%:h').'\1') - if res != ""|return res|endif - - let res = rails#underscore(s:findit('\v\s*<%(include|extend)\(=\s*<(\f+)>','\1')) - if res != ""|return res.".rb"|endif - - let res = s:findamethod('require','\1') - if res != ""|return res.(fnamemodify(res,':e') == '' ? '.rb' : '')|endif - - let res = s:findamethod('belongs_to\|has_one\|composed_of\|validates_associated\|scaffold','app/models/\1.rb') - if res != ""|return res|endif - - let res = rails#singularize(s:findamethod('has_many\|has_and_belongs_to_many','app/models/\1')) - if res != ""|return res.".rb"|endif - - let res = rails#singularize(s:findamethod('create_table\|change_table\|drop_table\|add_column\|rename_column\|remove_column\|add_index','app/models/\1')) - if res != ""|return res.".rb"|endif - - let res = rails#singularize(s:findasymbol('through','app/models/\1')) - if res != ""|return res.".rb"|endif - - let res = s:findamethod('fixtures','fixtures/\1') - if res != "" - return RailsFilePath() =~ '\\s*','app/controllers/\1') - if res =~ '#'|return s:sub(res,'#','_controller.rb#')|endif - - let res = s:findamethod('\%(match\|get\|put\|post\|delete\|redirect\)\s*(\=\s*[:''"][^''"]*[''"]\=\s*\%(,\s*:to\s*\)\==>\s*','app/controllers/\1') - if res =~ '#'|return s:sub(res,'#','_controller.rb#')|endif - - let res = s:findamethod('layout','\=s:findlayout(submatch(1))') - if res != ""|return res|endif - - let res = s:findasymbol('layout','\=s:findlayout(submatch(1))') - if res != ""|return res|endif - - let res = s:findamethod('helper','app/helpers/\1_helper.rb') - if res != ""|return res|endif - - let res = s:findasymbol('controller','app/controllers/\1_controller.rb') - if res != ""|return res|endif - - let res = s:findasymbol('action','\1') - if res != ""|return res|endif - - let res = s:findasymbol('template','app/views/\1') - if res != ""|return res|endif - - let res = s:sub(s:sub(s:findasymbol('partial','\1'),'^/',''),'\k+$','_&') - if res != ""|return res."\n".s:findview(res)|endif - - let res = s:sub(s:sub(s:findfromview('render\s*(\=\s*:partial\s\+=>\s*','\1'),'^/',''),'\k+$','_&') - if res != ""|return res."\n".s:findview(res)|endif - - let res = s:findamethod('render\s*:\%(template\|action\)\s\+=>\s*','\1.'.format.'\n\1') - if res != ""|return res|endif - - let res = s:sub(s:findfromview('render','\1'),'^/','') - if RailsFileType() =~ '^view\>' | let res = s:sub(res,'[^/]+$','_&') | endif - if res != ""|return res."\n".s:findview(res)|endif - - let res = s:findamethod('redirect_to\s*(\=\s*:action\s\+=>\s*','\1') - if res != ""|return res|endif - - let res = s:findfromview('stylesheet_link_tag','public/stylesheets/\1') - if res != '' && fnamemodify(res, ':e') == '' " Append the default extension iff the filename doesn't already contains an extension - let res .= '.css' - end - if res != ""|return res|endif - - let res = s:sub(s:findfromview('javascript_include_tag','public/javascripts/\1'),'/defaults>','/application') - if res != '' && fnamemodify(res, ':e') == '' " Append the default extension iff the filename doesn't already contains an extension - let res .= '.js' - end - if res != ""|return res|endif - - if RailsFileType() =~ '^controller\>' - let contr = s:controller() - let view = s:findit('\s*\(\=','/\1') - let res = s:findview(contr.'/'.view) - if res != ""|return res|endif - endif - - let old_isfname = &isfname - try - set isfname=@,48-57,/,-,_,:,# - " TODO: grab visual selection in visual mode - let cfile = expand("") - finally - let &isfname = old_isfname - endtry - let res = s:RailsIncludefind(cfile,1) - return res -endfunction - -function! s:app_named_route_file(route) dict - call self.route_names() - if self.cache.has("named_routes") && has_key(self.cache.get("named_routes"),a:route) - return self.cache.get("named_routes")[a:route] - endif - return "" -endfunction - -function! s:app_route_names() dict - if self.cache.needs("named_routes") - let exec = "ActionController::Routing::Routes.named_routes.each {|n,r| puts %{#{n} app/controllers/#{r.requirements[:controller]}_controller.rb##{r.requirements[:action]}}}" - let string = self.eval(exec) - let routes = {} - for line in split(string,"\n") - let route = split(line," ") - let name = route[0] - let routes[name] = route[1] - endfor - call self.cache.set("named_routes",routes) - endif - - return keys(self.cache.get("named_routes")) -endfunction - -call s:add_methods('app', ['route_names','named_route_file']) - -function! RailsNamedRoutes() - return rails#app().route_names() -endfunction - -function! s:RailsIncludefind(str,...) - if a:str ==# "ApplicationController" - return "application_controller.rb\napp/controllers/application.rb" - elseif a:str ==# "Test::Unit::TestCase" - return "test/unit/testcase.rb" - endif - let str = a:str - if a:0 == 1 - " Get the text before the filename under the cursor. - " We'll cheat and peak at this in a bit - let line = s:linepeak() - let line = s:sub(line,'([:"'."'".']|\%[qQ]=[[({<])=\f*$','') - else - let line = "" - endif - let str = s:sub(str,'^\s*','') - let str = s:sub(str,'\s*$','') - let str = s:sub(str,'^:=[:@]','') - let str = s:sub(str,':0x\x+$','') " For # style output - let str = s:gsub(str,"[\"']",'') - if line =~# '\<\(require\|load\)\s*(\s*$' - return str - elseif str =~# '^\l\w*#\w\+$' - return 'app/controllers/'.s:sub(str,'#','_controller.rb#') - endif - let str = rails#underscore(str) - let fpat = '\(\s*\%("\f*"\|:\f*\|'."'\\f*'".'\)\s*,\s*\)*' - if a:str =~# '\u' - " Classes should always be in .rb files - let str .= '.rb' - elseif line =~# ':partial\s*=>\s*' - let str = s:sub(str,'([^/]+)$','_\1') - let str = s:findview(str) - elseif line =~# '\\s*' - let str = s:findview(s:sub(str,'^/=','layouts/')) - elseif line =~# ':controller\s*=>\s*' - let str = 'app/controllers/'.str.'_controller.rb' - elseif line =~# '\\s*$' && RailsFileType() =~# '^config-routes\>') - if line !~# ':as\s*=>\s*$' - let str = s:sub(str,'_%(path|url)$','') - let str = s:sub(str,'^hash_for_','') - endif - let file = rails#app().named_route_file(str) - if file == "" - let str = s:sub(str,'^formatted_','') - if str =~# '^\%(new\|edit\)_' - let str = 'app/controllers/'.s:sub(rails#pluralize(str),'^(new|edit)_(.*)','\2_controller.rb#\1') - elseif str ==# rails#singularize(str) - " If the word can't be singularized, it's probably a link to the show - " method. We should verify by checking for an argument, but that's - " difficult the way things here are currently structured. - let str = 'app/controllers/'.rails#pluralize(str).'_controller.rb#show' - else - let str = 'app/controllers/'.str.'_controller.rb#index' - endif - else - let str = file - endif - elseif str !~ '/' - " If we made it this far, we'll risk making it singular. - let str = rails#singularize(str) - let str = s:sub(str,'_id$','') - endif - if str =~ '^/' && !filereadable(str) - let str = s:sub(str,'^/','') - endif - if str =~# '^lib/' && !filereadable(str) - let str = s:sub(str,'^lib/','') - endif - return str -endfunction - -" }}}1 -" File Finders {{{1 - -function! s:addfilecmds(type) - let l = s:sub(a:type,'^.','\l&') - let cmds = 'ESVTD ' - let cmd = '' - while cmds != '' - let cplt = " -complete=customlist,".s:sid.l."List" - exe "command! -buffer -bar ".(cmd == 'D' ? '-range=0 ' : '')."-nargs=*".cplt." R".cmd.l." :call s:".l.'Edit("'.(cmd == 'D' ? '' : '').cmd.'",)' - let cmd = strpart(cmds,0,1) - let cmds = strpart(cmds,1) - endwhile -endfunction - -function! s:BufFinderCommands() - command! -buffer -bar -nargs=+ Rnavcommand :call s:Navcommand(0,) - call s:addfilecmds("metal") - call s:addfilecmds("model") - call s:addfilecmds("view") - call s:addfilecmds("controller") - call s:addfilecmds("mailer") - call s:addfilecmds("migration") - call s:addfilecmds("observer") - call s:addfilecmds("helper") - call s:addfilecmds("layout") - call s:addfilecmds("fixtures") - call s:addfilecmds("locale") - if rails#app().has('test') || rails#app().has('spec') - call s:addfilecmds("unittest") - call s:addfilecmds("functionaltest") - endif - if rails#app().has('test') || rails#app().has('spec') || rails#app().has('cucumber') - call s:addfilecmds("integrationtest") - endif - if rails#app().has('spec') - call s:addfilecmds("spec") - endif - call s:addfilecmds("stylesheet") - call s:addfilecmds("javascript") - call s:addfilecmds("plugin") - call s:addfilecmds("task") - call s:addfilecmds("lib") - call s:addfilecmds("environment") - call s:addfilecmds("initializer") -endfunction - -function! s:completion_filter(results,A) - let results = sort(type(a:results) == type("") ? split(a:results,"\n") : copy(a:results)) - call filter(results,'v:val !~# "\\~$"') - let filtered = filter(copy(results),'s:startswith(v:val,a:A)') - if !empty(filtered) | return filtered | endif - let regex = s:gsub(a:A,'[^/]','[&].*') - let filtered = filter(copy(results),'v:val =~# "^".regex') - if !empty(filtered) | return filtered | endif - let regex = s:gsub(a:A,'.','[&].*') - let filtered = filter(copy(results),'v:val =~# regex') - return filtered -endfunction - -function! s:autocamelize(files,test) - if a:test =~# '^\u' - return s:completion_filter(map(copy(a:files),'rails#camelize(v:val)'),a:test) - else - return s:completion_filter(a:files,a:test) - endif -endfunction - -function! s:app_relglob(path,glob,...) dict - if exists("+shellslash") && ! &shellslash - let old_ss = &shellslash - let &shellslash = 1 - endif - let path = a:path - if path !~ '^/' && path !~ '^\w:' - let path = self.path(path) - endif - let suffix = a:0 ? a:1 : '' - let full_paths = split(glob(path.a:glob.suffix),"\n") - let relative_paths = [] - for entry in full_paths - if suffix == '' && isdirectory(entry) && entry !~ '/$' - let entry .= '/' - endif - let relative_paths += [entry[strlen(path) : -strlen(suffix)-1]] - endfor - if exists("old_ss") - let &shellslash = old_ss - endif - return relative_paths -endfunction - -call s:add_methods('app', ['relglob']) - -function! s:relglob(...) - return join(call(rails#app().relglob,a:000,rails#app()),"\n") -endfunction - -function! s:helperList(A,L,P) - return s:autocamelize(rails#app().relglob("app/helpers/","**/*","_helper.rb"),a:A) -endfunction - -function! s:controllerList(A,L,P) - let con = rails#app().relglob("app/controllers/","**/*",".rb") - call map(con,'s:sub(v:val,"_controller$","")') - return s:autocamelize(con,a:A) -endfunction - -function! s:mailerList(A,L,P) - return s:autocamelize(rails#app().relglob("app/mailers/","**/*",".rb"),a:A) -endfunction - -function! s:viewList(A,L,P) - let c = s:controller(1) - let top = rails#app().relglob("app/views/",s:fuzzyglob(a:A)) - call filter(top,'v:val !~# "\\~$"') - if c != '' && a:A !~ '/' - let local = rails#app().relglob("app/views/".c."/","*.*[^~]") - return s:completion_filter(local+top,a:A) - endif - return s:completion_filter(top,a:A) -endfunction - -function! s:layoutList(A,L,P) - return s:completion_filter(rails#app().relglob("app/views/layouts/","*"),a:A) -endfunction - -function! s:stylesheetList(A,L,P) - return s:completion_filter(rails#app().relglob("public/stylesheets/","**/*",".css"),a:A) -endfunction - -function! s:javascriptList(A,L,P) - return s:completion_filter(rails#app().relglob("public/javascripts/","**/*",".js"),a:A) -endfunction - -function! s:metalList(A,L,P) - return s:autocamelize(rails#app().relglob("app/metal/","**/*",".rb"),a:A) -endfunction - -function! s:modelList(A,L,P) - let models = rails#app().relglob("app/models/","**/*",".rb") - call filter(models,'v:val !~# "_observer$"') - return s:autocamelize(models,a:A) -endfunction - -function! s:observerList(A,L,P) - return s:autocamelize(rails#app().relglob("app/models/","**/*","_observer.rb"),a:A) -endfunction - -function! s:fixturesList(A,L,P) - return s:completion_filter(rails#app().relglob("test/fixtures/","**/*")+rails#app().relglob("spec/fixtures/","**/*"),a:A) -endfunction - -function! s:localeList(A,L,P) - return s:completion_filter(rails#app().relglob("config/locales/","**/*"),a:A) -endfunction - -function! s:migrationList(A,L,P) - if a:A =~ '^\d' - let migrations = rails#app().relglob("db/migrate/",a:A."[0-9_]*",".rb") - return map(migrations,'matchstr(v:val,"^[0-9]*")') - else - let migrations = rails#app().relglob("db/migrate/","[0-9]*[0-9]_*",".rb") - call map(migrations,'s:sub(v:val,"^[0-9]*_","")') - return s:autocamelize(migrations,a:A) - endif -endfunction - -function! s:unittestList(A,L,P) - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/unit/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/models/","**/*","_spec.rb") - endif - return s:autocamelize(found,a:A) -endfunction - -function! s:functionaltestList(A,L,P) - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/functional/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/controllers/","**/*","_spec.rb") - endif - return s:autocamelize(found,a:A) -endfunction - -function! s:integrationtestList(A,L,P) - if a:A =~# '^\u' - return s:autocamelize(rails#app().relglob("test/integration/","**/*","_test.rb"),a:A) - endif - let found = [] - if rails#app().has('test') - let found += rails#app().relglob("test/integration/","**/*","_test.rb") - endif - if rails#app().has('spec') - let found += rails#app().relglob("spec/integration/","**/*","_spec.rb") - endif - if rails#app().has('cucumber') - let found += rails#app().relglob("features/","**/*",".feature") - endif - return s:completion_filter(found,a:A) -endfunction - -function! s:specList(A,L,P) - return s:completion_filter(rails#app().relglob("spec/","**/*","_spec.rb"),a:A) -endfunction - -function! s:pluginList(A,L,P) - if a:A =~ '/' - return s:completion_filter(rails#app().relglob('vendor/plugins/',matchstr(a:A,'.\{-\}/').'**/*'),a:A) - else - return s:completion_filter(rails#app().relglob('vendor/plugins/',"*","/init.rb"),a:A) - endif -endfunction - -" Task files, not actual rake tasks -function! s:taskList(A,L,P) - let all = rails#app().relglob("lib/tasks/","**/*",".rake") - if RailsFilePath() =~ '\','".name."',\"".prefix."\",".string(suffix).",".string(filter).",".string(default).",)" - let cmd = strpart(cmds,0,1) - let cmds = strpart(cmds,1) - endwhile -endfunction - -function! s:CommandList(A,L,P) - let cmd = matchstr(a:L,'\CR[A-Z]\=\w\+') - exe cmd." &" - let lp = s:last_prefix . "\n" - let res = [] - while lp != "" - let p = matchstr(lp,'.\{-\}\ze\n') - let lp = s:sub(lp,'.{-}\n','') - let res += rails#app().relglob(p,s:last_filter,s:last_suffix) - endwhile - if s:last_camelize - return s:autocamelize(res,a:A) - else - return s:completion_filter(res,a:A) - endif -endfunction - -function! s:CommandEdit(cmd,name,prefix,suffix,filter,default,...) - if a:0 && a:1 == "&" - let s:last_prefix = a:prefix - let s:last_suffix = a:suffix - let s:last_filter = a:filter - let s:last_camelize = (a:suffix =~# '\.rb$') - else - if a:default == "both()" - if s:model() != "" - let default = s:model() - else - let default = s:controller() - endif - elseif a:default == "model()" - let default = s:model(1) - elseif a:default == "controller()" - let default = s:controller(1) - else - let default = a:default - endif - call s:EditSimpleRb(a:cmd,a:name,a:0 ? a:1 : default,a:prefix,a:suffix) - endif -endfunction - -function! s:EditSimpleRb(cmd,name,target,prefix,suffix,...) - let cmd = s:findcmdfor(a:cmd) - if a:target == "" - " Good idea to emulate error numbers like this? - return s:error("E471: Argument required") - endif - let f = a:0 ? a:target : rails#underscore(a:target) - let jump = matchstr(f,'[#!].*\|:\d*\%(:in\)\=$') - let f = s:sub(f,'[#!].*|:\d*%(:in)=$','') - if jump =~ '^!' - let cmd = s:editcmdfor(cmd) - endif - if f == '.' - let f = s:sub(f,'\.$','') - else - let f .= a:suffix.jump - endif - let f = s:gsub(a:prefix,'\n',f.'\n').f - return s:findedit(cmd,f) -endfunction - -function! s:app_migration(file) dict - let arg = a:file - if arg =~ '^0$\|^0\=[#:]' - let suffix = s:sub(arg,'^0*','') - if self.has_file('db/schema.rb') - return 'db/schema.rb'.suffix - elseif self.has_file('db/'.s:environment().'_structure.sql') - return 'db/'.s:environment().'_structure.sql'.suffix - else - return 'db/schema.rb'.suffix - endif - elseif arg =~ '^\d$' - let glob = '00'.arg.'_*.rb' - elseif arg =~ '^\d\d$' - let glob = '0'.arg.'_*.rb' - elseif arg =~ '^\d\d\d$' - let glob = ''.arg.'_*.rb' - elseif arg == '' - let glob = '*.rb' - else - let glob = '*'.rails#underscore(arg).'*rb' - endif - let migr = s:sub(glob(self.path('db/migrate/').glob),'.*\n','') - if s:startswith(migr,self.path()) - let migr = strpart(migr,1+strlen(self.path())) - endif - return migr -endfunction - -call s:add_methods('app', ['migration']) - -function! s:migrationEdit(cmd,...) - let cmd = s:findcmdfor(a:cmd) - let arg = a:0 ? a:1 : '' - let migr = arg == "." ? "db/migrate" : rails#app().migration(arg) - if migr != '' - call s:findedit(cmd,migr) - else - return s:error("Migration not found".(arg=='' ? '' : ': '.arg)) - endif -endfunction - -function! s:fixturesEdit(cmd,...) - if a:0 - let c = rails#underscore(a:1) - else - let c = rails#pluralize(s:model(1)) - endif - if c == "" - return s:error("E471: Argument required") - endif - let e = fnamemodify(c,':e') - let e = e == '' ? e : '.'.e - let c = fnamemodify(c,':r') - let file = get(rails#app().test_suites(),0,'test').'/fixtures/'.c.e - if file =~ '\.\w\+$' && rails#app().find_file(c.e,["test/fixtures","spec/fixtures"]) ==# '' - call s:edit(a:cmd,file) - else - call s:findedit(a:cmd,rails#app().find_file(c.e,["test/fixtures","spec/fixtures"],[".yml",".csv"],file)) - endif -endfunction - -function! s:localeEdit(cmd,...) - let c = a:0 ? a:1 : rails#app().default_locale() - if c =~# '\.' - call s:edit(a:cmd,rails#app().find_file(c,'config/locales',[],'config/locales/'.c)) - else - call s:findedit(a:cmd,rails#app().find_file(c,'config/locales',['.yml','.rb'],'config/locales/'.c)) - endif -endfunction - -function! s:metalEdit(cmd,...) - if a:0 - call s:EditSimpleRb(a:cmd,"metal",a:1,"app/metal/",".rb") - else - call s:EditSimpleRb(a:cmd,"metal",'config/boot',"",".rb") - endif -endfunction - -function! s:modelEdit(cmd,...) - call s:EditSimpleRb(a:cmd,"model",a:0? a:1 : s:model(1),"app/models/",".rb") -endfunction - -function! s:observerEdit(cmd,...) - call s:EditSimpleRb(a:cmd,"observer",a:0? a:1 : s:model(1),"app/models/","_observer.rb") -endfunction - -function! s:viewEdit(cmd,...) - if a:0 && a:1 =~ '^[^!#:]' - let view = matchstr(a:1,'[^!#:]*') - elseif rails#buffer().type_name('controller','mailer') - let view = s:lastmethod(line('.')) - else - let view = '' - endif - if view == '' - return s:error("No view name given") - elseif view == '.' - return s:edit(a:cmd,'app/views') - elseif view !~ '/' && s:controller(1) != '' - let view = s:controller(1) . '/' . view - endif - if view !~ '/' - return s:error("Cannot find view without controller") - endif - let file = "app/views/".view - let found = s:findview(view) - if found != '' - let dir = fnamemodify(rails#app().path(found),':h') - if !isdirectory(dir) - if a:0 && a:1 =~ '!' - call mkdir(dir) - else - return s:error('No such directory') - endif - endif - call s:edit(a:cmd,found) - elseif file =~ '\.\w\+$' - call s:findedit(a:cmd,file) - else - let format = s:format(rails#buffer().type_name('mailer') ? 'text' : 'html') - if glob(rails#app().path(file.'.'.format).'.*[^~]') != '' - let file .= '.' . format - endif - call s:findedit(a:cmd,file) - endif -endfunction - -function! s:findview(name) - let self = rails#buffer() - let name = a:name - let pre = 'app/views/' - if name !~# '/' - let controller = self.controller_name(1) - if controller != '' - let name = controller.'/'.name - endif - endif - if name =~# '\.\w\+\.\w\+$' || name =~# '\.'.s:viewspattern().'$' - return pre.name - else - for format in ['.'.s:format('html'), ''] - for type in split(s:view_types,',') - if self.app().has_file(pre.name.format.'.'.type) - return pre.name.format.'.'.type - endif - endfor - endfor - endif - return '' -endfunction - -function! s:findlayout(name) - return s:findview("layouts/".(a:name == '' ? 'application' : a:name)) -endfunction - -function! s:layoutEdit(cmd,...) - if a:0 - return s:viewEdit(a:cmd,"layouts/".a:1) - endif - let file = s:findlayout(s:controller(1)) - if file == "" - let file = s:findlayout("application") - endif - if file == "" - let file = "app/views/layouts/application.html.erb" - endif - call s:edit(a:cmd,s:sub(file,'^/','')) -endfunction - -function! s:controllerEdit(cmd,...) - let suffix = '.rb' - if a:0 == 0 - let controller = s:controller(1) - if RailsFileType() =~ '^view\%(-layout\|-partial\)\@!' - let suffix .= '#'.expand('%:t:r') - endif - else - let controller = a:1 - endif - if rails#app().has_file("app/controllers/".controller."_controller.rb") || !rails#app().has_file("app/controllers/".controller.".rb") - let suffix = "_controller".suffix - endif - return s:EditSimpleRb(a:cmd,"controller",controller,"app/controllers/",suffix) -endfunction - -function! s:mailerEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"mailer",a:0? a:1 : s:controller(1),"app/mailers/\napp/models/",".rb") -endfunction - -function! s:helperEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"helper",a:0? a:1 : s:controller(1),"app/helpers/","_helper.rb") -endfunction - -function! s:stylesheetEdit(cmd,...) - let name = a:0 ? a:1 : s:controller(1) - if rails#app().has('sass') && rails#app().has_file('public/stylesheets/sass/'.name.'.sass') - return s:EditSimpleRb(a:cmd,"stylesheet",name,"public/stylesheets/sass/",".sass",1) - else - return s:EditSimpleRb(a:cmd,"stylesheet",name,"public/stylesheets/",".css",1) - endif -endfunction - -function! s:javascriptEdit(cmd,...) - return s:EditSimpleRb(a:cmd,"javascript",a:0? a:1 : "application","public/javascripts/",".js",1) -endfunction - -function! s:unittestEdit(cmd,...) - let f = rails#underscore(a:0 ? matchstr(a:1,'[^!#:]*') : s:model(1)) - let jump = a:0 ? matchstr(a:1,'[!#:].*') : '' - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/unit/','_test.rb'], 'spec': ['spec/models/','_spec.rb']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping['test']] - endif - for [prefix, suffix] in tests - if !a:0 && RailsFileType() =~# '^model-aro\>' && f != '' && f !~# '_observer$' - if rails#app().has_file(prefix.f.'_observer'.suffix) - return s:findedit(cmd,prefix.f.'_observer'.suffix.jump) - endif - endif - endfor - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"unittest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:functionaltestEdit(cmd,...) - let f = rails#underscore(a:0 ? matchstr(a:1,'[^!#:]*') : s:controller(1)) - let jump = a:0 ? matchstr(a:1,'[!#:].*') : '' - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/functional/','_test.rb'], 'spec': ['spec/controllers/','_spec.rb']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping[tests]] - endif - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - elseif rails#app().has_file(prefix.f.'_controller'.suffix) - return s:findedit(cmd,prefix.f.'_controller'.suffix.jump) - elseif rails#app().has_file(prefix.f.'_api'.suffix) - return s:findedit(cmd,prefix.f.'_api'.suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"functionaltest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:integrationtestEdit(cmd,...) - if !a:0 - return s:EditSimpleRb(a:cmd,"integrationtest","test/test_helper\nfeatures/support/env\nspec/spec_helper","",".rb") - endif - let f = rails#underscore(matchstr(a:1,'[^!#:]*')) - let jump = matchstr(a:1,'[!#:].*') - if jump =~ '!' - let cmd = s:editcmdfor(a:cmd) - else - let cmd = s:findcmdfor(a:cmd) - endif - let mapping = {'test': ['test/integration/','_test.rb'], 'spec': ['spec/integration/','_spec.rb'], 'cucumber': ['features/','.feature']} - let tests = map(filter(rails#app().test_suites(),'has_key(mapping,v:val)'),'get(mapping,v:val)') - if empty(tests) - let tests = [mapping['test']] - endif - for [prefix, suffix] in tests - if rails#app().has_file(prefix.f.suffix) - return s:findedit(cmd,prefix.f.suffix.jump) - elseif rails#app().has_file(prefix.rails#underscore(f).suffix) - return s:findedit(cmd,prefix.rails#underscore(f).suffix.jump) - endif - endfor - return s:EditSimpleRb(a:cmd,"integrationtest",f.jump,tests[0][0],tests[0][1],1) -endfunction - -function! s:specEdit(cmd,...) - if a:0 - return s:EditSimpleRb(a:cmd,"spec",a:1,"spec/","_spec.rb") - else - call s:EditSimpleRb(a:cmd,"spec","spec_helper","spec/",".rb") - endif -endfunction - -function! s:pluginEdit(cmd,...) - let cmd = s:findcmdfor(a:cmd) - let plugin = "" - let extra = "" - if RailsFilePath() =~ '\','split') - let cmd = s:sub(cmd,'find>','edit') - return cmd -endfunction - -function! s:try(cmd) abort - if !exists(":try") - " I've seen at least one weird setup without :try - exe a:cmd - else - try - exe a:cmd - catch - call s:error(s:sub(v:exception,'^.{-}:\zeE','')) - return 0 - endtry - endif - return 1 -endfunction - -function! s:findedit(cmd,files,...) abort - let cmd = s:findcmdfor(a:cmd) - let files = type(a:files) == type([]) ? copy(a:files) : split(a:files,"\n") - if len(files) == 1 - let file = files[0] - else - let file = get(filter(copy(files),'rails#app().has_file(s:sub(v:val,"#.*|:\\d*$",""))'),0,get(files,0,'')) - endif - if file =~ '[#!]\|:\d*\%(:in\)\=$' - let djump = matchstr(file,'!.*\|#\zs.*\|:\zs\d*\ze\%(:in\)\=$') - let file = s:sub(file,'[#!].*|:\d*%(:in)=$','') - else - let djump = '' - endif - if file == '' - let testcmd = "edit" - elseif isdirectory(rails#app().path(file)) - let arg = file == "." ? rails#app().path() : rails#app().path(file) - let testcmd = s:editcmdfor(cmd).' '.(a:0 ? a:1 . ' ' : '').s:escarg(arg) - exe testcmd - return - elseif rails#app().path() =~ '://' || cmd =~ 'edit' || cmd =~ 'split' - if file !~ '^/' && file !~ '^\w:' && file !~ '://' - let file = s:escarg(rails#app().path(file)) - endif - let testcmd = s:editcmdfor(cmd).' '.(a:0 ? a:1 . ' ' : '').file - else - let testcmd = cmd.' '.(a:0 ? a:1 . ' ' : '').file - endif - if s:try(testcmd) - call s:djump(djump) - endif -endfunction - -function! s:edit(cmd,file,...) - let cmd = s:editcmdfor(a:cmd) - let cmd .= ' '.(a:0 ? a:1 . ' ' : '') - let file = a:file - if file !~ '^/' && file !~ '^\w:' && file !~ '://' - exe cmd."`=fnamemodify(rails#app().path(file),':.')`" - else - exe cmd.file - endif -endfunction - -function! s:Alternate(cmd,line1,line2,count,...) - if a:0 - if a:count && a:cmd !~# 'D' - return call('s:Find',[1,a:line1.a:cmd]+a:000) - elseif a:count - return call('s:Edit',[1,a:line1.a:cmd]+a:000) - else - return call('s:Edit',[1,a:cmd]+a:000) - endif - else - let file = s:getopt(a:count ? 'related' : 'alternate', 'bl') - if file == '' - let file = rails#buffer().related(a:count) - endif - if file != '' - call s:findedit(a:cmd,file) - else - call s:warn("No alternate file is defined") - endif - endif -endfunction - -function! s:Related(cmd,line1,line2,count,...) - if a:count == 0 && a:0 == 0 - return s:Alternate(a:cmd,a:line1,a:line1,a:line1) - else - return call('s:Alternate',[a:cmd,a:line1,a:line2,a:count]+a:000) - endif -endfunction - -function! s:Complete_related(A,L,P) - if a:L =~# '^[[:alpha:]]' - return s:Complete_edit(a:A,a:L,a:P) - else - return s:Complete_find(a:A,a:L,a:P) - endif -endfunction - -function! s:readable_related(...) dict abort - let f = self.name() - let t = self.type_name() - if a:0 && a:1 - let lastmethod = self.last_method(a:1) - if t =~ '^\%(controller\|mailer\)\>' && lastmethod != "" - let root = s:sub(s:sub(s:sub(f,'/application%(_controller)=\.rb$','/shared_controller.rb'),'/%(controllers|models|mailers)/','/views/'),'%(_controller)=\.rb$','/'.lastmethod) - let format = self.last_format(a:1) - if format == '' - let format = t =~# '^mailer\>' ? 'text' : 'html' - endif - if glob(self.app().path().'/'.root.'.'.format.'.*[^~]') != '' - return root . '.' . format - else - return root - endif - elseif f =~ '\' - return s:sub(s:sub(s:sub(f,'/views/','/controllers/'),'/layouts/(\k+)\..*$','/\1_controller.rb'),'' - let controller = s:sub(s:sub(f,'/views/','/controllers/'),'/(\k+%(\.\k+)=)\..*$','_controller.rb#\1') - let controller2 = s:sub(s:sub(f,'/views/','/controllers/'),'/(\k+%(\.\k+)=)\..*$','.rb#\1') - let mailer = s:sub(s:sub(f,'/views/','/mailers/'),'/(\k+%(\.\k+)=)\..*$','.rb#\1') - let model = s:sub(s:sub(f,'/views/','/models/'),'/(\k+)\..*$','.rb#\1') - if self.app().has_file(s:sub(controller,'#.{-}$','')) - return controller - elseif self.app().has_file(s:sub(controller2,'#.{-}$','')) - return controller2 - elseif self.app().has_file(s:sub(mailer,'#.{-}$','')) - return mailer - elseif self.app().has_file(s:sub(model,'#.{-}$','')) || model =~ '_mailer\.rb#' - return model - else - return controller - endif - elseif t =~ '^controller\>' - return s:sub(s:sub(f,'/controllers/','/helpers/'),'%(_controller)=\.rb$','_helper.rb') - " elseif t=~ '^helper\>' - " return s:findlayout(s:controller()) - elseif t =~ '^model-arb\>' - let table_name = matchstr(join(self.getline(1,50),"\n"),'\n\s*set_table_name\s*[:"'']\zs\w\+') - if table_name == '' - let table_name = rails#pluralize(s:gsub(s:sub(fnamemodify(f,':r'),'.{-}' - return s:sub(f,'_observer\.rb$','.rb') - elseif f =~ '\ me') - let migration = "db/migrate/".get(candidates,0,migrations[0]).".rb" - endif - return migration . (exists('l:lastmethod') && lastmethod != '' ? '#'.lastmethod : '') - elseif f =~ '\' - return "public/javascripts/application.js" - elseif f =~ '\' - let spec1 = fnamemodify(f,':s?\' - let dest = fnamemodify(f,':r:s?/layouts\>??').'/layout.'.fnamemodify(f,':e') - else - let dest = f - endif - return s:sub(s:sub(dest,'' - let api = s:sub(s:sub(f,'/controllers/','/apis/'),'_controller\.rb$','_api.rb') - return api - elseif t =~ '^api\>' - return s:sub(s:sub(f,'/apis/','/controllers/'),'_api\.rb$','_controller.rb') - elseif t =~ '^helper\>' - let controller = s:sub(s:sub(f,'/helpers/','/controllers/'),'_helper\.rb$','_controller.rb') - let controller = s:sub(controller,'application_controller','application') - let spec = s:sub(s:sub(f,'' && f =~ '\' - let file = rails#singularize(fnamemodify(f,":t:r")).'_test.rb' - return file - elseif f == '' - call s:warn("No filename present") - elseif f =~ '\' - return s:sub(s:sub(f,'' - return s:sub(file,'app/models/','test/unit/')."\n".s:sub(s:sub(file,'_test\.rb$','_spec.rb'),'app/models/','spec/models/') - elseif t =~ '^controller\>' - return s:sub(file,'' - return s:sub(file,'test/unit/','app/models/')."\n".s:sub(file,'test/unit/','lib/') - elseif t =~ '^test-functional\>' - if file =~ '_api\.rb' - return s:sub(file,'test/functional/','app/apis/') - elseif file =~ '_controller\.rb' - return s:sub(file,'test/functional/','app/controllers/') - else - return s:sub(file,'test/functional/','') - endif - elseif t == 'spec-lib' - return s:sub(file,'' - return s:sub(file,' 1 - return s:error("Incorrect number of arguments") - endif - if a:1 =~ '[^a-z0-9_/.]' - return s:error("Invalid partial name") - endif - let rails_root = rails#app().path() - let ext = expand("%:e") - let file = s:sub(a:1,'%(/|^)\zs_\ze[^/]*$','') - let first = a:firstline - let last = a:lastline - let range = first.",".last - if RailsFileType() =~ '^view-layout\>' - if RailsFilePath() =~ '\' - let curdir = 'app/views/shared' - if file !~ '/' - let file = "shared/" .file - endif - else - let curdir = s:sub(RailsFilePath(),'.* 0 - if bufloaded(out) - return s:error("Partial already open in buffer ".bufnr(out)) - else - exe "bwipeout ".bufnr(out) - endif - endif - " No tabs, they'll just complicate things - if ext =~? '^\%(rhtml\|erb\|dryml\)$' - let erub1 = '\<\%\s*' - let erub2 = '\s*-=\%\>' - else - let erub1 = '' - let erub2 = '' - endif - let spaces = matchstr(getline(first),"^ *") - if getline(last+1) =~ '\v^\s*'.erub1.'end'.erub2.'\s*$' - let fspaces = matchstr(getline(last+1),"^ *") - if getline(first-1) =~ '\v^'.fspaces.erub1.'for\s+(\k+)\s+in\s+([^ %>]+)'.erub2.'\s*$' - let collection = s:sub(getline(first-1),'^'.fspaces.erub1.'for\s+(\k+)\s+in\s+([^ >]+)'.erub2.'\s*$','\1>\2') - elseif getline(first-1) =~ '\v^'.fspaces.erub1.'([^ %>]+)\.each\s+do\s+\|\s*(\k+)\s*\|'.erub2.'\s*$' - let collection = s:sub(getline(first-1),'^'.fspaces.erub1.'([^ %>]+)\.each\s+do\s+\|\s*(\k+)\s*\|'.erub2.'\s*$','\2>\1') - endif - if collection != '' - let var = matchstr(collection,'^\k\+') - let collection = s:sub(collection,'^\k+\>','') - let first -= 1 - let last += 1 - endif - else - let fspaces = spaces - endif - let renderstr = "render :partial => '".fnamemodify(file,":r:r")."'" - if collection != "" - let renderstr .= ", :collection => ".collection - elseif "@".name != var - let renderstr .= ", :object => ".var - endif - if ext =~? '^\%(rhtml\|erb\|dryml\)$' - let renderstr = "<%= ".renderstr." %>" - elseif ext == "rxml" || ext == "builder" - let renderstr = "xml << ".s:sub(renderstr,"render ","render(").")" - elseif ext == "rjs" - let renderstr = "page << ".s:sub(renderstr,"render ","render(").")" - elseif ext == "haml" - let renderstr = "= ".renderstr - elseif ext == "mn" - let renderstr = "_".renderstr - endif - let buf = @@ - silent exe range."yank" - let partial = @@ - let @@ = buf - let old_ai = &ai - try - let &ai = 0 - silent exe "norm! :".first.",".last."change\".fspaces.renderstr."\.\" - finally - let &ai = old_ai - endtry - if renderstr =~ '<%' - norm ^6w - else - norm ^5w - endif - let ft = &ft - if &hidden - enew - else - new - endif - let shortout = fnamemodify(out,':.') - silent file `=shortout` - let &ft = ft - let @@ = partial - silent put - 0delete - let @@ = buf - if spaces != "" - silent! exe '%substitute/^'.spaces.'//' - endif - silent! exe '%substitute?\%(\w\|[@:"'."'".'-]\)\@?'.name.'?g' - 1 - call RailsBufInit(rails_root) - if exists("l:partial_warn") - call s:warn("Warning: partial exists!") - endif -endfunction - -" }}}1 -" Migration Inversion {{{1 - -function! s:mkeep(str) - " Things to keep (like comments) from a migration statement - return matchstr(a:str,' #[^{].*') -endfunction - -function! s:mextargs(str,num) - if a:str =~ '^\s*\w\+\s*(' - return s:sub(matchstr(a:str,'^\s*\w\+\s*\zs(\%([^,)]\+[,)]\)\{,'.a:num.'\}'),',$',')') - else - return s:sub(s:sub(matchstr(a:str,'\w\+\>\zs\s*\%([^,){ ]*[, ]*\)\{,'.a:num.'\}'),'[, ]*$',''),'^\s+',' ') - endif -endfunction - -function! s:migspc(line) - return matchstr(a:line,'^\s*') -endfunction - -function! s:invertrange(beg,end) - let str = "" - let lnum = a:beg - while lnum <= a:end - let line = getline(lnum) - let add = "" - if line == '' - let add = ' ' - elseif line =~ '^\s*\(#[^{].*\)\=$' - let add = line - elseif line =~ '\' - let add = s:migspc(line)."drop_table".s:mextargs(line,1).s:mkeep(line) - let lnum = s:endof(lnum) - elseif line =~ '\' - let add = s:sub(line,'\s*\(=\s*([^,){ ]*).*','create_table \1 do |t|'."\n".matchstr(line,'^\s*').'end').s:mkeep(line) - elseif line =~ '\' - let add = s:migspc(line).'remove_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\' - let add = s:sub(line,'','add_column') - elseif line =~ '\' - let add = s:migspc(line).'remove_index'.s:mextargs(line,1) - let mat = matchstr(line,':name\s*=>\s*\zs[^ ,)]*') - if mat != '' - let add = s:sub(add,'\)=$',', :name => '.mat.'&') - else - let mat = matchstr(line,'\[^,]*,\s*\zs\%(\[[^]]*\]\|[:"'."'".']\w*["'."'".']\=\)') - if mat != '' - let add = s:sub(add,'\)=$',', :column => '.mat.'&') - endif - endif - let add .= s:mkeep(line) - elseif line =~ '\' - let add = s:sub(s:sub(line,'\s*','') - elseif line =~ '\' - let add = s:sub(line,'' - let add = s:migspc(line).'change_column'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\' - let add = s:migspc(line).'change_column_default'.s:mextargs(line,2).s:mkeep(line) - elseif line =~ '\.update_all(\(["'."'".']\).*\1)$' || line =~ '\.update_all \(["'."'".']\).*\1$' - " .update_all('a = b') => .update_all('b = a') - let pre = matchstr(line,'^.*\.update_all[( ][}'."'".'"]') - let post = matchstr(line,'["'."'".'])\=$') - let mat = strpart(line,strlen(pre),strlen(line)-strlen(pre)-strlen(post)) - let mat = s:gsub(','.mat.',','%(,\s*)@<=([^ ,=]{-})(\s*\=\s*)([^,=]{-})%(\s*,)@=','\3\2\1') - let add = pre.s:sub(s:sub(mat,'^,',''),',$','').post - elseif line =~ '^s\*\%(if\|unless\|while\|until\|for\)\>' - let lnum = s:endof(lnum) - endif - if lnum == 0 - return -1 - endif - if add == "" - let add = s:sub(line,'^\s*\zs.*','raise ActiveRecord::IrreversibleMigration') - elseif add == " " - let add = "" - endif - let str = add."\n".str - let lnum += 1 - endwhile - let str = s:gsub(str,'(\s*raise ActiveRecord::IrreversibleMigration\n)+','\1') - return str -endfunction - -function! s:Invert(bang) - let err = "Could not parse method" - let src = "up" - let dst = "down" - let beg = search('\%('.&l:define.'\).*'.src.'\>',"w") - let end = s:endof(beg) - if beg + 1 == end - let src = "down" - let dst = "up" - let beg = search('\%('.&l:define.'\).*'.src.'\>',"w") - let end = s:endof(beg) - endif - if !beg || !end - return s:error(err) - endif - let str = s:invertrange(beg+1,end-1) - if str == -1 - return s:error(err) - endif - let beg = search('\%('.&l:define.'\).*'.dst.'\>',"w") - let end = s:endof(beg) - if !beg || !end - return s:error(err) - endif - if foldclosed(beg) > 0 - exe beg."foldopen!" - endif - if beg + 1 < end - exe (beg+1).",".(end-1)."delete _" - endif - if str != '' - exe beg.'put =str' - exe 1+beg - endif -endfunction - -" }}}1 -" Cache {{{1 - -let s:cache_prototype = {'dict': {}} - -function! s:cache_clear(...) dict - if a:0 == 0 - let self.dict = {} - elseif has_key(self,'dict') && has_key(self.dict,a:1) - unlet! self.dict[a:1] - endif -endfunction - -function! rails#cache_clear(...) - if exists('b:rails_root') - return call(rails#app().cache.clear,a:000,rails#app().cache) - endif -endfunction - -function! s:cache_get(...) dict - if a:0 == 1 - return self.dict[a:1] - else - return self.dict - endif -endfunction - -function! s:cache_has(key) dict - return has_key(self.dict,a:key) -endfunction - -function! s:cache_needs(key) dict - return !has_key(self.dict,a:key) -endfunction - -function! s:cache_set(key,value) dict - let self.dict[a:key] = a:value -endfunction - -call s:add_methods('cache', ['clear','needs','has','get','set']) - -let s:app_prototype.cache = s:cache_prototype - -" }}}1 -" Syntax {{{1 - -function! s:resetomnicomplete() - if exists("+completefunc") && &completefunc == 'syntaxcomplete#Complete' - if exists("g:loaded_syntax_completion") - " Ugly but necessary, until we have our own completion - unlet g:loaded_syntax_completion - silent! delfunction syntaxcomplete#Complete - endif - endif -endfunction - -function! s:helpermethods() - return "" - \."atom_feed audio_path audio_tag auto_discovery_link_tag auto_link " - \."benchmark button_to button_to_function button_to_remote " - \."cache capture cdata_section check_box check_box_tag collection_select concat content_for content_tag content_tag_for csrf_meta_tag current_cycle cycle " - \."date_select datetime_select debug distance_of_time_in_words distance_of_time_in_words_to_now div_for dom_class dom_id draggable_element draggable_element_js drop_receiving_element drop_receiving_element_js " - \."error_message_on error_messages_for escape_javascript escape_once evaluate_remote_response excerpt " - \."field_set_tag fields_for file_field file_field_tag form form_for form_remote_for form_remote_tag form_tag " - \."grouped_collection_select grouped_options_for_select " - \."hidden_field hidden_field_tag highlight " - \."image_path image_submit_tag image_tag input " - \."javascript_cdata_section javascript_include_tag javascript_path javascript_tag " - \."l label label_tag link_to link_to_function link_to_if link_to_remote link_to_unless link_to_unless_current localize " - \."mail_to markdown " - \."number_to_currency number_to_human_size number_to_percentage number_to_phone number_with_delimiter number_with_precision " - \."observe_field observe_form option_groups_from_collection_for_select options_for_select options_from_collection_for_select " - \."partial_path password_field password_field_tag path_to_audio path_to_image path_to_javascript path_to_stylesheet path_to_video periodically_call_remote pluralize " - \."radio_button radio_button_tag raw remote_form_for remote_function reset_cycle " - \."safe_concat sanitize sanitize_css select select_date select_datetime select_day select_hour select_minute select_month select_second select_tag select_time select_year simple_format sortable_element sortable_element_js strip_links strip_tags stylesheet_link_tag stylesheet_path submit_tag submit_to_remote " - \."t tag text_area text_area_tag text_field text_field_tag textilize textilize_without_paragraph time_ago_in_words time_select time_zone_options_for_select time_zone_select translate truncate " - \."update_page update_page_tag url_for " - \."video_path video_tag visual_effect " - \."word_wrap" -endfunction - -function! s:app_user_classes() dict - if self.cache.needs("user_classes") - let controllers = self.relglob("app/controllers/","**/*",".rb") - call map(controllers,'v:val == "application" ? v:val."_controller" : v:val') - let classes = - \ self.relglob("app/models/","**/*",".rb") + - \ controllers + - \ self.relglob("app/helpers/","**/*",".rb") + - \ self.relglob("lib/","**/*",".rb") - call map(classes,'rails#camelize(v:val)') - call self.cache.set("user_classes",classes) - endif - return self.cache.get('user_classes') -endfunction - -function! s:app_user_assertions() dict - if self.cache.needs("user_assertions") - if self.has_file("test/test_helper.rb") - let assertions = map(filter(s:readfile(self.path("test/test_helper.rb")),'v:val =~ "^ def assert_"'),'matchstr(v:val,"^ def \\zsassert_\\w\\+")') - else - let assertions = [] - endif - call self.cache.set("user_assertions",assertions) - endif - return self.cache.get('user_assertions') -endfunction - -call s:add_methods('app', ['user_classes','user_assertions']) - -function! s:BufSyntax() - if (!exists("g:rails_syntax") || g:rails_syntax) - let t = RailsFileType() - let s:javascript_functions = "$ $$ $A $F $H $R $w jQuery" - let classes = s:gsub(join(rails#app().user_classes(),' '),'::',' ') - if &syntax == 'ruby' - if classes != '' - exe "syn keyword rubyRailsUserClass ".classes." containedin=rubyClassDeclaration,rubyModuleDeclaration,rubyClass,rubyModule" - endif - if t == '' - syn keyword rubyRailsMethod params request response session headers cookies flash - endif - if t =~ '^api\>' - syn keyword rubyRailsAPIMethod api_method inflect_names - endif - if t =~ '^model$' || t =~ '^model-arb\>' - syn keyword rubyRailsARMethod default_scope named_scope scope serialize - syn keyword rubyRailsARAssociationMethod belongs_to has_one has_many has_and_belongs_to_many composed_of accepts_nested_attributes_for - syn keyword rubyRailsARCallbackMethod before_create before_destroy before_save before_update before_validation before_validation_on_create before_validation_on_update - syn keyword rubyRailsARCallbackMethod after_create after_destroy after_save after_update after_validation after_validation_on_create after_validation_on_update - syn keyword rubyRailsARClassMethod attr_accessible attr_protected establish_connection set_inheritance_column set_locking_column set_primary_key set_sequence_name set_table_name - syn keyword rubyRailsARValidationMethod validate validates validate_on_create validate_on_update validates_acceptance_of validates_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of - syn keyword rubyRailsMethod logger - endif - if t =~ '^model-aro\>' - syn keyword rubyRailsARMethod observe - endif - if t =~ '^mailer\>' - syn keyword rubyRailsMethod logger attachments - syn keyword rubyRailsRenderMethod mail render - syn keyword rubyRailsControllerMethod default helper helper_attr helper_method - endif - if t =~ '^controller\>' || t =~ '^view\>' || t=~ '^helper\>' - syn keyword rubyRailsMethod params request response session headers cookies flash - syn keyword rubyRailsRenderMethod render - syn keyword rubyRailsMethod logger - endif - if t =~ '^helper\>' || t=~ '^view\>' - exe "syn keyword rubyRailsHelperMethod ".s:gsub(s:helpermethods(),'<%(content_for|select)\s+','') - syn match rubyRailsHelperMethod '\\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!' - syn match rubyRailsHelperMethod '\<\%(content_for?\=\|current_page?\)' - syn match rubyRailsViewMethod '\.\@' - if t =~ '\' - syn keyword rubyRailsMethod local_assigns - endif - elseif t =~ '^controller\>' - syn keyword rubyRailsControllerMethod helper helper_attr helper_method filter layout url_for serialize exempt_from_layout filter_parameter_logging hide_action cache_sweeper protect_from_forgery caches_page cache_page caches_action expire_page expire_action rescue_from - syn keyword rubyRailsRenderMethod render_to_string redirect_to head - syn match rubyRailsRenderMethod '\?\@!' - syn keyword rubyRailsFilterMethod before_filter append_before_filter prepend_before_filter after_filter append_after_filter prepend_after_filter around_filter append_around_filter prepend_around_filter skip_before_filter skip_after_filter - syn keyword rubyRailsFilterMethod verify - endif - if t =~ '^\%(db-\)\=\%(migration\|schema\)\>' - syn keyword rubyRailsMigrationMethod create_table change_table drop_table rename_table add_column rename_column change_column change_column_default remove_column add_index remove_index - endif - if t =~ '^test\>' - if !empty(rails#app().user_assertions()) - exe "syn keyword rubyRailsUserMethod ".join(rails#app().user_assertions()) - endif - syn keyword rubyRailsTestMethod add_assertion assert assert_block assert_equal assert_in_delta assert_instance_of assert_kind_of assert_match assert_nil assert_no_match assert_not_equal assert_not_nil assert_not_same assert_nothing_raised assert_nothing_thrown assert_operator assert_raise assert_respond_to assert_same assert_send assert_throws assert_recognizes assert_generates assert_routing flunk fixtures fixture_path use_transactional_fixtures use_instantiated_fixtures assert_difference assert_no_difference assert_valid - syn keyword rubyRailsTestMethod test setup teardown - if t !~ '^test-unit\>' - syn match rubyRailsTestControllerMethod '\.\@' - syn keyword rubyRailsTestControllerMethod get_via_redirect post_via_redirect put_via_redirect delete_via_redirect request_via_redirect - syn keyword rubyRailsTestControllerMethod assert_response assert_redirected_to assert_template assert_recognizes assert_generates assert_routing assert_dom_equal assert_dom_not_equal assert_select assert_select_rjs assert_select_encoded assert_select_email assert_tag assert_no_tag - endif - elseif t=~ '^spec\>' - syn keyword rubyRailsTestMethod describe context it its specify it_should_behave_like before after subject fixtures controller_name helper_name - syn keyword rubyRailsTestMethod violated pending expect mock mock_model stub_model - syn match rubyRailsTestMethod '\.\@!\@!' - if t !~ '^spec-model\>' - syn match rubyRailsTestControllerMethod '\.\@' - syn keyword rubyRailsTestControllerMethod integrate_views - syn keyword rubyRailsMethod params request response session flash - endif - endif - if t =~ '^task\>' - syn match rubyRailsRakeMethod '^\s*\zs\%(task\|file\|namespace\|desc\|before\|after\|on\)\>\%(\s*=\)\@!' - endif - if t =~ '^model-awss\>' - syn keyword rubyRailsMethod member - endif - if t =~ '^config-routes\>' - syn match rubyRailsMethod '\.\zs\%(connect\|named_route\)\>' - syn keyword rubyRailsMethod match get put post delete redirect root resource resources collection member nested scope namespace controller constraints - endif - syn keyword rubyRailsMethod debugger - syn keyword rubyRailsMethod alias_attribute alias_method_chain attr_accessor_with_default attr_internal attr_internal_accessor attr_internal_reader attr_internal_writer delegate mattr_accessor mattr_reader mattr_writer superclass_delegating_accessor superclass_delegating_reader superclass_delegating_writer - syn keyword rubyRailsMethod cattr_accessor cattr_reader cattr_writer class_inheritable_accessor class_inheritable_array class_inheritable_array_writer class_inheritable_hash class_inheritable_hash_writer class_inheritable_option class_inheritable_reader class_inheritable_writer inheritable_attributes read_inheritable_attribute reset_inheritable_attributes write_inheritable_array write_inheritable_attribute write_inheritable_hash - syn keyword rubyRailsInclude require_dependency gem - - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:order\s*=>\s*\)\@<="+ skip=+\\\\\|\\"+ end=+"+ contains=@rubyStringSpecial,railsOrderSpecial - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:order\s*=>\s*\)\@<='+ skip=+\\\\\|\\'+ end=+'+ contains=@rubyStringSpecial,railsOrderSpecial - syn match railsOrderSpecial +\c\<\%(DE\|A\)SC\>+ contained - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:conditions\s*=>\s*\[\s*\)\@<="+ skip=+\\\\\|\\"+ end=+"+ contains=@rubyStringSpecial,railsConditionsSpecial - syn region rubyString matchgroup=rubyStringDelimiter start=+\%(:conditions\s*=>\s*\[\s*\)\@<='+ skip=+\\\\\|\\'+ end=+'+ contains=@rubyStringSpecial,railsConditionsSpecial - syn match railsConditionsSpecial +?\|:\h\w*+ contained - syn cluster rubyNotTop add=railsOrderSpecial,railsConditionsSpecial - - " XHTML highlighting inside %Q<> - unlet! b:current_syntax - let removenorend = !exists("g:html_no_rendering") - let g:html_no_rendering = 1 - syn include @htmlTop syntax/xhtml.vim - if removenorend - unlet! g:html_no_rendering - endif - let b:current_syntax = "ruby" - " Restore syn sync, as best we can - if !exists("g:ruby_minlines") - let g:ruby_minlines = 50 - endif - syn sync fromstart - exe "syn sync minlines=" . g:ruby_minlines - syn case match - syn region rubyString matchgroup=rubyStringDelimiter start=+%Q\=<+ end=+>+ contains=@htmlTop,@rubyStringSpecial - syn cluster htmlArgCluster add=@rubyStringSpecial - syn cluster htmlPreProc add=@rubyStringSpecial - - elseif &syntax == "eruby" || &syntax == "haml" - syn case match - if classes != '' - exe "syn keyword erubyRailsUserClass ".classes." contained containedin=@erubyRailsRegions" - endif - if &syntax == "haml" - syn cluster erubyRailsRegions contains=hamlRubyCodeIncluded,hamlRubyCode,hamlRubyHash,@hamlEmbeddedRuby,rubyInterpolation - else - syn cluster erubyRailsRegions contains=erubyOneLiner,erubyBlock,erubyExpression,rubyInterpolation - endif - exe "syn keyword erubyRailsHelperMethod ".s:gsub(s:helpermethods(),'<%(content_for|select)\s+','')." contained containedin=@erubyRailsRegions" - syn match erubyRailsHelperMethod '\\%(\s*{\|\s*do\>\|\s*(\=\s*&\)\@!' contained containedin=@erubyRailsRegions - syn match erubyRailsHelperMethod '\<\%(content_for?\=\|current_page?\)' contained containedin=@erubyRailsRegions - syn keyword erubyRailsMethod debugger logger contained containedin=@erubyRailsRegions - syn keyword erubyRailsMethod params request response session headers cookies flash contained containedin=@erubyRailsRegions - syn match erubyRailsViewMethod '\.\@' contained containedin=@erubyRailsRegions - if t =~ '\' - syn keyword erubyRailsMethod local_assigns contained containedin=@erubyRailsRegions - endif - syn keyword erubyRailsRenderMethod render contained containedin=@erubyRailsRegions - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction contained ".s:javascript_functions - syn cluster htmlJavaScript add=javascriptRailsFunction - elseif &syntax == "yaml" - syn case match - " Modeled after syntax/eruby.vim - unlet! b:current_syntax - let g:main_syntax = 'eruby' - syn include @rubyTop syntax/ruby.vim - unlet g:main_syntax - syn cluster yamlRailsRegions contains=yamlRailsOneLiner,yamlRailsBlock,yamlRailsExpression - syn region yamlRailsOneLiner matchgroup=yamlRailsDelimiter start="^%%\@!" end="$" contains=@rubyRailsTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment keepend oneline - syn region yamlRailsBlock matchgroup=yamlRailsDelimiter start="<%%\@!" end="%>" contains=@rubyTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment - syn region yamlRailsExpression matchgroup=yamlRailsDelimiter start="<%=" end="%>" contains=@rubyTop containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment - syn region yamlRailsComment matchgroup=yamlRailsDelimiter start="<%#" end="%>" contains=rubyTodo,@Spell containedin=ALLBUT,@yamlRailsRegions,yamlRailsComment keepend - syn match yamlRailsMethod '\.\@' contained containedin=@yamlRailsRegions - if classes != '' - exe "syn keyword yamlRailsUserClass ".classes." contained containedin=@yamlRailsRegions" - endif - let b:current_syntax = "yaml" - elseif &syntax == "html" - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction contained ".s:javascript_functions - syn cluster htmlJavaScript add=javascriptRailsFunction - elseif &syntax == "javascript" - " The syntax file included with Vim incorrectly sets syn case ignore. - syn case match - set isk+=$ - exe "syn keyword javascriptRailsFunction ".s:javascript_functions - - endif - endif - call s:HiDefaults() -endfunction - -function! s:HiDefaults() - hi def link rubyRailsAPIMethod rubyRailsMethod - hi def link rubyRailsARAssociationMethod rubyRailsARMethod - hi def link rubyRailsARCallbackMethod rubyRailsARMethod - hi def link rubyRailsARClassMethod rubyRailsARMethod - hi def link rubyRailsARValidationMethod rubyRailsARMethod - hi def link rubyRailsARMethod rubyRailsMethod - hi def link rubyRailsRenderMethod rubyRailsMethod - hi def link rubyRailsHelperMethod rubyRailsMethod - hi def link rubyRailsViewMethod rubyRailsMethod - hi def link rubyRailsMigrationMethod rubyRailsMethod - hi def link rubyRailsControllerMethod rubyRailsMethod - hi def link rubyRailsFilterMethod rubyRailsMethod - hi def link rubyRailsTestControllerMethod rubyRailsTestMethod - hi def link rubyRailsTestMethod rubyRailsMethod - hi def link rubyRailsRakeMethod rubyRailsMethod - hi def link rubyRailsMethod railsMethod - hi def link rubyRailsInclude rubyInclude - hi def link rubyRailsUserClass railsUserClass - hi def link rubyRailsUserMethod railsUserMethod - hi def link erubyRailsHelperMethod erubyRailsMethod - hi def link erubyRailsViewMethod erubyRailsMethod - hi def link erubyRailsRenderMethod erubyRailsMethod - hi def link erubyRailsMethod railsMethod - hi def link erubyRailsUserMethod railsUserMethod - hi def link railsUserMethod railsMethod - hi def link erubyRailsUserClass railsUserClass - hi def link yamlRailsDelimiter Delimiter - hi def link yamlRailsMethod railsMethod - hi def link yamlRailsComment Comment - hi def link yamlRailsUserClass railsUserClass - hi def link yamlRailsUserMethod railsUserMethod - hi def link javascriptRailsFunction railsMethod - hi def link railsUserClass railsClass - hi def link railsMethod Function - hi def link railsClass Type - hi def link railsOrderSpecial railsStringSpecial - hi def link railsConditionsSpecial railsStringSpecial - hi def link railsStringSpecial Identifier -endfunction - -function! rails#log_syntax() - syn match railslogRender '^\s*\<\%(Processing\|Rendering\|Rendered\|Redirected\|Completed\)\>' - syn match railslogComment '^\s*# .*' - syn match railslogModel '^\s*\u\%(\w\|:\)* \%(Load\%( Including Associations\| IDs For Limited Eager Loading\)\=\|Columns\|Count\|Create\|Update\|Destroy\|Delete all\)\>' skipwhite nextgroup=railslogModelNum - syn match railslogModel '^\s*SQL\>' skipwhite nextgroup=railslogModelNum - syn region railslogModelNum start='(' end=')' contains=railslogNumber contained skipwhite nextgroup=railslogSQL - syn match railslogSQL '\u.*$' contained - " Destroy generates multiline SQL, ugh - syn match railslogSQL '^ \%(FROM\|WHERE\|ON\|AND\|OR\|ORDER\) .*$' - syn match railslogNumber '\<\d\+\>%' - syn match railslogNumber '[ (]\@<=\<\d\+\.\d\+\>' - syn region railslogString start='"' skip='\\"' end='"' oneline contained - syn region railslogHash start='{' end='}' oneline contains=railslogHash,railslogString - syn match railslogIP '\<\d\{1,3\}\%(\.\d\{1,3}\)\{3\}\>' - syn match railslogTimestamp '\<\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\>' - syn match railslogSessionID '\<\x\{32\}\>' - syn match railslogIdentifier '^\s*\%(Session ID\|Parameters\)\ze:' - syn match railslogSuccess '\<2\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogRedirect '\<3\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogError '\<[45]\d\d \u[A-Za-z0-9 ]*\>' - syn match railslogError '^DEPRECATION WARNING\>' - syn keyword railslogHTTP OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT - syn region railslogStackTrace start=":\d\+:in `\w\+'$" end="^\s*$" keepend fold - hi def link railslogComment Comment - hi def link railslogRender Keyword - hi def link railslogModel Type - hi def link railslogSQL PreProc - hi def link railslogNumber Number - hi def link railslogString String - hi def link railslogSessionID Constant - hi def link railslogIdentifier Identifier - hi def link railslogRedirect railslogSuccess - hi def link railslogSuccess Special - hi def link railslogError Error - hi def link railslogHTTP Special -endfunction - -" }}}1 -" Statusline {{{1 - -function! s:addtostatus(letter,status) - let status = a:status - if status !~ 'rails' && g:rails_statusline - let status=substitute(status,'\C%'.tolower(a:letter),'%'.tolower(a:letter).'%{rails#statusline()}','') - if status !~ 'rails' - let status=substitute(status,'\C%'.toupper(a:letter),'%'.toupper(a:letter).'%{rails#STATUSLINE()}','') - endif - endif - return status -endfunction - -function! s:BufInitStatusline() - if g:rails_statusline - if &l:statusline == '' - let &l:statusline = &g:statusline - endif - if &l:statusline == '' - let &l:statusline='%<%f %h%m%r%=' - if &ruler - let &l:statusline .= '%-16( %l,%c-%v %)%P' - endif - endif - let &l:statusline = s:InjectIntoStatusline(&l:statusline) - endif -endfunction - -function! s:InitStatusline() - if g:rails_statusline - if &g:statusline == '' - let &g:statusline='%<%f %h%m%r%=' - if &ruler - let &g:statusline .= '%-16( %l,%c-%v %)%P' - endif - endif - let &g:statusline = s:InjectIntoStatusline(&g:statusline) - endif -endfunction - -function! s:InjectIntoStatusline(status) - let status = a:status - if status !~ 'rails' - let status = s:addtostatus('y',status) - let status = s:addtostatus('r',status) - let status = s:addtostatus('m',status) - let status = s:addtostatus('w',status) - let status = s:addtostatus('h',status) - if status !~ 'rails' - let status=substitute(status,'%=','%{rails#statusline()}%=','') - endif - if status !~ 'rails' && status != '' - let status .= '%{rails#statusline()}' - endif - endif - return status -endfunction - -function! rails#statusline(...) - if exists("b:rails_root") - let t = RailsFileType() - if t != "" && a:0 && a:1 - return "[Rails-".t."]" - else - return "[Rails]" - endif - else - return "" - endif -endfunction - -function! rails#STATUSLINE(...) - if exists("b:rails_root") - let t = RailsFileType() - if t != "" && a:0 && a:1 - return ",RAILS-".toupper(t) - else - return ",RAILS" - endif - else - return "" - endif -endfunction - -" }}}1 -" Mappings {{{1 - -function! s:BufMappings() - nnoremap RailsAlternate :A - nnoremap RailsRelated :R - nnoremap RailsFind :REfind - nnoremap RailsSplitFind :RSfind - nnoremap RailsVSplitFind :RVfind - nnoremap RailsTabFind :RTfind - if g:rails_mappings - if !hasmapto("RailsFind") - nmap gf RailsFind - endif - if !hasmapto("RailsSplitFind") - nmap f RailsSplitFind - endif - if !hasmapto("RailsTabFind") - nmap gf RailsTabFind - endif - if !hasmapto("RailsAlternate") - nmap [f RailsAlternate - endif - if !hasmapto("RailsRelated") - nmap ]f RailsRelated - endif - if exists("$CREAM") - imap RailsFind - imap RailsAlternate - imap RailsRelated - endif - endif - " SelectBuf you're a dirty hack - let v:errmsg = "" -endfunction - -" }}}1 -" Project {{{ - -function! s:Project(bang,arg) - let rr = rails#app().path() - exe "Project ".a:arg - let line = search('^[^ =]*="'.s:gsub(rr,'[\/]','[\\/]').'"') - let projname = s:gsub(fnamemodify(rr,':t'),'\=','-') " .'_on_rails' - if line && a:bang - let projname = matchstr(getline('.'),'^[^=]*') - " Most of this would be unnecessary if the project.vim author had just put - " the newlines AFTER each project rather than before. Ugh. - norm zR0"_d% - if line('.') > 2 - delete _ - endif - if line('.') != line('$') - .-2 - endif - let line = 0 - elseif !line - $ - endif - if !line - if line('.') > 1 - append - -. - endif - let line = line('.')+1 - call s:NewProject(projname,rr) - endif - normal! zMzo - if search("^ app=app {","W",line+10) - normal! zo - exe line - endif - normal! 0zt -endfunction - -function! s:NewProject(proj,rr) - let line = line('.')+1 - let template = s:NewProjectTemplate(a:proj,a:rr) - silent put =template - exe line - " Ugh. how else can I force detecting folds? - setlocal foldmethod=manual - norm! $% - silent exe "doautocmd User ".s:escarg(a:rr)."/Rproject" - let newline = line('.') - exe line - norm! $% - if line('.') != newline - call s:warn("Warning: Rproject autocommand failed to leave cursor at end of project") - endif - exe line - setlocal foldmethod=marker - setlocal nomodified - " FIXME: make undo stop here - if !exists("g:maplocalleader") - silent! normal \R - else " Needs to be tested - exe 'silent! normal '.g:maplocalleader.'R' - endif -endfunction - -function! s:NewProjectTemplate(proj,rr) - let str = a:proj.'="'.a:rr."\" CD=. filter=\"*\" {\n" - let str .= " app=app {\n" - for dir in ['apis','controllers','helpers','models','views'] - let str .= s:addprojectdir(a:rr,'app',dir) - endfor - let str .= " }\n" - let str .= " config=config {\n environments=environments {\n }\n }\n" - let str .= " db=db {\n" - let str .= s:addprojectdir(a:rr,'db','migrate') - let str .= " }\n" - let str .= " lib=lib filter=\"* */**/*.rb \" {\n tasks=tasks filter=\"**/*.rake\" {\n }\n }\n" - let str .= " public=public {\n images=images {\n }\n javascripts=javascripts {\n }\n stylesheets=stylesheets {\n }\n }\n" - if isdirectory(a:rr.'/spec') - let str .= " spec=spec {\n" - for dir in ['controllers','fixtures','helpers','models','views'] - let str .= s:addprojectdir(a:rr,'spec',dir) - endfor - let str .= " }\n" - endif - if isdirectory(a:rr.'/test') - let str .= " test=test {\n" - for dir in ['fixtures','functional','integration','mocks','unit'] - let str .= s:addprojectdir(a:rr,'test',dir) - endfor - let str .= " }\n" - end - let str .= "}\n" - return str -endfunction - -function! s:addprojectdir(rr,parentdir,dir) - if isdirectory(a:rr.'/'.a:parentdir.'/'.a:dir) - return ' '.a:dir.'='.a:dir." filter=\"**\" {\n }\n" - else - return '' - endif -endfunction - -" }}}1 -" Database {{{1 - -function! s:extractdbvar(str,arg) - return matchstr("\n".a:str."\n",'\n'.a:arg.'=\zs.\{-\}\ze\n') -endfunction - -function! s:app_dbext_settings(environment) dict - if self.cache.needs('dbext_settings') - call self.cache.set('dbext_settings',{}) - endif - let cache = self.cache.get('dbext_settings') - if !has_key(cache,a:environment) - let dict = {} - if self.has_file("config/database.yml") - let cmdb = 'require %{yaml}; File.open(%q{'.self.path().'/config/database.yml}) {|f| y = YAML::load(f); e = y[%{' - let cmde = '}]; i=0; e=y[e] while e.respond_to?(:to_str) && (i+=1)<16; e.each{|k,v|puts k.to_s+%{=}+v.to_s}}' - let out = self.lightweight_ruby_eval(cmdb.a:environment.cmde) - let adapter = s:extractdbvar(out,'adapter') - let adapter = get({'postgresql': 'pgsql', 'sqlite3': 'sqlite', 'sqlserver': 'sqlsrv', 'sybase': 'asa', 'oci': 'ora'},adapter,adapter) - let dict['type'] = toupper(adapter) - let dict['user'] = s:extractdbvar(out,'username') - let dict['passwd'] = s:extractdbvar(out,'password') - if dict['passwd'] == '' && adapter == 'mysql' - " Hack to override password from .my.cnf - let dict['extra'] = ' --password=' - else - let dict['extra'] = '' - endif - let dict['dbname'] = s:extractdbvar(out,'database') - if dict['dbname'] == '' - let dict['dbname'] = s:extractdbvar(out,'dbfile') - endif - if dict['dbname'] != '' && dict['dbname'] !~ '^:' && adapter =~? '^sqlite' - let dict['dbname'] = self.path(dict['dbname']) - endif - let dict['profile'] = '' - let dict['srvname'] = s:extractdbvar(out,'host') - let dict['host'] = s:extractdbvar(out,'host') - let dict['port'] = s:extractdbvar(out,'port') - let dict['dsnname'] = s:extractdbvar(out,'dsn') - if dict['host'] =~? '^\cDBI:' - if dict['host'] =~? '\c\' - let dict['integratedlogin'] = 1 - endif - let dict['host'] = matchstr(dict['host'],'\c\<\%(Server\|Data Source\)\s*=\s*\zs[^;]*') - endif - call filter(dict,'v:val != ""') - endif - let cache[a:environment] = dict - endif - return cache[a:environment] -endfunction - -function! s:BufDatabase(...) - if exists("s:lock_database") || !exists('g:loaded_dbext') || !exists('b:rails_root') - return - endif - let self = rails#app() - let s:lock_database = 1 - if (a:0 && a:1 > 1) - call self.cache.clear('dbext_settings') - endif - if (a:0 > 1 && a:2 != '') - let env = a:2 - else - let env = s:environment() - endif - if (!self.cache.has('dbext_settings') || !has_key(self.cache.get('dbext_settings'),env)) && (a:0 ? a:1 : 0) <= 0 - unlet! s:lock_database - return - endif - let dict = self.dbext_settings(env) - for key in ['type', 'profile', 'bin', 'user', 'passwd', 'dbname', 'srvname', 'host', 'port', 'dsnname', 'extra', 'integratedlogin'] - let b:dbext_{key} = get(dict,key,'') - endfor - if b:dbext_type == 'PGSQL' - let $PGPASSWORD = b:dbext_passwd - elseif exists('$PGPASSWORD') - let $PGPASSWORD = '' - endif - unlet! s:lock_database -endfunction - -call s:add_methods('app', ['dbext_settings']) - -" }}}1 -" Abbreviations {{{1 - -function! s:selectiveexpand(pat,good,default,...) - if a:0 > 0 - let nd = a:1 - else - let nd = "" - endif - let c = nr2char(getchar(0)) - let good = a:good - if c == "" " ^] - return s:sub(good.(a:0 ? " ".a:1 : ''),'\s+$','') - elseif c == "\t" - return good.(a:0 ? " ".a:1 : '') - elseif c =~ a:pat - return good.c.(a:0 ? a:1 : '') - else - return a:default.c - endif -endfunction - -function! s:TheCWord() - let l = s:linepeak() - if l =~ '\<\%(find\|first\|last\|all\|paginate\)\>' - return s:selectiveexpand('..',':conditions => ',':c') - elseif l =~ '\\s*' - return s:selectiveexpand('..',':collection => ',':c') - elseif l =~ '\<\%(url_for\|link_to\|form_tag\)\>' || l =~ ':url\s*=>\s*{\s*' - return s:selectiveexpand('..',':controller => ',':c') - else - return s:selectiveexpand('..',':conditions => ',':c') - endif -endfunction - -function! s:AddSelectiveExpand(abbr,pat,expn,...) - let expn = s:gsub(s:gsub(a:expn ,'[\"|]','\\&'),'\<','\\') - let expn2 = s:gsub(s:gsub(a:0 ? a:1 : '','[\"|]','\\&'),'\<','\\') - if a:0 - exe "inoreabbrev ".a:abbr." =selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).",\"".expn2."\")" - else - exe "inoreabbrev ".a:abbr." =selectiveexpand(".string(a:pat).",\"".expn."\",".string(a:abbr).")" - endif -endfunction - -function! s:AddTabExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'..',a:expn) -endfunction - -function! s:AddBracketExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'[[.]',a:expn) -endfunction - -function! s:AddColonExpand(abbr,expn) - call s:AddSelectiveExpand(a:abbr,'[:.]',a:expn) -endfunction - -function! s:AddParenExpand(abbr,expn,...) - if a:0 - call s:AddSelectiveExpand(a:abbr,'(',a:expn,a:1) - else - call s:AddSelectiveExpand(a:abbr,'(',a:expn,'') - endif -endfunction - -function! s:BufAbbreviations() - command! -buffer -bar -nargs=* -bang Rabbrev :call s:Abbrev(0,) - " Some of these were cherry picked from the TextMate snippets - if g:rails_abbreviations - let t = RailsFileType() - " Limit to the right filetypes. But error on the liberal side - if t =~ '^\(controller\|view\|helper\|test-functional\|test-integration\)\>' - Rabbrev pa[ params - Rabbrev rq[ request - Rabbrev rs[ response - Rabbrev se[ session - Rabbrev hd[ headers - Rabbrev co[ cookies - Rabbrev fl[ flash - Rabbrev rr( render - Rabbrev ra( render :action\ =>\ - Rabbrev rc( render :controller\ =>\ - Rabbrev rf( render :file\ =>\ - Rabbrev ri( render :inline\ =>\ - Rabbrev rj( render :json\ =>\ - Rabbrev rl( render :layout\ =>\ - Rabbrev rp( render :partial\ =>\ - Rabbrev rt( render :text\ =>\ - Rabbrev rx( render :xml\ =>\ - endif - if t =~ '^\%(view\|helper\)\>' - Rabbrev dotiw distance_of_time_in_words - Rabbrev taiw time_ago_in_words - endif - if t =~ '^controller\>' - Rabbrev re( redirect_to - Rabbrev rea( redirect_to :action\ =>\ - Rabbrev rec( redirect_to :controller\ =>\ - Rabbrev rst( respond_to - endif - if t =~ '^model-arb\>' || t =~ '^model$' - Rabbrev bt( belongs_to - Rabbrev ho( has_one - Rabbrev hm( has_many - Rabbrev habtm( has_and_belongs_to_many - Rabbrev co( composed_of - Rabbrev va( validates_associated - Rabbrev vb( validates_acceptance_of - Rabbrev vc( validates_confirmation_of - Rabbrev ve( validates_exclusion_of - Rabbrev vf( validates_format_of - Rabbrev vi( validates_inclusion_of - Rabbrev vl( validates_length_of - Rabbrev vn( validates_numericality_of - Rabbrev vp( validates_presence_of - Rabbrev vu( validates_uniqueness_of - endif - if t =~ '^\%(db-\)\=\%(migration\|schema\)\>' - Rabbrev mac( add_column - Rabbrev mrnc( rename_column - Rabbrev mrc( remove_column - Rabbrev mct( create_table - Rabbrev mcht( change_table - Rabbrev mrnt( rename_table - Rabbrev mdt( drop_table - Rabbrev mcc( t.column - endif - if t =~ '^test\>' - Rabbrev ase( assert_equal - Rabbrev asko( assert_kind_of - Rabbrev asnn( assert_not_nil - Rabbrev asr( assert_raise - Rabbrev asre( assert_response - Rabbrev art( assert_redirected_to - endif - Rabbrev :a :action\ =>\ - " hax - Rabbrev :c :co________\ =>\ - inoreabbrev :c =TheCWord() - Rabbrev :i :id\ =>\ - Rabbrev :o :object\ =>\ - Rabbrev :p :partial\ =>\ - Rabbrev logd( logger.debug - Rabbrev logi( logger.info - Rabbrev logw( logger.warn - Rabbrev loge( logger.error - Rabbrev logf( logger.fatal - Rabbrev fi( find - Rabbrev AR:: ActiveRecord - Rabbrev AV:: ActionView - Rabbrev AC:: ActionController - Rabbrev AD:: ActionDispatch - Rabbrev AS:: ActiveSupport - Rabbrev AM:: ActionMailer - Rabbrev AO:: ActiveModel - Rabbrev AE:: ActiveResource - Rabbrev AWS:: ActionWebService - endif -endfunction - -function! s:Abbrev(bang,...) abort - if !exists("b:rails_abbreviations") - let b:rails_abbreviations = {} - endif - if a:0 > 3 || (a:bang && (a:0 != 1)) - return s:error("Rabbrev: invalid arguments") - endif - if a:0 == 0 - for key in sort(keys(b:rails_abbreviations)) - echo key . join(b:rails_abbreviations[key],"\t") - endfor - return - endif - let lhs = a:1 - let root = s:sub(lhs,'%(::|\(|\[)$','') - if a:bang - if has_key(b:rails_abbreviations,root) - call remove(b:rails_abbreviations,root) - endif - exe "iunabbrev ".root - return - endif - if a:0 > 3 || a:0 < 2 - return s:error("Rabbrev: invalid arguments") - endif - let rhs = a:2 - if has_key(b:rails_abbreviations,root) - call remove(b:rails_abbreviations,root) - endif - if lhs =~ '($' - let b:rails_abbreviations[root] = ["(", rhs . (a:0 > 2 ? "\t".a:3 : "")] - if a:0 > 2 - call s:AddParenExpand(root,rhs,a:3) - else - call s:AddParenExpand(root,rhs) - endif - return - endif - if a:0 > 2 - return s:error("Rabbrev: invalid arguments") - endif - if lhs =~ ':$' - call s:AddColonExpand(root,rhs) - elseif lhs =~ '\[$' - call s:AddBracketExpand(root,rhs) - elseif lhs =~ '\w$' - call s:AddTabExpand(lhs,rhs) - else - return s:error("Rabbrev: unimplemented") - endif - let b:rails_abbreviations[root] = [matchstr(lhs,'\W*$'),rhs] -endfunction - -" }}}1 -" Settings {{{1 - -function! s:Set(bang,...) - let c = 1 - let defscope = '' - for arg in a:000 - if arg =~? '^<[abgl]\=>$' - let defscope = (matchstr(arg,'<\zs.*\ze>')) - elseif arg !~ '=' - if defscope != '' && arg !~ '^\w:' - let arg = defscope.':'.opt - endif - let val = s:getopt(arg) - if val == '' && !has_key(s:opts(),arg) - call s:error("No such rails.vim option: ".arg) - else - echo arg."=".val - endif - else - let opt = matchstr(arg,'[^=]*') - let val = s:sub(arg,'^[^=]*\=','') - if defscope != '' && opt !~ '^\w:' - let opt = defscope.':'.opt - endif - call s:setopt(opt,val) - endif - endfor -endfunction - -function! s:getopt(opt,...) - let app = rails#app() - let opt = a:opt - if a:0 - let scope = a:1 - elseif opt =~ '^[abgl]:' - let scope = tolower(matchstr(opt,'^\w')) - let opt = s:sub(opt,'^\w:','') - else - let scope = 'abgl' - endif - let lnum = a:0 > 1 ? a:2 : line('.') - if scope =~ 'l' && &filetype != 'ruby' - let scope = s:sub(scope,'l','b') - endif - if scope =~ 'l' - call s:LocalModelines(lnum) - endif - let var = s:sname().'_'.opt - let lastmethod = s:lastmethod(lnum) - if lastmethod == '' | let lastmethod = ' ' | endif - " Get buffer option - if scope =~ 'l' && exists('b:_'.var) && has_key(b:_{var},lastmethod) - return b:_{var}[lastmethod] - elseif exists('b:'.var) && (scope =~ 'b' || (scope =~ 'l' && lastmethod == ' ')) - return b:{var} - elseif scope =~ 'a' && has_key(app,'options') && has_key(app.options,opt) - return app.options[opt] - elseif scope =~ 'g' && exists("g:".s:sname()."_".opt) - return g:{var} - else - return "" - endif -endfunction - -function! s:setopt(opt,val) - let app = rails#app() - if a:opt =~? '[abgl]:' - let scope = matchstr(a:opt,'^\w') - let opt = s:sub(a:opt,'^\w:','') - else - let scope = '' - let opt = a:opt - endif - let defscope = get(s:opts(),opt,'a') - if scope == '' - let scope = defscope - endif - if &filetype != 'ruby' && (scope ==# 'B' || scope ==# 'l') - let scope = 'b' - endif - let var = s:sname().'_'.opt - if opt =~ '\W' - return s:error("Invalid option ".a:opt) - elseif scope ==# 'B' && defscope == 'l' - if !exists('b:_'.var) | let b:_{var} = {} | endif - let b:_{var}[' '] = a:val - elseif scope =~? 'b' - let b:{var} = a:val - elseif scope =~? 'a' - if !has_key(app,'options') | let app.options = {} | endif - let app.options[opt] = a:val - elseif scope =~? 'g' - let g:{var} = a:val - elseif scope =~? 'l' - if !exists('b:_'.var) | let b:_{var} = {} | endif - let lastmethod = s:lastmethod(lnum) - let b:_{var}[lastmethod == '' ? ' ' : lastmethod] = a:val - else - return s:error("Invalid scope for ".a:opt) - endif -endfunction - -function! s:opts() - return {'alternate': 'b', 'controller': 'b', 'gnu_screen': 'a', 'model': 'b', 'preview': 'l', 'task': 'b', 'related': 'l', 'root_url': 'a'} -endfunction - -function! s:Complete_set(A,L,P) - if a:A =~ '=' - let opt = matchstr(a:A,'[^=]*') - return [opt."=".s:getopt(opt)] - else - let extra = matchstr(a:A,'^[abgl]:') - return filter(sort(map(keys(s:opts()),'extra.v:val')),'s:startswith(v:val,a:A)') - endif - return [] -endfunction - -function! s:BufModelines() - if !g:rails_modelines - return - endif - let lines = getline("$")."\n".getline(line("$")-1)."\n".getline(1)."\n".getline(2)."\n".getline(3)."\n" - let pat = '\s\+\zs.\{-\}\ze\%(\n\|\s\s\|#{\@!\|%>\|-->\|$\)' - let cnt = 1 - let mat = matchstr(lines,'\C\ ".mat - endif - let mat = matchstr(lines,'\C\ ".mat - endif - let mat = matchstr(lines,'\C\ 0 - if !exists("g:RAILS_HISTORY") - let g:RAILS_HISTORY = "" - endif - let path = a:path - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,path) - if has("win32") - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,s:gsub(path,'\\','/')) - endif - let path = fnamemodify(path,':p:~:h') - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,path) - if has("win32") - let g:RAILS_HISTORY = s:scrub(g:RAILS_HISTORY,s:gsub(path,'\\','/')) - endif - let g:RAILS_HISTORY = path."\n".g:RAILS_HISTORY - let g:RAILS_HISTORY = s:sub(g:RAILS_HISTORY,'%(.{-}\n){,'.g:rails_history_size.'}\zs.*','') - endif - call app.source_callback("config/syntax.vim") - if &ft == "mason" - setlocal filetype=eruby - elseif &ft =~ '^\%(conf\|ruby\)\=$' && expand("%:e") =~ '^\%(rjs\|rxml\|builder\|rake\|mab\)$' - setlocal filetype=ruby - elseif &ft =~ '^\%(conf\|ruby\)\=$' && expand("%:t") =~ '^\%(Rake\|Gem\|Cap\)file$' - setlocal filetype=ruby - elseif &ft =~ '^\%(liquid\)\=$' && expand("%:e") == "liquid" - setlocal filetype=liquid - elseif &ft =~ '^\%(haml\|x\=html\)\=$' && expand("%:e") == "haml" - setlocal filetype=haml - elseif &ft =~ '^\%(sass\|conf\)\=$' && expand("%:e") == "sass" - setlocal filetype=sass - elseif &ft =~ '^\%(dryml\)\=$' && expand("%:e") == "dryml" - setlocal filetype=dryml - elseif (&ft == "" || v:version < 701) && expand("%:e") =~ '^\%(rhtml\|erb\)$' - setlocal filetype=eruby - elseif (&ft == "" || v:version < 700) && expand("%:e") == 'yml' - setlocal filetype=yaml - elseif &ft =~ '^\%(conf\|yaml\)\=$' && expand("%:t") =~ '\.yml\.example$' - setlocal filetype=yaml - elseif firsttime - " Activate custom syntax - let &syntax = &syntax - endif - if firsttime - call s:BufInitStatusline() - endif - if expand("%:e") == "log" - setlocal modifiable filetype=railslog - silent! %s/\%(\e\[[0-9;]*m\|\r$\)//g - setlocal readonly nomodifiable noswapfile autoread foldmethod=syntax - nnoremap R :checktime - nnoremap G :checktime$ - nnoremap q :bwipe - $ - endif - call s:BufSettings() - call s:BufCommands() - call s:BufAbbreviations() - " snippetsEmu.vim - if exists('g:loaded_snippet') - silent! runtime! ftplugin/rails_snippets.vim - " filetype snippets need to come last for higher priority - exe "silent! runtime! ftplugin/".&filetype."_snippets.vim" - endif - let t = RailsFileType() - let t = "-".t - let f = '/'.RailsFilePath() - if f =~ '[ !#$%\,]' - let f = '' - endif - runtime! macros/rails.vim - silent doautocmd User Rails - if t != '-' - exe "silent doautocmd User Rails".s:gsub(t,'-','.') - endif - if f != '' - exe "silent doautocmd User Rails".f - endif - call app.source_callback("config/rails.vim") - call s:BufModelines() - call s:BufMappings() - return b:rails_root -endfunction - -function! s:SetBasePath() - let self = rails#buffer() - if self.app().path() =~ '://' - return - endif - let transformed_path = s:pathsplit(s:pathjoin([self.app().path()]))[0] - let add_dot = self.getvar('&path') =~# '^\.\%(,\|$\)' - let old_path = s:pathsplit(s:sub(self.getvar('&path'),'^\.%(,|$)','')) - call filter(old_path,'!s:startswith(v:val,transformed_path)') - - let path = ['app', 'app/models', 'app/controllers', 'app/helpers', 'config', 'lib', 'app/views'] - if self.controller_name() != '' - let path += ['app/views/'.self.controller_name(), 'public'] - endif - if self.app().has('test') - let path += ['test', 'test/unit', 'test/functional', 'test/integration'] - endif - if self.app().has('spec') - let path += ['spec', 'spec/models', 'spec/controllers', 'spec/helpers', 'spec/views', 'spec/lib', 'spec/integration'] - endif - let path += ['app/*', 'vendor', 'vendor/plugins/*/lib', 'vendor/plugins/*/test', 'vendor/rails/*/lib', 'vendor/rails/*/test'] - call map(path,'self.app().path(v:val)') - call self.setvar('&path',(add_dot ? '.,' : '').s:pathjoin([self.app().path()],path,old_path)) -endfunction - -function! s:BufSettings() - if !exists('b:rails_root') - return '' - endif - let self = rails#buffer() - call s:SetBasePath() - let rp = s:gsub(self.app().path(),'[ ,]','\\&') - if stridx(&tags,rp) == -1 - let &l:tags = rp . "/tmp/tags," . &tags . "," . rp . "/tags" - endif - if has("gui_win32") || has("gui_running") - let code = '*.rb;*.rake;Rakefile' - let templates = '*.'.s:gsub(s:view_types,',',';*.') - let fixtures = '*.yml;*.csv' - let statics = '*.html;*.css;*.js;*.xml;*.xsd;*.sql;.htaccess;README;README_FOR_APP' - let b:browsefilter = "" - \."All Rails Files\t".code.';'.templates.';'.fixtures.';'.statics."\n" - \."Source Code (*.rb, *.rake)\t".code."\n" - \."Templates (*.rhtml, *.rxml, *.rjs)\t".templates."\n" - \."Fixtures (*.yml, *.csv)\t".fixtures."\n" - \."Static Files (*.html, *.css, *.js)\t".statics."\n" - \."All Files (*.*)\t*.*\n" - endif - call self.setvar('&includeexpr','RailsIncludeexpr()') - call self.setvar('&suffixesadd', ".rb,.".s:gsub(s:view_types,',',',.').",.css,.js,.yml,.csv,.rake,.sql,.html,.xml") - let ft = self.getvar('&filetype') - if ft =~ '^\%(e\=ruby\|[yh]aml\|javascript\|css\|sass\)$' - call self.setvar('&shiftwidth',2) - call self.setvar('&softtabstop',2) - call self.setvar('&expandtab',1) - if exists('+completefunc') && self.getvar('&completefunc') == '' - call self.setvar('&completefunc','syntaxcomplete#Complete') - endif - endif - if ft == 'ruby' - call self.setvar('&suffixesadd',".rb,.".s:gsub(s:view_types,',',',.').",.yml,.csv,.rake,s.rb") - call self.setvar('&define',self.define_pattern()) - " This really belongs in after/ftplugin/ruby.vim but we'll be nice - if exists('g:loaded_surround') && self.getvar('surround_101') == '' - call self.setvar('surround_5', "\r\nend") - call self.setvar('surround_69', "\1expr: \1\rend") - call self.setvar('surround_101', "\r\nend") - endif - elseif ft == 'yaml' || fnamemodify(self.name(),':e') == 'yml' - call self.setvar('&define',self.define_pattern()) - call self.setvar('&suffixesadd',".yml,.csv,.rb,.".s:gsub(s:view_types,',',',.').",.rake,s.rb") - elseif ft == 'eruby' - call self.setvar('&suffixesadd',".".s:gsub(s:view_types,',',',.').",.rb,.css,.js,.html,.yml,.csv") - if exists("g:loaded_allml") - call self.setvar('allml_stylesheet_link_tag', "<%= stylesheet_link_tag '\r' %>") - call self.setvar('allml_javascript_include_tag', "<%= javascript_include_tag '\r' %>") - call self.setvar('allml_doctype_index', 10) - endif - if exists("g:loaded_ragtag") - call self.setvar('ragtag_stylesheet_link_tag', "<%= stylesheet_link_tag '\r' %>") - call self.setvar('ragtag_javascript_include_tag', "<%= javascript_include_tag '\r' %>") - call self.setvar('ragtag_doctype_index', 10) - endif - elseif ft == 'haml' - if exists("g:loaded_allml") - call self.setvar('allml_stylesheet_link_tag', "= stylesheet_link_tag '\r'") - call self.setvar('allml_javascript_include_tag', "= javascript_include_tag '\r'") - call self.setvar('allml_doctype_index', 10) - endif - if exists("g:loaded_ragtag") - call self.setvar('ragtag_stylesheet_link_tag', "= stylesheet_link_tag '\r'") - call self.setvar('ragtag_javascript_include_tag', "= javascript_include_tag '\r'") - call self.setvar('ragtag_doctype_index', 10) - endif - endif - if ft == 'eruby' || ft == 'yaml' - " surround.vim - if exists("g:loaded_surround") - " The idea behind the || part here is that one can normally define the - " surrounding to omit the hyphen (since standard ERuby does not use it) - " but have it added in Rails ERuby files. Unfortunately, this makes it - " difficult if you really don't want a hyphen in Rails ERuby files. If - " this is your desire, you will need to accomplish it via a rails.vim - " autocommand. - if self.getvar('surround_45') == '' || self.getvar('surround_45') == "<% \r %>" " - - call self.setvar('surround_45', "<% \r -%>") - endif - if self.getvar('surround_61') == '' " = - call self.setvar('surround_61', "<%= \r %>") - endif - if self.getvar("surround_35") == '' " # - call self.setvar('surround_35', "<%# \r %>") - endif - if self.getvar('surround_101') == '' || self.getvar('surround_101')== "<% \r %>\n<% end %>" "e - call self.setvar('surround_5', "<% \r -%>\n<% end -%>") - call self.setvar('surround_69', "<% \1expr: \1 -%>\r<% end -%>") - call self.setvar('surround_101', "<% \r -%>\n<% end -%>") - endif - endif - endif -endfunction - -" }}}1 -" Autocommands {{{1 - -augroup railsPluginAuto - autocmd! - autocmd User BufEnterRails call s:RefreshBuffer() - autocmd User BufEnterRails call s:resetomnicomplete() - autocmd User BufEnterRails call s:BufDatabase(-1) - autocmd User dbextPreConnection call s:BufDatabase(1) - autocmd BufWritePost */config/database.yml call rails#cache_clear("dbext_settings") - autocmd BufWritePost */test/test_helper.rb call rails#cache_clear("user_assertions") - autocmd BufWritePost */config/routes.rb call rails#cache_clear("named_routes") - autocmd BufWritePost */config/environment.rb call rails#cache_clear("default_locale") - autocmd BufWritePost */config/environments/*.rb call rails#cache_clear("environments") - autocmd BufWritePost */tasks/**.rake call rails#cache_clear("rake_tasks") - autocmd BufWritePost */generators/** call rails#cache_clear("generators") - autocmd FileType * if exists("b:rails_root") | call s:BufSettings() | endif - autocmd Syntax ruby,eruby,yaml,haml,javascript,railslog if exists("b:rails_root") | call s:BufSyntax() | endif - autocmd QuickFixCmdPre make* call s:push_chdir() - autocmd QuickFixCmdPost make* call s:pop_command() -augroup END - -" }}}1 -" Initialization {{{1 - -map xx xx -let s:sid = s:sub(maparg("xx"),'xx$','') -unmap xx -let s:file = expand(':p') - -if !exists('s:apps') - let s:apps = {} -endif - -" }}}1 - -let &cpo = s:cpo_save - -" vim:set sw=2 sts=2: diff --git a/vim/autoload/snipMate.vim b/vim/autoload/snipMate.vim deleted file mode 100644 index dcd28f66eb..0000000000 --- a/vim/autoload/snipMate.vim +++ /dev/null @@ -1,433 +0,0 @@ -fun! Filename(...) - let filename = expand('%:t:r') - if filename == '' | return a:0 == 2 ? a:2 : '' | endif - return !a:0 || a:1 == '' ? filename : substitute(a:1, '$1', filename, 'g') -endf - -fun s:RemoveSnippet() - unl! g:snipPos s:curPos s:snipLen s:endCol s:endLine s:prevLen - \ s:lastBuf s:oldWord - if exists('s:update') - unl s:startCol s:origWordLen s:update - if exists('s:oldVars') | unl s:oldVars s:oldEndCol | endif - endif - aug! snipMateAutocmds -endf - -fun snipMate#expandSnip(snip, col) - let lnum = line('.') | let col = a:col - - let snippet = s:ProcessSnippet(a:snip) - " Avoid error if eval evaluates to nothing - if snippet == '' | return '' | endif - - " Expand snippet onto current position with the tab stops removed - let snipLines = split(substitute(snippet, '$\d\+\|${\d\+.\{-}}', '', 'g'), "\n", 1) - - let line = getline(lnum) - let afterCursor = strpart(line, col - 1) - " Keep text after the cursor - if afterCursor != "\t" && afterCursor != ' ' - let line = strpart(line, 0, col - 1) - let snipLines[-1] .= afterCursor - else - let afterCursor = '' - " For some reason the cursor needs to move one right after this - if line != '' && col == 1 && &ve != 'all' && &ve != 'onemore' - let col += 1 - endif - endif - - call setline(lnum, line.snipLines[0]) - - " Autoindent snippet according to previous indentation - let indent = matchend(line, '^.\{-}\ze\(\S\|$\)') + 1 - call append(lnum, map(snipLines[1:], "'".strpart(line, 0, indent - 1)."'.v:val")) - - " Open any folds snippet expands into - if &fen | sil! exe lnum.','.(lnum + len(snipLines) - 1).'foldopen' | endif - - let [g:snipPos, s:snipLen] = s:BuildTabStops(snippet, lnum, col - indent, indent) - - if s:snipLen - aug snipMateAutocmds - au CursorMovedI * call s:UpdateChangedSnip(0) - au InsertEnter * call s:UpdateChangedSnip(1) - aug END - let s:lastBuf = bufnr(0) " Only expand snippet while in current buffer - let s:curPos = 0 - let s:endCol = g:snipPos[s:curPos][1] - let s:endLine = g:snipPos[s:curPos][0] - - call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) - let s:prevLen = [line('$'), col('$')] - if g:snipPos[s:curPos][2] != -1 | return s:SelectWord() | endif - else - unl g:snipPos s:snipLen - " Place cursor at end of snippet if no tab stop is given - let newlines = len(snipLines) - 1 - call cursor(lnum + newlines, indent + len(snipLines[-1]) - len(afterCursor) - \ + (newlines ? 0: col - 1)) - endif - return '' -endf - -" Prepare snippet to be processed by s:BuildTabStops -fun s:ProcessSnippet(snip) - let snippet = a:snip - " Evaluate eval (`...`) expressions. - " Using a loop here instead of a regex fixes a bug with nested "\=". - if stridx(snippet, '`') != -1 - while match(snippet, '`.\{-}`') != -1 - let snippet = substitute(snippet, '`.\{-}`', - \ substitute(eval(matchstr(snippet, '`\zs.\{-}\ze`')), - \ "\n\\%$", '', ''), '') - endw - let snippet = substitute(snippet, "\r", "\n", 'g') - endif - - " Place all text after a colon in a tab stop after the tab stop - " (e.g. "${#:foo}" becomes "${:foo}foo"). - " This helps tell the position of the tab stops later. - let snippet = substitute(snippet, '${\d\+:\(.\{-}\)}', '&\1', 'g') - - " Update the a:snip so that all the $# become the text after - " the colon in their associated ${#}. - " (e.g. "${1:foo}" turns all "$1"'s into "foo") - let i = 1 - while stridx(snippet, '${'.i) != -1 - let s = matchstr(snippet, '${'.i.':\zs.\{-}\ze}') - if s != '' - let snippet = substitute(snippet, '$'.i, s.'&', 'g') - endif - let i += 1 - endw - - if &et " Expand tabs to spaces if 'expandtab' is set. - return substitute(snippet, '\t', repeat(' ', &sts ? &sts : &sw), 'g') - endif - return snippet -endf - -" Counts occurences of haystack in needle -fun s:Count(haystack, needle) - let counter = 0 - let index = stridx(a:haystack, a:needle) - while index != -1 - let index = stridx(a:haystack, a:needle, index+1) - let counter += 1 - endw - return counter -endf - -" Builds a list of a list of each tab stop in the snippet containing: -" 1.) The tab stop's line number. -" 2.) The tab stop's column number -" (by getting the length of the string between the last "\n" and the -" tab stop). -" 3.) The length of the text after the colon for the current tab stop -" (e.g. "${1:foo}" would return 3). If there is no text, -1 is returned. -" 4.) If the "${#:}" construct is given, another list containing all -" the matches of "$#", to be replaced with the placeholder. This list is -" composed the same way as the parent; the first item is the line number, -" and the second is the column. -fun s:BuildTabStops(snip, lnum, col, indent) - let snipPos = [] - let i = 1 - let withoutVars = substitute(a:snip, '$\d\+', '', 'g') - while stridx(a:snip, '${'.i) != -1 - let beforeTabStop = matchstr(withoutVars, '^.*\ze${'.i.'\D') - let withoutOthers = substitute(withoutVars, '${\('.i.'\D\)\@!\d\+.\{-}}', '', 'g') - - let j = i - 1 - call add(snipPos, [0, 0, -1]) - let snipPos[j][0] = a:lnum + s:Count(beforeTabStop, "\n") - let snipPos[j][1] = a:indent + len(matchstr(withoutOthers, '.*\(\n\|^\)\zs.*\ze${'.i.'\D')) - if snipPos[j][0] == a:lnum | let snipPos[j][1] += a:col | endif - - " Get all $# matches in another list, if ${#:name} is given - if stridx(withoutVars, '${'.i.':') != -1 - let snipPos[j][2] = len(matchstr(withoutVars, '${'.i.':\zs.\{-}\ze}')) - let dots = repeat('.', snipPos[j][2]) - call add(snipPos[j], []) - let withoutOthers = substitute(a:snip, '${\d\+.\{-}}\|$'.i.'\@!\d\+', '', 'g') - while match(withoutOthers, '$'.i.'\(\D\|$\)') != -1 - let beforeMark = matchstr(withoutOthers, '^.\{-}\ze'.dots.'$'.i.'\(\D\|$\)') - call add(snipPos[j][3], [0, 0]) - let snipPos[j][3][-1][0] = a:lnum + s:Count(beforeMark, "\n") - let snipPos[j][3][-1][1] = a:indent + (snipPos[j][3][-1][0] > a:lnum - \ ? len(matchstr(beforeMark, '.*\n\zs.*')) - \ : a:col + len(beforeMark)) - let withoutOthers = substitute(withoutOthers, '$'.i.'\ze\(\D\|$\)', '', '') - endw - endif - let i += 1 - endw - return [snipPos, i - 1] -endf - -fun snipMate#jumpTabStop(backwards) - let leftPlaceholder = exists('s:origWordLen') - \ && s:origWordLen != g:snipPos[s:curPos][2] - if leftPlaceholder && exists('s:oldEndCol') - let startPlaceholder = s:oldEndCol + 1 - endif - - if exists('s:update') - call s:UpdatePlaceholderTabStops() - else - call s:UpdateTabStops() - endif - - " Don't reselect placeholder if it has been modified - if leftPlaceholder && g:snipPos[s:curPos][2] != -1 - if exists('startPlaceholder') - let g:snipPos[s:curPos][1] = startPlaceholder - else - let g:snipPos[s:curPos][1] = col('.') - let g:snipPos[s:curPos][2] = 0 - endif - endif - - let s:curPos += a:backwards ? -1 : 1 - " Loop over the snippet when going backwards from the beginning - if s:curPos < 0 | let s:curPos = s:snipLen - 1 | endif - - if s:curPos == s:snipLen - let sMode = s:endCol == g:snipPos[s:curPos-1][1]+g:snipPos[s:curPos-1][2] - call s:RemoveSnippet() - return sMode ? "\" : TriggerSnippet() - endif - - call cursor(g:snipPos[s:curPos][0], g:snipPos[s:curPos][1]) - - let s:endLine = g:snipPos[s:curPos][0] - let s:endCol = g:snipPos[s:curPos][1] - let s:prevLen = [line('$'), col('$')] - - return g:snipPos[s:curPos][2] == -1 ? '' : s:SelectWord() -endf - -fun s:UpdatePlaceholderTabStops() - let changeLen = s:origWordLen - g:snipPos[s:curPos][2] - unl s:startCol s:origWordLen s:update - if !exists('s:oldVars') | return | endif - " Update tab stops in snippet if text has been added via "$#" - " (e.g., in "${1:foo}bar$1${2}"). - if changeLen != 0 - let curLine = line('.') - - for pos in g:snipPos - if pos == g:snipPos[s:curPos] | continue | endif - let changed = pos[0] == curLine && pos[1] > s:oldEndCol - let changedVars = 0 - let endPlaceholder = pos[2] - 1 + pos[1] - " Subtract changeLen from each tab stop that was after any of - " the current tab stop's placeholders. - for [lnum, col] in s:oldVars - if lnum > pos[0] | break | endif - if pos[0] == lnum - if pos[1] > col || (pos[2] == -1 && pos[1] == col) - let changed += 1 - elseif col < endPlaceholder - let changedVars += 1 - endif - endif - endfor - let pos[1] -= changeLen * changed - let pos[2] -= changeLen * changedVars " Parse variables within placeholders - " e.g., "${1:foo} ${2:$1bar}" - - if pos[2] == -1 | continue | endif - " Do the same to any placeholders in the other tab stops. - for nPos in pos[3] - let changed = nPos[0] == curLine && nPos[1] > s:oldEndCol - for [lnum, col] in s:oldVars - if lnum > nPos[0] | break | endif - if nPos[0] == lnum && nPos[1] > col - let changed += 1 - endif - endfor - let nPos[1] -= changeLen * changed - endfor - endfor - endif - unl s:endCol s:oldVars s:oldEndCol -endf - -fun s:UpdateTabStops() - let changeLine = s:endLine - g:snipPos[s:curPos][0] - let changeCol = s:endCol - g:snipPos[s:curPos][1] - if exists('s:origWordLen') - let changeCol -= s:origWordLen - unl s:origWordLen - endif - let lnum = g:snipPos[s:curPos][0] - let col = g:snipPos[s:curPos][1] - " Update the line number of all proceeding tab stops if has - " been inserted. - if changeLine != 0 - let changeLine -= 1 - for pos in g:snipPos - if pos[0] >= lnum - if pos[0] == lnum | let pos[1] += changeCol | endif - let pos[0] += changeLine - endif - if pos[2] == -1 | continue | endif - for nPos in pos[3] - if nPos[0] >= lnum - if nPos[0] == lnum | let nPos[1] += changeCol | endif - let nPos[0] += changeLine - endif - endfor - endfor - elseif changeCol != 0 - " Update the column of all proceeding tab stops if text has - " been inserted/deleted in the current line. - for pos in g:snipPos - if pos[1] >= col && pos[0] == lnum - let pos[1] += changeCol - endif - if pos[2] == -1 | continue | endif - for nPos in pos[3] - if nPos[0] > lnum | break | endif - if nPos[0] == lnum && nPos[1] >= col - let nPos[1] += changeCol - endif - endfor - endfor - endif -endf - -fun s:SelectWord() - let s:origWordLen = g:snipPos[s:curPos][2] - let s:oldWord = strpart(getline('.'), g:snipPos[s:curPos][1] - 1, - \ s:origWordLen) - let s:prevLen[1] -= s:origWordLen - if !empty(g:snipPos[s:curPos][3]) - let s:update = 1 - let s:endCol = -1 - let s:startCol = g:snipPos[s:curPos][1] - 1 - endif - if !s:origWordLen | return '' | endif - let l = col('.') != 1 ? 'l' : '' - if &sel == 'exclusive' - return "\".l.'v'.s:origWordLen."l\" - endif - return s:origWordLen == 1 ? "\".l.'gh' - \ : "\".l.'v'.(s:origWordLen - 1)."l\" -endf - -" This updates the snippet as you type when text needs to be inserted -" into multiple places (e.g. in "${1:default text}foo$1bar$1", -" "default text" would be highlighted, and if the user types something, -" UpdateChangedSnip() would be called so that the text after "foo" & "bar" -" are updated accordingly) -" -" It also automatically quits the snippet if the cursor is moved out of it -" while in insert mode. -fun s:UpdateChangedSnip(entering) - if exists('g:snipPos') && bufnr(0) != s:lastBuf - call s:RemoveSnippet() - elseif exists('s:update') " If modifying a placeholder - if !exists('s:oldVars') && s:curPos + 1 < s:snipLen - " Save the old snippet & word length before it's updated - " s:startCol must be saved too, in case text is added - " before the snippet (e.g. in "foo$1${2}bar${1:foo}"). - let s:oldEndCol = s:startCol - let s:oldVars = deepcopy(g:snipPos[s:curPos][3]) - endif - let col = col('.') - 1 - - if s:endCol != -1 - let changeLen = col('$') - s:prevLen[1] - let s:endCol += changeLen - else " When being updated the first time, after leaving select mode - if a:entering | return | endif - let s:endCol = col - 1 - endif - - " If the cursor moves outside the snippet, quit it - if line('.') != g:snipPos[s:curPos][0] || col < s:startCol || - \ col - 1 > s:endCol - unl! s:startCol s:origWordLen s:oldVars s:update - return s:RemoveSnippet() - endif - - call s:UpdateVars() - let s:prevLen[1] = col('$') - elseif exists('g:snipPos') - if !a:entering && g:snipPos[s:curPos][2] != -1 - let g:snipPos[s:curPos][2] = -2 - endif - - let col = col('.') - let lnum = line('.') - let changeLine = line('$') - s:prevLen[0] - - if lnum == s:endLine - let s:endCol += col('$') - s:prevLen[1] - let s:prevLen = [line('$'), col('$')] - endif - if changeLine != 0 - let s:endLine += changeLine - let s:endCol = col - endif - - " Delete snippet if cursor moves out of it in insert mode - if (lnum == s:endLine && (col > s:endCol || col < g:snipPos[s:curPos][1])) - \ || lnum > s:endLine || lnum < g:snipPos[s:curPos][0] - call s:RemoveSnippet() - endif - endif -endf - -" This updates the variables in a snippet when a placeholder has been edited. -" (e.g., each "$1" in "${1:foo} $1bar $1bar") -fun s:UpdateVars() - let newWordLen = s:endCol - s:startCol + 1 - let newWord = strpart(getline('.'), s:startCol, newWordLen) - if newWord == s:oldWord || empty(g:snipPos[s:curPos][3]) - return - endif - - let changeLen = g:snipPos[s:curPos][2] - newWordLen - let curLine = line('.') - let startCol = col('.') - let oldStartSnip = s:startCol - let updateTabStops = changeLen != 0 - let i = 0 - - for [lnum, col] in g:snipPos[s:curPos][3] - if updateTabStops - let start = s:startCol - if lnum == curLine && col <= start - let s:startCol -= changeLen - let s:endCol -= changeLen - endif - for nPos in g:snipPos[s:curPos][3][(i):] - " This list is in ascending order, so quit if we've gone too far. - if nPos[0] > lnum | break | endif - if nPos[0] == lnum && nPos[1] > col - let nPos[1] -= changeLen - endif - endfor - if lnum == curLine && col > start - let col -= changeLen - let g:snipPos[s:curPos][3][i][1] = col - endif - let i += 1 - endif - - " "Very nomagic" is used here to allow special characters. - call setline(lnum, substitute(getline(lnum), '\%'.col.'c\V'. - \ escape(s:oldWord, '\'), escape(newWord, '\&'), '')) - endfor - if oldStartSnip != s:startCol - call cursor(0, startCol + s:startCol - oldStartSnip) - endif - - let s:oldWord = newWord - let g:snipPos[s:curPos][2] = newWordLen -endf -" vim:noet:sw=4:ts=4:ft=vim diff --git a/vim/autoload/tabular.vim b/vim/autoload/tabular.vim deleted file mode 100755 index 9ed60337d7..0000000000 --- a/vim/autoload/tabular.vim +++ /dev/null @@ -1,283 +0,0 @@ -" Tabular: Align columnar data using regex-designated column boundaries -" Maintainer: Matthew Wozniski (mjw@drexel.edu) -" Date: Thu, 11 Oct 2007 00:35:34 -0400 -" Version: 0.1 - -" Stupid vimscript crap {{{1 -let s:savecpo = &cpo -set cpo&vim - -" Private Functions {{{1 - -" Return the number of bytes in a string after expanding tabs to spaces. {{{2 -" This expansion is done based on the current value of 'tabstop' -function! s:Strlen(string) - let rv = 0 - let i = 0 - - for char in split(a:string, '\zs') - if char == "\t" - let rv += &ts - i - let i = 0 - else - let rv += 1 - let i = (i + 1) % &ts - endif - endfor - - return rv -endfunction - -" Align a string within a field {{{2 -" These functions do not trim leading and trailing spaces. - -" Right align 'string' in a field of size 'fieldwidth' -function! s:Right(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - return matchstr(a:string, '^\s*') . repeat(" ", spaces) . substitute(a:string, '^\s*', '', '') -endfunction - -" Left align 'string' in a field of size 'fieldwidth' -function! s:Left(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - return a:string . repeat(" ", spaces) -endfunction - -" Center align 'string' in a field of size 'fieldwidth' -function! s:Center(string, fieldwidth) - let spaces = a:fieldwidth - s:Strlen(a:string) - let right = spaces / 2 - let left = right + (right * 2 != spaces) - return repeat(" ", left) . a:string . repeat(" ", right) -endfunction - -" Remove spaces around a string {{{2 - -" Remove all trailing spaces from a string. -function! s:StripTrailingSpaces(string) - return matchstr(a:string, '^.\{-}\ze\s*$') -endfunction - -" Remove all leading spaces from a string. -function! s:StripLeadingSpaces(string) - return matchstr(a:string, '^\s*\zs.*$') -endfunction - -" Split a string into fields and delimiters {{{2 -" Like split(), but include the delimiters as elements -" All odd numbered elements are delimiters -" All even numbered elements are non-delimiters (including zero) -function! s:SplitDelim(string, delim) - let rv = [] - let beg = 0 - let idx = 0 - - let len = len(a:string) - - while 1 - let mid = match(a:string, a:delim, beg, 1) - if mid == -1 || mid == len - break - endif - - let matchstr = matchstr(a:string, a:delim, beg, 1) - let length = strlen(matchstr) - - if beg < mid - let rv += [ a:string[beg : mid-1] ] - else - let rv += [ "" ] - endif - - let beg = mid + length - let idx = beg - - if beg == mid - " Empty match, advance "beg" by one to avoid infinite loop - let rv += [ "" ] - let beg += 1 - else " beg > mid - let rv += [ a:string[mid : beg-1] ] - endif - endwhile - - let rv += [ strpart(a:string, idx) ] - - return rv -endfunction - -" Replace lines from `start' to `start + len - 1' with the given strings. {{{2 -" If more lines are needed to show all strings, they will be added. -" If there are too few strings to fill all lines, lines will be removed. -function! s:SetLines(start, len, strings) - if a:start > line('$') + 1 || a:start < 1 - throw "Invalid start line!" - endif - - if len(a:strings) > a:len - let fensave = &fen - let view = winsaveview() - call append(a:start + a:len - 1, repeat([''], len(a:strings) - a:len)) - call winrestview(view) - let &fen = fensave - elseif len(a:strings) < a:len - let fensave = &fen - let view = winsaveview() - sil exe (a:start + len(a:strings)) . ',' . (a:start + a:len - 1) . 'd_' - call winrestview(view) - let &fen = fensave - endif - - call setline(a:start, a:strings) -endfunction - -" Runs the given commandstring argument as an expression. {{{2 -" The commandstring expression is expected to reference the a:lines argument. -" If the commandstring expression returns a list the items of that list will -" replace the items in a:lines, otherwise the expression is assumed to have -" modified a:lines itself. -function! s:FilterString(lines, commandstring) - exe 'let rv = ' . a:commandstring - - if type(rv) == type(a:lines) && rv isnot a:lines - call filter(a:lines, 0) - call extend(a:lines, rv) - endif -endfunction - -" Public API {{{1 - -if !exists("g:tabular_default_format") - let g:tabular_default_format = "l1" -endif - -let s:formatelempat = '\%([lrc]\d\+\)' - -function! tabular#ElementFormatPattern() - return s:formatelempat -endfunction - -" Given a list of strings and a delimiter, split each string on every -" occurrence of the delimiter pattern, format each element according to either -" the provided format (optional) or the default format, and join them back -" together with enough space padding to guarantee that the nth delimiter of -" each string is aligned. -function! tabular#TabularizeStrings(strings, delim, ...) - if a:0 > 1 - echoerr "TabularizeStrings accepts only 2 or 3 arguments (got ".(a:0+2).")" - return 1 - endif - - let formatstr = (a:0 ? a:1 : g:tabular_default_format) - - if formatstr !~? s:formatelempat . '\+' - echoerr "Tabular: Invalid format \"" . formatstr . "\" specified!" - return 1 - endif - - let format = split(formatstr, s:formatelempat . '\zs') - - let lines = map(a:strings, 's:SplitDelim(v:val, a:delim)') - - " Strip spaces - " - Only from non-delimiters; spaces in delimiters must have been matched - " intentionally - " - Don't strip leading spaces from the first element; we like indenting. - for line in lines - if line[0] !~ '^\s*$' - let line[0] = s:StripTrailingSpaces(line[0]) - endif - if len(line) >= 3 - for i in range(2, len(line)-1, 2) - let line[i] = s:StripLeadingSpaces(s:StripTrailingSpaces(line[i])) - endfor - endif - endfor - - " Find the max length of each field - let maxes = [] - for line in lines - for i in range(len(line)) - if i == len(maxes) - let maxes += [ s:Strlen(line[i]) ] - else - let maxes[i] = max( [ maxes[i], s:Strlen(line[i]) ] ) - endif - endfor - endfor - - let lead_blank = empty(filter(copy(lines), 'v:val[0] =~ "\\S"')) - - " Concatenate the fields, according to the format pattern. - for idx in range(len(lines)) - let line = lines[idx] - for i in range(len(line)) - let how = format[i % len(format)][0] - let pad = format[i % len(format)][1:-1] - - if how =~? 'l' - let field = s:Left(line[i], maxes[i]) - elseif how =~? 'r' - let field = s:Right(line[i], maxes[i]) - elseif how =~? 'c' - let field = s:Center(line[i], maxes[i]) - endif - - let line[i] = field . (lead_blank && i == 0 ? '' : repeat(" ", pad)) - endfor - - let lines[idx] = s:StripTrailingSpaces(join(line, '')) - endfor -endfunction - -" Apply 0 or more filters, in sequence, to selected text in the buffer {{{2 -" The lines to be filtered are determined as follows: -" If the function is called with a range containing multiple lines, then -" those lines will be used as the range. -" If the function is called with no range or with a range of 1 line, then -" if "includepat" is not specified, -" that 1 line will be filtered, -" if "includepat" is specified and that line does not match it, -" no lines will be filtered -" if "includepat" is specified and that line does match it, -" all contiguous lines above and below the specified line matching the -" pattern will be filtered. -" -" The remaining arguments must each be a filter to apply to the text. -" Each filter must either be a String evaluating to a function to be called. -function! tabular#PipeRange(includepat, ...) range - let top = a:firstline - let bot = a:lastline - - if a:includepat != '' && top == bot - if top < 0 || top > line('$') || getline(top) !~ a:includepat - return - endif - while top > 1 && getline(top-1) =~ a:includepat - let top -= 1 - endwhile - while bot < line('$') && getline(bot+1) =~ a:includepat - let bot += 1 - endwhile - endif - - let lines = map(range(top, bot), 'getline(v:val)') - - for filter in a:000 - if type(filter) != type("") - echoerr "PipeRange: Bad filter: " . string(filter) - endif - - call s:FilterString(lines, filter) - - unlet filter - endfor - - call s:SetLines(top, bot - top + 1, lines) -endfunction - -" Stupid vimscript crap, part 2 {{{1 -let &cpo = s:savecpo -unlet s:savecpo - -" vim:set sw=2 sts=2 fdm=marker: diff --git a/vim/autoload/tcomment.vim b/vim/autoload/tcomment.vim deleted file mode 100644 index 75ac26896c..0000000000 --- a/vim/autoload/tcomment.vim +++ /dev/null @@ -1,576 +0,0 @@ -" tcomment.vim -" @Author: Tom Link (mailto:micathom AT gmail com?subject=[vim]) -" @Website: http://www.vim.org/account/profile.php?user_id=4037 -" @License: GPL (see http://www.gnu.org/licenses/gpl.txt) -" @Created: 2007-09-17. -" @Last Change: 2009-02-15. -" @Revision: 0.0.66 - -if &cp || exists("loaded_tcomment_autoload") - finish -endif -let loaded_tcomment_autoload = 1 - - -function! s:DefaultValue(option) - exec 'let '. a:option .' = &'. a:option - exec 'set '. a:option .'&' - exec 'let default = &'. a:option - exec 'let &'. a:option .' = '. a:option - return default -endf - -let s:defaultComments = s:DefaultValue('comments') -let s:defaultCommentString = s:DefaultValue('commentstring') -let s:nullCommentString = '%s' - -" tcomment#Comment(line1, line2, ?commentMode, ?commentAnyway, ?commentBegin, ?commentEnd) -" commentMode: -" G ... guess -" B ... block -" i ... maybe inline, guess -" I ... inline -" R ... right -" v ... visual -" o ... operator -function! tcomment#Comment(beg, end, ...) - " save the cursor position - let co = col('.') - let li = line('.') - let s:pos_end = getpos("'>") - let commentMode = a:0 >= 1 ? a:1 : 'G' - let commentAnyway = a:0 >= 2 ? (a:2 == '!') : 0 - " TLogVAR a:beg, a:end, a:1, commentMode, commentAnyway - if commentMode =~# 'i' - let commentMode = substitute(commentMode, '\Ci', line("'<") == line("'>") ? 'I' : 'G', 'g') - endif - if commentMode =~# 'R' || commentMode =~# 'I' - let cstart = col("'<") - if cstart == 0 - let cstart = col('.') - endif - if commentMode =~# 'R' - let commentMode = substitute(commentMode, '\CR', 'G', 'g') - let cend = 0 - else - let cend = col("'>") - if commentMode =~# 'o' - let cend += 1 - endif - endif - else - let cstart = 0 - let cend = 0 - endif - " TLogVAR commentMode, cstart, cend - " get the correct commentstring - if a:0 >= 3 && a:3 != '' - let cms = s:EncodeCommentPart(a:3) .'%s' - if a:0 >= 4 && a:4 != '' - let cms = cms . s:EncodeCommentPart(a:4) - endif - else - let [cms, commentMode] = s:GetCommentString(a:beg, a:end, commentMode) - endif - let cms0 = s:BlockGetCommentString(cms) - let cms0 = escape(cms0, '\') - " make whitespace optional; this conflicts with comments that require some - " whitespace - let cmtCheck = substitute(cms0, '\([ ]\)', '\1\\?', 'g') - " turn commentstring into a search pattern - let cmtCheck = s:SPrintF(cmtCheck, '\(\_.\{-}\)') - " set commentMode and indentStr - let [indentStr, uncomment] = s:CommentDef(a:beg, a:end, cmtCheck, commentMode, cstart, cend) - " TLogVAR indentStr, uncomment - if commentAnyway - let uncomment = 0 - endif - " go - if commentMode =~# 'B' - " We want a comment block - call s:CommentBlock(a:beg, a:end, uncomment, cmtCheck, cms, indentStr) - else - " call s:CommentLines(a:beg, a:end, cstart, cend, uncomment, cmtCheck, cms0, indentStr) - " We want commented lines - " final search pattern for uncommenting - let cmtCheck = escape('\V\^\(\s\{-}\)'. cmtCheck .'\$', '"/\') - " final pattern for commenting - let cmtReplace = escape(cms0, '"/') - silent exec a:beg .','. a:end .'s/\V'. - \ s:StartRx(cstart) . indentStr .'\zs\(\.\{-}\)'. s:EndRx(cend) .'/'. - \ '\=s:ProcessedLine('. uncomment .', submatch(0), "'. cmtCheck .'", "'. cmtReplace .'")/ge' - endif - " reposition cursor - " TLogVAR commentMode - if commentMode =~ '>' - call setpos('.', s:pos_end) - else - " TLogVAR li, co - call cursor(li, co) - endif -endf - -function! tcomment#Operator(type, ...) "{{{3 - let commentMode = a:0 >= 1 ? a:1 : '' - let bang = a:0 >= 2 ? a:2 : '' - if !exists('w:tcommentPos') - let w:tcommentPos = getpos(".") - endif - let sel_save = &selection - let &selection = "inclusive" - let reg_save = @@ - " let pos = getpos('.') - " TLogVAR a:type - try - if a:type == 'line' - silent exe "normal! '[V']" - let commentMode1 = 'G' - elseif a:type == 'block' - silent exe "normal! `[\`]" - let commentMode1 = 'I' - else - silent exe "normal! `[v`]" - let commentMode1 = 'i' - endif - if empty(commentMode) - let commentMode = commentMode1 - endif - let beg = line("'[") - let end = line("']") - norm!  - let commentMode .= g:tcommentOpModeExtra - call tcomment#Comment(beg, end, commentMode.'o', bang) - finally - let &selection = sel_save - let @@ = reg_save - if g:tcommentOpModeExtra !~ '>' - " TLogVAR pos - " call setpos('.', pos) - call setpos('.', w:tcommentPos) - unlet! w:tcommentPos - endif - endtry -endf - - -function! tcomment#OperatorLine(type) "{{{3 - call tcomment#Operator(a:type, 'G') -endf - - -function! tcomment#OperatorAnyway(type) "{{{3 - call tcomment#Operator(a:type, '', '!') -endf - - -function! tcomment#OperatorLineAnyway(type) "{{{3 - call tcomment#Operator(a:type, 'G', '!') -endf - - -" comment text as if it were of a specific filetype -function! tcomment#CommentAs(beg, end, commentAnyway, filetype, ...) - let ccount = a:0 >= 1 ? a:1 : 1 - " TLogVAR ccount - if a:filetype =~ '_block$' - let commentMode = 'B' - let ft = substitute(a:filetype, '_block$', '', '') - elseif a:filetype =~ '_inline$' - let commentMode = 'I' - let ft = substitute(a:filetype, '_inline$', '', '') - else - let commentMode = 'G' - let ft = a:filetype - endif - let [cms, commentMode] = s:GetCommentString(a:beg, a:end, commentMode, ft) - let pre = substitute(cms, '%s.*$', '', '') - let pre = substitute(pre, '%%', '%', 'g') - let post = substitute(cms, '^.\{-}%s', '', '') - let post = substitute(post, '%%', '%', 'g') - if ccount > 1 - let pre_l = matchlist(pre, '^\(\S\+\)\(.*\)$') - " TLogVAR pre_l - if !empty(get(pre_l, 1)) - let pre = repeat(pre_l[1], ccount) . pre_l[2] - endif - let post_l = matchlist(post, '^\(\s*\)\(.\+\)$') - " TLogVAR post_l - if !empty(get(post_l, 2)) - let post = post_l[1] . repeat(post_l[2], ccount) - endif - endif - keepjumps call tcomment#Comment(a:beg, a:end, commentMode, a:commentAnyway, pre, post) -endf - - -" ---------------------------------------------------------------- -" collect all variables matching ^tcomment_ -function! tcomment#CollectFileTypes() - if g:tcommentFileTypesDirty - redir => vars - silent let - redir END - let g:tcommentFileTypes = split(vars, '\n') - call filter(g:tcommentFileTypes, 'v:val =~ "tcomment_"') - call map(g:tcommentFileTypes, 'matchstr(v:val, ''tcomment_\zs\S\+'')') - call sort(g:tcommentFileTypes) - let g:tcommentFileTypesRx = '\V\^\('. join(g:tcommentFileTypes, '\|') .'\)\(\u\.\*\)\?\$' - let g:tcommentFileTypesDirty = 0 - endif -endf - -call tcomment#CollectFileTypes() - -" return a list of filetypes for which a tcomment_{&ft} is defined -function! tcomment#FileTypes(ArgLead, CmdLine, CursorPos) - " TLogVAR a:ArgLead, a:CmdLine, a:CursorPos - call tcomment#CollectFileTypes() - let types = copy(g:tcommentFileTypes) - if index(g:tcommentFileTypes, &filetype) != -1 - " TLogVAR &filetype - call insert(types, &filetype) - endif - if empty(a:ArgLead) - return types - else - return filter(types, 'v:val =~ ''\V''.a:ArgLead') - endif -endf - -function! s:EncodeCommentPart(string) - return substitute(a:string, '%', '%%', 'g') -endf - -" s:GetCommentString(beg, end, commentMode, ?filetype="") -function! s:GetCommentString(beg, end, commentMode, ...) - let ft = a:0 >= 1 ? a:1 : '' - if ft != '' - let [cms, commentMode] = s:GetCustomCommentString(ft, a:commentMode) - else - let cms = '' - let commentMode = a:commentMode - endif - if empty(cms) - if exists('b:commentstring') - let cms = b:commentstring - return s:GetCustomCommentString(&filetype, a:commentMode, cms) - elseif exists('b:commentStart') && b:commentStart != '' - let cms = s:EncodeCommentPart(b:commentStart) .' %s' - if exists('b:commentEnd') && b:commentEnd != '' - let cms = cms .' '. s:EncodeCommentPart(b:commentEnd) - endif - return s:GetCustomCommentString(&filetype, a:commentMode, cms) - elseif g:tcommentGuessFileType || (exists('g:tcommentGuessFileType_'. &filetype) - \ && g:tcommentGuessFileType_{&filetype} =~ '[^0]') - if g:tcommentGuessFileType_{&filetype} == 1 - let altFiletype = '' - else - let altFiletype = g:tcommentGuessFileType_{&filetype} - endif - return s:GuessFileType(a:beg, a:end, a:commentMode, &filetype, altFiletype) - else - return s:GetCustomCommentString(&filetype, a:commentMode, s:GuessCurrentCommentString(a:commentMode)) - endif - endif - return [cms, commentMode] -endf - -" s:SPrintF(formatstring, ?values ...) -" => string -function! s:SPrintF(string, ...) - let n = 1 - let r = '' - let s = a:string - while 1 - let i = match(s, '%\(.\)') - if i >= 0 - let x = s[i + 1] - let r = r . strpart(s, 0, i) - let s = strpart(s, i + 2) - if x == '%' - let r = r.'%' - else - if a:0 >= n - let v = a:{n} - let n = n + 1 - else - echoerr 'Malformed format string (too many arguments required): '. a:string - endif - if x ==# 's' - let r = r.v - elseif x ==# 'S' - let r = r.'"'.v.'"' - else - echoerr 'Malformed format string: '. a:string - endif - endif - else - return r.s - endif - endwh -endf - -function! s:StartRx(pos) - if a:pos == 0 - return '\^' - else - return '\%'. a:pos .'c' - endif -endf - -function! s:EndRx(pos) - if a:pos == 0 - return '\$' - else - return '\%'. a:pos .'c' - endif -endf - -function! s:GetIndentString(line, start) - let start = a:start > 0 ? a:start - 1 : 0 - return substitute(strpart(getline(a:line), start), '\V\^\s\*\zs\.\*\$', '', '') -endf - -function! s:CommentDef(beg, end, checkRx, commentMode, cstart, cend) - let mdrx = '\V'. s:StartRx(a:cstart) .'\s\*'. a:checkRx .'\s\*'. s:EndRx(0) - let line = getline(a:beg) - if a:cstart != 0 && a:cend != 0 - let line = strpart(line, 0, a:cend - 1) - endif - let uncomment = (line =~ mdrx) - let it = s:GetIndentString(a:beg, a:cstart) - let il = indent(a:beg) - let n = a:beg + 1 - while n <= a:end - if getline(n) =~ '\S' - let jl = indent(n) - if jl < il - let it = s:GetIndentString(n, a:cstart) - let il = jl - endif - if a:commentMode =~# 'G' - if !(getline(n) =~ mdrx) - let uncomment = 0 - endif - endif - endif - let n = n + 1 - endwh - if a:commentMode =~# 'B' - let t = @t - try - silent exec 'norm! '. a:beg.'G1|v'.a:end.'G$"ty' - let uncomment = (@t =~ mdrx) - finally - let @t = t - endtry - endif - return [it, uncomment] -endf - -function! s:ProcessedLine(uncomment, match, checkRx, replace) - if !(a:match =~ '\S' || g:tcommentBlankLines) - return a:match - endif - let ml = len(a:match) - if a:uncomment - let rv = substitute(a:match, a:checkRx, '\1\2', '') - else - let rv = s:SPrintF(a:replace, a:match) - endif - " let md = len(rv) - ml - let s:pos_end = getpos('.') - let s:pos_end[2] += len(rv) - " TLogVAR pe, md, a:match - let rv = escape(rv, '\ ') - let rv = substitute(rv, '\n', '\\\n', 'g') - return rv -endf - -function! s:CommentLines(beg, end, cstart, cend, uncomment, cmtCheck, cms0, indentStr) "{{{3 - " We want commented lines - " final search pattern for uncommenting - let cmtCheck = escape('\V\^\(\s\{-}\)'. a:cmtCheck .'\$', '"/\') - " final pattern for commenting - let cmtReplace = escape(a:cms0, '"/') - silent exec a:beg .','. a:end .'s/\V'. - \ s:StartRx(a:cstart) . a:indentStr .'\zs\(\.\{-}\)'. s:EndRx(a:cend) .'/'. - \ '\=s:ProcessedLine('. a:uncomment .', submatch(0), "'. a:cmtCheck .'", "'. cmtReplace .'")/ge' -endf - -function! s:CommentBlock(beg, end, uncomment, checkRx, replace, indentStr) - let t = @t - try - silent exec 'norm! '. a:beg.'G1|v'.a:end.'G$"td' - let ms = s:BlockGetMiddleString(a:replace) - let mx = escape(ms, '\') - if a:uncomment - let @t = substitute(@t, '\V\^\s\*'. a:checkRx .'\$', '\1', '') - if ms != '' - let @t = substitute(@t, '\V\n'. a:indentStr . mx, '\n'. a:indentStr, 'g') - endif - let @t = substitute(@t, '^\n', '', '') - let @t = substitute(@t, '\n\s*$', '', '') - else - let cs = s:BlockGetCommentString(a:replace) - let cs = a:indentStr . substitute(cs, '%s', '%s'. a:indentStr, '') - if ms != '' - let ms = a:indentStr . ms - let mx = a:indentStr . mx - let @t = substitute(@t, '^'. a:indentStr, '', 'g') - let @t = ms . substitute(@t, '\n'. a:indentStr, '\n'. mx, 'g') - endif - let @t = s:SPrintF(cs, "\n". @t ."\n") - endif - silent norm! "tP - finally - let @t = t - endtry -endf - -" inspired by Meikel Brandmeyer's EnhancedCommentify.vim -" this requires that a syntax names are prefixed by the filetype name -" s:GuessFileType(beg, end, commentMode, filetype, ?fallbackFiletype) -function! s:GuessFileType(beg, end, commentMode, filetype, ...) - if a:0 >= 1 && a:1 != '' - let [cms, commentMode] = s:GetCustomCommentString(a:1, a:commentMode) - if cms == '' - let cms = s:GuessCurrentCommentString(a:commentMode) - endif - else - let commentMode = s:CommentMode(a:commentMode, 'G') - let cms = s:GuessCurrentCommentString(0) - endif - let n = a:beg - " TLogVAR n, a:beg, a:end - while n <= a:end - let m = indent(n) + 1 - let le = len(getline(n)) - " TLogVAR m, le - while m < le - let syntaxName = synIDattr(synID(n, m, 1), 'name') - " TLogVAR syntaxName, n, m - let ftypeMap = get(g:tcommentSyntaxMap, syntaxName) - if !empty(ftypeMap) - " TLogVAR ftypeMap - return s:GetCustomCommentString(ftypeMap, a:commentMode, cms) - elseif syntaxName =~ g:tcommentFileTypesRx - let ft = substitute(syntaxName, g:tcommentFileTypesRx, '\1', '') - " TLogVAR ft - if exists('g:tcommentIgnoreTypes_'. a:filetype) && g:tcommentIgnoreTypes_{a:filetype} =~ '\<'.ft.'\>' - let m += 1 - else - return s:GetCustomCommentString(ft, a:commentMode, cms) - endif - elseif syntaxName == '' || syntaxName == 'None' || syntaxName =~ '^\u\+$' || syntaxName =~ '^\u\U*$' - let m += 1 - else - break - endif - endwh - let n += 1 - endwh - return [cms, commentMode] -endf - -function! s:CommentMode(commentMode, newmode) "{{{3 - return substitute(a:commentMode, '\w\+', a:newmode, 'g') -endf - -function! s:GuessCurrentCommentString(commentMode) - let valid_cms = (stridx(&commentstring, '%s') != -1) - if &commentstring != s:defaultCommentString && valid_cms - " The &commentstring appears to have been set and to be valid - return &commentstring - endif - if &comments != s:defaultComments - " the commentstring is the default one, so we assume that it wasn't - " explicitly set; we then try to reconstruct &cms from &comments - let cms = s:ConstructFromComments(a:commentMode) - if cms != s:nullCommentString - return cms - endif - endif - if valid_cms - " Before &commentstring appeared not to be set. As we don't know - " better we return it anyway if it is valid - return &commentstring - else - " &commentstring is invalid. So we return the identity string. - return s:nullCommentString - endif -endf - -function! s:ConstructFromComments(commentMode) - exec s:ExtractCommentsPart('') - if a:commentMode =~# 'G' && line != '' - return line .' %s' - endif - exec s:ExtractCommentsPart('s') - if s != '' - exec s:ExtractCommentsPart('e') - " if a:commentMode - " exec s:ExtractCommentsPart("m") - " if m != "" - " let m = "\n". m - " endif - " return s.'%s'.e.m - " else - return s.' %s '.e - " endif - endif - if line != '' - return line .' %s' - else - return s:nullCommentString - endif -endf - -function! s:ExtractCommentsPart(key) - " let key = a:key != "" ? a:key .'[^:]*' : "" - let key = a:key . '[bnflrxO0-9-]*' - let val = substitute(&comments, '^\(.\{-},\)\{-}'. key .':\([^,]\+\).*$', '\2', '') - if val == &comments - let val = '' - else - let val = substitute(val, '%', '%%', 'g') - endif - let var = a:key == '' ? 'line' : a:key - return 'let '. var .'="'. escape(val, '"') .'"' -endf - -" s:GetCustomCommentString(ft, commentMode, ?default="") -function! s:GetCustomCommentString(ft, commentMode, ...) - let commentMode = a:commentMode - let customComment = exists('g:tcomment_'. a:ft) - if commentMode =~# 'B' && exists('g:tcomment_'. a:ft .'_block') - let cms = g:tcomment_{a:ft}_block - elseif commentMode =~? 'I' && exists('g:tcomment_'. a:ft .'_inline') - let cms = g:tcomment_{a:ft}_inline - elseif customComment - let cms = g:tcomment_{a:ft} - let commentMode = s:CommentMode(commentMode, 'G') - elseif a:0 >= 1 - let cms = a:1 - let commentMode = s:CommentMode(commentMode, 'G') - else - let cms = '' - let commentMode = s:CommentMode(commentMode, 'G') - endif - return [cms, commentMode] -endf - -function! s:BlockGetCommentString(cms) - " return substitute(a:cms, '\n.*$', '', '') - return matchstr(a:cms, '^.\{-}\ze\(\n\|$\)') -endf - -function! s:BlockGetMiddleString(cms) - " let rv = substitute(a:cms, '^.\{-}\n\([^\n]*\)', '\1', '') - let rv = matchstr(a:cms, '\n\zs.*') - return rv == a:cms ? '' : rv -endf - - -redraw - diff --git a/vim/colors/railscasts.vim b/vim/colors/railscasts.vim deleted file mode 100644 index ff696928ef..0000000000 --- a/vim/colors/railscasts.vim +++ /dev/null @@ -1,97 +0,0 @@ -" Vim color scheme based on http://github.com/jpo/vim-railscasts-theme -" -" Name: railscasts.vim -" Maintainer: Ryan Bates -" License: MIT - -set background=dark -hi clear -if exists("syntax_on") - syntax reset -endif -let g:colors_name = "railscasts" - -" Colors -" Brown #BC9357 -" Dark Blue #6D9CBD -" Dark Green #509E50 -" Dark Orange #CC7733 -" Light Blue #CFCFFF -" Light Green #A5C160 -" Tan #FFC66D -" Red #DA4938 - -hi Normal guifg=#E6E1DC guibg=#232323 -hi Cursor guibg=#FFFFFF -hi CursorLine guibg=#333435 -hi LineNr guifg=#666666 -hi Visual guibg=#5A647E -hi Search guifg=NONE guibg=#131313 gui=NONE -hi Folded guifg=#F6F3E8 guibg=#444444 gui=NONE -hi Directory guifg=#A5C160 gui=NONE -hi Error guifg=#FFFFFF guibg=#990000 -hi MatchParen guifg=NONE guibg=#131313 -hi Title guifg=#E6E1DC - -hi Comment guifg=#BC9357 guibg=NONE gui=italic -hi! link Todo Comment - -hi String guifg=#A5C160 -hi! link Number String -hi! link rubyStringDelimiter String - -" nil, self, symbols -hi Constant guifg=#6D9CBD - -" def, end, include, load, require, alias, super, yield, lambda, proc -hi Define guifg=#CC7733 gui=NONE -hi! link Include Define -hi! link Keyword Define -hi! link Macro Define - -" #{foo}, <%= bar %> -hi Delimiter guifg=#509E50 -" hi erubyDelimiter guifg=NONE - -" function name (after def) -hi Function guifg=#FFC66D gui=NONE - -"@var, @@var, $var -hi Identifier guifg=#CFCFFF gui=NONE - -" #if, #else, #endif - -" case, begin, do, for, if, unless, while, until, else -hi Statement guifg=#CC7733 gui=NONE -hi! link PreProc Statement -hi! link PreCondit Statement - -" SomeClassName -hi Type guifg=NONE gui=NONE - -" has_many, respond_to, params -hi railsMethod guifg=#DA4938 gui=NONE - -hi DiffAdd guifg=#E6E1DC guibg=#144212 -hi DiffDelete guifg=#E6E1DC guibg=#660000 - -hi xmlTag guifg=#E8BF6A -hi! link xmlTagName xmlTag -hi! link xmlEndTag xmlTag -hi! link xmlArg xmlTag -hi! link htmlTag xmlTag -hi! link htmlTagName xmlTagName -hi! link htmlEndTag xmlEndTag -hi! link htmlArg xmlArg - -" Popup Menu -" ---------- -" normal item in popup -hi Pmenu guifg=#F6F3E8 guibg=#444444 gui=NONE -" selected item in popup -hi PmenuSel guifg=#000000 guibg=#A5C160 gui=NONE -" scrollbar in popup -hi PMenuSbar guibg=#5A647E gui=NONE -" thumb of the scrollbar in the popup -hi PMenuThumb guibg=#AAAAAA gui=NONE - diff --git a/vim/doc/NERD_tree.txt b/vim/doc/NERD_tree.txt deleted file mode 100644 index 2e2278c4d9..0000000000 --- a/vim/doc/NERD_tree.txt +++ /dev/null @@ -1,1222 +0,0 @@ -*NERD_tree.txt* A tree explorer plugin that owns your momma! - - - - omg its ... ~ - - ________ ________ _ ____________ ____ __________ ____________~ - /_ __/ / / / ____/ / | / / ____/ __ \/ __ \ /_ __/ __ \/ ____/ ____/~ - / / / /_/ / __/ / |/ / __/ / /_/ / / / / / / / /_/ / __/ / __/ ~ - / / / __ / /___ / /| / /___/ _, _/ /_/ / / / / _, _/ /___/ /___ ~ - /_/ /_/ /_/_____/ /_/ |_/_____/_/ |_/_____/ /_/ /_/ |_/_____/_____/ ~ - - - Reference Manual~ - - - - -============================================================================== -CONTENTS *NERDTree-contents* - - 1.Intro...................................|NERDTree| - 2.Functionality provided..................|NERDTreeFunctionality| - 2.1.Global commands...................|NERDTreeGlobalCommands| - 2.2.Bookmarks.........................|NERDTreeBookmarks| - 2.2.1.The bookmark table..........|NERDTreeBookmarkTable| - 2.2.2.Bookmark commands...........|NERDTreeBookmarkCommands| - 2.2.3.Invalid bookmarks...........|NERDTreeInvalidBookmarks| - 2.3.NERD tree mappings................|NERDTreeMappings| - 2.4.The NERD tree menu................|NERDTreeMenu| - 3.Options.................................|NERDTreeOptions| - 3.1.Option summary....................|NERDTreeOptionSummary| - 3.2.Option details....................|NERDTreeOptionDetails| - 4.The NERD tree API.......................|NERDTreeAPI| - 4.1.Key map API.......................|NERDTreeKeymapAPI| - 4.2.Menu API..........................|NERDTreeMenuAPI| - 5.About...................................|NERDTreeAbout| - 6.Changelog...............................|NERDTreeChangelog| - 7.Credits.................................|NERDTreeCredits| - 8.License.................................|NERDTreeLicense| - -============================================================================== -1. Intro *NERDTree* - -What is this "NERD tree"?? - -The NERD tree allows you to explore your filesystem and to open files and -directories. It presents the filesystem to you in the form of a tree which you -manipulate with the keyboard and/or mouse. It also allows you to perform -simple filesystem operations. - -The following features and functionality are provided by the NERD tree: - * Files and directories are displayed in a hierarchical tree structure - * Different highlighting is provided for the following types of nodes: - * files - * directories - * sym-links - * windows .lnk files - * read-only files - * executable files - * Many (customisable) mappings are provided to manipulate the tree: - * Mappings to open/close/explore directory nodes - * Mappings to open files in new/existing windows/tabs - * Mappings to change the current root of the tree - * Mappings to navigate around the tree - * ... - * Directories and files can be bookmarked. - * Most NERD tree navigation can also be done with the mouse - * Filtering of tree content (can be toggled at runtime) - * custom file filters to prevent e.g. vim backup files being displayed - * optional displaying of hidden files (. files) - * files can be "turned off" so that only directories are displayed - * The position and size of the NERD tree window can be customised - * The order in which the nodes in the tree are listed can be customised. - * A model of your filesystem is created/maintained as you explore it. This - has several advantages: - * All filesystem information is cached and is only re-read on demand - * If you revisit a part of the tree that you left earlier in your - session, the directory nodes will be opened/closed as you left them - * The script remembers the cursor position and window position in the NERD - tree so you can toggle it off (or just close the tree window) and then - reopen it (with NERDTreeToggle) the NERD tree window will appear exactly - as you left it - * You can have a separate NERD tree for each tab, share trees across tabs, - or a mix of both. - * By default the script overrides the default file browser (netw), so if - you :edit a directory a (slighly modified) NERD tree will appear in the - current window - * A programmable menu system is provided (simulates right clicking on a - node) - * one default menu plugin is provided to perform basic filesytem - operations (create/delete/move/copy files/directories) - * There's an API for adding your own keymappings - - -============================================================================== -2. Functionality provided *NERDTreeFunctionality* - ------------------------------------------------------------------------------- -2.1. Global Commands *NERDTreeGlobalCommands* - -:NERDTree [ | ] *:NERDTree* - Opens a fresh NERD tree. The root of the tree depends on the argument - given. There are 3 cases: If no argument is given, the current directory - will be used. If a directory is given, that will be used. If a bookmark - name is given, the corresponding directory will be used. For example: > - :NERDTree /home/marty/vim7/src - :NERDTree foo (foo is the name of a bookmark) -< -:NERDTreeFromBookmark *:NERDTreeFromBookmark* - Opens a fresh NERD tree with the root initialized to the dir for - . This only reason to use this command over :NERDTree is for - the completion (which is for bookmarks rather than directories). - -:NERDTreeToggle [ | ] *:NERDTreeToggle* - If a NERD tree already exists for this tab, it is reopened and rendered - again. If no NERD tree exists for this tab then this command acts the - same as the |:NERDTree| command. - -:NERDTreeMirror *:NERDTreeMirror* - Shares an existing NERD tree, from another tab, in the current tab. - Changes made to one tree are reflected in both as they are actually the - same buffer. - - If only one other NERD tree exists, that tree is automatically mirrored. If - more than one exists, the script will ask which tree to mirror. - -:NERDTreeClose *:NERDTreeClose* - Close the NERD tree in this tab. - -:NERDTreeFind *:NERDTreeFind* - Find the current file in the tree. If no tree exists for the current tab, - or the file is not under the current root, then initialize a new tree where - the root is the directory of the current file. - ------------------------------------------------------------------------------- -2.2. Bookmarks *NERDTreeBookmarks* - -Bookmarks in the NERD tree are a way to tag files or directories of interest. -For example, you could use bookmarks to tag all of your project directories. - ------------------------------------------------------------------------------- -2.2.1. The Bookmark Table *NERDTreeBookmarkTable* - -If the bookmark table is active (see |NERDTree-B| and -|'NERDTreeShowBookmarks'|), it will be rendered above the tree. You can double -click bookmarks or use the |NERDTree-o| mapping to activate them. See also, -|NERDTree-t| and |NERDTree-T| - ------------------------------------------------------------------------------- -2.2.2. Bookmark commands *NERDTreeBookmarkCommands* - -Note that the following commands are only available in the NERD tree buffer. - -:Bookmark - Bookmark the current node as . If there is already a - bookmark, it is overwritten. must not contain spaces. - -:BookmarkToRoot - Make the directory corresponding to the new root. If a treenode - corresponding to is already cached somewhere in the tree then - the current tree will be used, otherwise a fresh tree will be opened. - Note that if points to a file then its parent will be used - instead. - -:RevealBookmark - If the node is cached under the current root then it will be revealed - (i.e. directory nodes above it will be opened) and the cursor will be - placed on it. - -:OpenBookmark - must point to a file. The file is opened as though |NERDTree-o| - was applied. If the node is cached under the current root then it will be - revealed and the cursor will be placed on it. - -:ClearBookmarks [] - Remove all the given bookmarks. If no bookmarks are given then remove all - bookmarks on the current node. - -:ClearAllBookmarks - Remove all bookmarks. - -:ReadBookmarks - Re-read the bookmarks in the |'NERDTreeBookmarksFile'|. - -See also |:NERDTree| and |:NERDTreeFromBookmark|. - ------------------------------------------------------------------------------- -2.2.3. Invalid Bookmarks *NERDTreeInvalidBookmarks* - -If invalid bookmarks are detected, the script will issue an error message and -the invalid bookmarks will become unavailable for use. - -These bookmarks will still be stored in the bookmarks file (see -|'NERDTreeBookmarksFile'|), down the bottom. There will always be a blank line -after the valid bookmarks but before the invalid ones. - -Each line in the bookmarks file represents one bookmark. The proper format is: - - -After you have corrected any invalid bookmarks, either restart vim, or go -:ReadBookmarks from the NERD tree window. - ------------------------------------------------------------------------------- -2.3. NERD tree Mappings *NERDTreeMappings* - -Default Description~ help-tag~ -Key~ - -o.......Open files, directories and bookmarks....................|NERDTree-o| -go......Open selected file, but leave cursor in the NERDTree.....|NERDTree-go| -t.......Open selected node/bookmark in a new tab.................|NERDTree-t| -T.......Same as 't' but keep the focus on the current tab........|NERDTree-T| -i.......Open selected file in a split window.....................|NERDTree-i| -gi......Same as i, but leave the cursor on the NERDTree..........|NERDTree-gi| -s.......Open selected file in a new vsplit.......................|NERDTree-s| -gs......Same as s, but leave the cursor on the NERDTree..........|NERDTree-gs| -O.......Recursively open the selected directory..................|NERDTree-O| -x.......Close the current nodes parent...........................|NERDTree-x| -X.......Recursively close all children of the current node.......|NERDTree-X| -e.......Edit the current dif.....................................|NERDTree-e| - -...............same as |NERDTree-o|. -double-click.......same as the |NERDTree-o| map. -middle-click.......same as |NERDTree-i| for files, same as - |NERDTree-e| for dirs. - -D.......Delete the current bookmark .............................|NERDTree-D| - -P.......Jump to the root node....................................|NERDTree-P| -p.......Jump to current nodes parent.............................|NERDTree-p| -K.......Jump up inside directories at the current tree depth.....|NERDTree-K| -J.......Jump down inside directories at the current tree depth...|NERDTree-J| -...Jump down to the next sibling of the current directory...|NERDTree-C-J| -...Jump up to the previous sibling of the current directory.|NERDTree-C-K| - -C.......Change the tree root to the selected dir.................|NERDTree-C| -u.......Move the tree root up one directory......................|NERDTree-u| -U.......Same as 'u' except the old root node is left open........|NERDTree-U| -r.......Recursively refresh the current directory................|NERDTree-r| -R.......Recursively refresh the current root.....................|NERDTree-R| -m.......Display the NERD tree menu...............................|NERDTree-m| -cd......Change the CWD to the dir of the selected node...........|NERDTree-cd| - -I.......Toggle whether hidden files displayed....................|NERDTree-I| -f.......Toggle whether the file filters are used.................|NERDTree-f| -F.......Toggle whether files are displayed.......................|NERDTree-F| -B.......Toggle whether the bookmark table is displayed...........|NERDTree-B| - -q.......Close the NERDTree window................................|NERDTree-q| -A.......Zoom (maximize/minimize) the NERDTree window.............|NERDTree-A| -?.......Toggle the display of the quick help.....................|NERDTree-?| - ------------------------------------------------------------------------------- - *NERDTree-o* -Default key: o -Map option: NERDTreeMapActivateNode -Applies to: files and directories. - -If a file node is selected, it is opened in the previous window. - -If a directory is selected it is opened or closed depending on its current -state. - -If a bookmark that links to a directory is selected then that directory -becomes the new root. - -If a bookmark that links to a file is selected then that file is opened in the -previous window. - ------------------------------------------------------------------------------- - *NERDTree-go* -Default key: go -Map option: None -Applies to: files. - -If a file node is selected, it is opened in the previous window, but the -cursor does not move. - -The key combo for this mapping is always "g" + NERDTreeMapActivateNode (see -|NERDTree-o|). - ------------------------------------------------------------------------------- - *NERDTree-t* -Default key: t -Map option: NERDTreeMapOpenInTab -Applies to: files and directories. - -Opens the selected file in a new tab. If a directory is selected, a fresh -NERD Tree for that directory is opened in a new tab. - -If a bookmark which points to a directory is selected, open a NERD tree for -that directory in a new tab. If the bookmark points to a file, open that file -in a new tab. - ------------------------------------------------------------------------------- - *NERDTree-T* -Default key: T -Map option: NERDTreeMapOpenInTabSilent -Applies to: files and directories. - -The same as |NERDTree-t| except that the focus is kept in the current tab. - ------------------------------------------------------------------------------- - *NERDTree-i* -Default key: i -Map option: NERDTreeMapOpenSplit -Applies to: files. - -Opens the selected file in a new split window and puts the cursor in the new -window. - ------------------------------------------------------------------------------- - *NERDTree-gi* -Default key: gi -Map option: None -Applies to: files. - -The same as |NERDTree-i| except that the cursor is not moved. - -The key combo for this mapping is always "g" + NERDTreeMapOpenSplit (see -|NERDTree-i|). - ------------------------------------------------------------------------------- - *NERDTree-s* -Default key: s -Map option: NERDTreeMapOpenVSplit -Applies to: files. - -Opens the selected file in a new vertically split window and puts the cursor in -the new window. - ------------------------------------------------------------------------------- - *NERDTree-gs* -Default key: gs -Map option: None -Applies to: files. - -The same as |NERDTree-s| except that the cursor is not moved. - -The key combo for this mapping is always "g" + NERDTreeMapOpenVSplit (see -|NERDTree-s|). - ------------------------------------------------------------------------------- - *NERDTree-O* -Default key: O -Map option: NERDTreeMapOpenRecursively -Applies to: directories. - -Recursively opens the selelected directory. - -All files and directories are cached, but if a directory would not be -displayed due to file filters (see |'NERDTreeIgnore'| |NERDTree-f|) or the -hidden file filter (see |'NERDTreeShowHidden'|) then its contents are not -cached. This is handy, especially if you have .svn directories. - ------------------------------------------------------------------------------- - *NERDTree-x* -Default key: x -Map option: NERDTreeMapCloseDir -Applies to: files and directories. - -Closes the parent of the selected node. - ------------------------------------------------------------------------------- - *NERDTree-X* -Default key: X -Map option: NERDTreeMapCloseChildren -Applies to: directories. - -Recursively closes all children of the selected directory. - -Tip: To quickly "reset" the tree, use |NERDTree-P| with this mapping. - ------------------------------------------------------------------------------- - *NERDTree-e* -Default key: e -Map option: NERDTreeMapOpenExpl -Applies to: files and directories. - -|:edit|s the selected directory, or the selected file's directory. This could -result in a NERD tree or a netrw being opened, depending on -|'NERDTreeHijackNetrw'|. - ------------------------------------------------------------------------------- - *NERDTree-D* -Default key: D -Map option: NERDTreeMapDeleteBookmark -Applies to: lines in the bookmarks table - -Deletes the currently selected bookmark. - ------------------------------------------------------------------------------- - *NERDTree-P* -Default key: P -Map option: NERDTreeMapJumpRoot -Applies to: no restrictions. - -Jump to the tree root. - ------------------------------------------------------------------------------- - *NERDTree-p* -Default key: p -Map option: NERDTreeMapJumpParent -Applies to: files and directories. - -Jump to the parent node of the selected node. - ------------------------------------------------------------------------------- - *NERDTree-K* -Default key: K -Map option: NERDTreeMapJumpFirstChild -Applies to: files and directories. - -Jump to the first child of the current nodes parent. - -If the cursor is already on the first node then do the following: - * loop back thru the siblings of the current nodes parent until we find an - open dir with children - * go to the first child of that node - ------------------------------------------------------------------------------- - *NERDTree-J* -Default key: J -Map option: NERDTreeMapJumpLastChild -Applies to: files and directories. - -Jump to the last child of the current nodes parent. - -If the cursor is already on the last node then do the following: - * loop forward thru the siblings of the current nodes parent until we find - an open dir with children - * go to the last child of that node - ------------------------------------------------------------------------------- - *NERDTree-C-J* -Default key: -Map option: NERDTreeMapJumpNextSibling -Applies to: files and directories. - -Jump to the next sibling of the selected node. - ------------------------------------------------------------------------------- - *NERDTree-C-K* -Default key: -Map option: NERDTreeMapJumpPrevSibling -Applies to: files and directories. - -Jump to the previous sibling of the selected node. - ------------------------------------------------------------------------------- - *NERDTree-C* -Default key: C -Map option: NERDTreeMapChdir -Applies to: directories. - -Make the selected directory node the new tree root. If a file is selected, its -parent is used. - ------------------------------------------------------------------------------- - *NERDTree-u* -Default key: u -Map option: NERDTreeMapUpdir -Applies to: no restrictions. - -Move the tree root up a dir (like doing a "cd .."). - ------------------------------------------------------------------------------- - *NERDTree-U* -Default key: U -Map option: NERDTreeMapUpdirKeepOpen -Applies to: no restrictions. - -Like |NERDTree-u| except that the old tree root is kept open. - ------------------------------------------------------------------------------- - *NERDTree-r* -Default key: r -Map option: NERDTreeMapRefresh -Applies to: files and directories. - -If a dir is selected, recursively refresh that dir, i.e. scan the filesystem -for changes and represent them in the tree. - -If a file node is selected then the above is done on it's parent. - ------------------------------------------------------------------------------- - *NERDTree-R* -Default key: R -Map option: NERDTreeMapRefreshRoot -Applies to: no restrictions. - -Recursively refresh the tree root. - ------------------------------------------------------------------------------- - *NERDTree-m* -Default key: m -Map option: NERDTreeMapMenu -Applies to: files and directories. - -Display the NERD tree menu. See |NERDTreeMenu| for details. - ------------------------------------------------------------------------------- - *NERDTree-cd* -Default key: cd -Map option: NERDTreeMapChdir -Applies to: files and directories. - -Change vims current working directory to that of the selected node. - ------------------------------------------------------------------------------- - *NERDTree-I* -Default key: I -Map option: NERDTreeMapToggleHidden -Applies to: no restrictions. - -Toggles whether hidden files (i.e. "dot files") are displayed. - ------------------------------------------------------------------------------- - *NERDTree-f* -Default key: f -Map option: NERDTreeMapToggleFilters -Applies to: no restrictions. - -Toggles whether file filters are used. See |'NERDTreeIgnore'| for details. - ------------------------------------------------------------------------------- - *NERDTree-F* -Default key: F -Map option: NERDTreeMapToggleFiles -Applies to: no restrictions. - -Toggles whether file nodes are displayed. - ------------------------------------------------------------------------------- - *NERDTree-B* -Default key: B -Map option: NERDTreeMapToggleBookmarks -Applies to: no restrictions. - -Toggles whether the bookmarks table is displayed. - ------------------------------------------------------------------------------- - *NERDTree-q* -Default key: q -Map option: NERDTreeMapQuit -Applies to: no restrictions. - -Closes the NERDtree window. - ------------------------------------------------------------------------------- - *NERDTree-A* -Default key: A -Map option: NERDTreeMapToggleZoom -Applies to: no restrictions. - -Maximize (zoom) and minimize the NERDtree window. - ------------------------------------------------------------------------------- - *NERDTree-?* -Default key: ? -Map option: NERDTreeMapHelp -Applies to: no restrictions. - -Toggles whether the quickhelp is displayed. - ------------------------------------------------------------------------------- -2.3. The NERD tree menu *NERDTreeMenu* - -The NERD tree has a menu that can be programmed via the an API (see -|NERDTreeMenuAPI|). The idea is to simulate the "right click" menus that most -file explorers have. - -The script comes with two default menu plugins: exec_menuitem.vim and -fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for -creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a -menu item to execute executable files. - -Related tags: |NERDTree-m| |NERDTreeApi| - -============================================================================== -3. Customisation *NERDTreeOptions* - - ------------------------------------------------------------------------------- -3.1. Customisation summary *NERDTreeOptionSummary* - -The script provides the following options that can customise the behaviour the -NERD tree. These options should be set in your vimrc. - -|'loaded_nerd_tree'| Turns off the script. - -|'NERDChristmasTree'| Tells the NERD tree to make itself colourful - and pretty. - -|'NERDTreeAutoCenter'| Controls whether the NERD tree window centers - when the cursor moves within a specified - distance to the top/bottom of the window. -|'NERDTreeAutoCenterThreshold'| Controls the sensitivity of autocentering. - -|'NERDTreeCaseSensitiveSort'| Tells the NERD tree whether to be case - sensitive or not when sorting nodes. - -|'NERDTreeChDirMode'| Tells the NERD tree if/when it should change - vim's current working directory. - -|'NERDTreeHighlightCursorline'| Tell the NERD tree whether to highlight the - current cursor line. - -|'NERDTreeHijackNetrw'| Tell the NERD tree whether to replace the netrw - autocommands for exploring local directories. - -|'NERDTreeIgnore'| Tells the NERD tree which files to ignore. - -|'NERDTreeBookmarksFile'| Where the bookmarks are stored. - -|'NERDTreeMouseMode'| Tells the NERD tree how to handle mouse - clicks. - -|'NERDTreeQuitOnOpen'| Closes the tree window after opening a file. - -|'NERDTreeShowBookmarks'| Tells the NERD tree whether to display the - bookmarks table on startup. - -|'NERDTreeShowFiles'| Tells the NERD tree whether to display files - in the tree on startup. - -|'NERDTreeShowHidden'| Tells the NERD tree whether to display hidden - files on startup. - -|'NERDTreeShowLineNumbers'| Tells the NERD tree whether to display line - numbers in the tree window. - -|'NERDTreeSortOrder'| Tell the NERD tree how to sort the nodes in - the tree. - -|'NERDTreeStatusline'| Set a statusline for NERD tree windows. - -|'NERDTreeWinPos'| Tells the script where to put the NERD tree - window. - -|'NERDTreeWinSize'| Sets the window size when the NERD tree is - opened. - ------------------------------------------------------------------------------- -3.2. Customisation details *NERDTreeOptionDetails* - -To enable any of the below options you should put the given line in your -~/.vimrc - - *'loaded_nerd_tree'* -If this plugin is making you feel homicidal, it may be a good idea to turn it -off with this line in your vimrc: > - let loaded_nerd_tree=1 -< ------------------------------------------------------------------------------- - *'NERDChristmasTree'* -Values: 0 or 1. -Default: 1. - -If this option is set to 1 then some extra syntax highlighting elements are -added to the nerd tree to make it more colourful. - -Set it to 0 for a more vanilla looking tree. - ------------------------------------------------------------------------------- - *'NERDTreeAutoCenter'* -Values: 0 or 1. -Default: 1 - -If set to 1, the NERD tree window will center around the cursor if it moves to -within |'NERDTreeAutoCenterThreshold'| lines of the top/bottom of the window. - -This is ONLY done in response to tree navigation mappings, -i.e. |NERDTree-J| |NERDTree-K| |NERDTree-C-J| |NERDTree-C-K| |NERDTree-p| -|NERDTree-P| - -The centering is done with a |zz| operation. - ------------------------------------------------------------------------------- - *'NERDTreeAutoCenterThreshold'* -Values: Any natural number. -Default: 3 - -This option controls the "sensitivity" of the NERD tree auto centering. See -|'NERDTreeAutoCenter'| for details. - ------------------------------------------------------------------------------- - *'NERDTreeCaseSensitiveSort'* -Values: 0 or 1. -Default: 0. - -By default the NERD tree does not sort nodes case sensitively, i.e. nodes -could appear like this: > - bar.c - Baz.c - blarg.c - boner.c - Foo.c -< -But, if you set this option to 1 then the case of the nodes will be taken into -account. The above nodes would then be sorted like this: > - Baz.c - Foo.c - bar.c - blarg.c - boner.c -< ------------------------------------------------------------------------------- - *'NERDTreeChDirMode'* - -Values: 0, 1 or 2. -Default: 0. - -Use this option to tell the script when (if at all) to change the current -working directory (CWD) for vim. - -If it is set to 0 then the CWD is never changed by the NERD tree. - -If set to 1 then the CWD is changed when the NERD tree is first loaded to the -directory it is initialized in. For example, if you start the NERD tree with > - :NERDTree /home/marty/foobar -< -then the CWD will be changed to /home/marty/foobar and will not be changed -again unless you init another NERD tree with a similar command. - -If the option is set to 2 then it behaves the same as if set to 1 except that -the CWD is changed whenever the tree root is changed. For example, if the CWD -is /home/marty/foobar and you make the node for /home/marty/foobar/baz the new -root then the CWD will become /home/marty/foobar/baz. - ------------------------------------------------------------------------------- - *'NERDTreeHighlightCursorline'* -Values: 0 or 1. -Default: 1. - -If set to 1, the current cursor line in the NERD tree buffer will be -highlighted. This is done using the |'cursorline'| option. - ------------------------------------------------------------------------------- - *'NERDTreeHijackNetrw'* -Values: 0 or 1. -Default: 1. - -If set to 1, doing a > - :edit -< -will open up a "secondary" NERD tree instead of a netrw in the target window. - -Secondary NERD trees behaves slighly different from a regular trees in the -following respects: - 1. 'o' will open the selected file in the same window as the tree, - replacing it. - 2. you can have as many secondary tree as you want in the same tab. - ------------------------------------------------------------------------------- - *'NERDTreeIgnore'* -Values: a list of regular expressions. -Default: ['\~$']. - -This option is used to specify which files the NERD tree should ignore. It -must be a list of regular expressions. When the NERD tree is rendered, any -files/dirs that match any of the regex's in 'NERDTreeIgnore' wont be -displayed. - -For example if you put the following line in your vimrc: > - let NERDTreeIgnore=['\.vim$', '\~$'] -< -then all files ending in .vim or ~ will be ignored. - -Note: to tell the NERD tree not to ignore any files you must use the following -line: > - let NERDTreeIgnore=[] -< - -The file filters can be turned on and off dynamically with the |NERDTree-f| -mapping. - ------------------------------------------------------------------------------- - *'NERDTreeBookmarksFile'* -Values: a path -Default: $HOME/.NERDTreeBookmarks - -This is where bookmarks are saved. See |NERDTreeBookmarkCommands|. - ------------------------------------------------------------------------------- - *'NERDTreeMouseMode'* -Values: 1, 2 or 3. -Default: 1. - -If set to 1 then a double click on a node is required to open it. -If set to 2 then a single click will open directory nodes, while a double -click will still be required for file nodes. -If set to 3 then a single click will open any node. - -Note: a double click anywhere on a line that a tree node is on will -activate it, but all single-click activations must be done on name of the node -itself. For example, if you have the following node: > - | | |-application.rb -< -then (to single click activate it) you must click somewhere in -'application.rb'. - ------------------------------------------------------------------------------- - *'NERDTreeQuitOnOpen'* - -Values: 0 or 1. -Default: 0 - -If set to 1, the NERD tree window will close after opening a file with the -|NERDTree-o|, |NERDTree-i|, |NERDTree-t| and |NERDTree-T| mappings. - ------------------------------------------------------------------------------- - *'NERDTreeShowBookmarks'* -Values: 0 or 1. -Default: 0. - -If this option is set to 1 then the bookmarks table will be displayed. - -This option can be toggled dynamically, per tree, with the |NERDTree-B| -mapping. - ------------------------------------------------------------------------------- - *'NERDTreeShowFiles'* -Values: 0 or 1. -Default: 1. - -If this option is set to 1 then files are displayed in the NERD tree. If it is -set to 0 then only directories are displayed. - -This option can be toggled dynamically, per tree, with the |NERDTree-F| -mapping and is useful for drastically shrinking the tree when you are -navigating to a different part of the tree. - ------------------------------------------------------------------------------- - *'NERDTreeShowHidden'* -Values: 0 or 1. -Default: 0. - -This option tells vim whether to display hidden files by default. This option -can be dynamically toggled, per tree, with the |NERDTree-I| mapping. Use one -of the follow lines to set this option: > - let NERDTreeShowHidden=0 - let NERDTreeShowHidden=1 -< - ------------------------------------------------------------------------------- - *'NERDTreeShowLineNumbers'* -Values: 0 or 1. -Default: 0. - -This option tells vim whether to display line numbers for the NERD tree -window. Use one of the follow lines to set this option: > - let NERDTreeShowLineNumbers=0 - let NERDTreeShowLineNumbers=1 -< - ------------------------------------------------------------------------------- - *'NERDTreeSortOrder'* -Values: a list of regular expressions. -Default: ['\/$', '*', '\.swp$', '\.bak$', '\~$'] - -This option is set to a list of regular expressions which are used to -specify the order of nodes under their parent. - -For example, if the option is set to: > - ['\.vim$', '\.c$', '\.h$', '*', 'foobar'] -< -then all .vim files will be placed at the top, followed by all .c files then -all .h files. All files containing the string 'foobar' will be placed at the -end. The star is a special flag: it tells the script that every node that -doesnt match any of the other regexps should be placed here. - -If no star is present in 'NERDTreeSortOrder' then one is automatically -appended to the array. - -The regex '\/$' should be used to match directory nodes. - -After this sorting is done, the files in each group are sorted alphabetically. - -Other examples: > - (1) ['*', '\/$'] - (2) [] - (3) ['\/$', '\.rb$', '\.php$', '*', '\.swp$', '\.bak$', '\~$'] -< -1. Directories will appear last, everything else will appear above. -2. Everything will simply appear in alphabetical order. -3. Dirs will appear first, then ruby and php. Swap files, bak files and vim - backup files will appear last with everything else preceding them. - ------------------------------------------------------------------------------- - *'NERDTreeStatusline'* -Values: Any valid statusline setting. -Default: %{b:NERDTreeRoot.path.strForOS(0)} - -Tells the script what to use as the |'statusline'| setting for NERD tree -windows. - -Note that the statusline is set using |:let-&| not |:set| so escaping spaces -isn't necessary. - -Setting this option to -1 will will deactivate it so that your global -statusline setting is used instead. - ------------------------------------------------------------------------------- - *'NERDTreeWinPos'* -Values: "left" or "right" -Default: "left". - -This option is used to determine where NERD tree window is placed on the -screen. - -This option makes it possible to use two different explorer plugins -simultaneously. For example, you could have the taglist plugin on the left of -the window and the NERD tree on the right. - ------------------------------------------------------------------------------- - *'NERDTreeWinSize'* -Values: a positive integer. -Default: 31. - -This option is used to change the size of the NERD tree when it is loaded. - -============================================================================== -4. The NERD tree API *NERDTreeAPI* - -The NERD tree script allows you to add custom key mappings and menu items via -a set of API calls. Any scripts that use this API should be placed in -~/.vim/nerdtree_plugin/ (*nix) or ~/vimfiles/nerdtree_plugin (windows). - -The script exposes some prototype objects that can be used to manipulate the -tree and/or get information from it: > - g:NERDTreePath - g:NERDTreeDirNode - g:NERDTreeFileNode - g:NERDTreeBookmark -< -See the code/comments in NERD_tree.vim to find how to use these objects. The -following code conventions are used: - * class members start with a capital letter - * instance members start with a lower case letter - * private members start with an underscore - -See this blog post for more details: - http://got-ravings.blogspot.com/2008/09/vim-pr0n-prototype-based-objects.html - ------------------------------------------------------------------------------- -4.1. Key map API *NERDTreeKeymapAPI* - -NERDTreeAddKeyMap({options}) *NERDTreeAddKeyMap()* - Adds a new keymapping for all NERD tree buffers. - {options} must be a dictionary, and must contain the following keys: - "key" - the trigger key for the new mapping - "callback" - the function the new mapping will be bound to - "quickhelpText" - the text that will appear in the quickhelp (see - |NERDTree-?|) - - Example: > - call NERDTreeAddKeyMap({ - \ 'key': 'b', - \ 'callback': 'NERDTreeEchoCurrentNode', - \ 'quickhelpText': 'echo full path of current node' }) - - function! NERDTreeEchoCurrentNode() - let n = g:NERDTreeFileNode.GetSelected() - if n != {} - echomsg 'Current node: ' . n.path.str() - endif - endfunction -< - This code should sit in a file like ~/.vim/nerdtree_plugin/mymapping.vim. - It adds a (rather useless) mapping on 'b' which echos the full path to the - current node. - ------------------------------------------------------------------------------- -4.2. Menu API *NERDTreeMenuAPI* - -NERDTreeAddSubmenu({options}) *NERDTreeAddSubmenu()* - Creates and returns a new submenu. - - {options} must be a dictionary and must contain the following keys: - "text" - the text of the submenu that the user will see - "shortcut" - a shortcut key for the submenu (need not be unique) - - The following keys are optional: - "isActiveCallback" - a function that will be called to determine whether - this submenu item will be displayed or not. The callback function must return - 0 or 1. - "parent" - the parent submenu of the new submenu (returned from a previous - invocation of NERDTreeAddSubmenu()). If this key is left out then the new - submenu will sit under the top level menu. - - See below for an example. - -NERDTreeAddMenuItem({options}) *NERDTreeAddMenuItem()* - Adds a new menu item to the NERD tree menu (see |NERDTreeMenu|). - - {options} must be a dictionary and must contain the - following keys: - "text" - the text of the menu item which the user will see - "shortcut" - a shortcut key for the menu item (need not be unique) - "callback" - the function that will be called when the user activates the - menu item. - - The following keys are optional: - "isActiveCallback" - a function that will be called to determine whether - this menu item will be displayed or not. The callback function must return - 0 or 1. - "parent" - if the menu item belongs under a submenu then this key must be - specified. This value for this key will be the object that - was returned when the submenu was created with |NERDTreeAddSubmenu()|. - - See below for an example. - -NERDTreeAddMenuSeparator([{options}]) *NERDTreeAddMenuSeparator()* - Adds a menu separator (a row of dashes). - - {options} is an optional dictionary that may contain the following keys: - "isActiveCallback" - see description in |NERDTreeAddMenuItem()|. - -Below is an example of the menu API in action. > - call NERDTreeAddMenuSeparator() - - call NERDTreeAddMenuItem({ - \ 'text': 'a (t)op level menu item', - \ 'shortcut': 't', - \ 'callback': 'SomeFunction' }) - - let submenu = NERDTreeAddSubmenu({ - \ 'text': 'a (s)ub menu', - \ 'shortcut': 's' }) - - call NERDTreeAddMenuItem({ - \ 'text': '(n)ested item 1', - \ 'shortcut': 'n', - \ 'callback': 'SomeFunction', - \ 'parent': submenu }) - - call NERDTreeAddMenuItem({ - \ 'text': '(n)ested item 2', - \ 'shortcut': 'n', - \ 'callback': 'SomeFunction', - \ 'parent': submenu }) -< -This will create the following menu: > - -------------------- - a (t)op level menu item - a (s)ub menu -< -Where selecting "a (s)ub menu" will lead to a second menu: > - (n)ested item 1 - (n)ested item 2 -< -When any of the 3 concrete menu items are selected the function "SomeFunction" -will be called. - ------------------------------------------------------------------------------- -NERDTreeRender() *NERDTreeRender()* - Re-renders the NERD tree buffer. Useful if you change the state of the - tree and you want to it to be reflected in the UI. - -============================================================================== -5. About *NERDTreeAbout* - -The author of the NERD tree is a terrible terrible monster called Martyzilla -who gobbles up small children with milk and sugar for breakfast. - -He can be reached at martin.grenfell at gmail dot com. He would love to hear -from you, so feel free to send him suggestions and/or comments about this -plugin. Don't be shy --- the worst he can do is slaughter you and stuff you in -the fridge for later ;) - -The latest stable versions can be found at - http://www.vim.org/scripts/script.php?script_id=1658 - -The latest dev versions are on github - http://github.com/scrooloose/nerdtree - - -============================================================================== -6. Changelog *NERDTreeChangelog* - -4.1.0 - features: - - NERDTreeFind to reveal the node for the current buffer in the tree, - see |NERDTreeFind|. This effectively merges the FindInNERDTree plugin (by - Doug McInnes) into the script. - - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan - Ritter and Rémi Prévost. - - truncate the root node if wider than the tree window. Thanks to Victor - Gonzalez. - - bugfixes: - - really fix window state restoring - - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, - jfilip1024, and Chris Chambers - -4.0.0 - - add a new programmable menu system (see :help NERDTreeMenu). - - add new APIs to add menus/menu-items to the menu system as well as - custom key mappings to the NERD tree buffer (see :help NERDTreeAPI). - - removed the old API functions - - added a mapping to maximize/restore the size of nerd tree window, thanks - to Guillaume Duranceau for the patch. See :help NERDTree-A for details. - - - fix a bug where secondary nerd trees (netrw hijacked trees) and - NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. - - fix a bug where the script ignored directories whose name ended in a dot, - thanks to Aggelos Orfanakos for the patch. - - fix a bug when using the x mapping on the tree root, thanks to Bryan - Venteicher for the patch. - - fix a bug where the cursor position/window size of the nerd tree buffer - wasnt being stored on closing the window, thanks to Richard Hart. - - fix a bug where NERDTreeMirror would mirror the wrong tree - -3.1.1 - - fix a bug where a non-listed no-name buffer was getting created every - time the tree windows was created, thanks to Derek Wyatt and owen1 - - make behave the same as the 'o' mapping - - some helptag fixes in the doc, thanks strull - - fix a bug when using :set nohidden and opening a file where the previous - buf was modified. Thanks iElectric - - other minor fixes - -3.1.0 - New features: - - add mappings to open files in a vsplit, see :help NERDTree-s and :help - NERDTree-gs - - make the statusline for the nerd tree window default to something - hopefully more useful. See :help 'NERDTreeStatusline' - Bugfixes: - - make the hijack netrw functionality work when vim is started with "vim - " (thanks to Alf Mikula for the patch). - - fix a bug where the CWD wasnt being changed for some operations even when - NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) - - add -bar to all the nerd tree :commands so they can chain with other - :commands (thanks to tpope) - - fix bugs when ignorecase was set (thanks to nach) - - fix a bug with the relative path code (thanks to nach) - - fix a bug where doing a :cd would cause :NERDTreeToggle to fail (thanks nach) - - -3.0.1 - Bugfixes: - - fix bugs with :NERDTreeToggle and :NERDTreeMirror when 'hidden - was not set - - fix a bug where :NERDTree would fail if was relative and - didnt start with a ./ or ../ Thanks to James Kanze. - - make the q mapping work with secondary (:e style) trees, - thanks to jamessan - - fix a bunch of small bugs with secondary trees - - More insane refactoring. - -3.0.0 - - hijack netrw so that doing an :edit will put a NERD tree in - the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' - - allow sharing of trees across tabs, see :help :NERDTreeMirror - - remove "top" and "bottom" as valid settings for NERDTreeWinPos - - change the '' mapping to 'i' - - change the 'H' mapping to 'I' - - lots of refactoring - -============================================================================== -7. Credits *NERDTreeCredits* - -Thanks to the following people for testing, bug reports, ideas etc. Without -you I probably would have got bored of the hacking the NERD tree and -just downloaded pr0n instead. - - Tim Carey-Smith (halorgium) - Vigil - Nick Brettell - Thomas Scott Urban - Terrance Cohen - Yegappan Lakshmanan - Jason Mills - Michael Geddes (frogonwheels) - Yu Jun - Michael Madsen - AOYAMA Shotaro - Zhang Weiwu - Niels Aan de Brugh - Olivier Yiptong - Zhang Shuhan - Cory Echols - Piotr Czachur - Yuan Jiang - Matan Nassau - Maxim Kim - Charlton Wang - Matt Wozniski (godlygeek) - knekk - Sean Chou - Ryan Penn - Simon Peter Nicholls - Michael Foobar - Tomasz Chomiuk - Denis Pokataev - Tim Pope (tpope) - James Kanze - James Vega (jamessan) - Frederic Chanal (nach) - Alf Mikula - Lucas S. Buchala - Curtis Harvey - Guillaume Duranceau - Richard Hart (hates) - Doug McInnes - Stefan Ritter - Rémi Prévost - Victor Gonzalez - Stephan Baumeister - Ricky - jfilip1024 - Chris Chambers - -============================================================================== -8. License *NERDTreeLicense* - -The NERD tree is released under the wtfpl. -See http://sam.zoy.org/wtfpl/COPYING. diff --git a/vim/doc/Tabular.txt b/vim/doc/Tabular.txt deleted file mode 100755 index 34f4765cd2..0000000000 --- a/vim/doc/Tabular.txt +++ /dev/null @@ -1,258 +0,0 @@ -*Tabular.txt* Configurable, flexible, intuitive text aligning - - *tabular* *tabular.vim* - - #|#|#|#|#| #| #| ~ - #| #|#|#| #|#|#| #| #| #| #|#|#| #| #|#| ~ - #| #| #| #| #| #| #| #| #| #| #|#| ~ - #| #| #| #| #| #| #| #| #| #| #| ~ - #| #|#|#| #|#|#| #|#|#| #| #|#|#| #| ~ - - For Vim version 7.0 or newer - - By Matt Wozniski - mjw@drexel.edu - - Reference Manual ~ - - *tabular-toc* - -1. Description |tabular-intro| -2. Walkthrough |tabular-walkthrough| -3. Scripting |tabular-scripting| - -The functionality mentioned here is a plugin, see |add-plugin|. -You can avoid loading this plugin by setting the "Tabular_loaded" global -variable in your |vimrc| file: > - :let g:tabular_loaded = 1 - -============================================================================== -1. Description *tabular-intro* - -Sometimes, it's useful to line up text. Naturally, it's nicer to have the -computer do this for you, since aligning things by hand quickly becomes -unpleasant. While there are other plugins for aligning text, the ones I've -tried are either impossibly difficult to understand and use, or too simplistic -to handle complicated tasks. This plugin aims to make the easy things easy -and the hard things possible, without providing an unnecessarily obtuse -interface. It's still a work in progress, and criticisms are welcome. - -============================================================================== -2. Walkthrough *tabular-walkthrough* - -Tabular's commands are based largely on regular expressions. The basic -technique used by Tabular is taking some regex to match field delimiters, -splitting the input lines at those delimiters, trimming unnecessary spaces -from the non-delimiter parts, padding the non-delimiter parts of the lines -with spaces to make them the same length, and joining things back together -again. - -For instance, consider starting with the following lines: -> - Some short phrase,some other phrase - A much longer phrase here,and another long phrase -< -Let's say we want to line these lines up at the commas. We can tell -Tabularize to do this by passing a pattern matching , to the Tabularize -command: -> - :Tabularize /, - - Some short phrase , some other phrase - A much longer phrase here , and another long phrase -< -I encourage you to try copying those lines to another buffer and trying to -call :Tabularize. You'll want to take notice of two things quickly: First, -instead of requiring a range, Tabularize tries to figure out what you want to -happen. Since it knows that you want to act on lines matching a comma, it -will look upwards and downwards for lines around the current line that match a -comma, and consider all contiguous lines matching the pattern to be the range -to be acted upon. You can always override this by specifying a range, though. - -The second thing you should notice is that you'll almost certainly be able to -abbreviate :Tabularize to :Tab - using this form in mappings and scripts is -discouraged as it will make conflicts with other scripts more likely, but for -interactive use it's a nice timesaver. - -So, anyway, now the commas line up. Splitting the lines on commas, Tabular -realized that 'Some short phrase' would need to be padded with spaces to match -the length of 'A much longer phrase here', and it did that before joining the -lines back together. You'll also notice that, in addition to the spaces -inserting for padding, extra spaces were inserted between fields. That's -because by default, Tabular prints things left-aligned with one space between -fields. If you wanted to print things right-aligned with no spaces between -fields, you would provide a different format to the Tabularize command: -> - :Tabularize /,/r0 - - Some short phrase, some other phrase - A much longer phrase here,and another long phrase -< -A format specifier is either l, r, or c, followed by one or more digits. If -the letter is l, the field will be left aligned, similarly for r and right -aligning and c and center aligning. The number following the letter is the -number of spaces padding to insert before the start of the next field. -Multiple format specifiers can be added to the same command - each field will -be printed with the next format specifier in the list; when they all have been -used the first will be used again, and so on. So, the last command right -aligned every field, then inserted 0 spaces of padding before the next field. -What if we wanted to right align the text before the comma, and left align the -text after the comma? The command would look like this: -> - :Tabularize /,/r1c1l0 - - Some short phrase , some other phrase - A much longer phrase here , and another long phrase -< -That command would be read as "Align the matching text, splitting fields on -commas. Print everything before the first comma right aligned, then 1 space, -then the comma center aligned, then 1 space, then everything after the comma -left aligned." Notice that the alignment of the field the comma is in is -irrelevant - since it's only 1 cell wide, it looks the same whether it's right, -left, or center aligned. Also notice that the 0 padding spaces specified for -the 3rd field are unused - but they would be used if there were enough fields -to require looping through the fields again. For instance: -> - abc,def,ghi - a,b - a,b,c - - :Tabularize /,/r1c1l0 - - abc , def, ghi - a , b - a , b , c -< -Notice that now, the format pattern has been reused; field 4 (the second comma) -is right aligned, field 5 is center aligned. No spaces were inserted between -the 3rd field (containing "def") and the 4th field (the second comma) because -the format specified 'l0'. - -But, what if you only wanted to act on the first comma on the line, rather than -all of the commas on the line? Let's say we want everything before the first -comma right aligned, then the comma, then everything after the comma left -aligned: -> - abc,def,ghi - a,b - a,b,c - - :Tabularize /^[^,]*\zs,/r0c0l0 - - abc,def,ghi - a,b - a,b,c -< -Here, we used a Vim regex that would only match the first comma on the line. -It matches the beginning of the line, followed by all the non-comma characters -up to the first comma, and then forgets about what it matched so far and -pretends that the match starts exactly at the comma. - -But, now that this command does exactly what we want it to, it's become pretty -unwieldy. It would be unpleasant to need to type that more than once or -twice. The solution is to assign a name to it. -> - :AddTabularPattern first_comma /^[^,]*\zs,/r0c0l0 -< -Now, typing ":Tabularize first_comma" will do the same thing as typing the -whole pattern out each time. Of course this is more useful if you store the -name in a file to be used later. - -NOTE: In order to make these new commands available every time vim starts, -you'll need to put those new commands into a .vim file in a plugin directory -somewhere in your 'runtimepath'. In order to make sure that Tabular.vim has -already been loaded before your file tries to use :AddTabularPattern or -:AddTabularPipeline, the new file should be installed in an after/plugin -directory in 'runtimepath'. In general, it will be safe to find out where the -TabularMaps.vim plugin was installed, and place other files extending -Tabular.vim in the same directory as TabularMaps.vim. For more information, -and some suggested best practices, check out the |tabular-scripting| section. - -Lastly, we'll approach the case where tabular cannot achieve your desired goal -just by splitting lines appart, trimming whitespace, padding with whitespace, -and rejoining the lines. As an example, consider the multiple_spaces command -from TabularMaps.vim. The goal is to split using two or more spaces as a -field delimiter, and join fields back together, properly lined up, with only -two spaces between the end of each field and the beginning of the next. -Unfortunately, Tabular can't do this with only the commands we know so far: -> - :Tabularize / / -< -The above function won't work, because it will consider "a b" as 5 fields -delimited by two pairs of 2 spaces ( 'a', ' ', '', ' ', 'b' ) instead of as -3 fields delimited by one set of 2 or more spaces ( 'a', ' ', 'b' ). -> - :Tabularize / \+/ -< -The above function won't work either, because it will leave the delimiter as 4 -spaces when used against "a b", meaning that we would fail at our goal of -collapsing everything down to two spaces between fields. So, we need a new -command to get around this: -> - :AddTabularPipeline multiple_spaces / \{2,}/ - \ map(a:lines, "substitute(v:val, ' \{2,}', ' ', 'g')") - \ | tabular#TabularizeStrings(a:lines, ' ', 'l0') -< -Yeah. I know it looks complicated. Bear with me. I probably will try to add -in some shortcuts for this syntax, but this verbose will be guaranteed to -always work. - -You should already recognize the name being assigned. The next thing to -happen is / \{2,}/ which is a pattern specifying which lines should -automatically be included in the range when no range is given. Without this, -there would be no pattern to use for extending the range. Everything after -that is a | separated list of expressions to be evaluated. In the context in -which they will be evaluated, a:lines will be set to a List of Strings -containing the text of the lines being filtered as they procede through the -pipeline you've set up. The \ at the start of the lines are just vim's line -continuation marker; you needn't worry much about them. So, the first -expression in the pipeline transforms each line by replacing every instance of -2 or more spaces with exactly two spaces. The second command in the pipeline -performs the equivalent of ":Tabularize / /l0"; the only difference is that -it is operating on a List of Strings rather than text in the buffer. At the -end of the pipeline, the Strings in the modified a:lines (or the return value -of the last expression in the pipeline, if it returns a List) will replace the -chosen range. - -============================================================================== -3. Extending *tabular-scripting* - -As mentioned above, the most important consideration when extending Tabular -with new maps or commands is that your plugin must be loaded after Tabular.vim -has finished loading, and only if Tabular.vim has loaded successfully. The -easiest approach to making sure it loads after Tabular.vim is simply putting -the new file (we'll call it "tabular_extra.vim" as an example) into an -"after/plugin/" directory in 'runtimepath', for instance: -> - ~/.vim/after/plugin/tabular_extra.vim -< -The default set of mappings, found in "TabularMaps.vim", is installed in -the after/plugin/ subdirectory of whatever directory Tabular was installed to. - -The other important consideration is making sure that your commands are only -called if Tabular.vim was actually loaded. The easiest way to do this is by -checking for the existence of the :Tabularize command at the start of your -plugin. A short example plugin would look like this: -> - " after/plugin/my_tabular_commands.vim - " Provides extra :Tabularize commands - - if !exists(':Tabularize') - finish " Give up here; the Tabular plugin musn't have been loaded - endif - - " Make line wrapping possible by resetting the 'cpo' option, first saving it - let s:save_cpo = &cpo - set cpo&vim - - AddTabularPattern! asterisk /*/l1 - - AddTabularPipeline! remove_leading_spaces /^ / - \ map(a:lines, "substitute(v:val, '^ *', '', '')") - - " Restore the saved value of 'cpo' - let &cpo = s:save_cpo - unlet s:save_cpo -< -============================================================================== -vim:tw=78:fo=tcq2:isk=!-~,^*,^\|,^\":ts=8:ft=help:norl: diff --git a/vim/doc/fuf.jax b/vim/doc/fuf.jax deleted file mode 100644 index 072afcc455..0000000000 --- a/vim/doc/fuf.jax +++ /dev/null @@ -1,1149 +0,0 @@ -*fuf.jax* バッファ/ファイル/その他を、あいまい検索 - - Copyright (c) 2007-2009 Takeshi NISHIDA - -FuzzyFinder *fuzzyfinder* *fuf* - -概要 |fuf-introduction| -インストール |fuf-installation| -使い方 |fuf-usage| -モード |fuf-modes| -詳細なトピック |fuf-detailed-topics| -コマンド |fuf-commands| -オプション |fuf-options| -VIMRC の例 |fuf-vimrc-example| -SPECIAL THANKS |fuf-thanks| -CHANGELOG |fuf-changelog| -あばうと |fuf-about| - -============================================================================== -概要 *fuf-introduction* - -FuzzyFinder はバッファ/ファイル/コマンド/ブックマーク/タグに素早くアクセスする -ための手段を提供します。入力されたパターンから変換されたあいまいパターンまたは -部分一致パターンで検索を行います。 - - 入力パターン あいまいパターン 部分一致パターン ~ -> - abc *a*b*c* *abc* - dir/file dir/*f*i*l*e* dir/*file* - d*r/file d*r/*f*i*l*e* d*r/*file* - ../**/s ../**/*s* ../**/*s* - (** : 再帰検索) -< -次のような場面で有用です: - - "./AhLongLongLongLongLongFile.txt" - "./AhLongLongLongLongLongName.txt" - "./OhLongLongLongLongLongFile.txt" - "./OhLongLongLongLongLongName.txt" <- 欲しいファイル :-O - -"ON" と入力すれば "OhLongLongLongLongLongName.txt" が選択できます. :-D - -FuzzyFinder が検索できる対象は次の通りです: - - バッファ - - ファイル - - ディレクトリ - - 最近使ったファイル - - 最近使ったコマンドライン - - ブックマーク - - タグ - - タグファイルに含まれるファイル - - ジャンプリスト - - チェンジリスト - - バッファの行 - - quickfix - - ヘルプ - -FuzzyFinder は ファイルを検索したりアイテムを選択するシステムを利用するための -API も提供します。 - -FuzzyFinder はマルチバイト文字をサポートしています。 - - -============================================================================== -インストール *fuf-installation* - -ZIPファイルをランタイムディレクトリに展開します。 - -以下のようにファイルが配置されるはずです。 -> - <ランタイムディレクトリ>/plugin/fuf.vim - <ランタイムディレクトリ>/autoload/fuf.vim - <ランタイムディレクトリ>/autoload/fuf/buffer.vim - ... -< -もしランタイムディレクトリが他のプラグインとごた混ぜになるのが嫌なら、ファイル -を新規ディレクトリに配置し、そのディレクトリのパスを 'runtimepath' に追加して -ください。アンインストールも楽になります。 - -その後 FuzzyFinder のヘルプを有効にするためにタグファイルを更新してください。 -詳しくは|add-local-help|を参照してください。 - -============================================================================== -使い方 *fuf-usage* - -次のコマンドで FuzzyFinder を起動します: - - コマンド モード ~ - |:FufBuffer| - Buffer モード (|fuf-buffer-mode|) - |:FufFile| - File モード (|fuf-file-mode|) - |:FufDir| - Directory モード (|fuf-dir-mode|) - |:FufMruFile| - MRU-File モード (|fuf-mrufile-mode|) - |:FufMruCmd| - MRU-Command モード (|fuf-mrucmd-mode|) - |:FufBookmark| - Bookmark モード (|fuf-bookmark-mode|) - |:FufTag| - Tag モード (|fuf-tag-mode|) - |:FufTaggedFile| - Tagged-File モード (|fuf-taggedfile-mode|) - |:FufJumpList| - Jump-List モード (|fuf-jumplist-mode|) - |:FufChangeList| - Change-List モード (|fuf-changelist-mode|) - |:FufQuickfix| - Quickfix モード (|fuf-quickfix-mode|) - |:FufLine| - Line モード (|fuf-line-mode|) - |:FufHelp| - Help モード (|fuf-help-mode|) - -これらのコマンドを押しやすいキーにマッピングすることを推奨します。 - -これらのコマンドを実行するとパターンを入力するための1行のバッファを開き、イン -サートモードを開始します。 - -FuzzyFinder は入力されたパターンにマッチするアイテムを検索し、それを補完メニュ -ーに表示します。パターンマッチングの詳細は|fuf-search-patterns|を参照してくだ -さい。 - -多くのアイテムがマッチングする場合、FuzzyFinder はレスポンスを向上させるために -列挙するアイテムの数(|g:fuf_enumeratingLimit|)を制限し、その際、入力されたパタ -ーンを"Error" グループでハイライトします。 - -補完メニューの最初のアイテムは自動的に選択状態になります。 - - (|g:fuf_keyPrevPattern|) と (|g:fuf_keyNextPattern|) で、履歴から -過去に入力したパターンを呼び出すことができます。 - -いろいろな方法で、選択されたアイテムを開くことができます: - - (|g:fuf_keyOpen|) - 直前のウィンドウで開きます。 - (|g:fuf_keyOpenSplit|) - ウィンドウを分割して開きます。 - (|g:fuf_keyOpenVsplit|) - ウィンドウを垂直分割して開きます。 - (|g:fuf_keyOpenTabpage|) - 別のタブページで開きます。 - -キャンセルして直前のウィンドウに戻るには、インサートモードを抜けてください。 - - (|g:fuf_keySwitchMatching|) で、検索方法をあいまいマッチングまたは -部分一致マッチングに交互に切り替えることができます。 - - (|g:fuf_keyNextMode|) と (|g:fuf_keyPrevMode|) で、インサートモー -ドを抜けることなくカレントモードを切り替えることが出来ます。 - -いくつかのモードでは、選択されたアイテムを (|g:fuf_keyPreview|) でプレビ -ューすることができます。同じアイテムでキーを繰り返すことで別の情報を表示させる -ことができます。プレビューをサポートするモードを起動すると、コマンドラインの高 -さが|g:fuf_previewHeight|になります。 - - -============================================================================== -モード *fuf-modes* - - *fuf-buffer-mode* -Buffer モード ~ - -このモードはバッファを選択して開くインターフェースを提供します。 - - *fuf-file-mode* -File モード ~ - -このモードはファイルを検索して開くインターフェースを提供します。 - - *fuf-dir-mode* -Directory モード ~ - -このモードはディレクトリを検索してカレントディレクトリを変更するインターフェー -スを提供します。 - - *fuf-mrufile-mode* -MRU-File モード ~ - -このモードは最近使ったファイルを選択して開くインターフェースを提供します。 - -|BufEnter| と |BufWritePost| で行う処理がパフォーマンス上の問題を起こしうるの -で、デフォルトでは|g:fuf_modesDisable|で無効化するモードに指定されています。 - - *fuf-mrucmd-mode* -MRU-Command モード ~ - -このモードは最近使ったコマンドラインを選択して開くインターフェースを提供します -。 -このモードに必要な、コマンドラインモードの のマッピングに副作用があるので、 -、デフォルトでは|g:fuf_modesDisable|で無効化するモードに指定されています。 - - *fuf-bookmark-mode* -Bookmark モード ~ - -このモードは事前に追加したブックマークを選択してその行へジャンプするインターフ -ェースを提供します。 - -|:FufAddBookmark|コマンドでカーソルのある行をブックマークに追加できます。この -コマンドを実行すると、ブックマーク名の入力を求められます。 - -FuzzyFinder はジャンプする行番号を調整します。ブックマークされた行がブックマー -クされたときのパターンとマッチしない場合、FuzzyFinder はブックマークされた位置 -の周辺でマッチする行を探します。なのでブックマークした行が多少移動していたとし -ても、そこでジャンプすることができます。ブックマークした行番号へ調整せずにジャ -ンプしたい場合、|g:fuf_bookmark_searchRange|を 0 に設定してください。 - -Bookmark モード中に (|g:fuf_bookmark_keyDelete|) を押すと選択したブックマ -ークを削除することができます。 - - *fuf-tag-mode* -Tag モード ~ - -このモードはタグを選択してその定義へジャンプするインターフェースを提供します。 - -以下は を置き換えるマッピングです。 -> - noremap :FufTagWithCursorWord! -< - - *fuf-taggedfile-mode* -Tagged-File モード ~ - -このモードはタグファイルに含まれるファイルを選択して開くインターフェースを提供 -します。 - - *fuf-jumplist-mode* -Jump-List モード ~ - -このモードはカレントウィンドウの|jumplist|から選択した位置へジャンプするインタ -ーフェースを提供します。 - - *fuf-changelist-mode* -Change-List モード ~ - -このモードはカレントバッファの|changelist|から選択した位置へジャンプするインタ -ーフェースを提供します。 - - *fuf-quickfix-mode* -Quickfix モード ~ - -このモードは|quickfix|リストから選択した位置へジャンプするインターフェースを提 -供します。 - - *fuf-line-mode* -Line モード ~ - -このモードはカレントバッファの行を選択してジャンプするインターフェースを提供し -ます。 - - *fuf-help-mode* -Help モード ~ - -このモードはヘルプタグを選択してそのヘルプページへジャンプするインターフェース -を提供します。 - - *fuf-givenfile-mode* -Given-File モード ~ - -このモードは与えられたリストから選択されたファイルを開く API を提供します。 - -API 関数: -> - function fuf#givenfile#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - FuzzyFinder 起動直後に挿入される文字列 - partialMatching - あいまい検索ではなく部分一致検索を行うか - prompt - プロンプト文字列 - items - アイテムのリスト - -利用例: -> - " ドットファイルを開く - call fuf#givenfile#launch('', 0, '>', split(glob('~/.*'), "\n")) -< - - *fuf-givendir-mode* -Given-Directory モード ~ - -このモードは与えられたリストから選択されたディレクトリにカレントディレクトリを -変更する API を提供します。 - -API 関数: -> - function fuf#givendir#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - FuzzyFinder 起動直後に挿入される文字列 - partialMatching - あいまい検索ではなく部分一致検索を行うか - prompt - プロンプト文字列 - items - アイテムのリスト - - -利用例: -> - " ランタイムディレクトリのどれかをカレントディレクトリにする - call fuf#givendir#launch('', 0, '>', split(&runtimepath, ',')) -< - - *fuf-givencmd-mode* -Given-Command モード ~ - -このモードは与えられたリストから選択されたコマンドを実行する API を提供します。 - -選択されたコマンドは feedkeys() によって実行されるので、ノーマルモードでの一連 -のキー入力をエミュレートさせることも可能です。 - -API 関数: -> - function fuf#givencmd#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - FuzzyFinder 起動直後に挿入される文字列 - partialMatching - あいまい検索ではなく部分一致検索を行うか - prompt - プロンプト文字列 - items - アイテムのリスト - - -利用例: -> - function GetAllCommands() - redir => commands - silent command - redir END - return map((split(commands, "\n")[3:]), - \ '":" . matchstr(v:val, ''^....\zs\S*'')') - endfunction - - " ユーザー定義コマンドを選択して実行 - call fuf#givencmd#launch('', 0, '>', GetAllCommands()) - -< - - *fuf-callbackfile-mode* -Callback-File モード ~ - -このモードはファイルを検索して選択されたファイルパスを得る API を提供します。 - -API 関数: -> - function fuf#callbackfile#launch( - \ initialPattern, partialMatching, prompt, exclude, listener) -< - initialPattern - FuzzyFinder 起動直後に挿入される文字列 - partialMatching - あいまい検索ではなく部分一致検索を行うか - prompt - プロンプト文字列 - exclude - 補完リストから除外したいアイテムの正規表現パターン - listener - 'onComplete' と 'onAbort' を持つ|Dictionary|。これ - らは FuzzyFinder 終了時に呼ばれます。 - listener.onComplete(item, method) は選択が完了したと - き、選択されたアイテム名とオープン方式番号の2引数と - 共に呼ばれます。listener.onAbort() は選択を中止した - ときに呼ばれます。 - -利用例: -> - let listener = {} - - function listener.onComplete(item, method) - echo "Item: " . a:item . "\nMethod: " . a:method - endfunction - - function listener.onAbort() - echo "Abort" - endfunction - - " カレントディレクトリからファイルを選択 - call fuf#callbackfile#launch('', 0, '>', '', listener) - - " ホームディレクトリからファイルを選択 - call fuf#callbackfile#launch('~/', 0, '>', '', listener) -< - - *fuf-callbackitem-mode* -Callback-Item モード ~ - -このモードは与えられたリストから選択されたアイテムを得るための API を提供しま -す。 - -API 関数: -> - function fuf#callbackitem#launch( - \ initialPattern, partialMatching, prompt, listener, items, forPath) -< - initialPattern - FuzzyFinder 起動直後に挿入される文字列 - partialMatching - あいまい検索ではなく部分一致検索を行うか - prompt - プロンプト文字列 - listener - 'onComplete' と 'onAbort' を持つ|Dictionary|。これ - らは FuzzyFinder 終了時に呼ばれます。 - listener.onComplete(item, method) は選択が完了したと - き、選択されたアイテム名とオープン方式番号の2引数と - 共に呼ばれます。listener.onAbort() は選択を中止した - ときに呼ばれます。 - items - アイテムのリスト - forPath - ファイル選択に特化したマッチングを利用するか - -利用例: -> - let listener = {} - - function listener.onComplete(item, method) - echo "Item: " . a:item . "\nMethod: " . a:method - endfunction - - function listener.onAbort() - echo "Abort" - endfunction - - " 与えられたリストからアイテムを選択 - call fuf#callbackitem#launch('', 0, '>', listener, ['ed', 'vi', 'vim'], 0) - - " 与えられたリストからファイルを選択 - call fuf#callbackitem#launch('', 0, '>', listener, ['../foo/bar', 'baz'], 1) -< - -============================================================================== -詳細なトピック *fuf-detailed-topics* - - *fuf-search-patterns* -検索パターン ~ - -検索パターンとして、一つのプライマリパターンと0個以上の絞り込みパターンを入力 -することができます。入力パターンは ";" (|g:fuf_patternSeparator|) で区切られ、 -最初のパターンがプライマリパターンになり、残りのパターンが絞り込みパターンにな -ります。 -> - プライマリ 絞り込み 絞り込み - |----------| |-------| |----| - >MruFile>bookmark.vim;autoload/;/home/ -< -プライマリパターンにマッチしたアイテムのリストを別のパターンで絞り込むために、 -絞り込みパターンを利用します。 - -プライマリパターンでは、あいまいマッチングと部分一致マッチングのうち、選択され -た方を行います。絞り込みパターンでは、常に部分一致マッチングを行います。 - -絞り込みパターンとして数値を入力した場合、アイテムのインデックスに対しても -マッチングします。 - -ファイルパスの静的な集合を対象とするモード (Buffer, MRU-File モードなど。File, -Directory モードなどではない) で|g:fuf_splitPathMatching|が真の場合、プライマ -リパターンのマッチングは head 部とtail 部に分けて行われます。 -> - head tail - |------||-----| - foo/bar/baz.vim - - あいまいマッチング例: - +----------------+---------+---------+---------+ - | item \ pattern | foo/bar | foo/ | bar | - +----------------+---------+---------+---------+ - | foo/bar | match | match | match | - | foo/abc | unmatch | match | unmatch | - | abc/bar | unmatch | unmatch | match | - | foobar | unmatch | unmatch | match | - | foooo/barrrr | match | match | match | - | foooo/fooooo | unmatch | match | unmatch | - +----------------+---------+---------+---------+ -< -上記のケースで、絞り込みパターンはパス全体に対してマッチングできます。 - - *fuf-sorting-of-completion-items* -補完アイテムのソート ~ - -FuzzyFinder は幾つかのルールに従って補完アイテムをソートします。 - -パターン全体が一部分にぴったりマッチするアイテムは優先されます。例えば、パター -ン "bc" ではアイテム "abc" は "bac" より優先されます。 - -このケースで、マッチする部分が先頭であるアイテムはそうでないアイテムより優先さ -れます。例えばパターン "foo" ではアイテム "foobar" は"barfoo" より優先されます -。 - -マッチング位置より後の文字数が少ないほど優先されます。例えばパターン "bar" で -はアイテム"foobar" は"foobarbaz"より優先されます。 - -単語の境界文字にだけマッチングするアイテムは優先されます。 例えば、パターン -"fb" ではアイテム"fooBarBaz" や "foo_bar_baz" などが優先されます。 - -加えて、FuzzyFinder には学習システムがあります。現在のパターンで、過去に補完さ -れたことのあるアイテムを優先します。 - - *fuf-reusing-window* -目的のバッファ/ファイルが開かれているウィンドウの再利用 ~ - -ウィンドウを分割してバッファ/ファイルを開くときに、現在のタブページでそれが開 -かれているウィンドウが見つかった場合、そこへ移動します。別のタブページでバッフ -ァ/ファイルを開くときに、他のタブページでそれが開かれているウィンドウが見つか -った場合、そこへ移動します。 - -常にバッファ/ファイルを新ウィンドウで開きたい場合、'reuse_window'オプションで -この機能を無効にすることができます。 - - *fuf-hiding-menu* -補完メニューの一時非表示 ~ - - で補完メニューを閉じることができます。また、で再度開くことがで -きます。 - - *fuf-abbreviation* *fuf-multiple-search* -短縮入力及び複合検索 ~ - -|g:fuf_abbrevMap|を設定することで、全モードで短縮入力と複合検索が利用できます。 - -例えば次のように設定したとします: -> - let g:fuf_abbrevMap = { - \ "^doc:" : [ - \ "~/project/**/doc/", - \ ".vim/doc/", - \ ], - \ } -< -そして File モードで "doc:txt" と入力すると、次の2つのパターンの検索結果を複合 -します: - - "~/project/**/doc/*t*x*t*" - ".vim/doc/*t*x*t*" - - *fuf-information-file* -情報ファイル ~ - -FuzzyFinder は補完統計、MRUデータ、ブックマークなどを -|g:fuf_infoFile|に書き込みます。 - -:FufEditInfo コマンドは情報ファイルの編集を補助します。このコマンドを -実行すると、情報ファイルを無名バッファに読み込みます。:write などで書き込みを -行うと、情報ファイルを更新します。 - - *fuf-cache* -キャッシュ ~ - -一旦キャッシュが生成されると、レスポンスを向上させるため自動的には更新されませ -ん。これを更新するには|:FufRenewCache|コマンドを実行してください。 - - *fuf-dot-sequence* -ドット列で親ディレクトリへ移動 ~ - -ドット列を入力することで親ディレクトリを上がっていくことができます。パス区切り -文字直後のドット列は "../" の列に展開されます。 - - ドット列 展開パターン ~ - /.. /../ - /... /../../ - /.... /../../../ - - *fuf-migemo* -Migemo とは ~ - -以下のページを参照してください。 - - http://0xcc.net/migemo/ - - http://www.kaoriya.net/#CMIGEMO - - -============================================================================== -コマンド *fuf-commands* - -See also: |fuf-vimrc-example| - - *:FufBuffer* -:FufBuffer [{pattern}] - Buffer モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufFile* -:FufFile [{pattern}] - File モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufFileWithFullCwd* -:FufFileWithFullCwd [{pattern}] - カレントディレクトリのフルパスを初期パターンとする以外は|:FufFile|と同 - じです。 - - *:FufFileWithCurrentBufferDir* -:FufFileWithCurrentBufferDir [{pattern}] - カレントバッファのディレクトリを初期パターンとする以外は|:FufFile|と同 - じです。 - - *:FufDir* -:FufDir [{pattern}] - Directory モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufDirWithFullCwd* -:FufDirWithFullCwd [{pattern}] - カレントディレクトリのフルパスを初期パターンとする以外は|:FufDir|と同 - じです。 - - *:FufDirWithCurrentBufferDir* -:FufDirWithCurrentBufferDir [{pattern}] - カレントバッファのディレクトリを初期パターンとする以外は|:FufDir|と同 - じです。 - - *:FufMruFile* -:FufMruFile [{pattern}] - MRU-File モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufMruCmd* -:FufMruCmd [{pattern}] - MRU-Command モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufBookmark* -:FufBookmark [{pattern}] - Bookmark モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufTag* -:FufTag [{pattern}] - Tag モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufTagWithCursorWord* -:FufTagWithCursorWord [{pattern}] - カーソル下の単語を初期パターンとする以外は|:FufTag|と同じです。 - - *:FufTaggedFile* -:FufTaggedFile [{pattern}] - Tagged-File モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufJumpList* -:FufJumpList [{pattern}] - Jump-List モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufChangeList* -:FufChangeList [{pattern}] - Change-List モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufQuickfix* -:FufQuickfix [{pattern}] - Quickfix モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufLine* -:FufLine [{pattern}] - Line モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufHelp* -:FufHelp[!] [{pattern}] - Help モードを起動します。 - - ! 修飾子を付けて実行した場合、あいまい検索ではなく部分一致検索を行うよ - うになります。 - - FuzzyFinder 起動後に {pattern} が挿入されます。 - - *:FufEditInfo* -:FufEditInfo - 情報ファイルを編集するためのバッファを開きます。詳しくは - |fuf-information-file|を参照してください。 - - *:FufAddBookmark* -:FufAddBookmark [{name}] - カーソル行をブックマークに追加します。詳しくは|fuf-adding-bookmark|を - 参照してください。 - - *:FufAddBookmarkAsSelectedText* -:FufAddBookmarkAsSelectedText - 最後に選択されたテキストをブックマーク名とする以外は|:FufAddBookmark| - と同じです。 - - *:FufRenewCache* -:FufRenewCache - 補完アイテムを作り直すためにキャッシュを削除します。詳しくは - |fuf-cache|を参照してください。 - - -============================================================================== -オプション *fuf-options* - - *fuf-options-for-all-modes* -全モード用 ~ - - *g:fuf_modesDisable* > - let g:fuf_modesDisable = [ 'mrufile', 'mrucmd', ] -< - 無効にするモード名のリスト。これに含まれるモードは初期化されず、イベン - トの処理も行われません。 - - *g:fuf_keyOpen* > - let g:fuf_keyOpen = '' -< - 補完を確定し、バッファ/ファイルを直前のウィンドウで開くキー。 - - *g:fuf_keyOpenSplit* > - let g:fuf_keyOpenSplit = '' -< - 補完を確定し、バッファ/ファイルを直前のウィンドウを分割して開くキー。 - - *g:fuf_keyOpenVsplit* > - let g:fuf_keyOpenVsplit = '' -< - 補完を確定し、バッファ/ファイルを直前のウィンドウを垂直分割して開くキ - ー。 - - *g:fuf_keyOpenTabpage* > - let g:fuf_keyOpenTabpage = '' -< - 補完を確定し、バッファ/ファイルを別タブページ開くキー。 - - *g:fuf_keyPreview* > - let g:fuf_keyPreview = '' -< - 選択されている補完アイテムの情報をコマンドライン領域に表示するキー。プ - レビューをサポートするモードでのみ作用します。 - - *g:fuf_keyNextMode* > - let g:fuf_keyNextMode = '' -< - 次のモードに切り替えるキー。 - - *g:fuf_keyPrevMode* > - let g:fuf_keyPrevMode = '' -< - 前のモードに切り替えるキー。 - - *g:fuf_keyPrevPattern* > - let g:fuf_keyPrevPattern = '' -< - 履歴から前の入力パターンを呼び出すキー。 - - *g:fuf_keyNextPattern* > - let g:fuf_keyNextPattern = '' -< - 履歴から次の入力パターンを呼び出すキー。 - - *g:fuf_keySwitchMatching* > - let g:fuf_keySwitchMatching = '' -< - あいまいマッチングと部分一致マッチングを切り替えるキー。 - - *g:fuf_infoFile* > - let g:fuf_infoFile = '~/.vim-fuf' -< - 補完統計、MRUデータ、ブックマークなどを書き込むファイル。空文字列を設 - 定するとファイルへの書き込みは行われなくなります。 - - *g:fuf_abbrevMap* > - let g:fuf_abbrevMap = {} -< - |Dictionary|型でそれぞれの値は|List|型です。入力されたテキストの、キー - にマッチする部分が対応する値に展開されます。 - - *g:fuf_patternSeparator* > - let g:fuf_patternSeparator = ';' -< - 入力パターンをプライマリパターンと絞り込みパターン列に区切る文字列。 - - *g:fuf_promptHighlight* > - let g:fuf_promptHighlight = 'Question' -< - プロンプトをハイライトするグループ名。 - - *g:fuf_ignoreCase* > - let g:fuf_ignoreCase = 1 -< - 真なら、大文字小文字を無視します。 - - *g:fuf_splitPathMatching* > - let g:fuf_splitPathMatching = 1 -< - 真なら、プライマリパターンのマッチングは head 部とtail 部に分けて行わ - れます。 - - See also: |fuf-search-patterns| - - *g:fuf_smartBs* > - let g:fuf_smartBs = 1 -< - 真なら、パス区切り文字の直後で を入力するとディレクトリ名1つ分を - 削除し、|g:fuf_patternSeparator|の直後で を入力するとパターン1つ分 - を削除します。 - - *g:fuf_reuseWindow* > - let g:fuf_reuseWindow = 1 -< - 真なら、すでに開かれているバッファを開くとき、目的のバッファを含むウィ - ンドウを再利用します。 - - *g:fuf_timeFormat* > - let g:fuf_timeFormat = '(%Y-%m-%d %H:%M:%S)' -< - アイテムが登録された日時の書式を設定します。書式の詳細は|strftime()|を - 参照してください。 - - *g:fuf_learningLimit* > - let g:fuf_learningLimit = 100 -< - 保持する補完統計データのモード毎の上限値です。 - - *g:fuf_enumeratingLimit* > - let g:fuf_enumeratingLimit = 50 -< - レスポンスを向上させるため、補完アイテムの列挙をこの数に達した時点で打 - ち切ります。 - - *g:fuf_maxMenuWidth* > - let g:fuf_maxMenuWidth = 78 -< - 長い補完アイテムは、この長さに収まるよう省略して表示します。 - - *g:fuf_previewHeight* > - let g:fuf_previewHeight = 5 -< - プレビューをサポートするモードを起動したとき、'cmdheight'がこの値に設 - 定されます。選択されている補完アイテムの情報がコマンドライン領域に表示 - されます。0 ならプレビュー機能は無効になります。 - - *g:fuf_useMigemo* > - let g:fuf_useMigemo = 0 -< - 真なら migemo を利用します。 - - *fuf-options-for-buffer-mode* -Buffer モード用 ~ - - *g:fuf_buffer_prompt* > - let g:fuf_buffer_prompt = '>Buffer[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_buffer_switchOrder* > - let g:fuf_buffer_switchOrder = 10 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_buffer_mruOrder* > - let g:fuf_buffer_mruOrder = 1 -< - 真なら、最後に使った時間順に補完アイテムをソートします。 - - *fuf-options-for-file-mode* -File モード用 ~ - - *g:fuf_file_prompt* > - let g:fuf_file_prompt = '>File[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_file_switchOrder* > - let g:fuf_file_switchOrder = 20 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_file_exclude* > - let g:fuf_file_exclude = '\v\~$|\.(o|exe|bak|swp)$|(^|[/\\])\.(hg|git|bzr)($|[/\\])' -< - 補完リストから除外したいアイテムの正規表現パターン。 - - *fuf-options-for-dir-mode* -Directory モード用 ~ - - *g:fuf_dir_prompt* > - let g:fuf_dir_prompt = '>Dir[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_dir_switchOrder* > - let g:fuf_dir_switchOrder = 30 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_dir_exclude* > - let g:fuf_dir_exclude = '\v(^|[/\\])\.(hg|git|bzr)($|[/\\])' -< - 補完リストから除外したいアイテムの正規表現パターン。 - - *fuf-options-for-mrufile-mode* -Mru-File モード用 ~ - - *g:fuf_mrufile_prompt* > - let g:fuf_mrufile_prompt = '>Mru-File[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_mrufile_switchOrder* > - let g:fuf_mrufile_switchOrder = 40 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_mrufile_exclude* > - let g:fuf_mrufile_exclude = '\v\~$|\.(bak|sw[po])$|^(\/\/|\\\\|\/mnt\/|\/media\/)' -< - 補完リストから除外したいアイテムの正規表現パターン。 - - *g:fuf_mrufile_maxItem* > - let g:fuf_mrufile_maxItem = 200 -< - 保持するMRUアイテムの上限値。 - - *fuf-options-for-mrucmd-mode* -Mru-Cmd モード用 ~ - - *g:fuf_mrucmd_prompt* > - let g:fuf_mrucmd_prompt = '>Mru-Cmd[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_mrucmd_switchOrder* > - let g:fuf_mrucmd_switchOrder = 50 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_mrucmd_exclude* > - let g:fuf_mrucmd_exclude = '^$' -< - 補完リストから除外したいアイテムの正規表現パターン。 - - *g:fuf_mrucmd_maxItem* > - let g:fuf_mrucmd_maxItem = 200 -< - 保持するMRUアイテムの上限値。 - - *fuf-options-for-Bookmark-mode* -Bookmark モード用 ~ - - *g:fuf_bookmark_prompt* > - let g:fuf_bookmark_prompt = '>Bookmark[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_bookmark_switchOrder* > - let g:fuf_bookmark_switchOrder = 60 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_bookmark_searchRange* > - let g:fuf_bookmark_searchRange = 400 -< - ジャンプするとき、ブックマークした位置からこの行数の範囲内でブックマー - クしたときのパターンとマッチする行を探します。 - - *g:fuf_bookmark_keyDelete* > - let g:fuf_bookmark_keyDelete = '' -< - 選択したブックマークを削除するキー。 - - *fuf-options-for-tag-mode* -Tag モード用 ~ - - *g:fuf_tag_prompt* > - let g:fuf_tag_prompt = '>Tag[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_tag_switchOrder* > - let g:fuf_tag_switchOrder = 70 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_tag_cache_dir* > - let g:fuf_tag_cache_dir = '~/.vim-fuf-cache/tag' -< - このディレクトリ内にキャッシュファイルが作成されます。空文字列なら作成 - されません。 - - *fuf-options-for-taggedfile-mode* -Tagged-File モード用 ~ - - *g:fuf_taggedfile_prompt* > - let g:fuf_taggedfile_prompt = '>Tagged-File[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_taggedfile_switchOrder* > - let g:fuf_taggedfile_switchOrder = 80 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_taggedfile_cache_dir* > - let g:fuf_taggedfile_cache_dir = '~/.vim-fuf-cache/taggedfile' -< - このディレクトリ内にキャッシュファイルが作成されます。空文字列なら作成 - されません。 - - *fuf-options-for-jumplist-mode* -Jump-List モード用 ~ - - *g:fuf_jumplist_prompt* > - let g:fuf_jumplist_prompt = '>Jump-List[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_jumplist_switchOrder* > - let g:fuf_jumplist_switchOrder = 90 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *fuf-options-for-changelist-mode* -Change-List モード用 ~ - - *g:fuf_changelist_prompt* > - let g:fuf_changelist_prompt = '>Change-List[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_changelist_switchOrder* > - let g:fuf_changelist_switchOrder = 100 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *fuf-options-for-quickfix-mode* -Quickfix モード用 ~ - - *g:fuf_quickfix_prompt* > - let g:fuf_quickfix_prompt = '>Quickfix[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_quickfix_switchOrder* > - let g:fuf_quickfix_switchOrder = 110 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *fuf-options-for-line-mode* -Line モード用 ~ - - *g:fuf_line_prompt* > - let g:fuf_line_prompt = '>Line[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_line_switchOrder* > - let g:fuf_line_switchOrder = 120 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *fuf-options-for-help-mode* -Help モード用 ~ - - *g:fuf_help_prompt* > - let g:fuf_help_prompt = '>Help[]>' -< - プロンプト文字列。"[]" はインジケータに置換されます。 - - *g:fuf_help_switchOrder* > - let g:fuf_help_switchOrder = 130 -< - 次/前のモードに切り替えるときの、モードの順位です。負数ならこのモード - には切り替えません。 - - *g:fuf_help_cache_dir* > - let g:fuf_help_cache_dir = '~/.vim-fuf-cache/help' -< - このディレクトリ内にキャッシュファイルが作成されます。空文字列なら作成 - されません。 - - -============================================================================== -vimrc の例 *fuf-vimrc-example* - -> - let g:fuf_modesDisable = [] - let g:fuf_abbrevMap = { - \ '^vr:' : map(filter(split(&runtimepath, ','), 'v:val !~ "after$"'), 'v:val . ''/**/'''), - \ '^m0:' : [ '/mnt/d/0/', '/mnt/j/0/' ], - \ } - let g:fuf_mrufile_maxItem = 300 - let g:fuf_mrucmd_maxItem = 400 - nnoremap :FufBuffer - nnoremap :FufFileWithCurrentBufferDir - nnoremap :FufFileWithFullCwd - nnoremap p :FufFile - nnoremap :FufDirWithCurrentBufferDir - nnoremap d :FufDirWithFullCwd - nnoremap D :FufDir - nnoremap :FufMruFile - nnoremap :FufMruCmd - nnoremap :FufBookmark - nnoremap :FufTag - nnoremap t :FufTag! - noremap g] :FufTagWithCursorWord! - nnoremap :FufTaggedFile - nnoremap :FufJumpList - nnoremap :FufChangeList - nnoremap :FufQuickfix - nnoremap :FufLine - nnoremap :FufHelp - nnoremap :FufAddBookmark - vnoremap :FufAddBookmarkAsSelectedText - nnoremap :FufEditInfo - nnoremap :FufRenewCache -< - -============================================================================== -あばうと *fuf-about* *fuf-contact* *fuf-author* - -作者: Takeshi NISHIDA -ライセンス: MIT Licence -URL: http://www.vim.org/scripts/script.php?script_id=1984 - http://bitbucket.org/ns9tks/vim-fuzzyfinder/ - -バグや要望など ~ - -こちらへどうぞ: http://bitbucket.org/ns9tks/vim-fuzzyfinder/issues/ - -============================================================================== - vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/fuf.txt b/vim/doc/fuf.txt deleted file mode 100644 index d6d64c0f65..0000000000 --- a/vim/doc/fuf.txt +++ /dev/null @@ -1,1562 +0,0 @@ -*fuf.txt* buffer/file/command/tag/etc explorer with fuzzy matching. - - Copyright (c) 2007-2009 Takeshi NISHIDA - -FuzzyFinder *fuzzyfinder* *fuf* - -INTRODUCTION |fuf-introduction| -INSTALLATION |fuf-installation| -USAGE |fuf-usage| -MODES |fuf-modes| -DETAILED TOPICS |fuf-detailed-topics| -COMMANDS |fuf-commands| -OPTIONS |fuf-options| -VIMRC EXAMPLE |fuf-vimrc-example| -SPECIAL THANKS |fuf-thanks| -CHANGELOG |fuf-changelog| -ABOUT |fuf-about| - -============================================================================== -INTRODUCTION *fuf-introduction* - -FuzzyFinder provides convenient ways to quickly reach the -buffer/file/command/bookmark/tag you want. FuzzyFinder searches with the -fuzzy/partial pattern to which it converted an entered pattern. - - Entered pattern Fuzzy pattern Partial pattern ~ -> - abc *a*b*c* *abc* - dir/file dir/*f*i*l*e* dir/*file* - d*r/file d*r/*f*i*l*e* d*r/*file* - ../**/s ../**/*s* ../**/*s* - (** allows searching a directory tree.) -< -You will be happy when: - - "./AhLongLongLongLongLongFile.txt" - "./AhLongLongLongLongLongName.txt" - "./OhLongLongLongLongLongFile.txt" - "./OhLongLongLongLongLongName.txt" <- you want :O - -Type "ON" and "OhLongLongLongLongLongName.txt" will be select. :D - -FuzzyFinder can search: - - - buffers - - files - - directories - - most recently used files - - most recently used command-lines - - bookmarks - - tags - - files which are included in current tagfiles - - jump list - - change list - - buffer lines - - quickfix - - help - -FuzzyFinder also provides APIs to use its system of searching files or -selecting items. - -FuzzyFinder supports multibyte characters. - - -============================================================================== -INSTALLATION *fuf-installation* - -Put all files into your runtime directory. If you have the zip file, extract -it to your runtime directory. - -You should place the files as follows: -> - /plugin/fuf.vim - /autoload/fuf.vim - /autoload/fuf/buffer.vim - ... -< -If you disgust to jumble up this plugin and other plugins in your runtime -directory, put the files into new directory and just add the directory path to -'runtimepath'. It's easy to uninstall the plugin. - -And then update your help tags files to enable fuzzyfinder help. See -|add-local-help| for details. - -============================================================================== -USAGE *fuf-usage* - -You can launch FuzzyFinder by following commands: - - Command Mode ~ - |:FufBuffer| - Buffer mode (|fuf-buffer-mode|) - |:FufFile| - File mode (|fuf-file-mode|) - |:FufDir| - Directory mode (|fuf-dir-mode|) - |:FufMruFile| - MRU-File mode (|fuf-mrufile-mode|) - |:FufMruCmd| - MRU-Command mode (|fuf-mrucmd-mode|) - |:FufBookmark| - Bookmark mode (|fuf-bookmark-mode|) - |:FufTag| - Tag mode (|fuf-tag-mode|) - |:FufTaggedFile| - Tagged-File mode (|fuf-taggedfile-mode|) - |:FufJumpList| - Jump-List mode (|fuf-jumplist-mode|) - |:FufChangeList| - Change-List mode (|fuf-changelist-mode|) - |:FufQuickfix| - Quickfix mode (|fuf-quickfix-mode|) - |:FufLine| - Line mode (|fuf-line-mode|) - |:FufHelp| - Help mode (|fuf-help-mode|) - -It is recommended to map these commands. - -These commands open 1-line buffer to enter search pattern and start insert -mode. - -FuzzyFinder searchs for matching items with an entered pattern and shows them -in a completion menu. For more details on pattern matching, see -|fuf-search-patterns|. - -If there are a lot of matching items, FuzzyFinder limits the number of -enumerating items (|g:fuf_enumeratingLimit|) to speed up a response time, and -highlights the pattern with "Error" group. - -The first item in the completion menu will be selected automatically. - -with (|g:fuf_keyPrevPattern|) and (|g:fuf_keyNextPattern|), You -can recall patterns which have been entered before from history. - -You can open a selected item in various ways: - - (|g:fuf_keyOpen|) - opens in a previous window. - (|g:fuf_keyOpenSplit|) - opens in a split window. - (|g:fuf_keyOpenVsplit|) - opens in a vertical-split window. - (|g:fuf_keyOpenTabpage|) - opens in a new tab page. - -To cancel and return to previous window, just leave Insert mode. - -With (|g:fuf_keySwitchMatching|), You can switch search method -between fuzzy matching and partial matching. - -With (|g:fuf_keyNextMode|) and (|g:fuf_keyPrevMode|), You can -switch current mode without leaving Insert mode . - -You can preview selected item with (|g:fuf_keyPreview|) in some modes. -Repeating the key on the same item might show another information. The height -of command-line area is changed to |g:fuf_previewHeight| when you launch a -mode supporting preview. - - -============================================================================== -MODES *fuf-modes* - - *fuf-buffer-mode* -Buffer mode ~ - -This mode provides an interface to select a buffer from a list of existing -buffers and open it. - - *fuf-file-mode* -File mode ~ - -This mode provides an interface to search a file and open it. - - *fuf-dir-mode* -Directory mode ~ - -This mode provides an interface to search a directory and change the current -directory. - - *fuf-mrufile-mode* -MRU-File mode ~ - -This mode provides an interface to select a file from most recently used files -and open it. - -This mode is set to disable in |g:fuf_modesDisable| by default because -processes for this mode in |BufEnter| and |BufWritePost| could cause -Performance issue. - - *fuf-mrucmd-mode* -MRU-Command mode ~ - -This mode provides an interface to select a command from most recently used -commands and execute it. - -This mode is set to disable in |g:fuf_modesDisable| by default because mapping - of Command-line mode required by this mode has side effects. - - *fuf-bookmark-mode* -Bookmark mode ~ - -This mode provides an interface to select one of the bookmarks you have added -beforehand and jump there. - -You can add a cursor line to bookmarks by |:FufAddBookmark| command. -Execute that command and you will be prompted to enter a bookmark name. - -FuzzyFinder adjusts a line number for jump. If a line of bookmarked position -does not match to a pattern when the bookmark was added, FuzzyFinder searches -a matching line around bookmarked position. So you can jump to a bookmarked -line even if the line is out of bookmarked position. If you want to jump to -bookmarked line number without the adjustment, set -|g:fuf_bookmark_searchRange| option to 0. - -Press (|g:fuf_bookmark_keyDelete|) in Bookmark mode and selected -bookmark will be deleted. - - *fuf-tag-mode* -Tag mode ~ - -This mode provides an interface to select a tag and jump to the definition of -it. - -Following mapping is the replacement for : -> - noremap :FufTagWithCursorWord! -< - - *fuf-taggedfile-mode* -Tagged-File mode ~ - -This mode provides an interface to select one of the files which are included -in current tagfiles and open it. - - *fuf-jumplist-mode* -Jump-List mode ~ - -This mode provides an interface to select one from the |jumplist| of the -current window and jump there. - - *fuf-changelist-mode* -Change-List mode ~ - -This mode provides an interface to select one from the |changelist| of the -current buffer and jump there. - - *fuf-quickfix-mode* -Quickfix mode ~ - -This mode provides an interface to select one from the |quickfix| list and -jump there. - - *fuf-line-mode* -Line mode ~ - -This mode provides an interface to select a line from current buffer and jump -there. - - *fuf-help-mode* -Help mode ~ - -This mode provides an interface to select a help tag and jump to the help -page. - - *fuf-givenfile-mode* -Given-File mode ~ - -This mode provides an API to open a selected file from a given list. - -API function: -> - function fuf#givenfile#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - String which is inserted after launching - FuzzyFinder. - partialMatching - If non-zero, enable partial matching instead of - fuzzy matching. - prompt - Prompt string - items - List of items. - -Example of use: -> - " Open one of your dotfiles. - call fuf#givenfile#launch('', 0, '>', split(glob('~/.*'), "\n")) -< - - *fuf-givendir-mode* -Given-Directory mode ~ - -This mode provides an API to change current working directory to a selected -one from a given list. - -API function: -> - function fuf#givendir#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - String which is inserted after launching - FuzzyFinder. - partialMatching - If non-zero, enable partial matching instead of - fuzzy matching. - prompt - Prompt string - items - List of items. - - -Example of use: -> - " Change current working directory to one of your runtime directory. - call fuf#givendir#launch('', 0, '>', split(&runtimepath, ',')) -< - - *fuf-givencmd-mode* -Given-Command mode ~ - -This mode provides an API to execute a selected command from a given list. - -A selected command is executed by |feedkeys()|, so it is able to emulate a -series of key input in Normal mode. - -API function: -> - function fuf#givencmd#launch( - \ initialPattern, partialMatching, prompt, items) -< - initialPattern - String which is inserted after launching - FuzzyFinder. - partialMatching - If non-zero, enable partial matching instead of - fuzzy matching. - prompt - Prompt string - items - List of items. - - -Example of use: -> - function GetAllCommands() - redir => commands - silent command - redir END - return map((split(commands, "\n")[3:]), - \ '":" . matchstr(v:val, ''^....\zs\S*'')') - endfunction - - " execute one of the user-defined commands - call fuf#givencmd#launch('', 0, '>', GetAllCommands()) - -< - - *fuf-callbackfile-mode* -Callback-File mode ~ - -This mode provides an API to find and get a file path which is selected by an -user. - -API function: -> - function fuf#callbackfile#launch( - \ initialPattern, partialMatching, prompt, exclude, listener) -< - initialPattern - String which is inserted after launching - FuzzyFinder. - partialMatching - If non-zero, enable partial matching instead of - fuzzy matching. - prompt - Prompt string. - exclude - Regexp pattern for items which you want to exclude - from completion list. - listener - |Dictionary| which has 'onComplete' and 'onAbort'. - They are called at the end of FuzzyFinder. - listener.onComplete(item, method) is called with 2 - arguments which are a name of selected item and a - number of open method when completed. - listener.onAbort() is called when aborted. - -Example of use: -> - let listener = {} - - function listener.onComplete(item, method) - echo "Item: " . a:item . "\nMethod: " . a:method - endfunction - - function listener.onAbort() - echo "Abort" - endfunction - - " Find a file from current working directory. - call fuf#callbackfile#launch('', 0, '>', '', listener) - - " Find a file from home directory. - call fuf#callbackfile#launch('~/', 0, '>', '', listener) -< - - *fuf-callbackitem-mode* -Callback-Item mode ~ - -This mode provides an API to get an item which is selected from a given list -by an user. - -API function: -> - function fuf#callbackitem#launch( - \ initialPattern, partialMatching, prompt, listener, items, forPath) -< - initialPattern - String which is inserted after launching - FuzzyFinder. - partialMatching - If non-zero, enable partial matching instead of - fuzzy matching. - prompt - Prompt string - listener - |Dictionary| which has 'onComplete' and 'onAbort'. - They are called at the end of FuzzyFinder. - listener.onComplete(item, method) is called with 2 - arguments which are a name of selected item and a - number of open method when completed. - listener.onAbort() is called when aborted. - items - List of items. - forPath - If non-zero, use a matching method for files. - -Example of use: -> - let listener = {} - - function listener.onComplete(item, method) - echo "Item: " . a:item . "\nMethod: " . a:method - endfunction - - function listener.onAbort() - echo "Abort" - endfunction - - " Select an item from a given list. - call fuf#callbackitem#launch('', 0, '>', listener, ['ed', 'vi', 'vim'], 0) - - " Select a file from a given list. - call fuf#callbackitem#launch('', 0, '>', listener, ['../foo/bar', 'baz'], 1) -< - -============================================================================== -DETAILED TOPICS *fuf-detailed-topics* - - *fuf-search-patterns* -Search Patterns ~ - -You can enter one primary pattern and zero or more refining patterns as search -patterns. An entered pattern is separated by ";" (|g:fuf_patternSeparator|), -and the first pattern is a primary pattern and the rest of patterns is a -refining pattern. -> - primary refining refining - |----------| |-------| |----| - >MruFile>bookmark.vim;autoload/;/home/ -< -A refining pattern is used to narrow down the list of matching items by -another pattern. - -With a primary pattern, FuzzyFinder does fuzzy matching or partial matching, -which you specified. With a refining pattern, FuzzyFinder always does partial -matching. - -When you enter a number as refining pattern, it also can match the index of -each item. - -In a mode which targets a static set of file paths (such as Buffer or MRU-File -mode, not File or Directory) and |g:fuf_splitPathMatching| is non-zero, -matching with a primary pattern is divided into head part and tail part and -done individually. -> - head tail - |------||-----| - foo/bar/baz.vim - - fuzzy matching example: - +----------------+---------+---------+---------+ - | item \ pattern | foo/bar | foo/ | bar | - +----------------+---------+---------+---------+ - | foo/bar | match | match | match | - | foo/abc | unmatch | match | unmatch | - | abc/bar | unmatch | unmatch | match | - | foobar | unmatch | unmatch | match | - | foooo/barrrr | match | match | match | - | foooo/fooooo | unmatch | match | unmatch | - +----------------+---------+---------+---------+ -< -refining pattern can match anywhere on each path in the above case. - - *fuf-sorting-of-completion-items* -Sorting Of Completion Items ~ - -FuzzyFinder sorts completion items with some rules. - -An item, one part of which is matched with a whole pattern, is placed upper. -E.g., with the pattern "bc", the item "abc" is placed upper than "bac". - -In the above case, items, each having matching part at the head of itself, are -placed upper than others. E.g., with the pattern "foo", the item "foobar" is -placed upper than "foobarbaz". - -And the shorter the length of the item after matching position puts it higher. -E.g., with the pattern "bar", the item "foobar" is placed upper than -"foobarbaz". - -If a pattern matches an item at only word boundaries of it, the item is placed -upper. E.g., with a pattern "fb", items such as "fooBarBaz" and "foo_bar_baz" -is placed upper. - -Plus, FuzzyFinder has a learning system. An item which has been completed in -the past with current pattern is placed upper. - - *fuf-reusing-window* -Reusing Of A Window Containing Target Buffer/File ~ - -If a window containing target buffer is found in current tab page when -FuzzyFinder is going to open the buffer in a split new window, move to it. If -a window containing target buffer is found in other tab page when FuzzyFinder -is going to open the buffer in a new tab page, move to it. - -You can disable that feature via 'reuse_window' options if always want to open -a buffer in a new window. - - *fuf-hiding-menu* -To Hide The Completion Menu Temporarily In FuzzyFinder ~ - -You can close it by and reopen it by . - - *fuf-abbreviation* *fuf-multiple-search* -Abbreviations And Multiple Search ~ - -You can use abbreviations and multiple search in all modes by setting -|g:fuf_abbrevMap| option. - -For example, set as below: -> - let g:fuf_abbrevMap = { - \ "^doc:" : [ - \ "~/project/**/doc/", - \ ".vim/doc/", - \ ], - \ } -< -and enter "doc:txt" in File mode, then FuzzyFinder searches by following -patterns: - - "~/project/**/doc/*t*x*t*" - ".vim/doc/*t*x*t*" - -and show concatenated search results. - - *fuf-information-file* -Information File ~ - -FuzzyFinder writes completion statistics, MRU data, bookmark, etc to -|g:fuf_infoFile|. - -|:FufEditInfo| command is helpful in editing your information file. -This command reads the information file in new unnamed buffer. Write the -buffer and the information file will be updated. - - *fuf-cache* -Cache ~ - -Once a cache was created, It is not automatically updated to speed up the -response time by default. To update it, use |:FufRenewCache| command. - - *fuf-dot-sequence* -Going Up Parent Directories With Dot Sequence ~ - -You can go up parent directories with entering dot sequence. Dot sequence -after a path separator is expanded to "../" sequence. - - Dot sequence Expanded pattern ~ - /.. /../ - /... /../../ - /.... /../../../ - - *fuf-migemo* -What Is Migemo ~ - -Migemo is a search method for Japanese language. - - -============================================================================== -COMMANDS *fuf-commands* - -See also: |fuf-vimrc-example| - - *:FufBuffer* -:FufBuffer[!] [{pattern}] - Launchs Buffer mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufFile* -:FufFile[!] [{pattern}] - Launchs File mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufFileWithFullCwd* -:FufFileWithFullCwd[!] [{pattern}] - Is mostly the same as |:FufFile|, except that initial pattern is a - full path of current working directory. - - *:FufFileWithCurrentBufferDir* -:FufFileWithCurrentBufferDir[!] [{pattern}] - Is mostly the same as |:FufFile|, except that initial pattern is a - path of directory current buffer is in. - - *:FufDir* -:FufDir[!] [{pattern}] - Launchs Directory mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufDirWithFullCwd* -:FufDirWithFullCwd[!] [{pattern}] - Is mostly the same as |:FufDir|, except that initial pattern is a full - path of current working directory. - - *:FufDirWithCurrentBufferDir* -:FufDirWithCurrentBufferDir[!] [{pattern}] - Is mostly the same as |:FufDir|, except that initial pattern is a path - of directory current buffer is in. - - *:FufMruFile* -:FufMruFile[!] [{pattern}] - Launchs MRU-File mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufMruCmd* -:FufMruCmd[!] [{pattern}] - Launchs MRU-Command mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufBookmark* -:FufBookmark[!] [{pattern}] - Launchs Bookmark mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufTag* -:FufTag[!] [{pattern}] - Launchs Tag mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufTagWithCursorWord* -:FufTagWithCursorWord[!] [{pattern}] - Is mostly the same as |:FufTag|, except that - - *:FufTaggedFile* -:FufTaggedFile[!] [{pattern}] - Launchs Tagged-File mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufJumpList* -:FufJumpList[!] [{pattern}] - Launchs Jump-List mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufChangeList* -:FufChangeList[!] [{pattern}] - Launchs Change-List mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufQuickfix* -:FufQuickfix[!] [{pattern}] - Launchs Quickfix mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufLine* -:FufLine[!] [{pattern}] - Launchs Line mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufHelp* -:FufHelp[!] [{pattern}] - Launchs Help mode. - - If a command was executed with a ! modifier, it does partial matching - instead of fuzzy matching. - - {pattern} will be inserted after launching FuzzyFinder. - - *:FufEditInfo* -:FufEditInfo - Opens a buffer for editing your information file. See - |fuf-information-file| for details. - - *:FufAddBookmark* -:FufAddBookmark [{name}] - Adds a cursor line to bookmarks. See |fuf-adding-bookmark| for - details. - - *:FufAddBookmarkAsSelectedText* -:FufAddBookmarkAsSelectedText - Is mostly the same as |:FufAddBookmark|, except that initial pattern - is last selected one. - - *:FufRenewCache* -:FufRenewCache - Removes caches to renew completion items. See |fuf-cache| for details. - - -============================================================================== -OPTIONS *fuf-options* - - *fuf-options-for-all-modes* -For All Modes ~ - - *g:fuf_modesDisable* > - let g:fuf_modesDisable = [ 'mrufile', 'mrucmd', ] -< - List of mode names to disable. - - Modes which are listed will never be initialized and never handle any - event. - - *g:fuf_keyOpen* > - let g:fuf_keyOpen = '' -< - Key mapped to select completion item or finish input and open a - buffer/file in previous window. - - *g:fuf_keyOpenSplit* > - let g:fuf_keyOpenSplit = '' -< - Key mapped to select completion item or finish input and open a - buffer/file in split new window - - *g:fuf_keyOpenVsplit* > - let g:fuf_keyOpenVsplit = '' -< - Key mapped to select completion item or finish input and open a - buffer/file in vertical-split new window. - - *g:fuf_keyOpenTabpage* > - let g:fuf_keyOpenTabpage = '' -< - - Key mapped to select completion item or finish input and open a - buffer/file in a new tab page. - - *g:fuf_keyPreview* > - let g:fuf_keyPreview = '' -< - - Key mapped to show information of selected completion item on - command-line area. This key makes sense only in modes supporting - preview. - - *g:fuf_keyNextMode* > - let g:fuf_keyNextMode = '' -< - Key mapped to switch to next mode. - - *g:fuf_keyPrevMode* > - let g:fuf_keyPrevMode = '' -< - Key mapped to switch to previous mode. - - *g:fuf_keyPrevPattern* > - let g:fuf_keyPrevPattern = '' -< - Key mapped to recall previous entered patten from history. - - *g:fuf_keyNextPattern* > - let g:fuf_keyNextPattern = '' -< - Key mapped to recall next entered patten from history. - - *g:fuf_keySwitchMatching* > - let g:fuf_keySwitchMatching = '' -< - Key mapped to switch between fuzzy matching and partial matching. - - *g:fuf_infoFile* > - let g:fuf_infoFile = '~/.vim-fuf' -< - Filename to write completion statistics, MRU data, bookmark, etc. If - empty string, FuzzyFinder does not write to a file. - - *g:fuf_abbrevMap* > - let g:fuf_abbrevMap = {} -< - |Dictionary|. Each value must be a |List|. All matchs of a - key in entered text is expanded with the value. - - *g:fuf_patternSeparator* > - let g:fuf_patternSeparator = ';' -< - String which sparates a input pattern into a primary pattern and - refining patterns. - - *g:fuf_promptHighlight* > - let g:fuf_promptHighlight = 'Question' -< - a highlight group name for a prompt string. - - *g:fuf_ignoreCase* > - let g:fuf_ignoreCase = 1 -< - If non-zero, FuzzyFinder ignores case in search patterns. - - *g:fuf_splitPathMatching* > - let g:fuf_splitPathMatching = 1 -< - If non-zero, matching with a primary pattern is divided into head part - and tail part and done individually. - - See also: |fuf-search-patterns| - - *g:fuf_smartBs* > - let g:fuf_smartBs = 1 -< - If non-zero, pressing after a path separator deletes one - directory name and pressing after |g:fuf_patternSeparator| - deletes one pattern. - - *g:fuf_reuseWindow* > - let g:fuf_reuseWindow = 1 -< - If non-zero and when FuzzyFinder opens a buffer which has already been - opened, it reuses a window containing the target buffer. - - *g:fuf_timeFormat* > - let g:fuf_timeFormat = '(%Y-%m-%d %H:%M:%S)' -< - String to format time string. See |strftime()| for details. - - *g:fuf_learningLimit* > - let g:fuf_learningLimit = 100 -< - Ceiling for the number of completion statistics to be stored. - - *g:fuf_enumeratingLimit* > - let g:fuf_enumeratingLimit = 50 -< - To speed up the response time, FuzzyFinder ends enumerating completion - items when found over this. - - *g:fuf_maxMenuWidth* > - let g:fuf_maxMenuWidth = 78 -< - If a length of a completion item is more than this, it is snipped in - completion menu. - - *g:fuf_previewHeight* > - let g:fuf_previewHeight = 5 -< - 'cmdheight' is set to this when a mode supporting preview is launched. - Information of selected completion item will be shown on command-line - area. If zero, preview feature is disabled. - - *g:fuf_useMigemo* > - let g:fuf_useMigemo = 0 -< - If non-zero, FuzzyFinder uses Migemo. - - *fuf-options-for-buffer-mode* -For Buffer Mode ~ - - *g:fuf_buffer_prompt* > - let g:fuf_buffer_prompt = '>Buffer[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_buffer_switchOrder* > - let g:fuf_buffer_switchOrder = 10 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_buffer_mruOrder* > - let g:fuf_buffer_mruOrder = 1 -< - If non-zero, completion items is sorted in order of recently used. - - *fuf-options-for-file-mode* -For File Mode ~ - - *g:fuf_file_prompt* > - let g:fuf_file_prompt = '>File[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_file_switchOrder* > - let g:fuf_file_switchOrder = 20 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_file_exclude* > - let g:fuf_file_exclude = '\v\~$|\.(o|exe|dll|bak|swp)$|(^|[/\\])\.(hg|git|bzr)($|[/\\])' -< - Regexp pattern for items which you want to exclude from completion - list. - - *fuf-options-for-dir-mode* -For Directory Mode ~ - - *g:fuf_dir_prompt* > - let g:fuf_dir_prompt = '>Dir[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_dir_switchOrder* > - let g:fuf_dir_switchOrder = 30 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_dir_exclude* > - let g:fuf_dir_exclude = '\v(^|[/\\])\.(hg|git|bzr)($|[/\\])' -< - Regexp pattern for items which you want to exclude from completion - list. - - *fuf-options-for-mrufile-mode* -For Mru-File Mode ~ - - *g:fuf_mrufile_prompt* > - let g:fuf_mrufile_prompt = '>Mru-File[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_mrufile_switchOrder* > - let g:fuf_mrufile_switchOrder = 40 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_mrufile_exclude* > - let g:fuf_mrufile_exclude = '\v\~$|\.(bak|sw[po])$|^(\/\/|\\\\|\/mnt\/|\/media\/)' -< - Regexp pattern for items which you want to exclude from completion - list. - - *g:fuf_mrufile_maxItem* > - let g:fuf_mrufile_maxItem = 200 -< - Ceiling for the number of MRU items to be stored. - - *fuf-options-for-mrucmd-mode* -For Mru-Cmd Mode ~ - - *g:fuf_mrucmd_prompt* > - let g:fuf_mrucmd_prompt = '>Mru-Cmd[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_mrucmd_switchOrder* > - let g:fuf_mrucmd_switchOrder = 50 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_mrucmd_exclude* > - let g:fuf_mrucmd_exclude = '^$' -< - Regexp pattern for items which you want to exclude from completion - list. - - *g:fuf_mrucmd_maxItem* > - let g:fuf_mrucmd_maxItem = 200 -< - This is the ceiling for the number of MRU items to be stored. - - *fuf-options-for-Bookmark-mode* -For Bookmark Mode ~ - - *g:fuf_bookmark_prompt* > - let g:fuf_bookmark_prompt = '>Bookmark[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_bookmark_switchOrder* > - let g:fuf_bookmark_switchOrder = 60 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_bookmark_searchRange* > - let g:fuf_bookmark_searchRange = 400 -< - Number of lines which FuzzyFinder searches a matching line from - bookmarked position within. - - *g:fuf_bookmark_keyDelete* > - let g:fuf_bookmark_keyDelete = '' -< - Key mapped to delete selected bookmark. - - *fuf-options-for-tag-mode* -For Tag Mode ~ - - *g:fuf_tag_prompt* > - let g:fuf_tag_prompt = '>Tag[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_tag_switchOrder* > - let g:fuf_tag_switchOrder = 70 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_tag_cache_dir* > - let g:fuf_tag_cache_dir = '~/.vim-fuf-cache/tag' -< - Cache files are created in this directory. If empty, they are not - created. - - *fuf-options-for-taggedfile-mode* -For Tagged-File Mode ~ - - *g:fuf_taggedfile_prompt* > - let g:fuf_taggedfile_prompt = '>Tagged-File[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_taggedfile_switchOrder* > - let g:fuf_taggedfile_switchOrder = 80 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_taggedfile_cache_dir* > - let g:fuf_taggedfile_cache_dir = '~/.vim-fuf-cache/taggedfile' -< - Cache files are created in this directory. If empty, they are not - created. - - *fuf-options-for-jumplist-mode* -For Jump-List Mode ~ - - *g:fuf_jumplist_prompt* > - let g:fuf_jumplist_prompt = '>Jump-List[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_jumplist_switchOrder* > - let g:fuf_jumplist_switchOrder = 90 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *fuf-options-for-changelist-mode* -For Change-List Mode ~ - - *g:fuf_changelist_prompt* > - let g:fuf_changelist_prompt = '>Change-List[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_changelist_switchOrder* > - let g:fuf_changelist_switchOrder = 100 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *fuf-options-for-quickfix-mode* -For Quickfix Mode ~ - - *g:fuf_quickfix_prompt* > - let g:fuf_quickfix_prompt = '>Quickfix[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_quickfix_switchOrder* > - let g:fuf_quickfix_switchOrder = 110 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *fuf-options-for-line-mode* -For Line Mode ~ - - *g:fuf_line_prompt* > - let g:fuf_line_prompt = '>Line[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_line_switchOrder* > - let g:fuf_line_switchOrder = 120 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *fuf-options-for-help-mode* -For Help Mode ~ - - *g:fuf_help_prompt* > - let g:fuf_help_prompt = '>Help[]>' -< - Prompt string. "[]" will be substituted with indicators. - - *g:fuf_help_switchOrder* > - let g:fuf_help_switchOrder = 130 -< - Number of order for switching to the next/previous mode. If negative - number, Fuzzyfinder never switches to this mode. - - *g:fuf_help_cache_dir* > - let g:fuf_help_cache_dir = '~/.vim-fuf-cache/help' -< - Cache files are created in this directory. If empty, they are not - created. - - -============================================================================== -VIMRC EXAMPLE *fuf-vimrc-example* - -> - let g:fuf_modesDisable = [] - let g:fuf_abbrevMap = { - \ '^vr:' : map(filter(split(&runtimepath, ','), 'v:val !~ "after$"'), 'v:val . ''/**/'''), - \ '^m0:' : [ '/mnt/d/0/', '/mnt/j/0/' ], - \ } - let g:fuf_mrufile_maxItem = 300 - let g:fuf_mrucmd_maxItem = 400 - nnoremap :FufBuffer - nnoremap :FufFileWithCurrentBufferDir - nnoremap :FufFileWithFullCwd - nnoremap p :FufFile - nnoremap :FufDirWithCurrentBufferDir - nnoremap d :FufDirWithFullCwd - nnoremap D :FufDir - nnoremap :FufMruFile - nnoremap :FufMruCmd - nnoremap :FufBookmark - nnoremap :FufTag - nnoremap t :FufTag! - noremap g] :FufTagWithCursorWord! - nnoremap :FufTaggedFile - nnoremap :FufJumpList - nnoremap :FufChangeList - nnoremap :FufQuickfix - nnoremap :FufLine - nnoremap :FufHelp - nnoremap :FufAddBookmark - vnoremap :FufAddBookmarkAsSelectedText - nnoremap :FufEditInfo - nnoremap :FufRenewCache -< - -============================================================================== -SPECIAL THANKS *fuf-thanks* - -- Vincent Wang -- Ingo Karkat -- Nikolay Golubev -- Brian Doyle -- id:secondlife -- Nathan Neff - - -============================================================================== -CHANGELOG *fuf-changelog* - -3.5: - - Added Line mode. - - Added Help mode. - - Added key mapping to switch between fuzzy matching and partial matching. - - Changed the default values of g:fuf_file_exclude for ignoring "*.dll". - - Changed Tag mode and Tagged-File mode to cache parsed data to files in - "~/.vim-fuf-cache/". - - Fixed a bug that repeating preview key produced no effect. - - Fixed a bug that File mode and Directory mode didn't list items in a - directory whose name includes uppercase characters. (Thanks, ryo7000) - -3.4: - - Added new feature which makes it possible to preview selected completion - item. - - Changed matching rules and added g:fuf_splitPathMatching. - - Changed sorting rules. - - Changed the default values of g:fuf_file_exclude and g:fuf_dir_exclude in - order to ignore ".hg", ".git", and ".bzr" directories. - - Changed the default value of g:fuf_mrufile_exclude in order to ignore - network files (\\*) on Windows and ignore /mnt/* and /media/* on Unix like - systems. - - Fixed a bug that an exclude pattern of File, Dir, and Callback-File mode - can't be changed. - -3.3: - - Added Jump-List mode, Change-List mode, and Quickfix mode which enable - jumps with jump list, change list, and quickfix list. - - Added new feature which deletes selected bookmark with FuzzyFinder and - g:fuf_bookmark_keyDelete option. - - Changed default values of g:fuf_keyPrevPattern. - - Changed to show error message when incompatible with a installed vim. - -3.2: - - Added g:fuf_promptHighlight option to integrate such options for each - mode. - - Changed APIs of Given-File, Given-Directory, Given-Command, Callback-File, - and Callback-Item modes to be able to set a prompt string. - - Changed default values of g:fuf_keyPrevPattern and g:fuf_keyNextPattern. - - Fixed a bug that MRU-File data was not updated When a file was opened with - FuzzyFinder. - - Fixed a bug with scoring matchings for sorting. Thanks to Vincent. - - Brought back the removed feature which is switching to an other mode in - FuzzyFinder. - -3.1: - - Added new feature to recall patterns which have been entered before from - history. - -3.0: - - Redesigned the whole plugin for improvements of maintainability and - performance. "fuzzyfinder" is abbreviated to "fuf" in the sorce code and - filenames. All commands and options are renamed. - - Added new feature which is refining pattern. - - Improved the rules for sorting completion items. Thanks to the suggestion - by Nathan, the rule for boundary matching was implemented. - - Changed to open one line buffer of FuzzyFinder with :topleft command - instead of :leftabove. The window will alway appear at the top and occupy - the full with of the vim window. Thanks to Jan Christoph. - - Changed default filename of information file. - - Changed MRU-File mode and MRU-Command mode to be disabled by default - due to performance and side effect issues. - - Removed the feature which is switching to an other mode in FuzzyFinder. - - Removed the feature which is temporarily switching 'ignorecase' in - FuzzyFinder. - -2.22.3: - - Fixed a bug that Fuzzyfinder could not open files with '$' in the name on - Windows. - -2.22.2: - - Changed to consider a length of a date/time string when abbreviates long - completion items. - - Fixed a bug that '**/' pattern did not search for files directly under the - current working directory in File mode. Thanks to Martin for reporting. - -2.22.1: - - Fixed a bug that Fuzzyfinder could not expand abbreviations to patterns - including '\' correctly. - - Fixed to show item number in Given-File, Given-Directory, and - Given-Command mode. - -2.22.0: - - More improved the abbreviation method for long completion items. - - Added Given-File mode for third-party script to select a file from a given - list and open. - - Added Given-Directory mode for third-party script to select a directory - from a given list and change current working directory to it. - - Added Given-Command mode for third-party script to select a command from a - given list and execute. - - Changed ways to launch Callback-File mode and Callback-item mode. - -2.21.0: - - Improved a method of trimming long completion items. Thanks to Andy, - pyrhockz, and Nathan. - - Changed not to map command-line for MRU-Command mode if - g:FuzzyFinderOptions.MruCmd.mode_available is set 0 before loading - fuzzyfinder.vim. - - Added Callback-File mode and Callback-Item mode for third-party script to - find a file/directory or an item from a given list using Fuzzyfinder. - - Changed not to append ".." to a completion menu in File/Directory mode. - Use dot sequence feature. - - Changed default value of g:FuzzyFinderOptions.File.excluded_path option. - - Changed default value of g:FuzzyFinderOptions.Dir.excluded_path option. - - Fixed a bug that couldn't jump to a tag. Thanks to Thinca. - -2.20: - - Added help files which are doc/fuzzyfinder.txt and doc/fuzzyfinder.jax. - - Fixed a bug that an error occurs if current directory included spaces. - Thanks id:cho45 and id:secondlife. - - Implemented a feature to reuse a window containing target buffer. - - Added g:FuzzyFinderOptions.Buffer.reuse_window option. - - Added g:FuzzyFinderOptions.File.reuse_window option. - - Added g:FuzzyFinderOptions.MruFile.reuse_window option. - - Added g:FuzzyFinderOptions.Bookmark.reuse_window option. - - Added g:FuzzyFinderOptions.TaggedFile.reuse_window option. - - Changed to use 'omnifunc' instead of 'completefunc'. Now you can use - to delete all entered characters. - - Changed default value of g:FuzzyFinderOptions.Base.key_open_tab option. - - Changed default value of g:FuzzyFinderOptions.Base.key_next_mode option. - - Changed default value of g:FuzzyFinderOptions.Base.key_prev_mode option. - - Changed default value of g:FuzzyFinderOptions.Base.key_ignore_case option. - - Changed to truncate long completion items from the head instead of tail. - - Added g:FuzzyFinderOptions.Base.max_menu_width option instead of - g:FuzzyFinderOptions.Base.trim_length option. - - Added :FuzzyFinderFileWithFullCwd command. - - Added :FuzzyFinderFileWithCurrentBufferDir command. - - Added :FuzzyFinderDirWithFullCwd command. - - Added :FuzzyFinderDirWithCurrentBufferDir command. - - Added :FuzzyFinderTagWithCursorWord command. - - Renamed :FuzzyFinderRemoveCache command to :FuzzyFinderRenewCache. - -2.19: - - Changed MRU-File mode that always formats completion items to be relative - to the home directory. - - Fixed a bug that a file was opened in an unintended window with Tag List - plugin. Thanks Alexey. - - Fixed a bug that garbage characters were entered when switched current - mode. Thanks id:lugecy. - -2.18: - - Improved rules for the sorting of completion items. - - Changed not to learn a completion if an entered pattern is empty. - - Fixed a bug that Buffer mode did not work. Thanks ryo7000. - -2.17: - - Introduced a learning system for the sorting of completion items. - - Added g:FuzzyFinderOptions.Base.learning_limit option. - - Changed the specification of the information file. Please remove your - information file for Fuzzyfinder. - -2.16: - - Improved response time by caching in MRU-File mode. - - Fixed a bug in Bookmark mode that Fuzzyfinder did not jump to the - Bookmarked line number when Bookmarked pattern was not found. - -2.15: - - Added Bookmark mode. - - Removed Favorite-file mode. Use Bookmark mode instead. - - Fixed not to record a entry of input() in MRU-Command mode. - -2.14: - - Changed to show buffer status in Buffer mode. - - Fixed a bug that an error occurs when nonexistent buffer-name was entered - in Buffer mode. Thanks Maxim Kim. - - Added 'enumerating_limit' option. Thanks id:secondlife. - - Removed 'matching_limit' option. Use 'enumerating_limit' instead. - -2.13: - - Fixed a bug that a directory disappeared when a file in that directory was - being opened in File/Mru-File mode. - -2.12: - - Changed to be able to show completion items in the order of recently used - in Buffer mode. - - Added g:FuzzyFinderOptions.Buffer.mru_order option. - -2.11: - - Changed that a dot sequence of entered pattern is expanded to parent - directories in File/Dir mode. - E.g.: "foo/...bar" -> "foo/../../bar" - - Fixed a bug that a prompt string was excessively inserted. - -2.10: - - Changed not to show a current buffer in a completion menu. - - Fixed a bug that a filename to open was not been escaped. - - Added 'prompt' option. - - Added 'prompt_highlight' option. - - Removed g:FuzzyFinderOptions.MruFile.no_special_buffer option. - -2.9: - - Enhanced behavior in Fuzzyfinder and added 'smart_bs' option. - - Fixed a bug that entered pattern was not been escaped. - - Fixed not to insert "zv" with "c/pattern" command in Normal mode. - - Avoid the slow down problem caused by filereadable() check for the MRU - information in BufEnter/BufWritePost. - -2.8.1: - - Fixed a bug caused by the non-escaped buffer name "[Fuzzyfinder]". - - Fixed a command to open in a new tab page in Buffer mode. -2.8: - - Added 'trim_length' option. - - Added 'switch_order' option. - - Fixed a bug that entered command did not become the newest in the history. - - Fixed a bug that folds could not open with in a command-line when - searching. - - Removed 'excluded_indicator' option. Now a completion list in Buffer mode - is the same as a result of :buffers. - -2.7: - - Changed to find an item whose index is matched with the number suffixed - with entered pattern. - - Fixed the cache bug after changing current directory in File mode. - -2.6.2: - - Fixed not to miss changes in options when updates the MRU information. - -2.6.1: - - Fixed a bug related to floating-point support. - - Added support for GetLatestVimScripts. - -2.6: - - Revived MRU-command mode. The problem with a command-line abbreviation was - solved. - - Changed the specification of the information file. - - Added :FuzzyFinderEditInfo command. - -2.5.1: - - Fixed to be able to match "foo/./bar" by "foo/**/bar" in File mode. - - Fixed to be able to open a space-containing file in File mode. - - Fixed to honor the current working directory properly in File mode. - -2.5: - - Fixed the bug that a wrong initial text is entered after switching to a - next mode. - - Fixed the bug that it does not return to previous window after leaving - Fuzzyfinder one. - -2.4: - - Fixed the bug that Fuzzyfinder fails to open a file caused by auto-cd - plugin/script. - -2.3: - - Added a key mapping to open items in a new tab page and - g:FuzzyFinderOptions.Base.key_open_tab opton. - - Changed to show Fuzzyfinder window above last window even if 'splitbelow' - was set. - - Changed to set nocursorline and nocursorcolumn in Fuzzyfinder. - - Fixed not to push up a buffer number unlimitedly. - -2.2: - - Added new feature, which is the partial matching. - - Fixed the bug that an error occurs when "'" was entered. - -2.1: - - Restructured the option system AGAIN. Sorry :p - - Changed to inherit a typed text when switching a mode without leaving - Insert mode. - - Changed commands which launch explorers to be able to take a argument for - initial text. - - Changed to complete file names by relative path and not full path in the - buffer/mru-file/tagged-file mode. - - Changed to highlight a typed text when the completion item was not found - or the completion process was aborted. - - Changed to create caches for each tag file and not working directory in - the tag/tagged-file mode. - - Fixed the bug that the buffer mode couldn't open a unnamed buffer. - - Added 'matching_limit' option. - - Removed 'max_match' option. Use 'matching_limit' option instead. - - Removed 'initial_text' option. Use command argument instead. - - Removed the MRU-command mode. - -2.0: - - Added the tag mode. - - Added the tagged-file mode. - - Added :FuzzyFinderRemoveCache command. - - Restructured the option system. many options are changed names or default - values of some options. - - Changed to hold and reuse caches of completion lists by default. - - Changed to set filetype 'fuzzyfinder'. - - Disabled the MRU-command mode by default because there are problems. - - Removed FuzzyFinderAddMode command. - -1.5: - - Added the directory mode. - - Fixed the bug that it caused an error when switch a mode in Insert mode. - - Changed g:FuzzyFinder_KeySwitchMode type to a list. - -1.4: - - Changed the specification of the information file. - - Added the MRU-commands mode. - - Renamed :FuzzyFinderAddFavorite command to :FuzzyFinderAddFavFile. - - Renamed g:FuzzyFinder_MruModeVars option to g:FuzzyFinder_MruFileModeVars. - - Renamed g:FuzzyFinder_FavoriteModeVars option to - g:FuzzyFinder_FavFileModeVars. - - Changed to show registered time of each item in MRU/favorite mode. - - Added 'timeFormat' option for MRU/favorite modes. - -1.3: - - Fixed a handling of multi-byte characters. - -1.2: - - Added support for Migemo. (Migemo is Japanese search method.) - -1.1: - - Added the favorite mode. - - Added new features, which are abbreviations and multiple search. - - Added 'abbrevMap' option for each mode. - - Added g:FuzzyFinder_MruModeVars['ignoreSpecialBuffers'] option. - - Fixed the bug that it did not work correctly when a user have mapped - or . - -1.0: - - Added the MRU mode. - - Added commands to add and use original mode. - - Improved the sorting algorithm for completion items. - - Added 'initialInput' option to automatically insert a text at the - beginning of a mode. - - Changed that 'excludedPath' option works for the entire path. - - Renamed some options. - - Changed default values of some options. - - Packed the mode-specific options to dictionaries. - - Removed some options. - -0.6: - - Fixed some bugs. - -0.5: - - Improved response by aborting processing too many items. - - Changed to be able to open a buffer/file not only in previous window but - also in new window. - - Fixed a bug that recursive searching with '**' does not work. - - Added g:FuzzyFinder_CompletionItemLimit option. - - Added g:FuzzyFinder_KeyOpen option. - -0.4: - - Improved response of the input. - - Improved the sorting algorithm for completion items. It is based on the - matching level. 1st is perfect matching, 2nd is prefix matching, and 3rd - is fuzzy matching. - - Added g:FuzzyFinder_ExcludePattern option. - - Removed g:FuzzyFinder_WildIgnore option. - - Removed g:FuzzyFinder_EchoPattern option. - - Removed g:FuzzyFinder_PathSeparator option. - - Changed the default value of g:FuzzyFinder_MinLengthFile from 1 to 0. - -0.3: - - Added g:FuzzyFinder_IgnoreCase option. - - Added g:FuzzyFinder_KeyToggleIgnoreCase option. - - Added g:FuzzyFinder_EchoPattern option. - - Changed the open command in a buffer mode from ":edit" to ":buffer" to - avoid being reset cursor position. - - Changed the default value of g:FuzzyFinder_KeyToggleMode from to - because does not work on some CUI environments. - - Changed to avoid being loaded by Vim before 7.0. - - Fixed a bug with making a fuzzy pattern which has '\'. - -0.2: - - A bug it does not work on Linux is fixed. - -0.1: - - First release. - - -============================================================================== -ABOUT *fuf-about* *fuf-contact* *fuf-author* - -Author: Takeshi NISHIDA -Licence: MIT Licence -URL: http://www.vim.org/scripts/script.php?script_id=1984 - http://bitbucket.org/ns9tks/vim-fuzzyfinder/ - -Bugs/Issues/Suggestions/Improvements ~ - -Please submit to http://bitbucket.org/ns9tks/vim-fuzzyfinder/issues/ . - -============================================================================== - vim:tw=78:ts=8:ft=help:norl: diff --git a/vim/doc/fugitive.txt b/vim/doc/fugitive.txt deleted file mode 100755 index 8ba2e8beb3..0000000000 --- a/vim/doc/fugitive.txt +++ /dev/null @@ -1,226 +0,0 @@ -*fugitive.txt* A Git wrapper so awesome, it should be illegal - -Author: Tim Pope *fugitive-author* -License: Same terms as Vim itself (see |license|) - -This plugin is only available if 'compatible' is not set. - -INTRODUCTION *fugitive* - -Install in ~/.vim, or in ~\vimfiles if you're on Windows and feeling lucky. -Vim 7.2 is recommended as it ships with syntax highlighting for many Git file -types. - -If you're in a hurry to get started, here are some things to try: - -In any file in your repository, run |:Gedit| HEAD. Press to jump to the -current branch. Press again to jump to the top most commit. Keep using - to explore parent commits, trees, and blobs. Use C in a tree or blob to -get back to the commit. - -Edit a file in the work tree and make some changes. Use |:Gdiff| to open up -the indexed version. Use |do| and |dp| on various hunks to bring the files in -sync, or use |:Gread| to pull in all changes. Write the indexed version to -stage the file. - -Run |:Gstatus| to check your repository's status. Use "-" to stage and reset -files and "p" to add/reset --patch them. Invoke |:Gcommit| to commit your -changes. - -Run |:Gblame| in a work tree file to see a blame in a vertical split. Press - on any line to reopen and reblame that file as it stood in that commit. -Press o or O on any line to inspect that commit in a split or a tab. - -Run |:Ggrep| to search the work tree or history. Run |:Gmove| to rename a -file. Run |:Gremove| to delete a file. - -COMMANDS *fugitive-commands* - -These commands are local to the buffers in which they work (generally, buffers -that are part of Git repositories). - - *fugitive-:Git* -:Git [args] Run an arbitrary git command. Similar to :!git [args] - but chdir to the repository tree first. - - *fugitive-:Gcd* -:Gcd [directory] |:cd| relative to the repository. - - *fugitive-:Glcd* -:Glcd [directory] |:lcd| relative to the repository. - - *fugitive-:Gstatus* -:Gstatus Bring up the output of git-status in the preview - window. In addition to standard motions, you can - use and to jump from filename to - filename. Press D to |:Gdiff| the file on the cursor - line, or dh to |:Gdiff!|. Press - to stage or unstage - the file on the cursor line. Press p to do so on a - per hunk basis (--patch). Press C to invoke - |:Gcommit|. - - *fugitive-:Gcommit* -:Gcommit [args] A wrapper around git-commit. If there is nothing - to commit, |:Gstatus| is called instead. Unless the - arguments given would skip the invocation of an editor - (e.g., -m), a split window will be used to obtain a - commit message. Write and close that window (:wq or - |:Gwrite|) to finish the commit. Unlike when running - the actual git-commit command, it is possible (but - unadvisable) to muck with the index with commands like - git-add and git-reset while a commit message is - pending. - - *fugitive-:Ggrep* -:Ggrep [args] |:grep| with git-grep as 'grepprg'. - - *fugitive-:Glog* -:Glog [args] Load all previous revisions of the current file into - the quickfix list. Additional git-log arguments can - be given (for example, --reverse). If "--" appears as - an argument, no file specific filtering is done, and - commits are loaded into the quickfix list. - - *fugitive-:Gedit* *fugitive-:Ge* -:Gedit [revision] |:edit| a |fugitive-revision|. - - *fugitive-:Gsplit* -:Gsplit [revision] |:split| a |fugitive-revision|. - - *fugitive-:Gvsplit* -:Gvsplit [revision] |:vsplit| a |fugitive-revision|. - - *fugitive-:Gtabedit* -:Gtabedit [revision] |:tabedit| a |fugitive-revision| - - *fugitive-:Gpedit* -:Gpedit [revision] |:pedit| a |fugitive-revision| - - *fugitive-:Gread* -:Gread [revision] Empty the buffer and |:read| a |fugitive-revision|. - When the argument is omitted, this is similar to - git-checkout on a work tree file or git-add on a stage - file, but without writing anything to disk. - -:{range}Gread [revision] - |:read| in a |fugitive-revision| after {range}. - - *fugitive-:Gread!* -:Gread! [revision] Deprecated synonym for |:Gread|. - - *fugitive-:Gwrite* -:Gwrite Write to the current file's path and stage the results. - When run in a work tree file, it is effectively git - add. Elsewhere, it is effectively git-checkout. A - great deal of effort is expended to behave sensibly - when the work tree or index version of the file is - open in another buffer. - -:Gwrite {path} You can give |:Gwrite| an explicit path of where in - the work tree to write. You can also give a path like - :0:foo.txt or even :0 to write to just that stage in - the index. - - *fugitive-:Gdiff* -:Gdiff [revision] Perform a |vimdiff| against the current file in the - given revision. With no argument, the version in the - index is used (which means a three-way diff during a - merge conflict, making it a git-mergetool - alternative). The newer of the two files is placed - to the right. Use |do| and |dp| and write to the - index file to simulate "git add --patch". - - *fugitive-:Gdiff!* -:Gdiff! [revision] Like |:Gdiff|, but split horizontally. - - *fugitive-:Gmove* -:Gmove {destination} Wrapper around git-mv that renames the buffer - afterward. The destination is relative to the current - directory except when started with a /, in which case - it is relative to the work tree. Add a ! to pass -f. - - *fugitive-:Gremove* -:Gremove Wrapper around git-rm that deletes the buffer - afterward. When invoked in an index file, --cached is - passed. Add a ! to pass -f and forcefully discard the - buffer. - - *fugitive-:Gblame* -:Gblame [flags] Run git-blame on the file and open the results in a - scroll bound vertical split. Press enter on a line to - reblame the file as it was in that commit. You can - give any of ltwfsMC as flags and they will be passed - along to git-blame. - -:[range]Gblame [flags] Run git-blame on the given range. - -MAPPINGS *fugitive-mappings* - -These maps are available in Git objects. - - *fugitive-* - Jump to the revision under the cursor. - - *fugitive-o* -o Jump to the revision under the cursor in a new split. - - *fugitive-O* -O Jump to the revision under the cursor in a new tab. - - *fugitive-~* -~ Go to the current file in the [count]th first - ancestor. - - *fugitive-P* -P Go to the current file in the [count]th parent. - - *fugitive-C* -C Go to the commit containing the current file. - - *fugitive-a* -a Show the current tag, commit, or tree in an alternate - format. - -SPECIFYING REVISIONS *fugitive-revision* - -Fugitive revisions are similar to Git revisions as defined in the "SPECIFYING -REVISIONS" section in the git-rev-parse man page. For commands that accept an -optional revision, the default is the file in the index for work tree files -and the work tree file for everything else. Example revisions follow. - -Revision Meaning ~ -HEAD .git/HEAD -master .git/refs/heads/master -HEAD^{} The commit referenced by HEAD -HEAD^ The parent of the commit referenced by HEAD -HEAD: The tree referenced by HEAD -/HEAD The file named HEAD in the work tree -Makefile The file named Makefile in the work tree -HEAD^:Makefile The file named Makefile in the parent of HEAD -:Makefile The file named Makefile in the index (writable) -- The current file in HEAD -^ The current file in the previous commit -~3 The current file 3 commits ago -: .git/index (Same as |:Gstatus|) -:0 The current file in the index -:1 The current file's common ancestor during a conflict -:2 The current file in the target branch during a conflict -:3 The current file in the merged branch during a conflict -:/foo The most recent commit with "foo" in the message - -STATUSLINE *fugitive-statusline* - - *fugitive#statusline()* -Add %{fugitive#statusline()} to your statusline to get an indicator including -the current branch and the currently edited file's commit. If you don't have -a statusline, this one matches the default when 'ruler' is set: -> - set statusline=%<%f\ %h%m%r%{fugitive#statusline()}%=%-14.(%l,%c%V%)\ %P -< -ABOUT *fugitive-about* - -Grab the latest version or report a bug on GitHub: - -http://github.com/tpope/vim-fugitive - - vim:tw=78:et:ft=help:norl: diff --git a/vim/doc/ragtag.txt b/vim/doc/ragtag.txt deleted file mode 100644 index a038b26ce1..0000000000 --- a/vim/doc/ragtag.txt +++ /dev/null @@ -1,82 +0,0 @@ -*ragtag.txt* Ghetto XML/HTML mappings (formerly allml.vim) - -Author: Tim Pope *ragtag-author* -License: Same terms as Vim itself (see |license|) - -This plugin is only available if 'compatible' is not set. - -INTRODUCTION *ragtag* - -These are my personal mappings for XML/XHTML editing, particularly with -dynamic content like PHP/ASP/eRuby. Because they are personal, less effort -has been put into customizability (if you like these mappings but the lack of -customizability poses an issue for you, let me know). Examples shown are for -eRuby. - -You might find these helpful in your vimrc: -> - inoremap o - inoremap - let g:ragtag_global_maps = 1 -< -MAPPINGS *ragtag-mappings* - -The table below shows what happens if the binding is pressed on the end of a -line consisting of "foo". - -Mapping Changed to (cursor = ^) ~ -= foo<%= ^ %> *ragtag-CTRL-X_=* -+ <%= foo^ %> *ragtag-CTRL-X_+* -- foo<% ^ %> *ragtag-CTRL-X_-* -_ <% foo^ %> *ragtag-CTRL-X__* -' foo<%# ^ %> *ragtag-CTRL-X_'* - (mnemonic: ' is a comment in ASP VBS) -" <%# foo^ %> *ragtag-CTRL-X_quote* - ^ *ragtag-CTRL-X_* - \n^\n *ragtag-CTRL-X_* -/ Last HTML tag closed *ragtag-CTRL-X_/* -! / (menu) *ragtag-CTRL-X_!* -@ *ragtag-CTRL-X_@* - (mnemonic: @ is used for importing in a CSS file) -# *ragtag-CTRL-X_#* -$ *ragtag-CTRL-X_$* - (mnemonic: $ is valid in javascript identifiers) - -For the bindings that generate HTML tag pairs, in a few cases, attributes will -be automatically added. For example, script becomes > - O - else - imap ] >O - endif - " <% %> - if &ft == "eruby" - inoremap - <%-%>3hi - inoremap _ I<%A-%>Fs - elseif &ft == "cf" - inoremap - - inoremap _ - else - imap - >2hi - imap _ IA>Fs - endif - " Comments - if &ft =~ '^asp' - imap ' '>2hi - imap " I'A>Fs - let b:surround_35 = maparg("","i")."' \r ".maparg(">","i") - elseif &ft == "jsp" - inoremap ' %----%>4hi - inoremap " I<%--A--%>Fs - let b:surround_35 = "<%-- \r --%>" - elseif &ft == "cf" - inoremap ' !------>4hi - inoremap " IFs - setlocal commentstring= - let b:surround_35 = "" - elseif &ft == "html" || &ft == "xml" || &ft == "xhtml" - inoremap ' !---->3hi - inoremap " IFs - let b:surround_35 = "" - elseif &ft == "django" - inoremap ' {##}2hi - inoremap " I{#A#}Fs - let b:surround_35 = "{# \r #}" - else - imap ' #>2hi - imap " I#A>Fs - let b:surround_35 = maparg("","i")."# \r ".maparg(">","i") - endif - imap % ragtagUrlEncode - imap & ragtagXmlEncode - imap % ragtagUrlV - imap & ragtagXmlV - if !exists("b:did_indent") - if s:subtype() == "xml" - runtime! indent/xml.vim - else - runtime! indent/html.vim - endif - endif - " Pet peeve. Do people still not close their

and

  • tags? - if exists("g:html_indent_tags") && g:html_indent_tags !~ '\\|p\>' - let g:html_indent_tags = g:html_indent_tags.'\|p\|li\|dt\|dd' - endif - set indentkeys+=!^F - let b:surround_indent = 1 - silent doautocmd User ragtag - silent doautocmd User allml -endfunction - -function! s:Leave() - call s:disableescape() -endfunction - -function! s:length(str) - return strlen(substitute(a:str,'.','.','g')) -endfunction - -function! s:repeat(str,cnt) - let cnt = a:cnt - let str = "" - while cnt > 0 - let str = str . a:str - let cnt = cnt - 1 - endwhile - return str -endfunction - -function! s:doctypeSeek() - if !exists("b:ragtag_doctype_index") - if exists("b:allml_doctype_index") - let b:ragtag_doctype_index = b:allml_doctype_index - elseif &ft == 'xhtml' || &ft == 'eruby' - let b:ragtag_doctype_index = 10 - elseif &ft != 'xml' - let b:ragtag_doctype_index = 7 - endif - endif - let index = b:ragtag_doctype_index - 1 - return (index < 0 ? s:repeat("\",-index) : s:repeat("\",index)) -endfunction - -function! s:stylesheetTag() - if !exists("b:ragtag_stylesheet_link_tag") - if exists("b:allml_stylesheet_link_tag") - let b:ragtag_stylesheet_link_tag = b:allml_stylesheet_link_tag - else - let b:ragtag_stylesheet_link_tag = "" - endif - endif - return s:insertTag(b:ragtag_stylesheet_link_tag) -endfunction - -function! s:javascriptIncludeTag() - if !exists("b:ragtag_javascript_include_tag") - if exists("b:allml_javascript_include_tag") - let b:ragtag_javascript_include_tag = b:allml_javascript_include_tag - else - let b:ragtag_javascript_include_tag = "" - endif - endif - return s:insertTag(b:ragtag_javascript_include_tag) -endfunction - -function! s:insertTag(tag) - let tag = a:tag - if s:subtype() == "html" - let tag = substitute(a:tag,'\s*/>','>','g') - endif - let before = matchstr(tag,'^.\{-\}\ze\r') - let after = matchstr(tag,'\r\zs\%(.*\r\)\@!.\{-\}$') - " middle isn't currently used - let middle = matchstr(tag,'\r\zs.\{-\}\ze\r') - return before.after.s:repeat("\",s:length(after)) -endfunction - - -function! s:htmlEn() - let b:ragtag_omni = &l:omnifunc - let b:ragtag_isk = &l:isk - " : is for namespaced xml attributes - setlocal omnifunc=htmlcomplete#CompleteTags isk+=: - return "" -endfunction - -function! s:htmlDis() - if exists("b:ragtag_omni") - let &l:omnifunc = b:ragtag_omni - unlet b:ragtag_omni - endif - if exists("b:ragtag_isk") - let &l:isk = b:ragtag_isk - unlet b:ragtag_isk - endif - return "" -endfunction - -function! s:subtype() - let top = getline(1)."\n".getline(2) - if (top =~ '' && &ft !~? 'html') || &ft =~? '^\%(xml\|xsd\|xslt\)$' - return "xml" - elseif top =~? '\' - return 'xhtml' - elseif top =~ '[^<]\' - return "html" - elseif &ft == "xhtml" || &ft == "eruby" - return "xhtml" - elseif exists("b:loaded_ragtag") - return "html" - else - return "" - endif -endfunction - -function! s:closetagback() - if s:subtype() == "html" - return ">\" - else - return " />\\\" - endif -endfunction - -function! s:closetag() - if s:subtype() == "html" - return ">" - else - return " />" - endif -endfunction - -function! s:charset() - let enc = &fileencoding - if enc == "" - let enc = &encoding - endif - if enc == "latin1" - return "ISO-8859-1" - elseif enc == "" - return "US-ASCII" - else - return enc - endif -endfunction - -function! s:tagextras() - if s:subtype() == "xml" - return "" - elseif @" == 'html' && s:subtype() == 'xhtml' - let lang = "en" - if exists("$LANG") && $LANG =~ '^..' - let lang = strpart($LANG,0,2) - endif - return ' xmlns="http://www.w3.org/1999/xhtml" lang="'.lang.'" xml:lang="'.lang.'"' - elseif @" == 'style' - return ' type="text/css"' - elseif @" == 'script' - return ' type="text/javascript"' - elseif @" == 'table' - return ' cellspacing="0"' - else - return "" - endif -endfunction - -inoremap urlspace =getinput()=~?'\%([?&]\&\)[%a-z0-9._~+-]*=[%a-z0-9._~+-]*$'?'+':'%20' - -function! s:urltab(htmlesc) - let line = s:getinput() - let g:line = line - if line =~ '[^ <>"'."'".']\@"'."'".']\@ ragtagBSUrl - inoremap %0A - imap ${2} -snippet scriptsrc - ${2} -snippet style - ${3} -snippet base - -snippet r - -snippet div -
    - ${2} -
    -# Embed QT Movie -snippet movie - - - - - - ${6} -snippet fieldset -
    - ${1:name} - - ${3} -
    -snippet form -
    - ${3} - - -

    -
    -snippet h1 -

    ${2:$1}

    -snippet input - ${4} -snippet label - ${7} -snippet link - ${4} -snippet mailto - ${3:email me} -snippet meta - ${3} -snippet opt - ${3} -snippet optt - ${2} -snippet select - ${5} -snippet table - - - -
    ${2:Header}
    ${3:Data}
    ${4} -snippet textarea - ${5} diff --git a/vim/snippets/java.snippets b/vim/snippets/java.snippets deleted file mode 100644 index fd705cb598..0000000000 --- a/vim/snippets/java.snippets +++ /dev/null @@ -1,78 +0,0 @@ -snippet main - public static void main (String [] args) - { - ${1:/* code */} - } -snippet pu - public -snippet po - protected -snippet pr - private -snippet st - static -snippet fi - final -snippet ab - abstract -snippet re - return -snippet br - break; -snippet de - default: - ${1} -snippet ca - catch(${1:Exception} ${2:e}) ${3} -snippet th - throw -snippet sy - synchronized -snippet im - import -snippet j.u - java.util -snippet j.i - java.io. -snippet j.b - java.beans. -snippet j.n - java.net. -snippet j.m - java.math. -snippet if - if (${1}) ${2} -snippet el - else -snippet elif - else if (${1}) ${2} -snippet wh - while (${1}) ${2} -snippet for - for (${1}; ${2}; ${3}) ${4} -snippet fore - for (${1} : ${2}) ${3} -snippet sw - switch (${1}) ${2} -snippet cs - case ${1}: - ${2} - ${3} -snippet tc - public class ${1:`Filename()`} extends ${2:TestCase} -snippet t - public void test${1:Name}() throws Exception ${2} -snippet cl - class ${1:`Filename("", "untitled")`} ${2} -snippet in - interface ${1:`Filename("", "untitled")`} ${2:extends Parent}${3} -snippet m - ${1:void} ${2:method}(${3}) ${4:throws }${5} -snippet v - ${1:String} ${2:var}${3: = null}${4};${5} -snippet co - static public final ${1:String} ${2:var} = ${3};${4} -snippet cos - static public final String ${1:var} = "${2}";${3} -snippet as - assert ${1:test} : "${2:Failure message}";${3} diff --git a/vim/snippets/javascript.snippets b/vim/snippets/javascript.snippets deleted file mode 100644 index 51f5e0502e..0000000000 --- a/vim/snippets/javascript.snippets +++ /dev/null @@ -1,74 +0,0 @@ -# Prototype -snippet proto - ${1:class_name}.prototype.${2:method_name} = - function(${3:first_argument}) { - ${4:// body...} - }; -# Function -snippet fun - function ${1:function_name} (${2:argument}) { - ${3:// body...} - } -# Anonymous Function -snippet f - function(${1}) {${2}}; -# if -snippet if - if (${1:true}) {${2}}; -# if ... else -snippet ife - if (${1:true}) {${2}} - else{${3}}; -# tertiary conditional -snippet t - ${1:/* condition */} ? ${2:a} : ${3:b} -# switch -snippet switch - switch(${1:expression}) { - case '${3:case}': - ${4:// code} - break; - ${5} - default: - ${2:// code} - } -# case -snippet case - case '${1:case}': - ${2:// code} - break; - ${3} -# for (...) {...} -snippet for - for (var ${2:i} = 0; $2 < ${1:Things}.length; $2${3:++}) { - ${4:$1[$2]} - }; -# for (...) {...} (Improved Native For-Loop) -snippet forr - for (var ${2:i} = ${1:Things}.length - 1; $2 >= 0; $2${3:--}) { - ${4:$1[$2]} - }; -# while (...) {...} -snippet wh - while (${1:/* condition */}) { - ${2:/* code */} - } -# do...while -snippet do - do { - ${2:/* code */} - } while (${1:/* condition */}); -# Object Method -snippet :f - ${1:method_name}: function(${2:attribute}) { - ${4} - }${3:,} -# setTimeout function -snippet timeout - setTimeout(function() {${3}}${2}, ${1:10}; -# Get Elements -snippet get - getElementsBy${1:TagName}('${2}')${3} -# Get Element -snippet gett - getElementBy${1:Id}('${2}')${3} diff --git a/vim/snippets/mako.snippets b/vim/snippets/mako.snippets deleted file mode 100644 index 2a0aef9ce5..0000000000 --- a/vim/snippets/mako.snippets +++ /dev/null @@ -1,54 +0,0 @@ -snippet def - <%def name="${1:name}"> - ${2:} - -snippet call - <%call expr="${1:name}"> - ${2:} - -snippet doc - <%doc> - ${1:} - -snippet text - <%text> - ${1:} - -snippet for - % for ${1:i} in ${2:iter}: - ${3:} - % endfor -snippet if if - % if ${1:condition}: - ${2:} - % endif -snippet if if/else - % if ${1:condition}: - ${2:} - % else: - ${3:} - % endif -snippet try - % try: - ${1:} - % except${2:}: - ${3:pass} - % endtry -snippet wh - % while ${1:}: - ${2:} - % endwhile -snippet $ - ${ ${1:} } -snippet <% - <% ${1:} %> -snippet -snippet inherit - <%inherit file="${1:filename}" /> -snippet include - <%include file="${1:filename}" /> -snippet namespace - <%namespace file="${1:name}" /> -snippet page - <%page args="${1:}" /> diff --git a/vim/snippets/objc.snippets b/vim/snippets/objc.snippets deleted file mode 100644 index 4749bb7762..0000000000 --- a/vim/snippets/objc.snippets +++ /dev/null @@ -1,184 +0,0 @@ -# #import <...> -snippet Imp - #import <${1:Cocoa/Cocoa.h}>${2} -# #import "..." -snippet imp - #import "${1:`Filename()`.h}"${2} -# @selector(...) -snippet sel - @selector(${1:method}:)${3} -# @"..." string -snippet s - @"${1}"${2} -# Object -snippet o - ${1:NSObject} *${2:foo} = [${3:$1 alloc}]${4};${5} -# NSLog(...) -snippet log - NSLog(@"${1:%@}"${2});${3} -# Class -snippet objc - @interface ${1:`Filename('', 'someClass')`} : ${2:NSObject} - { - } - @end - - @implementation $1 - ${3} - @end -# Class Interface -snippet int - @interface ${1:`Filename('', 'someClass')`} : ${2:NSObject} - {${3} - } - ${4} - @end -# Class Implementation -snippet impl - @implementation ${1:`Filename('', 'someClass')`} - ${2} - @end -snippet init - - (id)init - { - [super init]; - return self; - } -snippet ifself - if (self = [super init]) { - ${1:/* code */} - } - return self; -snippet ibo - IBOutlet ${1:NSSomeClass} *${2:$1};${3} -# Category -snippet cat - @interface ${1:NSObject} (${2:Category}) - @end - - @implementation $1 ($2) - ${3} - @end -# Category Interface -snippet cath - @interface ${1:NSObject} (${2:Category}) - ${3} - @end -# NSArray -snippet array - NSMutableArray *${1:array} = [NSMutable array];${2} -# NSDictionary -snippet dict - NSMutableDictionary *${1:dict} = [NSMutableDictionary dictionary];${2} -# NSBezierPath -snippet bez - NSBezierPath *${1:path} = [NSBezierPath bezierPath];${2} -# Method -snippet m - - (${1:id})${2:method} - { - ${3} - } -# Method declaration -snippet md - - (${1:id})${2:method};${3} -# IBAction declaration -snippet ibad - - (IBAction)${1:method}:(${2:id})sender;${3} -# IBAction method -snippet iba - - (IBAction)${1:method}:(${2:id})sender - { - ${3} - } -# awakeFromNib method -snippet wake - - (void)awakeFromNib - { - ${1} - } -# Class Method -snippet M - + (${1:id})${2:method} - {${3} - return nil; - } -# Sub-method (Call super) -snippet sm - - (${1:id})${2:method} - { - [super $2];${3} - return self; - } -# Method: Initialize -snippet I - + (void) initialize - { - [[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWIthObjectsAndKeys: - ${1}@"value", @"key", - nil]]; - } -# Accessor Methods For: -# Object -snippet objacc - - (${1:id})${2:thing} - { - return $2; - } - - - (void)set$2:($1)${3:new$2} - { - [$3 retain]; - [$2 release]; - $2 = $3; - }${4} -# for (object in array) -snippet forin - for (${1:Class} *${2:some$1} in ${3:array}) { - ${4} - } -snippet forarray - unsigned int ${1:object}Count = [${2:array} count]; - - for (unsigned int index = 0; index < $1Count; index++) { - ${3:id} $1 = [$2 $1AtIndex:index]; - ${4} - } -# IBOutlet -# @property (Objective-C 2.0) -snippet prop - @property (${1:retain}) ${2:NSSomeClass} ${3:*$2};${4} -# @synthesize (Objective-C 2.0) -snippet syn - @synthesize ${1:property};${2} -# [[ alloc] init] -snippet alloc - [[${1:foo} alloc] init${2}];${3} -# retain -snippet ret - [${1:foo} retain];${2} -# release -snippet rel - [${1:foo} release]; - ${2:$1 = nil;} -# autorelease -snippet arel - [${1:foo} autorelease]; -# autorelease pool -snippet pool - NSAutoreleasePool *${1:pool} = [[NSAutoreleasePool alloc] init]; - ${2:/* code */} - [$1 drain]; -# Throw an exception -snippet except - NSException *${1:badness}; - $1 = [NSException exceptionWithName:@"${2:$1Name}" - reason:@"${3}" - userInfo:nil]; - [$1 raise]; -snippet prag - #pragma mark ${1:foo} -snippet cl - @class ${1:Foo};${2} -snippet color - [[NSColor ${1:blackColor}] set]; diff --git a/vim/snippets/perl.snippets b/vim/snippets/perl.snippets deleted file mode 100644 index cf8f9fc856..0000000000 --- a/vim/snippets/perl.snippets +++ /dev/null @@ -1,91 +0,0 @@ -# #!/usr/bin/perl -snippet #! - #!/usr/bin/perl - -# Hash Pointer -snippet . - => -# Function -snippet sub - sub ${1:function_name} { - ${2:#body ...} - } -# Conditional -snippet if - if (${1}) { - ${2:# body...} - } -# Conditional if..else -snippet ife - if (${1}) { - ${2:# body...} - } else { - ${3:# else...} - } -# Conditional if..elsif..else -snippet ifee - if (${1}) { - ${2:# body...} - } elsif (${3}) { - ${4:# elsif...} - } else { - ${5:# else...} - } -# Conditional One-line -snippet xif - ${1:expression} if ${2:condition};${3} -# Unless conditional -snippet unless - unless (${1}) { - ${2:# body...} - } -# Unless conditional One-line -snippet xunless - ${1:expression} unless ${2:condition};${3} -# Try/Except -snippet eval - eval { - ${1:# do something risky...} - }; - if ($@) { - ${2:# handle failure...} - } -# While Loop -snippet wh - while (${1}) { - ${2:# body...} - } -# While Loop One-line -snippet xwh - ${1:expression} while ${2:condition};${3} -# For Loop -snippet for - for (my $${2:var} = 0; $$2 < ${1:count}; $$2${3:++}) { - ${4:# body...} - } -# Foreach Loop -snippet fore - foreach my $${1:x} (@${2:array}) { - ${3:# body...} - } -# Foreach Loop One-line -snippet xfore - ${1:expression} foreach @${2:array};${3} -# Package -snippet cl - package ${1:ClassName}; - - use base qw(${2:ParentClass}); - - sub new { - my $class = shift; - $class = ref $class if ref $class; - my $self = bless {}, $class; - $self; - } - - 1;${3} -# Read File -snippet slurp - my $${1:var}; - { local $/ = undef; local *FILE; open FILE, "<${2:file}"; $$1 = ; close FILE }${3} diff --git a/vim/snippets/php.snippets b/vim/snippets/php.snippets deleted file mode 100644 index 3ce9e26cc4..0000000000 --- a/vim/snippets/php.snippets +++ /dev/null @@ -1,216 +0,0 @@ -snippet php - -snippet ec - echo "${1:string}"${2}; -snippet inc - include '${1:file}';${2} -snippet inc1 - include_once '${1:file}';${2} -snippet req - require '${1:file}';${2} -snippet req1 - require_once '${1:file}';${2} -# $GLOBALS['...'] -snippet globals - $GLOBALS['${1:variable}']${2: = }${3:something}${4:;}${5} -snippet $_ COOKIE['...'] - $_COOKIE['${1:variable}']${2} -snippet $_ ENV['...'] - $_ENV['${1:variable}']${2} -snippet $_ FILES['...'] - $_FILES['${1:variable}']${2} -snippet $_ Get['...'] - $_GET['${1:variable}']${2} -snippet $_ POST['...'] - $_POST['${1:variable}']${2} -snippet $_ REQUEST['...'] - $_REQUEST['${1:variable}']${2} -snippet $_ SERVER['...'] - $_SERVER['${1:variable}']${2} -snippet $_ SESSION['...'] - $_SESSION['${1:variable}']${2} -# Start Docblock -snippet /* - /** - * ${1} - **/ -# Class - post doc -snippet doc_cp - /** - * ${1:undocumented class} - * - * @package ${2:default} - * @author ${3:`g:snips_author`} - **/${4} -# Class Variable - post doc -snippet doc_vp - /** - * ${1:undocumented class variable} - * - * @var ${2:string} - **/${3} -# Class Variable -snippet doc_v - /** - * ${3:undocumented class variable} - * - * @var ${4:string} - **/ - ${1:var} $${2};${5} -# Class -snippet doc_c - /** - * ${3:undocumented class} - * - * @packaged ${4:default} - * @author ${5:`g:snips_author`} - **/ - ${1:}class ${2:} - {${6} - } // END $1class $2 -# Constant Definition - post doc -snippet doc_dp - /** - * ${1:undocumented constant} - **/${2} -# Constant Definition -snippet doc_d - /** - * ${3:undocumented constant} - **/ - define(${1}, ${2});${4} -# Function - post doc -snippet doc_fp - /** - * ${1:undocumented function} - * - * @return ${2:void} - * @author ${3:`g:snips_author`} - **/${4} -# Function signature -snippet doc_s - /** - * ${4:undocumented function} - * - * @return ${5:void} - * @author ${6:`g:snips_author`} - **/ - ${1}function ${2}(${3});${7} -# Function -snippet doc_f - /** - * ${4:undocumented function} - * - * @return ${5:void} - * @author ${6:`g:snips_author`} - **/ - ${1}function ${2}(${3}) - {${7} - } -# Header -snippet doc_h - /** - * ${1} - * - * @author ${2:`g:snips_author`} - * @version ${3:$Id$} - * @copyright ${4:$2}, `strftime('%d %B, %Y')` - * @package ${5:default} - **/ - - /** - * Define DocBlock - *// -# Interface -snippet doc_i - /** - * ${2:undocumented class} - * - * @package ${3:default} - * @author ${4:`g:snips_author`} - **/ - interface ${1:} - {${5} - } // END interface $1 -# class ... -snippet class - /** - * ${1} - **/ - class ${2:ClassName} - { - ${3} - function ${4:__construct}(${5:argument}) - { - ${6:// code...} - } - } -# define(...) -snippet def - define('${1}'${2});${3} -# defined(...) -snippet def? - ${1}defined('${2}')${3} -snippet wh - while (${1:/* condition */}) { - ${2:// code...} - } -# do ... while -snippet do - do { - ${2:// code... } - } while (${1:/* condition */}); -snippet if - if (${1:/* condition */}) { - ${2:// code...} - } -snippet ife - if (${1:/* condition */}) { - ${2:// code...} - } else { - ${3:// code...} - } - ${4} -snippet else - else { - ${1:// code...} - } -snippet elseif - elseif (${1:/* condition */}) { - ${2:// code...} - } -# Tertiary conditional -snippet t - $${1:retVal} = (${2:condition}) ? ${3:a} : ${4:b};${5} -snippet switch - switch ($${1:variable}) { - case '${2:value}': - ${3:// code...} - break; - ${5} - default: - ${4:// code...} - break; - } -snippet case - case '${1:value}': - ${2:// code...} - break;${3} -snippet for - for ($${2:i} = 0; $$2 < ${1:count}; $$2${3:++}) { - ${4: // code...} - } -snippet foreach - foreach ($${1:variable} as $${2:key}) { - ${3:// code...} - } -snippet fun - ${1:public }function ${2:FunctionName}(${3}) - { - ${4:// code...} - } -# $... = array (...) -snippet array - $${1:arrayName} = array('${2}' => ${3});${4} diff --git a/vim/snippets/python.snippets b/vim/snippets/python.snippets deleted file mode 100644 index d511184a32..0000000000 --- a/vim/snippets/python.snippets +++ /dev/null @@ -1,86 +0,0 @@ -snippet #! - #!/usr/bin/python - -snippet imp - import ${1:module} -# Module Docstring -snippet docs - ''' - File: ${1:`Filename('$1.py', 'foo.py')`} - Author: ${2:`g:snips_author`} - Description: ${3} - ''' -snippet wh - while ${1:condition}: - ${2:# code...} -snippet for - for ${1:needle} in ${2:haystack}: - ${3:# code...} -# New Class -snippet cl - class ${1:ClassName}(${2:object}): - """${3:docstring for $1}""" - def __init__(self, ${4:arg}): - ${5:super($1, self).__init__()} - self.$4 = $4 - ${6} -# New Function -snippet def - def ${1:fname}(${2:`indent('.') ? 'self' : ''`}): - """${3:docstring for $1}""" - ${4:pass} -snippet deff - def ${1:fname}(${2:`indent('.') ? 'self' : ''`}): - ${3} -# New Method -snippet defs - def ${1:mname}(self, ${2:arg}): - ${3:pass} -# New Property -snippet property - def ${1:foo}(): - doc = "${2:The $1 property.}" - def fget(self): - ${3:return self._$1} - def fset(self, value): - ${4:self._$1 = value} -# Lambda -snippet ld - ${1:var} = lambda ${2:vars} : ${3:action} -snippet . - self. -snippet try Try/Except - try: - ${1:pass} - except ${2:Exception}, ${3:e}: - ${4:raise $3} -snippet try Try/Except/Else - try: - ${1:pass} - except ${2:Exception}, ${3:e}: - ${4:raise $3} - else: - ${5:pass} -snippet try Try/Except/Finally - try: - ${1:pass} - except ${2:Exception}, ${3:e}: - ${4:raise $3} - finally: - ${5:pass} -snippet try Try/Except/Else/Finally - try: - ${1:pass} - except ${2:Exception}, ${3:e}: - ${4:raise $3} - else: - ${5:pass} - finally: - ${6:pass} -# if __name__ == '__main__': -snippet ifmain - if __name__ == '__main__': - ${1:main()} -# __magic__ -snippet _ - __${1:init}__${2} diff --git a/vim/snippets/ruby.snippets b/vim/snippets/ruby.snippets deleted file mode 100644 index bf1d7f1765..0000000000 --- a/vim/snippets/ruby.snippets +++ /dev/null @@ -1,420 +0,0 @@ -# #!/usr/bin/ruby -snippet #! - #!/usr/bin/ruby - -# New Block -snippet =b - =begin rdoc - ${1} - =end -snippet y - :yields: ${1:arguments} -snippet rb - #!/usr/bin/env ruby -wKU - -snippet req - require "${1}"${2} -snippet # - # => -snippet end - __END__ -snippet case - case ${1:object} - when ${2:condition} - ${3} - end -snippet when - when ${1:condition} - ${2} -snippet def - def ${1:method_name} - ${2} - end -snippet deft - def test_${1:case_name} - ${2} - end -snippet if - if ${1:condition} - ${2} - end -snippet ife - if ${1:condition} - ${2} - else - ${3} - end -snippet elsif - elsif ${1:condition} - ${2} -snippet unless - unless ${1:condition} - ${2} - end -snippet while - while ${1:condition} - ${2} - end -snippet until - until ${1:condition} - ${2} - end -snippet cla class .. end - class ${1:`substitute(Filename(), '^.', '\u&', '')`} - ${2} - end -snippet cla class .. initialize .. end - class ${1:`substitute(Filename(), '^.', '\u&', '')`} - def initialize(${2:args}) - ${3} - end - - - end -snippet cla class .. < ParentClass .. initialize .. end - class ${1:`substitute(Filename(), '^.', '\u&', '')`} < ${2:ParentClass} - def initialize(${3:args}) - ${4} - end - - - end -snippet cla ClassName = Struct .. do .. end - ${1:`substitute(Filename(), '^.', '\u&', '')`} = Struct.new(:${2:attr_names}) do - def ${3:method_name} - ${4} - end - - - end -snippet cla class BlankSlate .. initialize .. end - class ${1:BlankSlate} - instance_methods.each { |meth| undef_method(meth) unless meth =~ /\A__/ } -snippet cla class << self .. end - class << ${1:self} - ${2} - end -# class .. < DelegateClass .. initialize .. end -snippet cla- - class ${1:`substitute(Filename(), '^.', '\u&', '')`} < DelegateClass(${2:ParentClass}) - def initialize(${3:args}) - super(${4:del_obj}) - - ${5} - end - - - end -snippet mod module .. end - module ${1:`substitute(Filename(), '^.', '\u&', '')`} - ${2} - end -snippet mod module .. module_function .. end - module ${1:`substitute(Filename(), '^.', '\u&', '')`} - module_function - - ${2} - end -snippet mod module .. ClassMethods .. end - module ${1:`substitute(Filename(), '^.', '\u&', '')`} - module ClassMethods - ${2} - end - - module InstanceMethods - - end - - def self.included(receiver) - receiver.extend ClassMethods - receiver.send :include, InstanceMethods - end - end -# attr_reader -snippet r - attr_reader :${1:attr_names} -# attr_writer -snippet w - attr_writer :${1:attr_names} -# attr_accessor -snippet rw - attr_accessor :${1:attr_names} -# include Enumerable -snippet Enum - include Enumerable - - def each(&block) - ${1} - end -# include Comparable -snippet Comp - include Comparable - - def <=>(other) - ${1} - end -# extend Forwardable -snippet Forw- - extend Forwardable -# def self -snippet defs - def self.${1:class_method_name} - ${2} - end -# def method_missing -snippet defmm - def method_missing(meth, *args, &blk) - ${1} - end -snippet defd - def_delegator :${1:@del_obj}, :${2:del_meth}, :${3:new_name} -snippet defds - def_delegators :${1:@del_obj}, :${2:del_methods} -snippet am - alias_method :${1:new_name}, :${2:old_name} -snippet app - if __FILE__ == $PROGRAM_NAME - ${1} - end -# usage_if() -snippet usai - if ARGV.${1} - abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${3} - end -# usage_unless() -snippet usau - unless ARGV.${1} - abort "Usage: #{$PROGRAM_NAME} ${2:ARGS_GO_HERE}"${3} - end -snippet array - Array.new(${1:10}) { |${2:i}| ${3} } -snippet hash - Hash.new { |${1:hash}, ${2:key}| $1[$2] = ${3} } -snippet file File.foreach() { |line| .. } - File.foreach(${1:"path/to/file"}) { |${2:line}| ${3} } -snippet file File.read() - File.read(${1:"path/to/file"})${2} -snippet Dir Dir.global() { |file| .. } - Dir.glob(${1:"dir/glob/*"}) { |${2:file}| ${3} } -snippet Dir Dir[".."] - Dir[${1:"glob/**/*.rb"}]${2} -snippet dir - Filename.dirname(__FILE__) -snippet deli - delete_if { |${1:e}| ${2} } -snippet fil - fill(${1:range}) { |${2:i}| ${3} } -# flatten_once() -snippet flao - inject(Array.new) { |${1:arr}, ${2:a}| $1.push(*$2)}${3} -snippet zip - zip(${1:enums}) { |${2:row}| ${3} } -# downto(0) { |n| .. } -snippet dow - downto(${1:0}) { |${2:n}| ${3} } -snippet ste - step(${1:2}) { |${2:n}| ${3} } -snippet tim - times { |${1:n}| ${2} } -snippet upt - upto(${1:1.0/0.0}) { |${2:n}| ${3} } -snippet loo - loop { ${1} } -snippet ea - each { |${1:e}| ${2} } -snippet eab - each_byte { |${1:byte}| ${2} } -snippet eac- each_char { |chr| .. } - each_char { |${1:chr}| ${2} } -snippet eac- each_cons(..) { |group| .. } - each_cons(${1:2}) { |${2:group}| ${3} } -snippet eai - each_index { |${1:i}| ${2} } -snippet eak - each_key { |${1:key}| ${2} } -snippet eal - each_line { |${1:line}| ${2} } -snippet eap - each_pair { |${1:name}, ${2:val}| ${3} } -snippet eas- - each_slice(${1:2}) { |${2:group}| ${3} } -snippet eav - each_value { |${1:val}| ${2} } -snippet eawi - each_with_index { |${1:e}, ${2:i}| ${3} } -snippet reve - reverse_each { |${1:e}| ${2} } -snippet inj - inject(${1:init}) { |${2:mem}, ${3:var}| ${4} } -snippet map - map { |${1:e}| ${2} } -snippet mapwi- - enum_with_index.map { |${1:e}, ${2:i}| ${3} } -snippet sor - sort { |a, b| ${1} } -snippet sorb - sort_by { |${1:e}| ${2} } -snippet ran - sort_by { rand } -snippet all - all? { |${1:e}| ${2} } -snippet any - any? { |${1:e}| ${2} } -snippet cl - classify { |${1:e}| ${2} } -snippet col - collect { |${1:e}| ${2} } -snippet det - detect { |${1:e}| ${2} } -snippet fet - fetch(${1:name}) { |${2:key}| ${3} } -snippet fin - find { |${1:e}| ${2} } -snippet fina - find_all { |${1:e}| ${2} } -snippet gre - grep(${1:/pattern/}) { |${2:match}| ${3} } -snippet sub - ${1:g}sub(${2:/pattern/}) { |${3:match}| ${4} } -snippet sca - scan(${1:/pattern/}) { |${2:match}| ${3} } -snippet max - max { |a, b|, ${1} } -snippet min - min { |a, b|, ${1} } -snippet par - partition { |${1:e}|, ${2} } -snippet rej - reject { |${1:e}|, ${2} } -snippet sel - select { |${1:e}|, ${2} } -snippet lam - lambda { |${1:args}| ${2} } -snippet do - do |${1:variable}| - ${2} - end -snippet : - :${1:key} => ${2:"value"}${3} -snippet ope - open(${1:"path/or/url/or/pipe"}, "${2:w}") { |${3:io}| ${4} } -# path_from_here() -snippet patfh - File.join(File.dirname(__FILE__), *%2[${1:rel path here}])${2} -# unix_filter {} -snippet unif - ARGF.each_line${1} do |${2:line}| - ${3} - end -# option_parse {} -snippet optp - require "optparse" - - options = {${1:default => "args"}} - - ARGV.options do |opts| - opts.banner = "Usage: #{File.basename($PROGRAM_NAME)} -snippet opt - opts.on( "-${1:o}", "--${2:long-option-name}", ${3:String}, - "${4:Option description.}") do |${5:opt}| - ${6} - end -snippet tc - require "test/unit" - - require "${1:library_file_name}" - - class Test${2:$1} < Test::Unit::TestCase - def test_${3:case_name} - ${4} - end - end -snippet ts - require "test/unit" - - require "tc_${1:test_case_file}" - require "tc_${2:test_case_file}"${3} -snippet as - assert(${1:test}, "${2:Failure message.}")${3} -snippet ase - assert_equal(${1:expected}, ${2:actual})${3} -snippet asne - assert_not_equal(${1:unexpected}, ${2:actual})${3} -snippet asid - assert_in_delta(${1:expected_float}, ${2:actual_float}, ${3:2 ** -20})${4} -snippet asio - assert_instance_of(${1:ExpectedClass}, ${2:actual_instance})${3} -snippet asko - assert_kind_of(${1:ExpectedKind}, ${2:actual_instance})${3} -snippet asn - assert_nil(${1:instance})${2} -snippet asnn - assert_not_nil(${1:instance})${2} -snippet asm - assert_match(/${1:expected_pattern}/, ${2:actual_string})${3} -snippet asnm - assert_no_match(/${1:unexpected_pattern}/, ${2:actual_string})${3} -snippet aso - assert_operator(${1:left}, :${2:operator}, ${3:right})${4} -snippet asr - assert_raise(${1:Exception}) { ${2} } -snippet asnr - assert_nothing_raised(${1:Exception}) { ${2} } -snippet asrt - assert_respond_to(${1:object}, :${2:method})${3} -snippet ass assert_same(..) - assert_same(${1:expected}, ${2:actual})${3} -snippet ass assert_send(..) - assert_send([${1:object}, :${2:message}, ${3:args}])${4} -snippet asns - assert_not_same(${1:unexpected}, ${2:actual})${3} -snippet ast - assert_throws(:${1:expected}) { ${2} } -snippet asnt - assert_nothing_thrown { ${1} } -snippet fl - flunk("${1:Failure message.}")${2} -# Benchmark.bmbm do .. end -snippet bm- - TESTS = ${1:10_000} - Benchmark.bmbm do |results| - ${2} - end -snippet rep - results.report("${1:name}:") { TESTS.times { ${2} }} -# Marshal.dump(.., file) -snippet Md - File.open(${1:"path/to/file.dump"}, "wb") { |${2:file}| Marshal.dump(${3:obj}, $2) }${4} -# Mashal.load(obj) -snippet Ml - File.open(${1:"path/to/file.dump"}, "rb") { |${2:file}| Marshal.load($2) }${3} -# deep_copy(..) -snippet deec - Marshal.load(Marshal.dump(${1:obj_to_copy}))${2} -snippet Pn- - PStore.new(${1:"file_name.pstore"})${2} -snippet tra - transaction(${1:true}) { ${2} } -# xmlread(..) -snippet xml- - REXML::Document.new(File.read(${1:"path/to/file"}))${2} -# xpath(..) { .. } -snippet xpa - elements.each(${1:"//Xpath"}) do |${2:node}| - ${3} - end -# class_from_name() -snippet clafn - split("::").inject(Object) { |par, const| par.const_get(const) } -# singleton_class() -snippet sinc - class << self; self end -snippet nam - namespace :${1:`Filename()`} do - ${2} - end -snippet tas - desc "${1:Task description\}" - task :${2:task_name => [:dependent, :tasks]} do - ${3} - end diff --git a/vim/snippets/sh.snippets b/vim/snippets/sh.snippets deleted file mode 100644 index f035126eec..0000000000 --- a/vim/snippets/sh.snippets +++ /dev/null @@ -1,28 +0,0 @@ -# #!/bin/bash -snippet #! - #!/bin/bash - -snippet if - if [[ ${1:condition} ]]; then - ${2:#statements} - fi -snippet elif - elif [[ ${1:condition} ]]; then - ${2:#statements} -snippet for - for (( ${2:i} = 0; $2 < ${1:count}; $2++ )); do - ${3:#statements} - done -snippet wh - while [[ ${1:condition} ]]; do - ${2:#statements} - done -snippet until - until [[ ${1:condition} ]]; do - ${2:#statements} - done -snippet case - case ${1:word} in - ${2:pattern}) - ${3};; - esac diff --git a/vim/snippets/snippet.snippets b/vim/snippets/snippet.snippets deleted file mode 100644 index 854c058202..0000000000 --- a/vim/snippets/snippet.snippets +++ /dev/null @@ -1,7 +0,0 @@ -# snippets for making snippets :) -snippet snip - snippet ${1:trigger} - ${2} -snippet msnip - snippet ${1:trigger} ${2:description} - ${3} diff --git a/vim/snippets/tcl.snippets b/vim/snippets/tcl.snippets deleted file mode 100644 index bee2ef8a4a..0000000000 --- a/vim/snippets/tcl.snippets +++ /dev/null @@ -1,92 +0,0 @@ -# #!/usr/bin/tclsh -snippet #! - #!/usr/bin/tclsh - -# Process -snippet pro - proc ${1:function_name} {${2:args}} { - ${3:#body ...} - } -#xif -snippet xif - ${1:expr}? ${2:true} : ${3:false} -# Conditional -snippet if - if {${1}} { - ${2:# body...} - } -# Conditional if..else -snippet ife - if {${1}} { - ${2:# body...} - } else { - ${3:# else...} - } -# Conditional if..elsif..else -snippet ifee - if {${1}} { - ${2:# body...} - } elseif {${3}} { - ${4:# elsif...} - } else { - ${5:# else...} - } -# If catch then -snippet ifc - if { [catch {${1:#do something...}} ${2:err}] } { - ${3:# handle failure...} - } -# Catch -snippet catch - catch {${1}} ${2:err} ${3:options} -# While Loop -snippet wh - while {${1}} { - ${2:# body...} - } -# For Loop -snippet for - for {set ${2:var} 0} {$$2 < ${1:count}} {${3:incr} $2} { - ${4:# body...} - } -# Foreach Loop -snippet fore - foreach ${1:x} {${2:#list}} { - ${3:# body...} - } -# after ms script... -snippet af - after ${1:ms} ${2:#do something} -# after cancel id -snippet afc - after cancel ${1:id or script} -# after idle -snippet afi - after idle ${1:script} -# after info id -snippet afin - after info ${1:id} -# Expr -snippet exp - expr {${1:#expression here}} -# Switch -snippet sw - switch ${1:var} { - ${3:pattern 1} { - ${4:#do something} - } - default { - ${2:#do something} - } - } -# Case -snippet ca - ${1:pattern} { - ${2:#do something} - }${3} -# Namespace eval -snippet ns - namespace eval ${1:path} {${2:#script...}} -# Namespace current -snippet nsc - namespace current diff --git a/vim/snippets/tex.snippets b/vim/snippets/tex.snippets deleted file mode 100644 index 22f7316532..0000000000 --- a/vim/snippets/tex.snippets +++ /dev/null @@ -1,115 +0,0 @@ -# \begin{}...\end{} -snippet begin - \begin{${1:env}} - ${2} - \end{$1} -# Tabular -snippet tab - \begin{${1:tabular}}{${2:c}} - ${3} - \end{$1} -# Align(ed) -snippet ali - \begin{align${1:ed}} - ${2} - \end{align$1} -# Gather(ed) -snippet gat - \begin{gather${1:ed}} - ${2} - \end{gather$1} -# Equation -snippet eq - \begin{equation} - ${1} - \end{equation} -# Unnumbered Equation -snippet \ - \\[ - ${1} - \\] -# Enumerate -snippet enum - \begin{enumerate} - \item ${1} - \end{enumerate} -# Itemize -snippet item - \begin{itemize} - \item ${1} - \end{itemize} -# Description -snippet desc - \begin{description} - \item[${1}] ${2} - \end{description} -# Matrix -snippet mat - \begin{${1:p/b/v/V/B/small}matrix} - ${2} - \end{$1matrix} -# Cases -snippet cas - \begin{cases} - ${1:equation}, &\text{ if }${2:case}\\ - ${3} - \end{cases} -# Split -snippet spl - \begin{split} - ${1} - \end{split} -# Part -snippet part - \part{${1:part name}} % (fold) - \label{prt:${2:$1}} - ${3} - % part $2 (end) -# Chapter -snippet cha - \chapter{${1:chapter name}} % (fold) - \label{cha:${2:$1}} - ${3} - % chapter $2 (end) -# Section -snippet sec - \section{${1:section name}} % (fold) - \label{sec:${2:$1}} - ${3} - % section $2 (end) -# Sub Section -snippet sub - \subsection{${1:subsection name}} % (fold) - \label{sub:${2:$1}} - ${3} - % subsection $2 (end) -# Sub Sub Section -snippet subs - \subsubsection{${1:subsubsection name}} % (fold) - \label{ssub:${2:$1}} - ${3} - % subsubsection $2 (end) -# Paragraph -snippet par - \paragraph{${1:paragraph name}} % (fold) - \label{par:${2:$1}} - ${3} - % paragraph $2 (end) -# Sub Paragraph -snippet subp - \subparagraph{${1:subparagraph name}} % (fold) - \label{subp:${2:$1}} - ${3} - % subparagraph $2 (end) -snippet itd - \item[${1:description}] ${2:item} -snippet figure - ${1:Figure}~\ref{${2:fig:}}${3} -snippet table - ${1:Table}~\ref{${2:tab:}}${3} -snippet listing - ${1:Listing}~\ref{${2:list}}${3} -snippet section - ${1:Section}~\ref{${2:sec:}}${3} -snippet page - ${1:page}~\pageref{${2}}${3} diff --git a/vim/snippets/vim.snippets b/vim/snippets/vim.snippets deleted file mode 100644 index 64e7807eb4..0000000000 --- a/vim/snippets/vim.snippets +++ /dev/null @@ -1,32 +0,0 @@ -snippet header - " File: ${1:`expand('%:t')`} - " Author: ${2:`g:snips_author`} - " Description: ${3} - ${4:" Last Modified: `strftime("%B %d, %Y")`} -snippet guard - if exists('${1:did_`Filename()`}') || &cp${2: || version < 700} - finish - endif - let $1 = 1${3} -snippet f - fun ${1:function_name}(${2}) - ${3:" code} - endf -snippet for - for ${1:needle} in ${2:haystack} - ${3:" code} - endfor -snippet wh - while ${1:condition} - ${2:" code} - endw -snippet if - if ${1:condition} - ${2:" code} - endif -snippet ife - if ${1:condition} - ${2} - else - ${3} - endif diff --git a/vim/snippets/zsh.snippets b/vim/snippets/zsh.snippets deleted file mode 100644 index 7aee05bd24..0000000000 --- a/vim/snippets/zsh.snippets +++ /dev/null @@ -1,58 +0,0 @@ -# #!/bin/zsh -snippet #! - #!/bin/zsh - -snippet if - if ${1:condition}; then - ${2:# statements} - fi -snippet ife - if ${1:condition}; then - ${2:# statements} - else - ${3:# statements} - fi -snippet elif - elif ${1:condition} ; then - ${2:# statements} -snippet for - for (( ${2:i} = 0; $2 < ${1:count}; $2++ )); do - ${3:# statements} - done -snippet fore - for ${1:item} in ${2:list}; do - ${3:# statements} - done -snippet wh - while ${1:condition}; do - ${2:# statements} - done -snippet until - until ${1:condition}; do - ${2:# statements} - done -snippet repeat - repeat ${1:integer}; do - ${2:# statements} - done -snippet case - case ${1:word} in - ${2:pattern}) - ${3};; - esac -snippet select - select ${1:answer} in ${2:choices}; do - ${3:# statements} - done -snippet ( - ( ${1:#statements} ) -snippet { - { ${1:#statements} } -snippet [ - [[ ${1:test} ]] -snippet always - { ${1:try} } always { ${2:always} } -snippet fun - function ${1:name} (${2:args}) { - ${3:# body} - } diff --git a/vim/syntax/snippet.vim b/vim/syntax/snippet.vim deleted file mode 100644 index 5e919e782a..0000000000 --- a/vim/syntax/snippet.vim +++ /dev/null @@ -1,19 +0,0 @@ -" Syntax highlighting for snippet files (used for snipMate.vim) -" Hopefully this should make snippets a bit nicer to write! -syn match snipComment '^#.*' -syn match placeHolder '\${\d\+\(:.\{-}\)\=}' contains=snipCommand -syn match tabStop '\$\d\+' -syn match snipCommand '`.\{-}`' -syn match snippet '^snippet.*' transparent contains=multiSnipText,snipKeyword -syn match multiSnipText '\S\+ \zs.*' contained -syn match snipKeyword '^snippet'me=s+8 contained -syn match snipError "^[^#s\t].*$" - -hi link snipComment Comment -hi link multiSnipText String -hi link snipKeyword Keyword -hi link snipComment Comment -hi link placeHolder Special -hi link tabStop Special -hi link snipCommand String -hi link snipError Error diff --git a/vimrc b/vimrc deleted file mode 100755 index 6a8c329a30..0000000000 --- a/vimrc +++ /dev/null @@ -1,207 +0,0 @@ -" based on http://github.com/jferris/config_files/blob/master/vimrc - -" Use Vim settings, rather then Vi settings (much better!). -" This must be first, because it changes other options as a side effect. -set nocompatible - -" allow backspacing over everything in insert mode -set backspace=indent,eol,start - -set nobackup -set nowritebackup -set history=50 " keep 50 lines of command line history -set ruler " show the cursor position all the time -set showcmd " display incomplete commands -set incsearch " do incremental searching - -" Don't use Ex mode, use Q for formatting -map Q gq - -" This is an alternative that also works in block mode, but the deleted -" text is lost and it only works for putting the current register. -"vnoremap p "_dp - -" Switch syntax highlighting on, when the terminal has colors -" Also switch on highlighting the last used search pattern. -if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on") - syntax on - set hlsearch -endif - -" Switch wrap off for everything -set nowrap - -" Only do this part when compiled with support for autocommands. -if has("autocmd") - " Enable file type detection. - " Use the default filetype settings, so that mail gets 'tw' set to 72, - " 'cindent' is on in C files, etc. - " Also load indent files, to automatically do language-dependent indenting. - filetype plugin indent on - - " Set File type to 'text' for files ending in .txt - autocmd BufNewFile,BufRead *.txt setfiletype text - - " Enable soft-wrapping for text files - autocmd FileType text,markdown,html,xhtml,eruby setlocal wrap linebreak nolist - - " Put these in an autocmd group, so that we can delete them easily. - augroup vimrcEx - au! - - " For all text files set 'textwidth' to 78 characters. - " autocmd FileType text setlocal textwidth=78 - - " When editing a file, always jump to the last known cursor position. - " Don't do it when the position is invalid or when inside an event handler - " (happens when dropping a file on gvim). - autocmd BufReadPost * - \ if line("'\"") > 0 && line("'\"") <= line("$") | - \ exe "normal g`\"" | - \ endif - - " Automatically load .vimrc source when saved - autocmd BufWritePost .vimrc source $MYVIMRC - - augroup END - -else - - set autoindent " always set autoindenting on - -endif " has("autocmd") - -" if has("folding") - " set foldenable - " set foldmethod=syntax - " set foldlevel=1 - " set foldnestmax=2 - " set foldtext=strpart(getline(v:foldstart),0,50).'\ ...\ '.substitute(getline(v:foldend),'^[\ #]*','','g').'\ ' -" endif - -" Softtabs, 2 spaces -set tabstop=2 -set shiftwidth=2 -set expandtab - -" Always display the status line -set laststatus=2 - -" \ is the leader character -let mapleader = "," - -" Edit the README_FOR_APP (makes :R commands work) -map R :e doc/README_FOR_APP - -" Leader shortcuts for Rails commands -map m :Rmodel -map c :Rcontroller -map v :Rview -map u :Runittest -map f :Rfunctionaltest -map tm :RTmodel -map tc :RTcontroller -map tv :RTview -map tu :RTunittest -map tf :RTfunctionaltest -map sm :RSmodel -map sc :RScontroller -map sv :RSview -map su :RSunittest -map sf :RSfunctionaltest - -" Hide search highlighting -map h :set invhls - -" Opens an edit command with the path of the currently edited file filled in -" Normal mode: e -map e :e =expand("%:p:h") . "/" - -" Opens a tab edit command with the path of the currently edited file filled in -" Normal mode: t -map te :tabe =expand("%:p:h") . "/" - -" Inserts the path of the currently edited file into a command -" Command mode: Ctrl+P -cmap =expand("%:p:h") . "/" - -" Duplicate a selection -" Visual mode: D -vmap D y'>p - -" Press Shift+P while in visual mode to replace the selection without -" overwriting the default register -vmap P p :call setreg('"', getreg('0')) - -" For Haml -au! BufRead,BufNewFile *.haml setfiletype haml - -" No Help, please -nmap - -" Press ^F from insert mode to insert the current file name -imap =expand("%") - -" Maps autocomplete to tab -imap - -imap => - -" Display extra whitespace -" set list listchars=tab:»·,trail:· - -" Edit routes -command! Rroutes :e config/routes.rb -command! Rschema :e db/schema.rb - -" Local config -if filereadable(".vimrc.local") - source .vimrc.local -endif - -" Use Ack instead of Grep when available -if executable("ack") - set grepprg=ack\ -H\ --nogroup\ --nocolor\ --ignore-dir=tmp\ --ignore-dir=coverage -endif - -" Color scheme -" colorscheme vividchalk -" highlight NonText guibg=#060606 -" highlight Folded guibg=#0A0A0A guifg=#9090D0 - -" Numbers -set number -set numberwidth=5 - -" Snippets are activated by Shift+Tab -let g:snippetsEmu_key = "" - -" Tab completion options -" (only complete to the longest unambiguous match, and show a menu) -set completeopt=longest,menu -set wildmode=list:longest,list:full -set complete=.,t - -" case only matters with mixed case expressions -set ignorecase -set smartcase - -" Tags -let g:Tlist_Ctags_Cmd="ctags --exclude='*.js'" -set tags=./tags; - -let g:fuf_splitPathMatching=1 - -" Open URL -command -bar -nargs=1 OpenURL :!open -function! OpenURL() - let s:uri = matchstr(getline("."), '[a-z]*:\/\/[^ >,;:]*') - echo s:uri - if s:uri != "" - exec "!open \"" . s:uri . "\"" - else - echo "No URI found in line." - endif -endfunction -map w :call OpenURL() - diff --git a/zlogin b/zlogin deleted file mode 100644 index dee825627e..0000000000 --- a/zlogin +++ /dev/null @@ -1,5 +0,0 @@ -# go to saved path if there is one -if [[ -f ~/.current_path~ ]]; then - cd `cat ~/.current_path~` - rm ~/.current_path~ -fi diff --git a/zsh/.zshenv b/zsh/.zshenv new file mode 100644 index 0000000000..0b7ea3b364 --- /dev/null +++ b/zsh/.zshenv @@ -0,0 +1,12 @@ +# zsh history config +export HISTFILE=~/.zsh_history +export HISTSIZE=1000 +export SAVEHIST=1000 + +# disable macOS session restoration +SHELL_SESSIONS_DISABLE=1 + +# assorted custom variables +export GPG_TTY=`tty` +export EDITOR="vim" +export GREP_OPTIONS='--color=auto' \ No newline at end of file diff --git a/zsh/.zshrc b/zsh/.zshrc new file mode 100644 index 0000000000..ff2f4612f1 --- /dev/null +++ b/zsh/.zshrc @@ -0,0 +1,55 @@ +# key bindings +bindkey -e + +# options +setopt prompt_subst +setopt autocd +unsetopt nomatch + +# bash-like word movement +autoload -U select-word-style +select-word-style bash + +# source control info +autoload -Uz vcs_info +zstyle ':vcs_info:*' enable git +zstyle ':vcs_info:*' check-for-changes true # dirty indicators +zstyle ':vcs_info:*' stagedstr '%F{green}*%f' # staged changes in repo +zstyle ':vcs_info:*' unstagedstr '%F{red}*%f' # unstaged changes +CUSTOM_GIT_PROMPT_FORMAT='%u%c %b' +ACTION_PROMPT_FORMAT=$CUSTOM_GIT_PROMPT_FORMAT' %F{magenta}%a%f' +zstyle ':vcs_info:*' formats $CUSTOM_GIT_PROMPT_FORMAT +zstyle ':vcs_info:*' actionformats $ACTION_PROMPT_FORMAT + +# run vcs_info before the prompt is displayed and check for untracked files +precmd() { + vcs_info +} + +# prompt +export PROMPT='%5~ %F{blue}>%f ' +export RPROMPT='${vcs_info_msg_0_}' + +### completion +autoload -Uz compinit +compinit + +# case insensitive completion +zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' + +# key-browsable suggestions +zstyle ':completion:*' menu select + +### aliases +alias ls="ls -Gh" +alias la="ls -lA" +alias rmr="rm -rf" +alias o="open" +alias g="git" +alias t="tmux new-session -A -s 0" +alias svim="sudo vim -u ~/.vimrc" +alias sudo='sudo ' # tell sudo to respect aliases +alias rbi='eval "$(rbenv init -)"' + +# use .localrc for settings specific to one system +[[ -f ~/.localrc ]] && . ~/.localrc diff --git a/zsh/aliases b/zsh/aliases deleted file mode 100644 index c9379348f4..0000000000 --- a/zsh/aliases +++ /dev/null @@ -1,33 +0,0 @@ -# cd -alias ..='cd ..' - -# ls -alias ls="ls -F" -alias l="ls -lAh" -alias ll="ls -l" -alias la='ls -A' - -# git -alias gl='git pull' -alias gp='git push' -alias gd='git diff' -alias gc='git commit' -alias gca='git commit -a' -alias gco='git checkout' -alias gb='git branch' -alias gs='git status' -alias grm="git status | grep deleted | awk '{print \$3}' | xargs git rm" -alias changelog='git log `git log -1 --format=%H -- CHANGELOG*`..; cat CHANGELOG*' - -# rails -alias sc='script/console' -alias ss='script/server' -alias sg='script/generate' -alias a='autotest -rails' -alias tlog='tail -f log/development.log' -alias scaffold='script/generate nifty_scaffold' -alias migrate='rake db:migrate db:test:clone' -alias rst='touch tmp/restart.txt' - -# commands starting with % for pasting from web -alias %=' ' diff --git a/zsh/completion b/zsh/completion deleted file mode 100644 index 4f22a94ef4..0000000000 --- a/zsh/completion +++ /dev/null @@ -1,8 +0,0 @@ -autoload -U compinit -compinit - -# matches case insensitive for lowercase -zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' - -# pasting with tabs doesn't perform completion -zstyle ':completion:*' insert-tab pending diff --git a/zsh/config b/zsh/config deleted file mode 100644 index 508d2b83b3..0000000000 --- a/zsh/config +++ /dev/null @@ -1,46 +0,0 @@ -if [[ -n $SSH_CONNECTION ]]; then - export PS1='%m:%3~$(git_info_for_prompt)%# ' -else - export PS1='%3~$(git_info_for_prompt)%# ' -fi - -export EDITOR='mate_wait' -export PATH="$HOME/bin:$HOME/.bin:/usr/local/homebrew/bin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:/usr/local/git/bin:$PATH" -export MANPATH="/usr/local/man:/usr/local/mysql/man:/usr/local/git/man:$MANPATH" - -fpath=(~/.zsh/functions $fpath) - -autoload -U ~/.zsh/functions/*(:t) - -HISTFILE=~/.zsh_history -HISTSIZE=1000 -SAVEHIST=1000 -REPORTTIME=10 # print elapsed time when more than 10 seconds - -setopt NO_BG_NICE # don't nice background tasks -setopt NO_HUP -setopt NO_LIST_BEEP -setopt LOCAL_OPTIONS # allow functions to have local options -setopt LOCAL_TRAPS # allow functions to have local traps -setopt HIST_VERIFY -setopt SHARE_HISTORY # share history between sessions ??? -setopt EXTENDED_HISTORY # add timestamps to history -setopt PROMPT_SUBST -setopt CORRECT -setopt COMPLETE_IN_WORD -setopt IGNORE_EOF - -setopt APPEND_HISTORY # adds history -setopt INC_APPEND_HISTORY SHARE_HISTORY # adds history incrementally and share it across sessions -setopt HIST_IGNORE_ALL_DUPS # don't record dupes in history -setopt HIST_REDUCE_BLANKS - -zle -N newtab - -bindkey '^[^[[D' backward-word -bindkey '^[^[[C' forward-word -bindkey '^[[5D' beginning-of-line -bindkey '^[[5C' end-of-line -bindkey '^[[3~' delete-char -bindkey '^[^N' newtab -bindkey '^?' backward-delete-char diff --git a/zsh/functions/_brew b/zsh/functions/_brew deleted file mode 100644 index 8ba6889557..0000000000 --- a/zsh/functions/_brew +++ /dev/null @@ -1,65 +0,0 @@ -#compdef brew - -# Brew ZSH completion function -# Drop this somewhere in your $fpath (like /usr/share/zsh/site-functions) -# and rename it _brew -# -# altered from _fink - -_brew_all_formulae() { - formulae=(`brew search`) -} - -_brew_installed_formulae() { - installed_formulae=(`brew list`) -} - -local -a _1st_arguments -_1st_arguments=( - 'install:install a formula' - 'remove:remove a formula' - 'search:search for a formula (/regex/ or string)' - 'list:list files in a formula or not-installed formulae' - 'link:link a formula' - 'unlink:unlink a formula' - 'home:visit the homepage of a formula or the brew project' - 'info:information about a formula' - 'prune:remove dead links' - 'update:freshen up links' - 'log:git commit log for a formula' - 'create:create a new formula' - 'edit:edit a formula' -) - -local expl -local -a formula installed_formulae - -_arguments \ - '(-v --verbose)'{-v,--verbose}'[verbose]' \ - '(--version)--version[version information]' \ - '(--prefix)--prefix[where brew lives on this system]' \ - '(--cache)--cache[brew cache]' \ - '*:: :->subcmds' && return 0 - -if (( CURRENT == 1 )); then - _describe -t commands "brew subcommand" _1st_arguments - return -fi - -case "$words[1]" in - list) - _arguments \ - '(--unbrewed)--unbrewed[files in brew --prefix not controlled by brew]' \ - '1: :->forms' && return 0 - - if [[ "$state" == forms ]]; then - _brew_installed_formulae - _requested installed_formulae expl 'installed formulae' compadd -a installed_formulae - fi ;; - install|home|log|info) - _brew_all_formulae - _wanted formulae expl 'all formulae' compadd -a formulae ;; - remove|edit|xo) - _brew_installed_formulae - _wanted installed_formulae expl 'installed formulae' compadd -a installed_formulae ;; -esac diff --git a/zsh/functions/_c b/zsh/functions/_c deleted file mode 100644 index 24ca71afa4..0000000000 --- a/zsh/functions/_c +++ /dev/null @@ -1,2 +0,0 @@ -#compdef c -_files -W ~/code -/ diff --git a/zsh/functions/_cap b/zsh/functions/_cap deleted file mode 100644 index a18cd2eede..0000000000 --- a/zsh/functions/_cap +++ /dev/null @@ -1,8 +0,0 @@ -#compdef cap -if [ -f Capfile ]; then - recent=`last_modified .cap_tasks~ Capfile **/deploy.rb` - if [[ $recent != '.cap_tasks~' ]]; then - cap --tasks | grep '#' | cut -d " " -f 2 > .cap_tasks~ - fi - compadd `cat .cap_tasks~` -fi diff --git a/zsh/functions/_gh b/zsh/functions/_gh deleted file mode 100644 index f9519e1365..0000000000 --- a/zsh/functions/_gh +++ /dev/null @@ -1,2 +0,0 @@ -#compdef gh -_github diff --git a/zsh/functions/_git-rm b/zsh/functions/_git-rm deleted file mode 100644 index a10baf9c4c..0000000000 --- a/zsh/functions/_git-rm +++ /dev/null @@ -1,7 +0,0 @@ -#compdef git-rm -_arguments -S -A '-*' \ - '-f[override the up-to-date check]' \ - "-n[don't actually remove the files, just show if they exist in the index]" \ - '-r[allow recursive removal when a leading directory-name is given]' \ - '--cached[only remove files from the index]' && ret=0 -_files diff --git a/zsh/functions/_github b/zsh/functions/_github deleted file mode 100644 index 65b7f9e0f5..0000000000 --- a/zsh/functions/_github +++ /dev/null @@ -1,72 +0,0 @@ -#compdef github - -_github() { - if (( CURRENT > 2 )); then - # shift words so _arguments doesn't have to be concerned with second command - (( CURRENT-- )) - shift words - # use _call_function here in case it doesn't exist - _call_function 1 _github_${words[1]} - else - _values "github command" \ - "fetch[Fetch from a remote to a local branch.]" \ - "ignore[Ignore a SHA (from 'github network commits')]" \ - "fetch_all[Fetch all refs from a user]" \ - "info[Info about this project.]" \ - "browse[Open this repo in a web browser.]" \ - "home[Open this repo's master branch in a web browser.]" \ - "clone[Clone a repo.]" \ - "pull-request[Generate the text for a pull request.]" \ - "network[Project network tools.]" \ - "pull[Pull from a remote.]" \ - "track[Track another user's repository.]" - fi -} - -_github_pull() { - _arguments \ - "--merge[Automatically merge remote's changes into your master.]" -} -_github_clone() { - _arguments \ - "--ssh[Clone using the git@github.com style url.]" -} - -_github_track() { - _arguments \ - "--private[Use git@github.com: instead of git://github.com/.]" \ - "--ssh[Equivalent to --private.]" -} - -_github_network() { - if (( CURRENT > 2 )); then - # shift words so _arguments doesn't have to be concerned with second command - (( CURRENT-- )) - shift words - # use _call_function here in case it doesn't exist - _call_function 1 _github_network_${words[1]} - else - _values "github network command" \ - "web[Open network in a web browser.]" \ - "list[List networked repositories.]" \ - "fetch[Fetched commits for a given networked repository.]" \ - "commits[List networked commits not pulled into this repo.]" - fi -} - -_github_network_commits() { - _arguments \ - "--project[Filter commits on a certain project.]" \ - "--author[Filter commits on a email address of author.]" \ - "--common[Show common branch point.]" \ - "--nocache[Do not use the cached network data.]" \ - "--sort[How to sort : date(*), branch, author.]" \ - "--thisbranch[Look at branches that match the current one]" \ - "--applies[Filter commits to patches that apply cleanly.]" \ - "--limit[Only look through the first X heads - useful for really large projects]" \ - "--before[Only show commits before a certain date.]" \ - "--after[Only show commits after a certain date.]" \ - "--shas[Only show shas.]" \ - "--cache[Use the network data even if it's expired.]" \ - "--noapply[Filter commits to patches that do not apply cleanly.]" -} diff --git a/zsh/functions/_h b/zsh/functions/_h deleted file mode 100644 index 725dc0a997..0000000000 --- a/zsh/functions/_h +++ /dev/null @@ -1,2 +0,0 @@ -#compdef h -_files -W ~ -/ diff --git a/zsh/functions/_rake b/zsh/functions/_rake deleted file mode 100644 index b448eda241..0000000000 --- a/zsh/functions/_rake +++ /dev/null @@ -1,8 +0,0 @@ -#compdef rake -if [ -f Rakefile ]; then - recent=`last_modified .rake_tasks~ Rakefile **/*.rake` - if [[ $recent != '.rake_tasks~' ]]; then - rake --silent --tasks | cut -d " " -f 2 > .rake_tasks~ - fi - compadd `cat .rake_tasks~` -fi diff --git a/zsh/functions/c b/zsh/functions/c deleted file mode 100644 index 89b6e1f68a..0000000000 --- a/zsh/functions/c +++ /dev/null @@ -1 +0,0 @@ -cd ~/code/$1; diff --git a/zsh/functions/gam b/zsh/functions/gam deleted file mode 100644 index a532c1b7dd..0000000000 --- a/zsh/functions/gam +++ /dev/null @@ -1 +0,0 @@ -curl $1 | git am diff --git a/zsh/functions/gfp b/zsh/functions/gfp deleted file mode 100644 index 5018b77cc6..0000000000 --- a/zsh/functions/gfp +++ /dev/null @@ -1 +0,0 @@ -git format-patch master --stdout > $1 diff --git a/zsh/functions/git_info_for_prompt b/zsh/functions/git_info_for_prompt deleted file mode 100644 index 9fed4e112a..0000000000 --- a/zsh/functions/git_info_for_prompt +++ /dev/null @@ -1,48 +0,0 @@ -local g="$(git rev-parse --git-dir 2>/dev/null)" -if [ -n "$g" ]; then - local r - local b - if [ -d "$g/../.dotest" ] - then - if test -f "$g/../.dotest/rebasing" - then - r="|REBASE" - elif test -f "$g/../.dotest/applying" - then - r="|AM" - else - r="|AM/REBASE" - fi - b="$(git symbolic-ref HEAD 2>/dev/null)" - elif [ -f "$g/.dotest-merge/interactive" ] - then - r="|REBASE-i" - b="$(cat "$g/.dotest-merge/head-name")" - elif [ -d "$g/.dotest-merge" ] - then - r="|REBASE-m" - b="$(cat "$g/.dotest-merge/head-name")" - elif [ -f "$g/MERGE_HEAD" ] - then - r="|MERGING" - b="$(git symbolic-ref HEAD 2>/dev/null)" - else - if [ -f "$g/BISECT_LOG" ] - then - r="|BISECTING" - fi - if ! b="$(git symbolic-ref HEAD 2>/dev/null)" - then - if ! b="tag: $(git describe --exact-match HEAD 2>/dev/null)" - then - b="$(cut -c1-7 "$g/HEAD")..." - fi - fi - fi - - if [ -n "$1" ]; then - printf "$1" "${b##refs/heads/}$r" - else - printf "[%s]" "${b##refs/heads/}$r" - fi -fi \ No newline at end of file diff --git a/zsh/functions/h b/zsh/functions/h deleted file mode 100644 index 1ab0d498da..0000000000 --- a/zsh/functions/h +++ /dev/null @@ -1 +0,0 @@ -cd ~/$1; diff --git a/zsh/functions/last_modified b/zsh/functions/last_modified deleted file mode 100644 index bd996e4507..0000000000 --- a/zsh/functions/last_modified +++ /dev/null @@ -1 +0,0 @@ -ls -t $* 2> /dev/null | head -n 1 diff --git a/zsh/functions/newtab b/zsh/functions/newtab deleted file mode 100644 index 3601a4b04a..0000000000 --- a/zsh/functions/newtab +++ /dev/null @@ -1,26 +0,0 @@ -savepath -osascript >/dev/null < ~/.current_path~ diff --git a/zsh/functions/verbose_completion b/zsh/functions/verbose_completion deleted file mode 100644 index 8ea12248c9..0000000000 --- a/zsh/functions/verbose_completion +++ /dev/null @@ -1,5 +0,0 @@ -zstyle ':completion:*' verbose yes -zstyle ':completion:*:descriptions' format '%B%d%b' -zstyle ':completion:*:messages' format '%d' -zstyle ':completion:*:warnings' format 'No matches for: %d' -zstyle ':completion:*' group-name '' diff --git a/zshrc b/zshrc deleted file mode 100644 index 985eff2c2d..0000000000 --- a/zshrc +++ /dev/null @@ -1,6 +0,0 @@ -. ~/.zsh/config -. ~/.zsh/aliases -. ~/.zsh/completion - -# use .localrc for settings specific to one system -[[ -f ~/.localrc ]] && . ~/.localrc