Bunch of changes inspired by r00k

This commit is contained in:
Michael Campagnaro 2013-07-07 17:25:47 -04:00
parent c5a1ed1258
commit cf3eea13fb
141 changed files with 22472 additions and 519 deletions

33
.gitmodules vendored
View File

@ -1,33 +0,0 @@
[submodule ".vim/bundle/vim-fugitive"]
path = .vim/bundle/vim-fugitive
url = git://github.com/tpope/vim-fugitive.git
[submodule ".vim/bundle/vim-colors-solarized"]
path = .vim/bundle/vim-colors-solarized
url = https://github.com/altercation/vim-colors-solarized
[submodule ".vim/bundle/vim-colorscheme-elrodeo"]
path = .vim/bundle/vim-colorscheme-elrodeo
url = git://github.com/chmllr/vim-colorscheme-elrodeo.git
[submodule ".vim/bundle/cctrlp.vim"]
path = .vim/bundle/cctrlp.vim
url = https://github.com/kien/ctrlp.vim.git
[submodule ".vim/bundle/vim-monokai"]
path = .vim/bundle/vim-monokai
url = git://github.com/sickill/vim-monokai.git
[submodule ".vim/bundle/vim-obsession"]
path = .vim/bundle/vim-obsession
url = git://github.com/tpope/vim-obsession.git
[submodule ".vim/bundle/ag"]
path = .vim/bundle/ag
url = https://github.com/rking/ag.vim
[submodule ".vim/bundle/webapi-vim"]
path = .vim/bundle/webapi-vim
url = git@github.com:mattn/webapi-vim.git
[submodule ".vim/bundle/gist-vim"]
path = .vim/bundle/gist-vim
url = git@github.com:mattn/gist-vim.git
[submodule ".vim/bundle/vim-rails"]
path = .vim/bundle/vim-rails
url = git://github.com/tpope/vim-rails.git
[submodule ".vim/bundle/vim-bundler"]
path = .vim/bundle/vim-bundler
url = git://github.com/tpope/vim-bundler.git

@ -1 +0,0 @@
Subproject commit f0134343434bc30a77d3ad2ca19d7e2f0a137461

@ -1 +0,0 @@
Subproject commit 7251d9dce85e45b41dab00d7d7032713847ed5ea

@ -1 +0,0 @@
Subproject commit 385140f2ff6065efccf32d58e52b25ae9952c677

@ -1 +0,0 @@
Subproject commit 94fdfe47d6f9e5f6d0406e03c021c24a539c9a76

@ -1 +0,0 @@
Subproject commit 528a59f26d12278698bb946f8fb82a63711eec21

@ -1 +0,0 @@
Subproject commit 01a23559bbbb1f28ff13fa2f11dbe66c356ee8b4

@ -1 +0,0 @@
Subproject commit 003f38c6a4d8e3d527e4e1dfeab6fdf05c8ff149

@ -1 +0,0 @@
Subproject commit 496ac9039f016fda75d7787a28abfba5481f7347

@ -1 +0,0 @@
Subproject commit d342229cc1fa5ed442179269b8358b4c42b52300

@ -1 +0,0 @@
Subproject commit 74f407e2f8d02dc6ff39ed370a25731d723e5cef

@ -1 +0,0 @@
Subproject commit 5731da5c074c1a86ed05d28f6f510347ff3f8d15

View File

@ -1,72 +0,0 @@
# fixme - the load process here seems a bit bizarre
unsetopt menu_complete # do not autoselect the first completion entry
unsetopt flowcontrol
setopt auto_menu # show completion menu on succesive tab press
setopt complete_in_word
setopt always_to_end
WORDCHARS=''
zmodload -i zsh/complist
## case-insensitive (all),partial-word and then substring completion
if [ "x$CASE_SENSITIVE" = "xtrue" ]; then
zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
unset CASE_SENSITIVE
else
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
fi
zstyle ':completion:*' list-colors ''
# should this be in keybindings?
bindkey -M menuselect '^o' accept-and-infer-next-history
zstyle ':completion:*:*:*:*:*' menu select
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'
zstyle ':completion:*:*:*:*:processes' command "ps -u `whoami` -o pid,user,comm -w -w"
# disable named-directories autocompletion
zstyle ':completion:*:cd:*' tag-order local-directories directory-stack path-directories
cdpath=(.)
# use /etc/hosts and known_hosts for hostname completion
[ -r /etc/ssh/ssh_known_hosts ] && _global_ssh_hosts=(${${${${(f)"$(</etc/ssh/ssh_known_hosts)"}:#[\|]*}%%\ *}%%,*}) || _ssh_hosts=()
[ -r ~/.ssh/known_hosts ] && _ssh_hosts=(${${${${(f)"$(<$HOME/.ssh/known_hosts)"}:#[\|]*}%%\ *}%%,*}) || _ssh_hosts=()
[ -r /etc/hosts ] && : ${(A)_etc_hosts:=${(s: :)${(ps:\t:)${${(f)~~"$(</etc/hosts)"}%%\#*}##[:blank:]#[^[:blank:]]#}}} || _etc_hosts=()
hosts=(
"$_global_ssh_hosts[@]"
"$_ssh_hosts[@]"
"$_etc_hosts[@]"
"$HOST"
localhost
)
zstyle ':completion:*:hosts' hosts $hosts
# Use caching so that commands like apt and dpkg complete are useable
zstyle ':completion::complete:*' use-cache 1
zstyle ':completion::complete:*' cache-path $ZSH/cache/
# Don't complete uninteresting users
zstyle ':completion:*:*:*:users' ignored-patterns \
adm amanda apache avahi beaglidx bin cacti canna clamav daemon \
dbus distcache dovecot fax ftp games gdm gkrellmd gopher \
hacluster haldaemon halt hsqldb ident junkbust ldap lp mail \
mailman mailnull mldonkey mysql nagios \
named netdump news nfsnobody nobody nscd ntp nut nx openvpn \
operator pcap postfix postgres privoxy pulse pvm quagga radvd \
rpc rpcuser rpm shutdown squid sshd sync uucp vcsa xfs
# ... unless we really want to.
zstyle '*' single-ignored show
if [ "x$COMPLETION_WAITING_DOTS" = "xtrue" ]; then
expand-or-complete-with-dots() {
echo -n "\e[31m......\e[0m"
zle expand-or-complete
zle redisplay
}
zle -N expand-or-complete-with-dots
bindkey "^I" expand-or-complete-with-dots
fi

View File

@ -1,46 +0,0 @@
#!/bin/sh
function _current_epoch() {
echo $(($(date +%s) / 60 / 60 / 24))
}
function _update_zsh_update() {
echo "LAST_EPOCH=$(_current_epoch)" > ~/.zsh-update
}
function _upgrade_zsh() {
/usr/bin/env ZSH=$ZSH /bin/sh $ZSH/tools/upgrade.sh
# update the zsh file
_update_zsh_update
}
if [ -f ~/.zsh-update ]
then
. ~/.zsh-update
if [[ -z "$LAST_EPOCH" ]]; then
_update_zsh_update && return 0;
fi
epoch_diff=$(($(_current_epoch) - $LAST_EPOCH))
if [ $epoch_diff -gt 13 ]
then
if [ "$DISABLE_UPDATE_PROMPT" = "true" ]
then
_upgrade_zsh
else
echo "[Oh My Zsh] Would you like to check for updates?"
echo "Type Y to update oh-my-zsh: \c"
read line
if [ "$line" = Y ] || [ "$line" = y ]; then
_upgrade_zsh
else
_update_zsh_update
fi
fi
fi
else
# create the zsh file
_update_zsh_update
fi

View File

@ -1,39 +0,0 @@
if [ -d ~/.oh-my-zsh ]
then
echo "\033[0;33mYou already have Oh My Zsh installed.\033[0m You'll need to remove ~/.oh-my-zsh if you want to install"
exit
fi
echo "\033[0;34mCloning Oh My Zsh...\033[0m"
hash git >/dev/null && /usr/bin/env git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh || {
echo "git not installed"
exit
}
echo "\033[0;34mLooking for an existing zsh config...\033[0m"
if [ -f ~/.zshrc ] || [ -h ~/.zshrc ]
then
echo "\033[0;33mFound ~/.zshrc.\033[0m \033[0;32]Backing up to ~/.zshrc.pre-oh-my-zsh\033[0m";
cp ~/.zshrc ~/.zshrc.pre-oh-my-zsh;
rm ~/.zshrc;
fi
echo "\033[0;34mUsing the Oh My Zsh template file and adding it to ~/.zshrc\033[0m"
cp ~/.oh-my-zsh/templates/zshrc.zsh-template ~/.zshrc
echo "\033[0;34mCopying your current PATH and adding it to the end of ~/.zshrc for you.\033[0m"
echo "export PATH=$PATH" >> ~/.zshrc
echo "\033[0;34mTime to change your default shell to zsh!\033[0m"
chsh -s `which zsh`
echo "\033[0;32m"' __ __ '"\033[0m"
echo "\033[0;32m"' ____ / /_ ____ ___ __ __ ____ _____/ /_ '"\033[0m"
echo "\033[0;32m"' / __ \/ __ \ / __ `__ \/ / / / /_ / / ___/ __ \ '"\033[0m"
echo "\033[0;32m"'/ /_/ / / / / / / / / / / /_/ / / /_(__ ) / / / '"\033[0m"
echo "\033[0;32m"'\____/_/ /_/ /_/ /_/ /_/\__, / /___/____/_/ /_/ '"\033[0m"
echo "\033[0;32m"' /____/ '"\033[0m"
echo "\n\n \033[0;32m....is now installed.\033[0m"
/usr/bin/env zsh
source ~/.zshrc

View File

@ -1,161 +0,0 @@
__require_tool_version_compare ()
{
(
# Locally ignore failures, otherwise we'll exit whenever $1 and $2
# are not equal!
set +e
awk_strverscmp='
# Use only awk features that work with 7th edition Unix awk (1978).
# My, what an old awk you have, Mr. Solaris!
END {
while (length(v1) || length(v2)) {
# Set d1 to be the next thing to compare from v1, and likewise for d2.
# Normally this is a single character, but if v1 and v2 contain digits,
# compare them as integers and fractions as strverscmp does.
if (v1 ~ /^[0-9]/ && v2 ~ /^[0-9]/) {
# Split v1 and v2 into their leading digit string components d1 and d2,
# and advance v1 and v2 past the leading digit strings.
for (len1 = 1; substr(v1, len1 + 1) ~ /^[0-9]/; len1++) continue
for (len2 = 1; substr(v2, len2 + 1) ~ /^[0-9]/; len2++) continue
d1 = substr(v1, 1, len1); v1 = substr(v1, len1 + 1)
d2 = substr(v2, 1, len2); v2 = substr(v2, len2 + 1)
if (d1 ~ /^0/) {
if (d2 ~ /^0/) {
# Compare two fractions.
while (d1 ~ /^0/ && d2 ~ /^0/) {
d1 = substr(d1, 2); len1--
d2 = substr(d2, 2); len2--
}
if (len1 != len2 && ! (len1 && len2 && substr(d1, 1, 1) == substr(d2, 1, 1))) {
# The two components differ in length, and the common prefix
# contains only leading zeros. Consider the longer to be less.
d1 = -len1
d2 = -len2
} else {
# Otherwise, compare as strings.
d1 = "x" d1
d2 = "x" d2
}
} else {
# A fraction is less than an integer.
exit 1
}
} else {
if (d2 ~ /^0/) {
# An integer is greater than a fraction.
exit 2
} else {
# Compare two integers.
d1 += 0
d2 += 0
}
}
} else {
# The normal case, without worrying about digits.
if (v1 == "") d1 = v1; else { d1 = substr(v1, 1, 1); v1 = substr(v1,2) }
if (v2 == "") d2 = v2; else { d2 = substr(v2, 1, 1); v2 = substr(v2,2) }
}
if (d1 < d2) exit 1
if (d1 > d2) exit 2
}
}
'
awk "$awk_strverscmp" v1="$1" v2="$2" /dev/null
case $? in
1) echo '<';;
0) echo '=';;
2) echo '>';;
esac
)
}
__require_tool_fatal ()
{
echo $@ >/dev/stderr
return 1
}
# Usage: require_tool program version
# Returns: 0 if $1 version if greater equals than $2, 1 otherwise.
# In case of error, message is written on error output.
#
# Example: require_tool gcc 4.6
# Use GCC environment variable if defined instead of lookup for the tool
# in the environment.
require_tool ()
{
envvar_name=$(echo $1 | tr '[:lower:]' '[:upper:]')
tool=$(printenv $envvar_name || echo $1)
local version=$($tool --version 2>/dev/null| \
sed -n 's/.*[^0-9.]\([0-9]*\.[0-9.]*\).*/\1/p;q')
if test x"$version" = x ; then
echo "$tool is required" >/dev/stderr
return 1
fi
case $(__require_tool_version_compare "$2" "$version") in
'>')
echo "$1 $2 or better is required: this is $tool $version" >/dev/stderr
return 1
;;
esac
}
usage() {
cat <<EOF
NAME
require_tool.sh - Ensure version of a tool is greater than the one expected
SYNOPSYS
require_tool.sh [ -h ]
[ --help ]
[ TOOL MIN_VERSION ]
DESCRIPTION
TOOL is the name or path of the program to check. If the name is specified, its
path is deduced from PATH environment variable. If environment variable TOOL
(in upper-case characters) is defined, considers its value as path to the tool.
MIN_VERSION is a string representing the minimum required version.
BEHAVIOR
* locate path to the program.
* execute $ TOOL_PATH --version
* extract version from standard output.
* compare this version to the expected one.
OPTIONS
-h --help
Display this message and exit 0
ERRORS
if program is not found or its version is prior to expected version,
a message is written to error output.
EXIT VALUE
returns 0 if program version if greater equals than expected version,
returns 1 otherwise.
EXAMPLE
$ require_tool.sh emacs 23
$ CC=g++ require_tool.sh cc 4.6
$ require_tool.sh zsh 4.5
EOF
}
for arg in $@; do
case $arg in
-h|--help)
usage
exit 0
;;
esac
done
if [ $# -gt 2 ] ; then
echo "ERROR: expecting 2 parameters. Please see option --help"
exit 1
fi
require_tool $@

View File

@ -1,96 +0,0 @@
#!/bin/zsh
# Zsh Theme Chooser by fox (fox91 at anche dot no)
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
THEMES_DIR="$ZSH/themes"
FAVLIST="${HOME}/.zsh_favlist"
source $ZSH/oh-my-zsh.sh
function noyes() {
read "a?$1 [y/N] "
if [[ $a == "N" || $a == "n" || $a = "" ]]; then
return 0
fi
return 1
}
function theme_preview() {
THEME=$1
THEME_NAME=`echo $THEME | sed s/\.zsh-theme$//`
print "$fg[blue]${(l.((${COLUMNS}-${#THEME_NAME}-5))..─.)}$reset_color $THEME_NAME $fg[blue]───$reset_color"
source "$THEMES_DIR/$THEME"
print -P $PROMPT
}
function banner() {
echo
echo "╺━┓┏━┓╻ ╻ ╺┳╸╻ ╻┏━╸┏┳┓┏━╸ ┏━╸╻ ╻┏━┓┏━┓┏━┓┏━╸┏━┓"
echo "┏━┛┗━┓┣━┫ ┃ ┣━┫┣╸ ┃┃┃┣╸ ┃ ┣━┫┃ ┃┃ ┃┗━┓┣╸ ┣┳┛"
echo "┗━╸┗━┛╹ ╹ ╹ ╹ ╹┗━╸╹ ╹┗━╸ ┗━╸╹ ╹┗━┛┗━┛┗━┛┗━╸╹┗╸"
echo
}
function usage() {
echo "Usage: $0 [options] [theme]"
echo
echo "Options"
echo " -l List available themes"
echo " -s Show all themes"
echo " -h Get this help message"
exit 1
}
function list_themes() {
for THEME in $(ls $THEMES_DIR); do
THEME_NAME=`echo $THEME | sed s/\.zsh-theme$//`
echo $THEME_NAME
done
}
function insert_favlist() {
if grep -q "$THEME_NAME" $FAVLIST 2> /dev/null ; then
echo "Already in favlist"
else
echo $THEME_NAME >> $FAVLIST
echo "Saved to favlist"
fi
}
function theme_chooser() {
for THEME in $(ls $THEMES_DIR); do
echo
theme_preview $THEME
echo
if [[ -z $1 ]]; then
noyes "Do you want to add it to your favourite list ($FAVLIST)?" || \
insert_favlist $THEME_NAME
echo
fi
done
}
while getopts ":lhs" Option
do
case $Option in
l ) list_themes ;;
s ) theme_chooser 0 ;;
h ) usage ;;
* ) usage ;; # Default.
esac
done
if [[ -z $Option ]]; then
if [[ -z $1 ]]; then
banner
echo
theme_chooser
else
theme_preview $1".zsh-theme"
fi
fi

View File

@ -1,20 +0,0 @@
echo "Removing ~/.oh-my-zsh"
if [[ -d ~/.oh-my-zsh ]]
then
rm -rf ~/.oh-my-zsh
fi
echo "Looking for an existing zsh config..."
if [ -f ~/.zshrc.pre-oh-my-zsh ] || [ -h ~/.zshrc.pre-oh-my-zsh ]
then
echo "Found ~/.zshrc. Backing up to ~/.zshrc.pre-oh-my-zsh";
rm ~/.zshrc;
cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc;
source ~/.zshrc;
else
echo "Switching back to bash"
chsh -s /bin/bash
source /etc/profile
fi
echo "Thanks for trying out Oh My Zsh. It's been uninstalled."

View File

@ -1,19 +0,0 @@
current_path=`pwd`
printf '\033[0;34m%s\033[0m\n' "Upgrading Oh My Zsh"
cd $ZSH
if git pull origin master
then
printf '\033[0;32m%s\033[0m\n' ' __ __ '
printf '\033[0;32m%s\033[0m\n' ' ____ / /_ ____ ___ __ __ ____ _____/ /_ '
printf '\033[0;32m%s\033[0m\n' ' / __ \/ __ \ / __ `__ \/ / / / /_ / / ___/ __ \ '
printf '\033[0;32m%s\033[0m\n' '/ /_/ / / / / / / / / / / /_/ / / /_(__ ) / / / '
printf '\033[0;32m%s\033[0m\n' '\____/_/ /_/ /_/ /_/ /_/\__, / /___/____/_/ /_/ '
printf '\033[0;32m%s\033[0m\n' ' /____/ '
printf '\033[0;34m%s\033[0m\n' 'Hooray! Oh My Zsh has been updated and/or is at the current version.'
printf '\033[0;34m%s\033[1m%s\033[0m\n' 'To keep up on the latest, be sure to follow Oh My Zsh on twitter: ' 'http://twitter.com/ohmyzsh'
else
printf '\033[0;31m%s\033[0m\n' 'There was an error updating. Try again later?'
fi
cd "$current_path"

42
Rakefile Normal file
View File

@ -0,0 +1,42 @@
require 'rake'
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 notes fonts iterm id_dsa.pub .git .gitignore].include? file
if File.exist?(File.join(ENV['HOME'], ".#{file}"))
if replace_all
replace_file(file)
else
print "overwrite ~/.#{file}? [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}"
end
end
else
link_file(file)
end
end
system %Q{mkdir ~/.tmp}
end
def replace_file(file)
system %Q{rm "$HOME/.#{file}"}
link_file(file)
end
def link_file(file)
puts "linking ~/.#{file}"
system %Q{ln -s "$PWD/#{file}" "$HOME/.#{file}"}
end

View File

@ -40,7 +40,7 @@
sp = stash pop sp = stash pop
sd = stash drop sd = stash drop
sa = stash apply sa = stash apply
st = status -s -b st = status
ci = commit ci = commit
cp = cherry-pick cp = cherry-pick
co = checkout co = checkout
@ -57,6 +57,7 @@
ff = merge --ff-only ff = merge --ff-only
pff = pull --ff-only pff = pull --ff-only
noff = merge --no-ff noff = merge --no-ff
theirs = merge -Xtheirs
la = !git ll --all la = !git ll --all
ll = "!source ~/.githelpers && pretty_git_log" ll = "!source ~/.githelpers && pretty_git_log"
div = divergence div = divergence

8
gitignore Normal file
View File

@ -0,0 +1,8 @@
.DS_Store
.svn
*~
tags
log/
db/*.sqlite3
.netrwhist
project-notes.txt

View File

View File

@ -0,0 +1,43 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
#config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.before(:each) do
clean_mongodb
Resque.reset!
end
def clean_mongodb
Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/}.each {|c| c.find.remove_all}
end
# TODO add additional functionality defined in test_helper as it is needed. e.g.
# factory_girl
end

View File

@ -0,0 +1,53 @@
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'mongoid'
require 'pry'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
require 'support/mongoid'
# NOTE: make sure to change this for other projects
Mongoid::Config.connect_to('campusperks_test')
RSpec.configure do |config|
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.before(:each) do
clean_mongodb
end
def clean_mongodb
Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/}.each {|c| c.find.remove_all}
end
end
# Stubs out a module so that Rails doesn't have to be loaded when testing classes that
# make use of Rails functionality in production.
#
# An example usage:
#
# require_relative '../spec_helper_lite'
# stub_module 'ActiveModel::Conversion'
# stub_module 'ActiveModel::Naming'
#
# describe Post do
# ...
# end
#
def stub_module(full_name)
full_name.to_s.split(/::/).reduce(Object) do|context, name|
begin
context.const_get(name)
rescue NameError
context.const_set(name, Module.new)
end
end
end

3
vim/.netrwhist Normal file
View File

@ -0,0 +1,3 @@
let g:netrw_dirhistmax =10
let g:netrw_dirhist_cnt =1
let g:netrw_dirhist_1='/Users/sauron/code/projects/dotfiles/zsh/func'

2
vim/bundle/ag/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
tags
ag-vim.tgz

74
vim/bundle/ag/README.md Normal file
View File

@ -0,0 +1,74 @@
# ag.vim #
This plugin is a front for ag, A.K.A.
[the_silver_searcher](https://github.com/ggreer/the_silver_searcher). Ag can
be used as a replacement for 153% of the uses of `ack`. This plugin will allow
you to run ag from vim, and shows the results in a split window.
## Installation ##
### The Silver Searcher
You have to first install [ag](https://github.com/ggreer/the_silver_searcher), itself. On Mac+Homebrew, Gentoo Linux, several others, there's package named `the_silver_searcher`, but if your OS/distro don't have one, the GitHub repo installs fine:
```sh
git clone https://github.com/ggreer/the_silver_searcher ag && cd ag && ./build.sh && sudo make install
```
* Then, if you're using [pathogen](https://github.com/tpope/vim-pathogen):
```sh
cd ~/.vim/bundle && git clone https://github.com/rking/ag.vim ag && vim +HelpTags
```
* Or, if you're using [Vundle](https://github.com/gmarik/vundle):
```sh
echo "Bundle 'rking/ag.vim'" >> ~/.vimrc && vim +BundleInstall
```
### Configuation
You can specify a custom ag name and path in your .vimrc like so:
let g:agprg="<custom-ag-path-goes-here> --column"
## Usage ##
:Ag [options] {pattern} [{directory}]
Search recursively in {directory} (which defaults to the current directory) for the {pattern}.
Files containing the search term will be listed in the split window, along with
the line number of the occurrence, once for each occurrence. [Enter] on a line
in this window will open the file, and place the cursor on the matching line.
Just like where you use :grep, :grepadd, :lgrep, and :lgrepadd, you can use `:Ag`, `:AgAdd`, `:LAg`, and `:LAgAdd` respectively. (See `doc/ag.txt`, or install and `:h Ag` for more information.)
### Gotchas ###
Some characters have special meaning, and need to be escaped your search pattern. For instance, '#'. You have to escape it like this `:Ag '\\\#define foo'` to search for `#define foo`. (From [blueyed in issue #5](https://github.com/mileszs/ack.vim/issues/5).)
Sometimes `git grep` is even faster, though in my experience it's not noticably so.
### Keyboard Shortcuts ###
In the quickfix window, you can use:
o to open (same as enter)
go to preview file (open but maintain focus on ag.vim results)
t to open in new tab
T to open in new tab silently
h to open in horizontal split
H to open in horizontal split silently
v to open in vertical split
gv to open in vertical split silently
q to close the quickfix window
### Acknowledgements
This Vim plugin is derived (and by derived, I mean copied, almost entirely)
from [milesz's ack.vim](https://github.com/mileszs/ack.vim), which I also
recommend installing since you might be in a situation where you have ack but
not ag, and don't want to stop to install ag. Also, ack supports `--type`, and
a few other features.

3
vim/bundle/ag/Rakefile Normal file
View File

@ -0,0 +1,3 @@
task :tgz do
sh 'cd ..; tar czvf ag/ag-vim.tgz ag/{plugin,autoload,doc}'
end

View File

@ -0,0 +1,101 @@
" NOTE: You must, of course, install ag / the_silver_searcher
" Location of the ag utility
if !exists("g:agprg")
let g:agprg="ag --column"
endif
if !exists("g:ag_apply_qmappings")
let g:ag_apply_qmappings = !exists("g:ag_qhandler")
endif
if !exists("g:ag_apply_lmappings")
let g:ag_apply_lmappings = !exists("g:ag_lhandler")
endif
if !exists("g:ag_qhandler")
let g:ag_qhandler="botright copen"
endif
if !exists("g:ag_lhandler")
let g:ag_lhandler="botright lopen"
endif
function! ag#Ag(cmd, args)
" If no pattern is provided, search for the word under the cursor
if empty(a:args)
let l:grepargs = expand("<cword>")
else
let l:grepargs = a:args . join(a:000, ' ')
end
" Format, used to manage column jump
if a:cmd =~# '-g$'
let g:agformat="%f"
else
let g:agformat="%f:%l:%c:%m"
end
let grepprg_bak=&grepprg
let grepformat_bak=&grepformat
try
let &grepprg=g:agprg
let &grepformat=g:agformat
silent execute a:cmd . " " . escape(l:grepargs, '|')
finally
let &grepprg=grepprg_bak
let &grepformat=grepformat_bak
endtry
if a:cmd =~# '^l'
exe g:ag_lhandler
let l:apply_mappings = g:ag_apply_lmappings
else
exe g:ag_qhandler
let l:apply_mappings = g:ag_apply_qmappings
endif
" If highlighting is on, highlight the search keyword.
if exists("g:aghighlight")
let @/=a:args
set hlsearch
end
redraw!
if l:apply_mappings
exec "nnoremap <silent> <buffer> q :ccl<CR>"
exec "nnoremap <silent> <buffer> t <C-W><CR><C-W>T"
exec "nnoremap <silent> <buffer> T <C-W><CR><C-W>TgT<C-W><C-W>"
exec "nnoremap <silent> <buffer> o <CR>"
exec "nnoremap <silent> <buffer> go <CR><C-W><C-W>"
exec "nnoremap <silent> <buffer> h <C-W><CR><C-W>K"
exec "nnoremap <silent> <buffer> H <C-W><CR><C-W>K<C-W>b"
exec "nnoremap <silent> <buffer> v <C-W><CR><C-W>H<C-W>b<C-W>J<C-W>t"
exec "nnoremap <silent> <buffer> gv <C-W><CR><C-W>H<C-W>b<C-W>J"
echom "ag.vim keys: q=quit <cr>/t/h/v=enter/tab/split/vsplit go/T/H/gv=preview versions of same"
endif
endfunction
function! ag#AgFromSearch(cmd, args)
let search = getreg('/')
" translate vim regular expression to perl regular expression.
let search = substitute(search,'\(\\<\|\\>\)','\\b','g')
call ag#Ag(a:cmd, '"' . search .'" '. a:args)
endfunction
function! ag#GetDocLocations()
let dp = ''
for p in split(&rtp,',')
let p = p.'/doc/'
if isdirectory(p)
let dp = p.'*.txt '.dp
endif
endfor
return dp
endfunction
function! ag#AgHelp(cmd,args)
let args = a:args.' '.ag#GetDocLocations()
call ag#Ag(a:cmd,args)
endfunction

80
vim/bundle/ag/doc/ag.txt Normal file
View File

@ -0,0 +1,80 @@
*ag.txt* Plugin that integrates ag with Vim
==============================================================================
INTRODUCTION *ag*
This plugin is a front for the_silver_searcher: ag. Ag can be used as a
replacement for ack. This plugin will allow you to run ag from vim, and
shows the results in a split window.
:Ag[!] [options] {pattern} [{directory}] *:Ag*
Search recursively in {directory} (which defaults to the current
directory) for the {pattern}. Behaves just like the |:grep| command, but
will open the |Quickfix| window for you. If [!] is not given the first
error is jumped to.
:AgAdd [options] {pattern} [{directory}] *:AgAdd*
Just like |:Ag|, but instead of making a new list, the matches are
appended to the current |quickfix| list.
:AgFromSearch [{directory}] *:AgFromSearch*
Just like |:Ag| but the pattern is from previous search.
:LAg [options] {pattern} [{directory}] *:LAg*
Just like |:Ag| but instead of the |quickfix| list, matches are placed in
the current |location-list|.
:LAgAdd [options] {pattern} [{directory}] *:LAgAdd*
Just like |:AgAdd| but instead of the |quickfix| list, matches are added
to the current |location-list|
:AgFile [options] {pattern} [{directory}] *:AgFile*
Search recursively in {directory} (which defaults to the current
directory) for filenames matching the {pattern}. Behaves just like the
|:grep| command, but will open the |Quickfix| window for you.
:AgHelp[!] [options] {pattern} *:AgHelp*
Search vim documentation files for the {pattern}. Behaves just like the
|:Ag| command, but searches only vim documentation .txt files
:LAgHelp [options] {pattern} *:LAgHelp*
Just like |:AgHelp| but instead of the |quickfix| list, matches are placed
in the current |location-list|.
Files containing the search term will be listed in the split window, along
with the line number of the occurrence, once for each occurrence. <Enter> on
a line in this window will open the file, and place the cursor on the matching
line.
See http://betterthangrep.com/ for more information.
==============================================================================
MAPPINGS *ag-mappings*
The following keyboard shortcuts are available in the quickfix window:
o open file (same as enter).
go preview file (open but maintain focus on ag.vim results).
t open in a new tab.
T open in new tab silently.
h open in horizontal split.
H open in horizontal split silently.
v open in vertical split.
gv open in vertical split silently.
q close the quickfix window.

View File

@ -0,0 +1,9 @@
" NOTE: You must, of course, install ag / the_silver_searcher
command! -bang -nargs=* -complete=file Ag call ag#Ag('grep<bang>',<q-args>)
command! -bang -nargs=* -complete=file AgAdd call ag#Ag('grepadd<bang>', <q-args>)
command! -bang -nargs=* -complete=file AgFromSearch call ag#AgFromSearch('grep<bang>', <q-args>)
command! -bang -nargs=* -complete=file LAg call ag#Ag('lgrep<bang>', <q-args>)
command! -bang -nargs=* -complete=file LAgAdd call ag#Ag('lgrepadd<bang>', <q-args>)
command! -bang -nargs=* -complete=file AgFile call ag#Ag('grep<bang> -g', <q-args>)
command! -bang -nargs=* -complete=help AgHelp call ag#AgHelp('grep<bang>',<q-args>)
command! -bang -nargs=* -complete=help LAgHelp call ag#AgHelp('lgrep<bang>',<q-args>)

6
vim/bundle/cctrlp.vim/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
*.markdown
*.zip
note.txt
tags
.hg*
tmp/*

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,140 @@
" =============================================================================
" File: autoload/ctrlp/bookmarkdir.vim
" Description: Bookmarked directories extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_bookmarkdir') && g:loaded_ctrlp_bookmarkdir
fini
en
let g:loaded_ctrlp_bookmarkdir = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#bookmarkdir#init()',
\ 'accept': 'ctrlp#bookmarkdir#accept',
\ 'lname': 'bookmarked dirs',
\ 'sname': 'bkd',
\ 'type': 'tabs',
\ 'opmul': 1,
\ 'nolim': 1,
\ 'wipe': 'ctrlp#bookmarkdir#remove',
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
" Utilities {{{1
fu! s:getinput(str, ...)
echoh Identifier
cal inputsave()
let input = call('input', a:0 ? [a:str] + a:000 : [a:str])
cal inputrestore()
echoh None
retu input
endf
fu! s:cachefile()
if !exists('s:cadir') || !exists('s:cafile')
let s:cadir = ctrlp#utils#cachedir().ctrlp#utils#lash().'bkd'
let s:cafile = s:cadir.ctrlp#utils#lash().'cache.txt'
en
retu s:cafile
endf
fu! s:writecache(lines)
cal ctrlp#utils#writecache(a:lines, s:cadir, s:cafile)
endf
fu! s:getbookmarks()
retu ctrlp#utils#readfile(s:cachefile())
endf
fu! s:savebookmark(name, cwd)
let cwds = exists('+ssl') ? [tr(a:cwd, '\', '/'), tr(a:cwd, '/', '\')] : [a:cwd]
let entries = filter(s:getbookmarks(), 'index(cwds, s:parts(v:val)[1]) < 0')
cal s:writecache(insert(entries, a:name.' '.a:cwd))
endf
fu! s:setentries()
let time = getftime(s:cachefile())
if !( exists('s:bookmarks') && time == s:bookmarks[0] )
let s:bookmarks = [time, s:getbookmarks()]
en
endf
fu! s:parts(str)
let mlist = matchlist(a:str, '\v([^\t]+)\t(.*)$')
retu mlist != [] ? mlist[1:2] : ['', '']
endf
fu! s:process(entries, type)
retu map(a:entries, 's:modify(v:val, a:type)')
endf
fu! s:modify(entry, type)
let [name, dir] = s:parts(a:entry)
let dir = fnamemodify(dir, a:type)
retu name.' '.( dir == '' ? '.' : dir )
endf
fu! s:msg(name, cwd)
redr
echoh Identifier | echon 'Bookmarked ' | echoh Constant
echon a:name.' ' | echoh Directory | echon a:cwd
echoh None
endf
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPBookmark', 'Identifier')
cal ctrlp#hicheck('CtrlPTabExtra', 'Comment')
sy match CtrlPBookmark '^> [^\t]\+' contains=CtrlPLinePre
sy match CtrlPTabExtra '\zs\t.*\ze$'
en
endf
" Public {{{1
fu! ctrlp#bookmarkdir#init()
cal s:setentries()
cal s:syntax()
retu s:process(copy(s:bookmarks[1]), ':.')
endf
fu! ctrlp#bookmarkdir#accept(mode, str)
let parts = s:parts(s:modify(a:str, ':p'))
cal call('s:savebookmark', parts)
if a:mode =~ 't\|v\|h'
cal ctrlp#exit()
en
cal ctrlp#setdir(parts[1], a:mode =~ 't\|h' ? 'chd!' : 'lc!')
if a:mode == 'e'
cal ctrlp#switchtype(0)
cal ctrlp#recordhist()
cal ctrlp#prtclear()
en
endf
fu! ctrlp#bookmarkdir#add(dir)
let str = 'Directory to bookmark: '
let cwd = a:dir != '' ? a:dir : s:getinput(str, getcwd(), 'dir')
if cwd == '' | retu | en
let cwd = fnamemodify(cwd, ':p')
let name = s:getinput('Bookmark as: ', cwd)
if name == '' | retu | en
let name = tr(name, ' ', ' ')
cal s:savebookmark(name, cwd)
cal s:msg(name, cwd)
endf
fu! ctrlp#bookmarkdir#remove(entries)
cal s:process(a:entries, ':p')
cal s:writecache(a:entries == [] ? [] :
\ filter(s:getbookmarks(), 'index(a:entries, v:val) < 0'))
cal s:setentries()
retu s:process(copy(s:bookmarks[1]), ':.')
endf
fu! ctrlp#bookmarkdir#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,261 @@
" =============================================================================
" File: autoload/ctrlp/buffertag.vim
" Description: Buffer Tag extension
" Maintainer: Kien Nguyen <github.com/kien>
" Credits: Much of the code was taken from tagbar.vim by Jan Larres, plus
" a few lines from taglist.vim by Yegappan Lakshmanan and from
" buffertag.vim by Takeshi Nishida.
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_buftag') && g:loaded_ctrlp_buftag
fini
en
let g:loaded_ctrlp_buftag = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#buffertag#init(s:crfile)',
\ 'accept': 'ctrlp#buffertag#accept',
\ 'lname': 'buffer tags',
\ 'sname': 'bft',
\ 'exit': 'ctrlp#buffertag#exit()',
\ 'type': 'tabs',
\ 'opts': 'ctrlp#buffertag#opts()',
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
let [s:pref, s:opts] = ['g:ctrlp_buftag_', {
\ 'systemenc': ['s:enc', &enc],
\ 'ctags_bin': ['s:bin', ''],
\ 'types': ['s:usr_types', {}],
\ }]
let s:bins = [
\ 'ctags-exuberant',
\ 'exuberant-ctags',
\ 'exctags',
\ '/usr/local/bin/ctags',
\ '/opt/local/bin/ctags',
\ 'ctags',
\ 'ctags.exe',
\ 'tags',
\ ]
let s:types = {
\ 'asm' : '%sasm%sasm%sdlmt',
\ 'aspperl': '%sasp%sasp%sfsv',
\ 'aspvbs' : '%sasp%sasp%sfsv',
\ 'awk' : '%sawk%sawk%sf',
\ 'beta' : '%sbeta%sbeta%sfsv',
\ 'c' : '%sc%sc%sdgsutvf',
\ 'cpp' : '%sc++%sc++%snvdtcgsuf',
\ 'cs' : '%sc#%sc#%sdtncEgsipm',
\ 'cobol' : '%scobol%scobol%sdfgpPs',
\ 'eiffel' : '%seiffel%seiffel%scf',
\ 'erlang' : '%serlang%serlang%sdrmf',
\ 'expect' : '%stcl%stcl%scfp',
\ 'fortran': '%sfortran%sfortran%spbceiklmntvfs',
\ 'html' : '%shtml%shtml%saf',
\ 'java' : '%sjava%sjava%spcifm',
\ 'javascript': '%sjavascript%sjavascript%sf',
\ 'lisp' : '%slisp%slisp%sf',
\ 'lua' : '%slua%slua%sf',
\ 'make' : '%smake%smake%sm',
\ 'pascal' : '%spascal%spascal%sfp',
\ 'perl' : '%sperl%sperl%sclps',
\ 'php' : '%sphp%sphp%scdvf',
\ 'python' : '%spython%spython%scmf',
\ 'rexx' : '%srexx%srexx%ss',
\ 'ruby' : '%sruby%sruby%scfFm',
\ 'scheme' : '%sscheme%sscheme%ssf',
\ 'sh' : '%ssh%ssh%sf',
\ 'csh' : '%ssh%ssh%sf',
\ 'zsh' : '%ssh%ssh%sf',
\ 'slang' : '%sslang%sslang%snf',
\ 'sml' : '%ssml%ssml%secsrtvf',
\ 'sql' : '%ssql%ssql%scFPrstTvfp',
\ 'tcl' : '%stcl%stcl%scfmp',
\ 'vera' : '%svera%svera%scdefgmpPtTvx',
\ 'verilog': '%sverilog%sverilog%smcPertwpvf',
\ 'vim' : '%svim%svim%savf',
\ 'yacc' : '%syacc%syacc%sl',
\ }
cal map(s:types, 'printf(v:val, "--language-force=", " --", "-types=")')
if executable('jsctags')
cal extend(s:types, { 'javascript': { 'args': '-f -', 'bin': 'jsctags' } })
en
fu! ctrlp#buffertag#opts()
for [ke, va] in items(s:opts)
let {va[0]} = exists(s:pref.ke) ? {s:pref.ke} : va[1]
endfo
" Ctags bin
if empty(s:bin)
for bin in s:bins | if executable(bin)
let s:bin = bin
brea
en | endfo
el
let s:bin = expand(s:bin, 1)
en
" Types
cal extend(s:types, s:usr_types)
endf
" Utilities {{{1
fu! s:validfile(fname, ftype)
if ( !empty(a:fname) || !empty(a:ftype) ) && filereadable(a:fname)
\ && index(keys(s:types), a:ftype) >= 0 | retu 1 | en
retu 0
endf
fu! s:exectags(cmd)
if exists('+ssl')
let [ssl, &ssl] = [&ssl, 0]
en
if &sh =~ 'cmd\.exe'
let [sxq, &sxq, shcf, &shcf] = [&sxq, '"', &shcf, '/s /c']
en
let output = system(a:cmd)
if &sh =~ 'cmd\.exe'
let [&sxq, &shcf] = [sxq, shcf]
en
if exists('+ssl')
let &ssl = ssl
en
retu output
endf
fu! s:exectagsonfile(fname, ftype)
let [ags, ft] = ['-f - --sort=no --excmd=pattern --fields=nKs ', a:ftype]
if type(s:types[ft]) == 1
let ags .= s:types[ft]
let bin = s:bin
elsei type(s:types[ft]) == 4
let ags = s:types[ft]['args']
let bin = expand(s:types[ft]['bin'], 1)
en
if empty(bin) | retu '' | en
let cmd = s:esctagscmd(bin, ags, a:fname)
if empty(cmd) | retu '' | en
let output = s:exectags(cmd)
if v:shell_error || output =~ 'Warning: cannot open' | retu '' | en
retu output
endf
fu! s:esctagscmd(bin, args, ...)
if exists('+ssl')
let [ssl, &ssl] = [&ssl, 0]
en
let fname = a:0 ? shellescape(a:1) : ''
let cmd = shellescape(a:bin).' '.a:args.' '.fname
if &sh =~ 'cmd\.exe'
let cmd = substitute(cmd, '[&()@^<>|]', '^\0', 'g')
en
if exists('+ssl')
let &ssl = ssl
en
if has('iconv')
let last = s:enc != &enc ? s:enc : !empty($LANG) ? $LANG : &enc
let cmd = iconv(cmd, &enc, last)
en
retu cmd
endf
fu! s:process(fname, ftype)
if !s:validfile(a:fname, a:ftype) | retu [] | endif
let ftime = getftime(a:fname)
if has_key(g:ctrlp_buftags, a:fname)
\ && g:ctrlp_buftags[a:fname]['time'] >= ftime
let lines = g:ctrlp_buftags[a:fname]['lines']
el
let data = s:exectagsonfile(a:fname, a:ftype)
let [raw, lines] = [split(data, '\n\+'), []]
for line in raw
if line !~# '^!_TAG_' && len(split(line, ';"')) == 2
let parsed_line = s:parseline(line)
if parsed_line != ''
cal add(lines, parsed_line)
en
en
endfo
let cache = { a:fname : { 'time': ftime, 'lines': lines } }
cal extend(g:ctrlp_buftags, cache)
en
retu lines
endf
fu! s:parseline(line)
let vals = matchlist(a:line,
\ '\v^([^\t]+)\t(.+)\t[?/]\^?(.{-1,})\$?[?/]\;\"\t(.+)\tline(no)?\:(\d+)')
if vals == [] | retu '' | en
let [bufnr, bufname] = [bufnr('^'.vals[2].'$'), fnamemodify(vals[2], ':p:t')]
retu vals[1].' '.vals[4].'|'.bufnr.':'.bufname.'|'.vals[6].'| '.vals[3]
endf
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPTagKind', 'Title')
cal ctrlp#hicheck('CtrlPBufName', 'Directory')
cal ctrlp#hicheck('CtrlPTabExtra', 'Comment')
sy match CtrlPTagKind '\zs[^\t|]\+\ze|\d\+:[^|]\+|\d\+|'
sy match CtrlPBufName '|\d\+:\zs[^|]\+\ze|\d\+|'
sy match CtrlPTabExtra '\zs\t.*\ze$' contains=CtrlPBufName,CtrlPTagKind
en
endf
fu! s:chknearby(pat)
if match(getline('.'), a:pat) < 0
let [int, forw, maxl] = [1, 1, line('$')]
wh !search(a:pat, 'W'.( forw ? '' : 'b' ))
if !forw
if int > maxl | brea | en
let int += int
en
let forw = !forw
endw
en
endf
" Public {{{1
fu! ctrlp#buffertag#init(fname)
let bufs = exists('s:btmode') && s:btmode
\ ? filter(ctrlp#buffers(), 'filereadable(v:val)')
\ : [exists('s:bufname') ? s:bufname : a:fname]
let lines = []
for each in bufs
let bname = fnamemodify(each, ':p')
let tftype = get(split(getbufvar('^'.bname.'$', '&ft'), '\.'), 0, '')
cal extend(lines, s:process(bname, tftype))
endfo
cal s:syntax()
retu lines
endf
fu! ctrlp#buffertag#accept(mode, str)
let vals = matchlist(a:str,
\ '\v^[^\t]+\t+[^\t|]+\|(\d+)\:[^\t|]+\|(\d+)\|\s(.+)$')
let bufnr = str2nr(get(vals, 1))
if bufnr
cal ctrlp#acceptfile(a:mode, bufname(bufnr))
exe 'norm!' str2nr(get(vals, 2, line('.'))).'G'
cal s:chknearby('\V\C'.get(vals, 3, ''))
sil! norm! zvzz
en
endf
fu! ctrlp#buffertag#cmd(mode, ...)
let s:btmode = a:mode
if a:0 && !empty(a:1)
let s:bufname = fnamemodify(a:1, ':p')
en
retu s:id
endf
fu! ctrlp#buffertag#exit()
unl! s:btmode s:bufname
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,95 @@
" =============================================================================
" File: autoload/ctrlp/changes.vim
" Description: Change list extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_changes') && g:loaded_ctrlp_changes
fini
en
let g:loaded_ctrlp_changes = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#changes#init(s:bufnr, s:crbufnr)',
\ 'accept': 'ctrlp#changes#accept',
\ 'lname': 'changes',
\ 'sname': 'chs',
\ 'exit': 'ctrlp#changes#exit()',
\ 'type': 'tabe',
\ 'sort': 0,
\ 'nolim': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
" Utilities {{{1
fu! s:changelist(bufnr)
sil! exe 'noa hid b' a:bufnr
redi => result
sil! changes
redi END
retu map(split(result, "\n")[1:], 'tr(v:val, " ", " ")')
endf
fu! s:process(clines, ...)
let [clines, evas] = [[], []]
for each in a:clines
let parts = matchlist(each, '\v^.\s*\d+\s+(\d+)\s+(\d+)\s(.*)$')
if !empty(parts)
if parts[3] == '' | let parts[3] = ' ' | en
cal add(clines, parts[3].' |'.a:1.':'.a:2.'|'.parts[1].':'.parts[2].'|')
en
endfo
retu reverse(filter(clines, 'count(clines, v:val) == 1'))
endf
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPBufName', 'Directory')
cal ctrlp#hicheck('CtrlPTabExtra', 'Comment')
sy match CtrlPBufName '\t|\d\+:\zs[^|]\+\ze|\d\+:\d\+|$'
sy match CtrlPTabExtra '\zs\t.*\ze$' contains=CtrlPBufName
en
endf
" Public {{{1
fu! ctrlp#changes#init(original_bufnr, bufnr)
let bufnr = exists('s:bufnr') ? s:bufnr : a:bufnr
let bufs = exists('s:clmode') && s:clmode ? ctrlp#buffers('id') : [bufnr]
cal filter(bufs, 'v:val > 0')
let [swb, &swb] = [&swb, '']
let lines = []
for each in bufs
let fnamet = fnamemodify(bufname(each), ':t')
cal extend(lines, s:process(s:changelist(each), each, fnamet))
endfo
sil! exe 'noa hid b' a:original_bufnr
let &swb = swb
cal ctrlp#syntax()
cal s:syntax()
retu lines
endf
fu! ctrlp#changes#accept(mode, str)
let info = matchlist(a:str, '\t|\(\d\+\):[^|]\+|\(\d\+\):\(\d\+\)|$')
let bufnr = str2nr(get(info, 1))
if bufnr
cal ctrlp#acceptfile(a:mode, bufname(bufnr))
cal cursor(get(info, 2), get(info, 3))
sil! norm! zvzz
en
endf
fu! ctrlp#changes#cmd(mode, ...)
let s:clmode = a:mode
if a:0 && !empty(a:1)
let s:bufnr = bufnr('^'.fnamemodify(a:1, ':p').'$')
en
retu s:id
endf
fu! ctrlp#changes#exit()
unl! s:clmode s:bufnr
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,93 @@
" =============================================================================
" File: autoload/ctrlp/dir.vim
" Description: Directory extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_dir') && g:loaded_ctrlp_dir
fini
en
let [g:loaded_ctrlp_dir, g:ctrlp_newdir] = [1, 0]
let s:ars = ['s:maxdepth', 's:maxfiles', 's:compare_lim', 's:glob', 's:caching']
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#dir#init('.join(s:ars, ', ').')',
\ 'accept': 'ctrlp#dir#accept',
\ 'lname': 'dirs',
\ 'sname': 'dir',
\ 'type': 'path',
\ 'specinput': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
let s:dircounts = {}
" Utilities {{{1
fu! s:globdirs(dirs, depth)
let entries = split(globpath(a:dirs, s:glob), "\n")
let [dirs, depth] = [ctrlp#dirnfile(entries)[0], a:depth + 1]
cal extend(g:ctrlp_alldirs, dirs)
let nr = len(g:ctrlp_alldirs)
if !empty(dirs) && !s:max(nr, s:maxfiles) && depth <= s:maxdepth
sil! cal ctrlp#progress(nr)
cal map(dirs, 'ctrlp#utils#fnesc(v:val, "g", ",")')
cal s:globdirs(join(dirs, ','), depth)
en
endf
fu! s:max(len, max)
retu a:max && a:len > a:max
endf
fu! s:nocache()
retu !s:caching || ( s:caching > 1 && get(s:dircounts, s:cwd) < s:caching )
endf
" Public {{{1
fu! ctrlp#dir#init(...)
let s:cwd = getcwd()
for each in range(len(s:ars))
let {s:ars[each]} = a:{each + 1}
endfo
let cadir = ctrlp#utils#cachedir().ctrlp#utils#lash().'dir'
let cafile = cadir.ctrlp#utils#lash().ctrlp#utils#cachefile('dir')
if g:ctrlp_newdir || s:nocache() || !filereadable(cafile)
let [s:initcwd, g:ctrlp_alldirs] = [s:cwd, []]
cal s:globdirs(ctrlp#utils#fnesc(s:cwd, 'g', ','), 0)
cal ctrlp#rmbasedir(g:ctrlp_alldirs)
if len(g:ctrlp_alldirs) <= s:compare_lim
cal sort(g:ctrlp_alldirs, 'ctrlp#complen')
en
cal ctrlp#utils#writecache(g:ctrlp_alldirs, cadir, cafile)
let g:ctrlp_newdir = 0
el
if !( exists('s:initcwd') && s:initcwd == s:cwd )
let s:initcwd = s:cwd
let g:ctrlp_alldirs = ctrlp#utils#readfile(cafile)
en
en
cal extend(s:dircounts, { s:cwd : len(g:ctrlp_alldirs) })
retu g:ctrlp_alldirs
endf
fu! ctrlp#dir#accept(mode, str)
let path = a:mode == 'h' ? getcwd() : s:cwd.ctrlp#utils#lash().a:str
if a:mode =~ 't\|v\|h'
cal ctrlp#exit()
en
cal ctrlp#setdir(path, a:mode =~ 't\|h' ? 'chd!' : 'lc!')
if a:mode == 'e'
sil! cal ctrlp#statusline()
cal ctrlp#setlines(s:id)
cal ctrlp#recordhist()
cal ctrlp#prtclear()
en
endf
fu! ctrlp#dir#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,62 @@
" =============================================================================
" File: autoload/ctrlp/line.vim
" Description: Line extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_line') && g:loaded_ctrlp_line
fini
en
let g:loaded_ctrlp_line = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#line#init()',
\ 'accept': 'ctrlp#line#accept',
\ 'lname': 'lines',
\ 'sname': 'lns',
\ 'type': 'tabe',
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
" Utilities {{{1
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPBufName', 'Directory')
cal ctrlp#hicheck('CtrlPTabExtra', 'Comment')
sy match CtrlPBufName '\t|\zs[^|]\+\ze|\d\+:\d\+|$'
sy match CtrlPTabExtra '\zs\t.*\ze$' contains=CtrlPBufName
en
endf
" Public {{{1
fu! ctrlp#line#init()
let [bufs, lines] = [ctrlp#buffers('id'), []]
for bufnr in bufs
let [lfb, bufn] = [getbufline(bufnr, 1, '$'), bufname(bufnr)]
let lfb = lfb == [] ? ctrlp#utils#readfile(fnamemodify(bufn, ':p')) : lfb
cal map(lfb, 'tr(v:val, '' '', '' '')')
let [linenr, len_lfb, buft] = [1, len(lfb), fnamemodify(bufn, ':t')]
wh linenr <= len_lfb
let lfb[linenr - 1] .= ' |'.buft.'|'.bufnr.':'.linenr.'|'
let linenr += 1
endw
cal extend(lines, filter(lfb, 'v:val !~ ''^\s*\t|[^|]\+|\d\+:\d\+|$'''))
endfo
cal s:syntax()
retu lines
endf
fu! ctrlp#line#accept(mode, str)
let info = matchlist(a:str, '\t|[^|]\+|\(\d\+\):\(\d\+\)|$')
let bufnr = str2nr(get(info, 1))
if bufnr
cal ctrlp#acceptfile(a:mode, bufname(bufnr), get(info, 2))
en
endf
fu! ctrlp#line#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,83 @@
" =============================================================================
" File: autoload/ctrlp/mixed.vim
" Description: Mixing Files + MRU + Buffers
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_mixed') && g:loaded_ctrlp_mixed
fini
en
let [g:loaded_ctrlp_mixed, g:ctrlp_newmix] = [1, 0]
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#mixed#init(s:compare_lim)',
\ 'accept': 'ctrlp#acceptfile',
\ 'lname': 'fil + mru + buf',
\ 'sname': 'mix',
\ 'type': 'path',
\ 'opmul': 1,
\ 'specinput': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
" Utilities {{{1
fu! s:newcache(cwd)
if g:ctrlp_newmix || !has_key(g:ctrlp_allmixes, 'data') | retu 1 | en
retu g:ctrlp_allmixes['cwd'] != a:cwd
\ || g:ctrlp_allmixes['filtime'] < getftime(ctrlp#utils#cachefile())
\ || g:ctrlp_allmixes['mrutime'] < getftime(ctrlp#mrufiles#cachefile())
\ || g:ctrlp_allmixes['bufs'] < len(ctrlp#mrufiles#bufs())
endf
fu! s:getnewmix(cwd, clim)
if g:ctrlp_newmix
cal ctrlp#mrufiles#refresh('raw')
let g:ctrlp_newcache = 1
en
let g:ctrlp_lines = copy(ctrlp#files())
cal ctrlp#progress('Mixing...')
let mrufs = copy(ctrlp#mrufiles#list('raw'))
if exists('+ssl') && &ssl
cal map(mrufs, 'tr(v:val, "\\", "/")')
en
let bufs = map(ctrlp#buffers('id'), 'fnamemodify(bufname(v:val), ":p")')
let mrufs = bufs + filter(mrufs, 'index(bufs, v:val) < 0')
if len(mrufs) > len(g:ctrlp_lines)
cal filter(mrufs, 'stridx(v:val, a:cwd)')
el
let cwd_mrufs = filter(copy(mrufs), '!stridx(v:val, a:cwd)')
let cwd_mrufs = ctrlp#rmbasedir(cwd_mrufs)
for each in cwd_mrufs
let id = index(g:ctrlp_lines, each)
if id >= 0 | cal remove(g:ctrlp_lines, id) | en
endfo
en
cal map(mrufs, 'fnamemodify(v:val, ":.")')
let g:ctrlp_lines = len(mrufs) > len(g:ctrlp_lines)
\ ? g:ctrlp_lines + mrufs : mrufs + g:ctrlp_lines
if len(g:ctrlp_lines) <= a:clim
cal sort(g:ctrlp_lines, 'ctrlp#complen')
en
let g:ctrlp_allmixes = { 'filtime': getftime(ctrlp#utils#cachefile()),
\ 'mrutime': getftime(ctrlp#mrufiles#cachefile()), 'cwd': a:cwd,
\ 'bufs': len(ctrlp#mrufiles#bufs()), 'data': g:ctrlp_lines }
endf
" Public {{{1
fu! ctrlp#mixed#init(clim)
let cwd = getcwd()
if s:newcache(cwd)
cal s:getnewmix(cwd, a:clim)
el
let g:ctrlp_lines = g:ctrlp_allmixes['data']
en
let g:ctrlp_newmix = 0
retu g:ctrlp_lines
endf
fu! ctrlp#mixed#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,129 @@
" =============================================================================
" File: autoload/ctrlp/mrufiles.vim
" Description: Most Recently Used Files extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Static variables {{{1
let [s:mrbs, s:mrufs] = [[], []]
fu! ctrlp#mrufiles#opts()
let [pref, opts] = ['g:ctrlp_mruf_', {
\ 'max': ['s:max', 250],
\ 'include': ['s:in', ''],
\ 'exclude': ['s:ex', ''],
\ 'case_sensitive': ['s:cseno', 1],
\ 'relative': ['s:re', 0],
\ }]
for [ke, va] in items(opts)
let [{va[0]}, {pref.ke}] = [pref.ke, exists(pref.ke) ? {pref.ke} : va[1]]
endfo
endf
cal ctrlp#mrufiles#opts()
" Utilities {{{1
fu! s:excl(fn)
retu !empty({s:ex}) && a:fn =~# {s:ex}
endf
fu! s:mergelists()
let diskmrufs = ctrlp#utils#readfile(ctrlp#mrufiles#cachefile())
cal filter(diskmrufs, 'index(s:mrufs, v:val) < 0')
let mrufs = s:mrufs + diskmrufs
retu s:chop(mrufs)
endf
fu! s:chop(mrufs)
if len(a:mrufs) > {s:max} | cal remove(a:mrufs, {s:max}, -1) | en
retu a:mrufs
endf
fu! s:reformat(mrufs)
if {s:re}
let cwd = exists('+ssl') ? tr(getcwd(), '/', '\') : getcwd()
cal filter(a:mrufs, '!stridx(v:val, cwd)')
en
retu map(a:mrufs, 'fnamemodify(v:val, ":.")')
endf
fu! s:record(bufnr)
if s:locked | retu | en
let bufnr = a:bufnr + 0
let bufname = bufname(bufnr)
if bufnr > 0 && !empty(bufname)
cal filter(s:mrbs, 'v:val != bufnr')
cal insert(s:mrbs, bufnr)
cal s:addtomrufs(bufname)
en
endf
fu! s:addtomrufs(fname)
let fn = fnamemodify(a:fname, ':p')
let fn = exists('+ssl') ? tr(fn, '/', '\') : fn
if ( !empty({s:in}) && fn !~# {s:in} ) || ( !empty({s:ex}) && fn =~# {s:ex} )
\ || !empty(getbufvar('^'.fn.'$', '&bt')) || !filereadable(fn) | retu
en
cal filter(s:mrufs, 'v:val !='.( {s:cseno} ? '#' : '?' ).' fn')
cal insert(s:mrufs, fn)
endf
fu! s:savetofile(mrufs)
cal ctrlp#utils#writecache(a:mrufs, s:cadir, s:cafile)
endf
" Public {{{1
fu! ctrlp#mrufiles#refresh(...)
let s:mrufs = s:mergelists()
cal filter(s:mrufs, '!empty(ctrlp#utils#glob(v:val, 1)) && !s:excl(v:val)')
if exists('+ssl')
cal map(s:mrufs, 'tr(v:val, "/", "\\")')
cal filter(s:mrufs, 'count(s:mrufs, v:val) == 1')
en
cal s:savetofile(s:mrufs)
retu a:0 && a:1 == 'raw' ? [] : s:reformat(copy(s:mrufs))
endf
fu! ctrlp#mrufiles#remove(files)
let s:mrufs = []
if a:files != []
let s:mrufs = s:mergelists()
cal filter(s:mrufs, 'index(a:files, v:val, 0, '.(!{s:cseno}).') < 0')
en
cal s:savetofile(s:mrufs)
retu s:reformat(copy(s:mrufs))
endf
fu! ctrlp#mrufiles#add(fn)
if !empty(a:fn)
cal s:addtomrufs(a:fn)
en
endf
fu! ctrlp#mrufiles#list(...)
retu a:0 ? a:1 == 'raw' ? s:mergelists() : 0 : s:reformat(s:mergelists())
endf
fu! ctrlp#mrufiles#bufs()
retu s:mrbs
endf
fu! ctrlp#mrufiles#cachefile()
if !exists('s:cadir') || !exists('s:cafile')
let s:cadir = ctrlp#utils#cachedir().ctrlp#utils#lash().'mru'
let s:cafile = s:cadir.ctrlp#utils#lash().'cache.txt'
en
retu s:cafile
endf
fu! ctrlp#mrufiles#init()
if !has('autocmd') | retu | en
let s:locked = 0
aug CtrlPMRUF
au!
au BufAdd,BufEnter,BufLeave,BufUnload * cal s:record(expand('<abuf>', 1))
au QuickFixCmdPre *vimgrep* let s:locked = 1
au QuickFixCmdPost *vimgrep* let s:locked = 0
au VimLeavePre * cal s:savetofile(s:mergelists())
aug END
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,59 @@
" =============================================================================
" File: autoload/ctrlp/quickfix.vim
" Description: Quickfix extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_quickfix') && g:loaded_ctrlp_quickfix
fini
en
let g:loaded_ctrlp_quickfix = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#quickfix#init()',
\ 'accept': 'ctrlp#quickfix#accept',
\ 'lname': 'quickfix',
\ 'sname': 'qfx',
\ 'type': 'line',
\ 'sort': 0,
\ 'nolim': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
fu! s:lineout(dict)
retu printf('%s|%d:%d| %s', bufname(a:dict['bufnr']), a:dict['lnum'],
\ a:dict['col'], matchstr(a:dict['text'], '\s*\zs.*\S'))
endf
" Utilities {{{1
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPqfLineCol', 'Search')
sy match CtrlPqfLineCol '|\zs\d\+:\d\+\ze|'
en
endf
" Public {{{1
fu! ctrlp#quickfix#init()
cal s:syntax()
retu map(getqflist(), 's:lineout(v:val)')
endf
fu! ctrlp#quickfix#accept(mode, str)
let vals = matchlist(a:str, '^\([^|]\+\ze\)|\(\d\+\):\(\d\+\)|')
if vals == [] || vals[1] == '' | retu | en
cal ctrlp#acceptfile(a:mode, vals[1])
let cur_pos = getpos('.')[1:2]
if cur_pos != [1, 1] && cur_pos != map(vals[2:3], 'str2nr(v:val)')
mark '
en
cal cursor(vals[2], vals[3])
sil! norm! zvzz
endf
fu! ctrlp#quickfix#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,59 @@
" =============================================================================
" File: autoload/ctrlp/rtscript.vim
" Description: Runtime scripts extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_rtscript') && g:loaded_ctrlp_rtscript
fini
en
let [g:loaded_ctrlp_rtscript, g:ctrlp_newrts] = [1, 0]
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#rtscript#init(s:caching)',
\ 'accept': 'ctrlp#acceptfile',
\ 'lname': 'runtime scripts',
\ 'sname': 'rts',
\ 'type': 'path',
\ 'opmul': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
let s:filecounts = {}
" Utilities {{{1
fu! s:nocache()
retu g:ctrlp_newrts ||
\ !s:caching || ( s:caching > 1 && get(s:filecounts, s:cwd) < s:caching )
endf
" Public {{{1
fu! ctrlp#rtscript#init(caching)
let [s:caching, s:cwd] = [a:caching, getcwd()]
if s:nocache() ||
\ !( exists('g:ctrlp_rtscache') && g:ctrlp_rtscache[0] == &rtp )
sil! cal ctrlp#progress('Indexing...')
let entries = split(globpath(ctrlp#utils#fnesc(&rtp, 'g'), '**/*.*'), "\n")
cal filter(entries, 'count(entries, v:val) == 1')
let [entries, echoed] = [ctrlp#dirnfile(entries)[1], 1]
el
let [entries, results] = g:ctrlp_rtscache[2:3]
en
if s:nocache() ||
\ !( exists('g:ctrlp_rtscache') && g:ctrlp_rtscache[:1] == [&rtp, s:cwd] )
if !exists('echoed')
sil! cal ctrlp#progress('Processing...')
en
let results = map(copy(entries), 'fnamemodify(v:val, '':.'')')
en
let [g:ctrlp_rtscache, g:ctrlp_newrts] = [[&rtp, s:cwd, entries, results], 0]
cal extend(s:filecounts, { s:cwd : len(results) })
retu results
endf
fu! ctrlp#rtscript#id()
retu s:id
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,125 @@
" =============================================================================
" File: autoload/ctrlp/tag.vim
" Description: Tag file extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if exists('g:loaded_ctrlp_tag') && g:loaded_ctrlp_tag
fini
en
let g:loaded_ctrlp_tag = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#tag#init()',
\ 'accept': 'ctrlp#tag#accept',
\ 'lname': 'tags',
\ 'sname': 'tag',
\ 'enter': 'ctrlp#tag#enter()',
\ 'type': 'tabs',
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
" Utilities {{{1
fu! s:findcount(str)
let [tg, fname] = split(a:str, '\t\+\ze[^\t]\+$')
let tgs = taglist('^'.tg.'$')
if len(tgs) < 2
retu [1, 1]
en
let bname = fnamemodify(bufname('%'), ':p')
let fname = expand(fnamemodify(simplify(fname), ':s?^[.\/]\+??:p:.'), 1)
let [fnd, ct, pos, idx] = [0, 0, 0, 0]
wh idx < len(tgs)
if bname == fnamemodify(tgs[idx]["filename"], ':p')
cal insert(tgs, remove(tgs, idx))
brea
en
let idx += 1
endw
for each in tgs
let ct += 1
let fulname = fnamemodify(each["filename"], ':p')
if stridx(fulname, fname) >= 0
\ && strlen(fname) + stridx(fulname, fname) == strlen(fulname)
let fnd += 1
let pos = ct
en
if fnd > 1 | brea | en
endfo
retu [fnd, pos]
endf
fu! s:filter(tags)
let nr = 0
wh 0 < 1
if a:tags == [] | brea | en
if a:tags[nr] =~ '^!' && a:tags[nr] !~# '^!_TAG_'
let nr += 1
con
en
if a:tags[nr] =~# '^!_TAG_' && len(a:tags) > nr
cal remove(a:tags, nr)
el
brea
en
endw
retu a:tags
endf
fu! s:syntax()
if !ctrlp#nosy()
cal ctrlp#hicheck('CtrlPTabExtra', 'Comment')
sy match CtrlPTabExtra '\zs\t.*\ze$'
en
endf
" Public {{{1
fu! ctrlp#tag#init()
if empty(s:tagfiles) | retu [] | en
let g:ctrlp_alltags = []
let tagfiles = sort(filter(s:tagfiles, 'count(s:tagfiles, v:val) == 1'))
for each in tagfiles
let alltags = s:filter(ctrlp#utils#readfile(each))
cal extend(g:ctrlp_alltags, alltags)
endfo
cal s:syntax()
retu g:ctrlp_alltags
endf
fu! ctrlp#tag#accept(mode, str)
cal ctrlp#exit()
let str = matchstr(a:str, '^[^\t]\+\t\+[^\t]\+\ze\t')
let [tg, fnd] = [split(str, '^[^\t]\+\zs\t')[0], s:findcount(str)]
let cmds = {
\ 't': ['tab sp', 'tab stj'],
\ 'h': ['sp', 'stj'],
\ 'v': ['vs', 'vert stj'],
\ 'e': ['', 'tj'],
\ }
let cmd = fnd[0] == 1 ? cmds[a:mode][0] : cmds[a:mode][1]
let cmd = a:mode == 'e' && ctrlp#modfilecond(!&aw)
\ ? ( cmd == 'tj' ? 'stj' : 'sp' ) : cmd
let cmd = a:mode == 't' ? ctrlp#tabcount().cmd : cmd
if fnd[0] == 1
if cmd != ''
exe cmd
en
exe fnd[1].'ta' tg
el
exe cmd tg
en
cal ctrlp#setlcdir()
endf
fu! ctrlp#tag#id()
retu s:id
endf
fu! ctrlp#tag#enter()
let tfs = tagfiles()
let s:tagfiles = tfs != [] ? filter(map(tfs, 'fnamemodify(v:val, ":p")'),
\ 'filereadable(v:val)') : []
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,154 @@
" =============================================================================
" File: autoload/ctrlp/undo.vim
" Description: Undo extension
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Init {{{1
if ( exists('g:loaded_ctrlp_undo') && g:loaded_ctrlp_undo )
fini
en
let g:loaded_ctrlp_undo = 1
cal add(g:ctrlp_ext_vars, {
\ 'init': 'ctrlp#undo#init()',
\ 'accept': 'ctrlp#undo#accept',
\ 'lname': 'undo',
\ 'sname': 'udo',
\ 'enter': 'ctrlp#undo#enter()',
\ 'exit': 'ctrlp#undo#exit()',
\ 'type': 'line',
\ 'sort': 0,
\ 'nolim': 1,
\ })
let s:id = g:ctrlp_builtins + len(g:ctrlp_ext_vars)
let s:text = map(['second', 'seconds', 'minutes', 'hours', 'days', 'weeks',
\ 'months', 'years'], '" ".v:val." ago"')
" Utilities {{{1
fu! s:getundo()
if exists('*undotree')
\ && ( v:version > 703 || ( v:version == 703 && has('patch005') ) )
retu [1, undotree()]
el
redi => result
sil! undol
redi END
retu [0, split(result, "\n")[1:]]
en
endf
fu! s:flatten(tree, cur)
let flatdict = {}
for each in a:tree
let saved = has_key(each, 'save') ? 'saved' : ''
let current = each['seq'] == a:cur ? 'current' : ''
cal extend(flatdict, { each['seq'] : [each['time'], saved, current] })
if has_key(each, 'alt')
cal extend(flatdict, s:flatten(each['alt'], a:cur))
en
endfo
retu flatdict
endf
fu! s:elapsed(nr)
let [text, time] = [s:text, localtime() - a:nr]
let mins = time / 60
let hrs = time / 3600
let days = time / 86400
let wks = time / 604800
let mons = time / 2592000
let yrs = time / 31536000
if yrs > 1
retu yrs.text[7]
elsei mons > 1
retu mons.text[6]
elsei wks > 1
retu wks.text[5]
elsei days > 1
retu days.text[4]
elsei hrs > 1
retu hrs.text[3]
elsei mins > 1
retu mins.text[2]
elsei time == 1
retu time.text[0]
elsei time < 120
retu time.text[1]
en
endf
fu! s:syntax()
if ctrlp#nosy() | retu | en
for [ke, va] in items({'T': 'Directory', 'Br': 'Comment', 'Nr': 'String',
\ 'Sv': 'Comment', 'Po': 'Title'})
cal ctrlp#hicheck('CtrlPUndo'.ke, va)
endfo
sy match CtrlPUndoT '\v\d+ \zs[^ ]+\ze|\d+:\d+:\d+'
sy match CtrlPUndoBr '\[\|\]'
sy match CtrlPUndoNr '\[\d\+\]' contains=CtrlPUndoBr
sy match CtrlPUndoSv 'saved'
sy match CtrlPUndoPo 'current'
endf
fu! s:dict2list(dict)
for ke in keys(a:dict)
let a:dict[ke][0] = s:elapsed(a:dict[ke][0])
endfo
retu map(keys(a:dict), 'eval(''[v:val, a:dict[v:val]]'')')
endf
fu! s:compval(...)
retu a:2[0] - a:1[0]
endf
fu! s:format(...)
let saved = !empty(a:1[1][1]) ? ' '.a:1[1][1] : ''
let current = !empty(a:1[1][2]) ? ' '.a:1[1][2] : ''
retu a:1[1][0].' ['.a:1[0].']'.saved.current
endf
fu! s:formatul(...)
let parts = matchlist(a:1,
\ '\v^\s+(\d+)\s+\d+\s+([^ ]+\s?[^ ]+|\d+\s\w+\s\w+)(\s*\d*)$')
retu parts == [] ? '----'
\ : parts[2].' ['.parts[1].']'.( parts[3] != '' ? ' saved' : '' )
endf
" Public {{{1
fu! ctrlp#undo#init()
let entries = s:undos[0] ? s:undos[1]['entries'] : s:undos[1]
if empty(entries) | retu [] | en
if !exists('s:lines')
if s:undos[0]
let entries = s:dict2list(s:flatten(entries, s:undos[1]['seq_cur']))
let s:lines = map(sort(entries, 's:compval'), 's:format(v:val)')
el
let s:lines = map(reverse(entries), 's:formatul(v:val)')
en
en
cal s:syntax()
retu s:lines
endf
fu! ctrlp#undo#accept(mode, str)
let undon = matchstr(a:str, '\[\zs\d\+\ze\]')
if empty(undon) | retu | en
cal ctrlp#exit()
exe 'u' undon
endf
fu! ctrlp#undo#id()
retu s:id
endf
fu! ctrlp#undo#enter()
let s:undos = s:getundo()
endf
fu! ctrlp#undo#exit()
unl! s:lines
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

View File

@ -0,0 +1,120 @@
" =============================================================================
" File: autoload/ctrlp/utils.vim
" Description: Utilities
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" Static variables {{{1
fu! ctrlp#utils#lash()
retu &ssl || !exists('+ssl') ? '/' : '\'
endf
fu! s:lash(...)
retu ( a:0 ? a:1 : getcwd() ) !~ '[\/]$' ? s:lash : ''
endf
fu! ctrlp#utils#opts()
let s:lash = ctrlp#utils#lash()
let usrhome = $HOME.s:lash($HOME)
let cahome = exists('$XDG_CACHE_HOME') ? $XDG_CACHE_HOME : usrhome.'.cache'
let cadir = isdirectory(usrhome.'.ctrlp_cache')
\ ? usrhome.'.ctrlp_cache' : cahome.s:lash(cahome).'ctrlp'
if exists('g:ctrlp_cache_dir')
let cadir = expand(g:ctrlp_cache_dir, 1)
if isdirectory(cadir.s:lash(cadir).'.ctrlp_cache')
let cadir = cadir.s:lash(cadir).'.ctrlp_cache'
en
en
let s:cache_dir = cadir
endf
cal ctrlp#utils#opts()
let s:wig_cond = v:version > 702 || ( v:version == 702 && has('patch051') )
" Files and Directories {{{1
fu! ctrlp#utils#cachedir()
retu s:cache_dir
endf
fu! ctrlp#utils#cachefile(...)
let [tail, dir] = [a:0 == 1 ? '.'.a:1 : '', a:0 == 2 ? a:1 : getcwd()]
let cache_file = substitute(dir, '\([\/]\|^\a\zs:\)', '%', 'g').tail.'.txt'
retu a:0 == 1 ? cache_file : s:cache_dir.s:lash(s:cache_dir).cache_file
endf
fu! ctrlp#utils#readfile(file)
if filereadable(a:file)
let data = readfile(a:file)
if empty(data) || type(data) != 3
unl data
let data = []
en
retu data
en
retu []
endf
fu! ctrlp#utils#mkdir(dir)
if exists('*mkdir') && !isdirectory(a:dir)
sil! cal mkdir(a:dir, 'p')
en
retu a:dir
endf
fu! ctrlp#utils#writecache(lines, ...)
if isdirectory(ctrlp#utils#mkdir(a:0 ? a:1 : s:cache_dir))
sil! cal writefile(a:lines, a:0 >= 2 ? a:2 : ctrlp#utils#cachefile())
en
endf
fu! ctrlp#utils#glob(...)
let path = ctrlp#utils#fnesc(a:1, 'g')
retu s:wig_cond ? glob(path, a:2) : glob(path)
endf
fu! ctrlp#utils#globpath(...)
retu call('globpath', s:wig_cond ? a:000 : a:000[:1])
endf
fu! ctrlp#utils#fnesc(path, type, ...)
if exists('*fnameescape')
if exists('+ssl')
if a:type == 'c'
let path = escape(a:path, '%#')
elsei a:type == 'f'
let path = fnameescape(a:path)
elsei a:type == 'g'
let path = escape(a:path, '?*')
en
let path = substitute(path, '[', '[[]', 'g')
el
let path = fnameescape(a:path)
en
el
if exists('+ssl')
if a:type == 'c'
let path = escape(a:path, '%#')
elsei a:type == 'f'
let path = escape(a:path, " \t\n%#*?|<\"")
elsei a:type == 'g'
let path = escape(a:path, '?*')
en
let path = substitute(path, '[', '[[]', 'g')
el
let path = escape(a:path, " \t\n*?[{`$\\%#'\"|!<")
en
en
retu a:0 ? escape(path, a:1) : path
endf
fu! ctrlp#utils#dircompl(...)
let [hsl, str] = [match(a:1, '[\/]'), '']
let par = substitute(a:1, '[^\/]*$', '', '')
let path = !hsl ? par : hsl > 0 ? getcwd().s:lash().par : getcwd()
for dir in split(globpath(ctrlp#utils#fnesc(path, 'g', ','), '*/'), '\n')
let str .= par.split(dir, '[\/]')[-1]."\n"
endfo
retu str
endf
"}}}
" vim:fen:fdm=marker:fmr={{{,}}}:fdl=0:fdc=1:ts=2:sw=2:sts=2

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,69 @@
" =============================================================================
" File: plugin/ctrlp.vim
" Description: Fuzzy file, buffer, mru, tag, etc finder.
" Author: Kien Nguyen <github.com/kien>
" =============================================================================
" GetLatestVimScripts: 3736 1 :AutoInstall: ctrlp.zip
if ( exists('g:loaded_ctrlp') && g:loaded_ctrlp ) || v:version < 700 || &cp
fini
en
let g:loaded_ctrlp = 1
let [g:ctrlp_lines, g:ctrlp_allfiles, g:ctrlp_alltags, g:ctrlp_alldirs,
\ g:ctrlp_allmixes, g:ctrlp_buftags, g:ctrlp_ext_vars, g:ctrlp_builtins]
\ = [[], [], [], [], {}, {}, [], 2]
if !exists('g:ctrlp_map') | let g:ctrlp_map = '<c-p>' | en
if !exists('g:ctrlp_cmd') | let g:ctrlp_cmd = 'CtrlP' | en
com! -n=? -com=custom,ctrlp#utils#dircompl CtrlP
\ cal ctrlp#init(0, { 'dir': <q-args> })
com! -n=? -com=custom,ctrlp#utils#dircompl CtrlPMRUFiles
\ cal ctrlp#init(2, { 'dir': <q-args> })
com! -bar CtrlPBuffer cal ctrlp#init(1)
com! -n=? CtrlPLastMode cal ctrlp#init(-1, { 'args': <q-args> })
com! -bar CtrlPClearCache cal ctrlp#clr()
com! -bar CtrlPClearAllCaches cal ctrlp#clra()
com! -bar ClearCtrlPCache cal ctrlp#clr()
com! -bar ClearAllCtrlPCaches cal ctrlp#clra()
com! -bar CtrlPCurWD cal ctrlp#init(0, { 'mode': '' })
com! -bar CtrlPCurFile cal ctrlp#init(0, { 'mode': 'c' })
com! -bar CtrlPRoot cal ctrlp#init(0, { 'mode': 'r' })
if g:ctrlp_map != '' && !hasmapto(':<c-u>'.g:ctrlp_cmd.'<cr>', 'n')
exe 'nn <silent>' g:ctrlp_map ':<c-u>'.g:ctrlp_cmd.'<cr>'
en
cal ctrlp#mrufiles#init()
com! -bar CtrlPTag cal ctrlp#init(ctrlp#tag#id())
com! -bar CtrlPQuickfix cal ctrlp#init(ctrlp#quickfix#id())
com! -n=? -com=custom,ctrlp#utils#dircompl CtrlPDir
\ cal ctrlp#init(ctrlp#dir#id(), { 'dir': <q-args> })
com! -n=? -com=buffer CtrlPBufTag
\ cal ctrlp#init(ctrlp#buffertag#cmd(0, <q-args>))
com! -bar CtrlPBufTagAll cal ctrlp#init(ctrlp#buffertag#cmd(1))
com! -bar CtrlPRTS cal ctrlp#init(ctrlp#rtscript#id())
com! -bar CtrlPUndo cal ctrlp#init(ctrlp#undo#id())
com! -bar CtrlPLine cal ctrlp#init(ctrlp#line#id())
com! -n=? -com=buffer CtrlPChange
\ cal ctrlp#init(ctrlp#changes#cmd(0, <q-args>))
com! -bar CtrlPChangeAll cal ctrlp#init(ctrlp#changes#cmd(1))
com! -bar CtrlPMixed cal ctrlp#init(ctrlp#mixed#id())
com! -bar CtrlPBookmarkDir cal ctrlp#init(ctrlp#bookmarkdir#id())
com! -n=? -com=custom,ctrlp#utils#dircompl CtrlPBookmarkDirAdd
\ cal ctrlp#call('ctrlp#bookmarkdir#add', <q-args>)
" vim:ts=2:sw=2:sts=2

View File

@ -0,0 +1,86 @@
# ctrlp.vim
Full path fuzzy __file__, __buffer__, __mru__, __tag__, __...__ finder for Vim.
* Written in pure Vimscript for MacVim, gVim and Vim 7.0+.
* Full support for Vim's regexp as search patterns.
* Built-in Most Recently Used (MRU) files monitoring.
* Built-in project's root finder.
* Open multiple files at once.
* Create new files and directories.
* [Extensible][2].
![ctrlp][1]
## Basic Usage
* Run `:CtrlP` or `:CtrlP [starting-directory]` to invoke CtrlP in find file mode.
* Run `:CtrlPBuffer` or `:CtrlPMRU` to invoke CtrlP in find buffer or find MRU file mode.
* Run `:CtrlPMixed` to search in Files, Buffers and MRU files at the same time.
Check `:help ctrlp-commands` and `:help ctrlp-extensions` for other commands.
##### Once CtrlP is open:
* Press `<F5>` to purge the cache for the current directory to get new files, remove deleted files and apply new ignore options.
* Press `<c-f>` and `<c-b>` to cycle between modes.
* Press `<c-d>` to switch to filename only search instead of full path.
* Press `<c-r>` to switch to regexp mode.
* Use `<c-n>`, `<c-p>` to select the next/previous string in the prompt's history.
* Use `<c-y>` to create a new file and its parent directories.
* Use `<c-z>` to mark/unmark multiple files and `<c-o>` to open them.
Run `:help ctrlp-mappings` or submit `?` in CtrlP for more mapping help.
* Submit two or more dots `..` to go up the directory tree by one or multiple levels.
* End the input string with a colon `:` followed by a command to execute it on the opening file(s):
Use `:25` to jump to line 25.
Use `:diffthis` when opening multiple files to run `:diffthis` on the first 4 files.
## Basic Options
* Change the default mapping and the default command to invoke CtrlP:
```vim
let g:ctrlp_map = '<c-p>'
let g:ctrlp_cmd = 'CtrlP'
```
* When invoked, unless a starting directory is specified, CtrlP will set its local working directory according to this variable:
```vim
let g:ctrlp_working_path_mode = 'ra'
```
`'c'` - the directory of the current file.
`'r'` - the nearest ancestor that contains one of these directories or files: `.git` `.hg` `.svn` `.bzr` `_darcs`
`'a'` - like c, but only if the current working directory outside of CtrlP is not a direct ancestor of the directory of the current file.
`0` or `''` (empty string) - disable this feature.
Define additional root markers with the `g:ctrlp_root_markers` option.
* Exclude files and directories using Vim's `wildignore` and CtrlP's own `g:ctrlp_custom_ignore`:
```vim
set wildignore+=*/tmp/*,*.so,*.swp,*.zip " MacOSX/Linux
set wildignore+=*\\tmp\\*,*.swp,*.zip,*.exe " Windows
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_custom_ignore = {
\ 'dir': '\v[\/]\.(git|hg|svn)$',
\ 'file': '\v\.(exe|so|dll)$',
\ 'link': 'some_bad_symbolic_links',
\ }
```
* Use a custom file listing command:
```vim
let g:ctrlp_user_command = 'find %s -type f' " MacOSX/Linux
let g:ctrlp_user_command = 'dir %s /-n /b /s /a-d' " Windows
```
Check `:help ctrlp-options` for other options.
## Installation
Use your favorite method or check the homepage for a [quick installation guide][3].
[1]: http://i.imgur.com/yIynr.png
[2]: https://github.com/kien/ctrlp.vim/tree/extensions
[3]: http://kien.github.com/ctrlp.vim#installation

View File

@ -0,0 +1,11 @@
all : gist-vim.zip
remove-zip:
-rm -f doc/tags
-rm -f gist-vim.zip
gist-vim.zip: remove-zip
zip -r gist-vim.zip autoload plugin doc README.mkd
release: gist-vim.zip
vimup update-script gist.vim

View File

@ -0,0 +1,224 @@
### Gist.vim
This is a vimscript for creating gists (http://gist.github.com).
For the latest version please see https://github.com/mattn/gist-vim.
## Usage:
- Post current buffer to gist, using default privacy option.
:Gist
- Post selected text to gist, using default privacy option.
This applies to all permutations listed below (except multi).
:'<,'>Gist
- Create a private gist.
:Gist -p
- Create a public gist.
(Only relevant if you've set gists to be private by default.)
:Gist -P
> This is only relevant if you've set gists to be private by default;
> if you get an empty gist list, try ":Gist --abandon".
- Create a gist anonymously.
:Gist -a
- Create a gist with all open buffers.
:Gist -m
- Edit the gist (you need to have opened the gist buffer first).
You can update the gist with the ":w" command within the gist buffer.
:Gist -e
- Edit the gist with name 'foo.js' (you need to have opened the gist buffer
first).
:Gist -e foo.js
- Post/Edit with the description " (you need to have opened the gist buffer
first). >
:Gist -s something
:Gist -e -s something
- Delete the gist (you need to have opened the gist buffer first).
Password authentication is needed.
:Gist -d
- Fork the gist (you need to have opened the gist buffer first).
Password authentication is needed.
:Gist -f
- Star the gist (you need to have opened the gist buffer first).
Password authentication is needed.
:Gist +1
- Unstar the gist (you need to have opened the gist buffer first).
Password authentication is needed.
:Gist -1
- Get gist XXXXX.
:Gist XXXXX
- Get gist XXXXX and add to clipboard.
:Gist -c XXXXX
- List your public gists.
:Gist -l
- List gists from user "mattn".
:Gist -l mattn
- List everyone's gists.
:Gist -la
- List gists from your starred gists.
:Gist -ls
## Tips:
If you set g:gist_clip_command, gist.vim will copy the gist code with option
'-c'.
- Mac:
let g:gist_clip_command = 'pbcopy'
- Linux:
let g:gist_clip_command = 'xclip -selection clipboard'
- Others (cygwin?):
let g:gist_clip_command = 'putclip'
If you want to detect filetype from the filename:
let g:gist_detect_filetype = 1
If you want to open browser after the post:
let g:gist_open_browser_after_post = 1
If you want to change the browser:
let g:gist_browser_command = 'w3m %URL%'
or:
let g:gist_browser_command = 'opera %URL% &'
On windows, this should work with your user settings.
If you want to show your private gists with ":Gist -l":
let g:gist_show_privates = 1
If you want your gist to be private by default:
let g:gist_post_private = 1
If you want to manipulate multiple files in a gist:
let g:gist_get_multiplefile = 1
If you want to use on Github Enterprise:
let g:github_api_url = 'http://your-github-enterprise-domain/api/v3'
You need to either set global git config:
$ git config --global github.user Username
## License:
Copyright 2010 by Yasuhiro Matsumoto
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
## Install:
Copy it to your plugin directory.
gist.vim will create a curl cookie-jar file in your runtimepath.
- rtp:
- autoload/gist.vim
- plugin/gist.vim
If you want to uninstall gist.vim, remember to also remove `~/.gist-vim`.
You need to install webapi-vim also:
http://www.vim.org/scripts/script.php?script_id=4019
If you want to use latest one:
https://github.com/mattn/webapi-vim
### Install with [Vundle](https://github.com/gmarik/vundle)
Add the following lines to your `.vimrc`.
Bundle 'mattn/webapi-vim'
Bundle 'mattn/gist-vim'
Now restart Vim and run `:BundleInstall`.
## Requirements:
- curl command (http://curl.haxx.se/)
- webapi-vim (https://github.com/mattn/webapi-vim)
- and if you want to use your git profile, the git command-line client.
## Setup:
This plugin uses github API v3. Setting value is stored in `~/.gist-vim`.
gist-vim have two ways to access APIs.
First, you need to set your Github username in global git config:
$ git config --global github.user Username
Then, gist.vim will ask for your password to create an authorization when you
first use it. The password is not stored and only the OAuth access token will
be kept for later use. You can revoke the token at any time from the list of
["Authorized applications" on Github's "Account Settings" page](https://github.com/settings/applications).

View File

@ -0,0 +1,919 @@
"=============================================================================
" File: gist.vim
" Author: Yasuhiro Matsumoto <mattn.jp@gmail.com>
" Last Change: 21-Jan-2013.
" Version: 7.1
" WebPage: http://github.com/mattn/gist-vim
" License: BSD
let s:save_cpo = &cpo
set cpo&vim
if !exists('g:github_user') && !executable('git')
echohl ErrorMsg | echomsg "Gist: require 'git' command" | echohl None
finish
endif
if !executable('curl')
echohl ErrorMsg | echomsg "Gist: require 'curl' command" | echohl None
finish
endif
let s:configfile = expand('~/.gist-vim')
if !exists('g:github_user')
let s:system = function(get(g:, 'webapi#system_function', 'system'))
let g:github_user = substitute(s:system('git config --get github.user'), "\n", '', '')
if strlen(g:github_user) == 0
let g:github_user = $GITHUB_USER
end
endif
if !exists('g:github_api_url')
let g:github_api_url = 'https://api.github.com'
endif
if !exists('g:gist_update_on_write')
let g:gist_update_on_write = 1
endif
function! s:get_browser_command()
let gist_browser_command = get(g:, 'gist_browser_command', '')
if gist_browser_command == ''
if has('win32') || has('win64')
let gist_browser_command = '!start rundll32 url.dll,FileProtocolHandler %URL%'
elseif has('mac') || has('macunix') || has('gui_macvim') || system('uname') =~? '^darwin'
let gist_browser_command = 'open %URL%'
elseif executable('xdg-open')
let gist_browser_command = 'xdg-open %URL%'
elseif executable('firefox')
let gist_browser_command = 'firefox %URL% &'
else
let gist_browser_command = ''
endif
endif
return gist_browser_command
endfunction
function! s:open_browser(url)
let cmd = s:get_browser_command()
if len(cmd) == 0
redraw
echohl WarningMsg
echo "It seems that you don't have general web browser. Open URL below."
echohl None
echo a:url
return
endif
if cmd =~ '^!'
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g')
silent! exec cmd
elseif cmd =~ '^:[A-Z]'
let cmd = substitute(cmd, '%URL%', '\=a:url', 'g')
exec cmd
else
let cmd = substitute(cmd, '%URL%', '\=shellescape(a:url)', 'g')
call system(cmd)
endif
endfunction
function! s:shellwords(str)
let words = split(a:str, '\%(\([^ \t\''"]\+\)\|''\([^\'']*\)''\|"\(\%([^\"\\]\|\\.\)*\)"\)\zs\s*\ze')
let words = map(words, 'substitute(v:val, ''\\\([\\ ]\)'', ''\1'', "g")')
let words = map(words, 'matchstr(v:val, ''^\%\("\zs\(.*\)\ze"\|''''\zs\(.*\)\ze''''\|.*\)$'')')
return words
endfunction
function! s:format_gist(gist)
let files = sort(keys(a:gist.files))
if empty(files)
return ""
endif
let file = a:gist.files[files[0]]
if has_key(file, "content")
let code = file.content
let code = "\n".join(map(split(code, "\n"), '" ".v:val'), "\n")
else
let code = ""
endif
return printf("gist: %s %s%s", a:gist.id, type(a:gist.description)==0?"": a:gist.description, code)
endfunction
" Note: A colon in the file name has side effects on Windows due to NTFS Alternate Data Streams; avoid it.
let s:bufprefix = 'gist' . (has('unix') ? ':' : '_')
function! s:GistList(gistls, page)
if a:gistls == '-all'
let url = g:github_api_url.'/gists/public'
elseif get(g:, 'gist_show_privates', 0) && a:gistls == 'starred'
let url = g:github_api_url.'/gists/starred'
elseif get(g:, 'gist_show_privates') && a:gistls == 'mine'
let url = g:github_api_url.'/gists'
else
let url = g:github_api_url.'/users/'.a:gistls.'/gists'
endif
let winnum = bufwinnr(bufnr(s:bufprefix.a:gistls))
if winnum != -1
if winnum != bufwinnr('%')
exe winnum 'wincmd w'
endif
setlocal modifiable
else
exec 'silent noautocmd split' s:bufprefix.a:gistls
endif
if a:page > 1
let oldlines = getline(0, line('$'))
let url = url . '?page=' . a:page
endif
setlocal modifiable
let old_undolevels = &undolevels
let oldlines = []
silent %d _
redraw | echon 'Listing gists... '
let auth = s:GistGetAuthHeader()
if len(auth) == 0
bw!
redraw
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
endif
let res = webapi#http#get(url, '', { "Authorization": auth })
if v:shell_error != 0
bw!
redraw
echohl ErrorMsg | echomsg 'Gists not found' | echohl None
return
endif
let content = webapi#json#decode(res.content)
if type(content) == 4 && has_key(content, 'message') && len(content.message)
bw!
redraw
echohl ErrorMsg | echomsg content.message | echohl None
if content.message == 'Bad credentials'
call delete(s:configfile)
endif
return
endif
let lines = map(filter(content, '!empty(v:val.files)'), 's:format_gist(v:val)')
call setline(1, split(join(lines, "\n"), "\n"))
$put='more...'
let b:gistls = a:gistls
let b:page = a:page
setlocal buftype=nofile bufhidden=hide noswapfile
setlocal nomodified
setlocal nomodifiable
syntax match SpecialKey /^gist:/he=e-1
nnoremap <silent> <buffer> <cr> :call <SID>GistListAction(0)<cr>
nnoremap <silent> <buffer> <s-cr> :call <SID>GistListAction(1)<cr>
cal cursor(1+len(oldlines),1)
nohlsearch
redraw | echo ''
endfunction
function! gist#list(user, ...)
let page = get(a:000, 0, 0)
if a:user == '-all'
let url = g:github_api_url.'/gists/public'
elseif get(g:, 'gist_show_privates', 0) && a:user == 'starred'
let url = g:github_api_url.'/gists/starred'
elseif get(g:, 'gist_show_privates') && a:user == 'mine'
let url = g:github_api_url.'/gists'
else
let url = g:github_api_url.'/users/'.a:user.'/gists'
endif
let auth = s:GistGetAuthHeader()
if len(auth) == 0
return []
endif
let res = webapi#http#get(url, '', { "Authorization": auth })
return webapi#json#decode(res.content)
endfunction
function! s:GistGetFileName(gistid)
let auth = s:GistGetAuthHeader()
if len(auth) == 0
return ''
endif
let res = webapi#http#get(g:github_api_url.'/gists/'.a:gistid, '', { "Authorization": auth })
let gist = webapi#json#decode(res.content)
if has_key(gist, 'files')
return sort(keys(gist.files))[0]
endif
return ''
endfunction
function! s:GistDetectFiletype(gistid)
let auth = s:GistGetAuthHeader()
if len(auth) == 0
return ''
endif
let res = webapi#http#get(g:github_api_url.'/gists/'.a:gistid, '', { "Authorization": auth })
let gist = webapi#json#decode(res.content)
let filename = sort(keys(gist.files))[0]
let ext = fnamemodify(filename, ':e')
if has_key(s:extmap, ext)
let type = s:extmap[ext]
else
let type = get(gist.files[filename], "type", "text")
endif
silent! exec "setlocal ft=".tolower(type)
endfunction
function! s:GistWrite(fname)
if substitute(a:fname, '\\', '/', 'g') == expand("%:p:gs@\\@/@")
if g:gist_update_on_write != 2 || v:cmdbang
Gist -e
else
echohl ErrorMsg | echomsg 'Please type ":w!" to update a gist.' | echohl None
endif
else
exe "w".(v:cmdbang ? "!" : "") fnameescape(v:cmdarg) fnameescape(a:fname)
silent! exe "file" fnameescape(a:fname)
silent! au! BufWriteCmd <buffer>
endif
endfunction
function! s:GistGet(gistid, clipboard)
redraw | echon 'Getting gist... '
let res = webapi#http#get(g:github_api_url.'/gists/'.a:gistid, '', { "Authorization": s:GistGetAuthHeader() })
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let gist = webapi#json#decode(res.content)
if get(g:, 'gist_get_multiplefile', 0) != 0
let num_file = len(keys(gist.files))
else
let num_file = 1
endif
redraw
if num_file > len(keys(gist.files))
echohl ErrorMsg | echomsg 'Gist not found' | echohl None
return
endif
for n in range(num_file)
try
let old_undolevels = &undolevels
let filename = sort(keys(gist.files))[n]
let winnum = bufwinnr(bufnr(s:bufprefix.a:gistid."/".filename))
if winnum != -1
if winnum != bufwinnr('%')
exe winnum 'wincmd w'
endif
setlocal modifiable
else
exec 'silent noautocmd new'
setlocal noswapfile
exec 'noautocmd file' s:bufprefix.a:gistid."/".fnameescape(filename)
endif
set undolevels=-1
filetype detect
silent %d _
let content = gist.files[filename].content
call setline(1, split(content, "\n"))
let b:gist = {
\ "filename": filename,
\ "id": gist.id,
\ "description": gist.description,
\ "private": gist.public =~ 'true',
\}
catch
let &undolevels = old_undolevels
bw!
redraw
echohl ErrorMsg | echomsg 'Gist contains binary' | echohl None
return
endtry
let &undolevels = old_undolevels
setlocal buftype=acwrite bufhidden=delete noswapfile
setlocal nomodified
doau StdinReadPost,BufRead,BufReadPost
let gist_detect_filetype = get(g:, 'gist_detect_filetype', 0)
if (&ft == '' && gist_detect_filetype == 1) || gist_detect_filetype == 2
call s:GistDetectFiletype(a:gistid)
endif
if a:clipboard
if exists('g:gist_clip_command')
exec 'silent w !'.g:gist_clip_command
elseif has('clipboard')
silent! %yank +
else
%yank
endif
endif
1
au! BufWriteCmd <buffer> call s:GistWrite(expand("<amatch>"))
endfor
else
bw!
redraw
echohl ErrorMsg | echomsg 'Gist not found' | echohl None
return
endif
endfunction
function! s:GistListAction(shift)
let line = getline('.')
let mx = '^gist:\s*\zs\(\w\+\)\ze.*'
if line =~# mx
let gistid = matchstr(line, mx)
if a:shift
call s:open_browser("https://gist.github.com/" . gistid)
else
call s:GistGet(gistid, 0)
endif
return
endif
if line =~# '^more\.\.\.$'
call s:GistList(b:gistls, b:page+1)
return
endif
endfunction
function! s:GistUpdate(content, gistid, gistnm, desc)
let gist = { "id": a:gistid, "files" : {}, "description": "","public": function('webapi#json#true') }
if exists('b:gist')
if has_key(b:gist, 'private') && b:gist.private | let gist["public"] = function('webapi#json#false') | endif
if has_key(b:gist, 'description') | let gist["description"] = b:gist.description | endif
if has_key(b:gist, 'filename') | let filename = b:gist.filename | endif
else
let filename = a:gistnm
if len(filename) == 0 | let filename = s:GistGetFileName(a:gistid) | endif
if len(filename) == 0 | let filename = s:get_current_filename(1) | endif
endif
let auth = s:GistGetAuthHeader()
if len(auth) == 0
redraw
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
endif
" Update description
" If no new description specified, keep the old description
if a:desc != ' '
let gist["description"] = a:desc
else
let res = webapi#http#get(g:github_api_url.'/gists/'.a:gistid, '', { "Authorization": auth })
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let old_gist = webapi#json#decode(res.content)
let gist["description"] = old_gist.description
endif
endif
let gist.files[filename] = { "content": a:content, "filename": filename }
redraw | echon 'Updating gist... '
let res = webapi#http#post(g:github_api_url.'/gists/' . a:gistid,
\ webapi#json#encode(gist), {
\ "Authorization": auth,
\ "Content-Type": "application/json",
\})
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let obj = webapi#json#decode(res.content)
let loc = obj["html_url"]
redraw | echomsg 'Done: '.loc
let b:gist = {"id": a:gistid, "filename": filename}
setlocal nomodified
else
let loc = ''
let status = matchstr(status, '^\d\+\s*\zs.*')
echohl ErrorMsg | echomsg 'Post failed: '.status | echohl None
endif
return loc
endfunction
function! s:GistDelete(gistid)
let auth = s:GistGetAuthHeader()
if len(auth) == 0
redraw
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
endif
redraw | echon 'Deleting gist... '
let res = webapi#http#post(g:github_api_url.'/gists/'.a:gistid, '', {
\ "Authorization": auth,
\ "Content-Type": "application/json",
\}, 'DELETE')
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
redraw | echomsg 'Done: '
if exists('b:gist')
unlet b:gist
endif
else
let status = matchstr(status, '^\d\+\s*\zs.*')
echohl ErrorMsg | echomsg 'Delete failed: '.status | echohl None
endif
endfunction
function! s:get_current_filename(no)
let filename = expand('%:t')
if len(filename) == 0 && &ft != ''
let pair = filter(items(s:extmap), 'v:val[1] == &ft')
if len(pair) > 0
let filename = printf('gistfile%d%s', a:no, pair[0][0])
endif
endif
if filename == ''
let filename = printf('gistfile%d.txt', a:no)
endif
return filename
endfunction
" GistPost function:
" Post new gist to github
"
" if there is an embedded gist url or gist id in your file,
" it will just update it.
" -- by c9s
"
" embedded gist url format:
"
" Gist: https://gist.github.com/123123
"
" embedded gist id format:
"
" GistID: 123123
"
function! s:GistPost(content, private, desc, anonymous)
let gist = { "files" : {}, "description": "","public": function('webapi#json#true') }
if a:desc != ' ' | let gist["description"] = a:desc | endif
if a:private | let gist["public"] = function('webapi#json#false') | endif
let filename = s:get_current_filename(1)
let gist.files[filename] = { "content": a:content, "filename": filename }
let header = {"Content-Type": "application/json"}
if !a:anonymous
let auth = s:GistGetAuthHeader()
if len(auth) == 0
redraw
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
endif
let header["Authorization"] = auth
endif
redraw | echon 'Posting it to gist... '
let res = webapi#http#post(g:github_api_url.'/gists', webapi#json#encode(gist), header)
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let obj = webapi#json#decode(res.content)
let loc = obj["html_url"]
redraw | echomsg 'Done: '.loc
let b:gist = {
\ "filename": filename,
\ "id": matchstr(loc, '[^/]\+$'),
\ "description": gist['description'],
\ "private": a:private,
\}
else
let loc = ''
let status = matchstr(status, '^\d\+\s*\zs.*')
echohl ErrorMsg | echomsg 'Post failed: '.status | echohl None
endif
return loc
endfunction
function! s:GistPostBuffers(private, desc, anonymous)
let bufnrs = range(1, bufnr("$"))
let bn = bufnr('%')
let query = []
let gist = { "files" : {}, "description": "","public": function('webapi#json#true') }
if a:desc != ' ' | let gist["description"] = a:desc | endif
if a:private | let gist["public"] = function('webapi#json#false') | endif
let index = 1
for bufnr in bufnrs
if !bufexists(bufnr) || buflisted(bufnr) == 0
continue
endif
echo "Creating gist content".index."... "
silent! exec "buffer!" bufnr
let content = join(getline(1, line('$')), "\n")
let filename = s:get_current_filename(index)
let gist.files[filename] = { "content": content, "filename": filename }
let index = index + 1
endfor
silent! exec "buffer!" bn
let header = {"Content-Type": "application/json"}
if !a:anonymous
let auth = s:GistGetAuthHeader()
if len(auth) == 0
redraw
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
endif
let header["Authorization"] = auth
endif
redraw | echon 'Posting it to gist... '
let res = webapi#http#post(g:github_api_url.'/gists', webapi#json#encode(gist), header)
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let obj = webapi#json#decode(res.content)
let loc = obj["html_url"]
redraw | echomsg 'Done: '.loc
let b:gist = {"id": matchstr(loc, '[^/]\+$'), "filename": filename, "private": a:private}
else
let loc = ''
let status = matchstr(status, '^\d\+\s*\zs.*')
echohl ErrorMsg | echomsg 'Post failed: '.status | echohl None
endif
return loc
endfunction
function! gist#Gist(count, line1, line2, ...)
redraw
if strlen(g:github_user) == 0
echohl ErrorMsg | echomsg "You don't have github account. read ':help gist-vim-setup'." | echohl None
return
endif
let bufname = bufname("%")
" find GistID: in content , then we should just update
let gistid = ''
let gistls = ''
let gistnm = ''
let gistdesc = ' '
let private = get(g:, 'gist_post_private', 0)
let multibuffer = 0
let clipboard = 0
let deletepost = 0
let editpost = 0
let anonymous = 0
let listmx = '^\%(-l\|--list\)\s*\([^\s]\+\)\?$'
let bufnamemx = '^' . s:bufprefix .'\(\zs[0-9a-f]\+\ze\|\zs[0-9a-f]\+\ze[/\\].*\)$'
if bufname =~ bufnamemx
let gistidbuf = matchstr(bufname, bufnamemx)
else
let gistidbuf = matchstr(join(getline(a:line1, a:line2), "\n"), 'GistID:\s*\zs\w\+')
endif
let args = (a:0 > 0) ? s:shellwords(a:1) : []
for arg in args
if arg =~ '^\(-h\|--help\)$\C'
help :Gist
return
elseif arg =~ '^\(-la\|--listall\)$\C'
let gistls = '-all'
elseif arg =~ '^\(-ls\|--liststar\)$\C'
let gistls = 'starred'
elseif arg =~ '^\(-l\|--list\)$\C'
if get(g:, 'gist_show_privates')
let gistls = 'mine'
else
let gistls = g:github_user
endif
elseif arg =~ '^\(-m\|--multibuffer\)$\C'
let multibuffer = 1
elseif arg =~ '^\(-p\|--private\)$\C'
let private = 1
elseif arg =~ '^\(-P\|--public\)$\C'
let private = 0
elseif arg =~ '^\(-a\|--anonymous\)$\C'
let anonymous = 1
elseif arg =~ '^\(-s\|--description\)$\C'
let gistdesc = ''
elseif arg =~ '^\(-c\|--clipboard\)$\C'
let clipboard = 1
elseif arg =~ '^--rawurl$\C' && gistidbuf != '' && g:github_api_url == 'https://api.github.com'
let gistid = gistidbuf
echo 'https://gist.github.com/raw/'.gistid
return
elseif arg =~ '^\(-d\|--delete\)$\C' && gistidbuf != ''
let gistid = gistidbuf
let deletepost = 1
elseif arg =~ '^\(-e\|--edit\)$\C' && gistidbuf != ''
let gistid = gistidbuf
let editpost = 1
elseif arg =~ '^\(+1\|--star\)$\C' && gistidbuf != ''
let auth = s:GistGetAuthHeader()
if len(auth) == 0
echohl ErrorMsg | echomsg v:errmsg | echohl None
else
let gistid = gistidbuf
let res = webapi#http#post(g:github_api_url.'/gists/'.gistid.'/star', '', { "Authorization": auth }, 'PUT')
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
echomsg "Stared" gistid
else
echohl ErrorMsg | echomsg 'Star failed' | echohl None
endif
endif
return
elseif arg =~ '^\(-1\|--unstar\)$\C' && gistidbuf != ''
let auth = s:GistGetAuthHeader()
if len(auth) == 0
echohl ErrorMsg | echomsg v:errmsg | echohl None
else
let gistid = gistidbuf
let res = webapi#http#post(g:github_api_url.'/gists/'.gistid.'/star', '', { "Authorization": auth }, 'DELETE')
if status =~ '^2'
echomsg "Unstared" gistid
else
echohl ErrorMsg | echomsg 'Unstar failed' | echohl None
endif
endif
return
elseif arg =~ '^\(-f\|--fork\)$\C' && gistidbuf != ''
let auth = s:GistGetAuthHeader()
if len(auth) == 0
echohl ErrorMsg | echomsg v:errmsg | echohl None
return
else
let gistid = gistidbuf
let res = webapi#http#post(g:github_api_url.'/gists/'.gistid.'/fork', '', { "Authorization": auth })
let status = matchstr(matchstr(res.header, '^Status:'), '^[^:]\+: \zs.*')
if status =~ '^2'
let obj = webapi#json#decode(res.content)
let gistid = obj["id"]
else
echohl ErrorMsg | echomsg 'Fork failed' | echohl None
return
endif
endif
elseif arg !~ '^-' && len(gistnm) == 0
if gistdesc != ' '
let gistdesc = matchstr(arg, '^\s*\zs.*\ze\s*$')
elseif editpost == 1 || deletepost == 1
let gistnm = arg
elseif len(gistls) > 0 && arg != '^\w\+$\C'
let gistls = arg
elseif arg =~ '^[0-9a-z]\+$\C'
let gistid = arg
else
echohl ErrorMsg | echomsg 'Invalid arguments: '.arg | echohl None
unlet args
return 0
endif
elseif len(arg) > 0
echohl ErrorMsg | echomsg 'Invalid arguments: '.arg | echohl None
unlet args
return 0
endif
endfor
unlet args
"echo "gistid=".gistid
"echo "gistls=".gistls
"echo "gistnm=".gistnm
"echo "gistdesc=".gistdesc
"echo "private=".private
"echo "clipboard=".clipboard
"echo "editpost=".editpost
"echo "deletepost=".deletepost
if gistidbuf != '' && gistid == '' && editpost == 0 && deletepost == 0
let editpost = 1
let gistid = gistidbuf
endif
if len(gistls) > 0
call s:GistList(gistls, 1)
elseif len(gistid) > 0 && editpost == 0 && deletepost == 0
call s:GistGet(gistid, clipboard)
else
let url = ''
if multibuffer == 1
let url = s:GistPostBuffers(private, gistdesc, anonymous)
else
if a:count < 1
let content = join(getline(a:line1, a:line2), "\n")
else
let save_regcont = @"
let save_regtype = getregtype('"')
silent! normal! gvy
let content = @"
call setreg('"', save_regcont, save_regtype)
endif
if editpost == 1
let url = s:GistUpdate(content, gistid, gistnm, gistdesc)
elseif deletepost == 1
call s:GistDelete(gistid)
else
let url = s:GistPost(content, private, gistdesc, anonymous)
endif
if a:count >= 1 && get(g:, 'gist_keep_selection', 0) == 1
silent! normal! gv
endif
endif
if len(url) > 0
if get(g:, 'gist_open_browser_after_post', 0) == 1
call s:open_browser(url)
endif
let gist_put_url_to_clipboard_after_post = get(g:, 'gist_put_url_to_clipboard_after_post', 1)
if gist_put_url_to_clipboard_after_post > 0
if gist_put_url_to_clipboard_after_post == 2
let url = url . "\n"
endif
if exists('g:gist_clip_command')
call system(g:gist_clip_command, url)
elseif has('unix') && !has('xterm_clipboard')
let @" = url
else
let @+ = url
endif
endif
endif
endif
return 1
endfunction
function! s:GistGetAuthHeader()
if get(g:, 'gist_use_password_in_gitconfig', 0) != 0
let password = substitute(system('git config --get github.password'), "\n", '', '')
if password =~ '^!' | let password = system(password[1:]) | endif
return printf("basic %s", webapi#base64#b64encode(g:github_user.":".password))
endif
let auth = ""
if filereadable(s:configfile)
let str = join(readfile(s:configfile), "")
if type(str) == 1
let auth = str
endif
endif
if len(auth) > 0
return auth
endif
redraw
echohl WarningMsg
echo 'Gist.vim requires authorization to use the Github API. These settings are stored in "~/.gist-vim". If you want to revoke, do "rm ~/.gist-vim".'
echohl None
let password = inputsecret("Github Password for ".g:github_user.":")
if len(password) > 0
let insecureSecret = printf("basic %s", webapi#base64#b64encode(g:github_user.":".password))
let res = webapi#http#post(g:github_api_url.'/authorizations', webapi#json#encode({
\ "scopes" : ["gist"],
\ "note" : "Gist.vim on ".hostname(),
\ "note_url" : "http://www.vim.org/scripts/script.php?script_id=2423"
\}), {
\ "Content-Type" : "application/json",
\ "Authorization" : insecureSecret,
\})
let authorization = webapi#json#decode(res.content)
if has_key(authorization, 'token')
let secret = printf("token %s", authorization.token)
call writefile([secret], s:configfile)
if !(has('win32') || has('win64'))
call system("chmod go= ".s:configfile)
endif
elseif has_key(authorization, 'message')
let secret = ''
let v:errmsg = authorization.message
endif
else
let secret = ''
let v:errmsg = 'Canceled'
endif
return secret
endfunction
let s:extmap = {
\".adb": "ada",
\".ahk": "ahk",
\".arc": "arc",
\".as": "actionscript",
\".asm": "asm",
\".asp": "asp",
\".aw": "php",
\".b": "b",
\".bat": "bat",
\".befunge": "befunge",
\".bmx": "bmx",
\".boo": "boo",
\".c-objdump": "c-objdump",
\".c": "c",
\".cfg": "cfg",
\".cfm": "cfm",
\".ck": "ck",
\".cl": "cl",
\".clj": "clj",
\".cmake": "cmake",
\".coffee": "coffee",
\".cpp": "cpp",
\".cppobjdump": "cppobjdump",
\".cs": "csharp",
\".css": "css",
\".cw": "cw",
\".d-objdump": "d-objdump",
\".d": "d",
\".darcspatch": "darcspatch",
\".diff": "diff",
\".duby": "duby",
\".dylan": "dylan",
\".e": "e",
\".ebuild": "ebuild",
\".eclass": "eclass",
\".el": "lisp",
\".erb": "erb",
\".erl": "erlang",
\".f90": "f90",
\".factor": "factor",
\".feature": "feature",
\".fs": "fs",
\".fy": "fy",
\".go": "go",
\".groovy": "groovy",
\".gs": "gs",
\".gsp": "gsp",
\".haml": "haml",
\".hs": "haskell",
\".html": "html",
\".hx": "hx",
\".ik": "ik",
\".ino": "ino",
\".io": "io",
\".j": "j",
\".java": "java",
\".js": "javascript",
\".json": "json",
\".jsp": "jsp",
\".kid": "kid",
\".lhs": "lhs",
\".lisp": "lisp",
\".ll": "ll",
\".lua": "lua",
\".ly": "ly",
\".m": "objc",
\".mak": "mak",
\".man": "man",
\".mao": "mao",
\".matlab": "matlab",
\".md": "markdown",
\".minid": "minid",
\".ml": "ml",
\".moo": "moo",
\".mu": "mu",
\".mustache": "mustache",
\".mxt": "mxt",
\".myt": "myt",
\".n": "n",
\".nim": "nim",
\".nu": "nu",
\".numpy": "numpy",
\".objdump": "objdump",
\".ooc": "ooc",
\".parrot": "parrot",
\".pas": "pas",
\".pasm": "pasm",
\".pd": "pd",
\".phtml": "phtml",
\".pir": "pir",
\".pl": "perl",
\".po": "po",
\".py": "python",
\".pytb": "pytb",
\".pyx": "pyx",
\".r": "r",
\".raw": "raw",
\".rb": "ruby",
\".rhtml": "rhtml",
\".rkt": "rkt",
\".rs": "rs",
\".rst": "rst",
\".s": "s",
\".sass": "sass",
\".sc": "sc",
\".scala": "scala",
\".scm": "scheme",
\".scpt": "scpt",
\".scss": "scss",
\".self": "self",
\".sh": "sh",
\".sml": "sml",
\".sql": "sql",
\".st": "smalltalk",
\".tcl": "tcl",
\".tcsh": "tcsh",
\".tex": "tex",
\".textile": "textile",
\".tpl": "smarty",
\".twig": "twig",
\".txt" : "text",
\".v": "verilog",
\".vala": "vala",
\".vb": "vbnet",
\".vhd": "vhdl",
\".vim": "vim",
\".weechatlog": "weechatlog",
\".xml": "xml",
\".xq": "xquery",
\".xs": "xs",
\".yml": "yaml",
\}
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:set et:

View File

@ -0,0 +1,279 @@
*Gist.vim* Vimscript for creating gists (http://gist.github.com)
Usage |gist-vim-usage|
Tips |gist-vim-tips|
License |gist-vim-license|
Install |gist-vim-install|
Requirements |gist-vim-requirements|
Setup |gist-vim-setup|
This is a vimscript for creating gists (http://gist.github.com)
For the latest version please see https://github.com/mattn/gist-vim.
==============================================================================
USAGE *:Gist* *gist-vim-usage*
- Post current buffer to gist, using default privacy option. >
:Gist
<
- Post selected text to gist, using defualt privacy option.
This applies to all permutations listed below (except multi). >
:'<,'>Gist
<
- Create a private gist. >
:Gist -p
<
- Create a public gist.
(Only relevant if you've set gists to be private by default.) >
:Gist -P
<
- Post whole text to gist as public.
This is only relevant if you've set gists to be private by default.
>
:Gist -P
<
- Create a gist anonymously. >
:Gist -a
<
- Create a gist with all open buffers. >
:Gist -m
<
- Edit the gist (you need to have opened the gist buffer first).
You can update the gist with the {:w} command within the gist buffer. >
:Gist -e
<
- Edit the gist with name "foo.js" (you need to have opened the gist buffer
first). >
:Gist -e foo.js
<
- Post/Edit with the description " (you need to have opened the gist buffer
first). >
:Gist -s something
:Gist -e -s something
<
- Delete the gist (you need to have opened the gist buffer first).
Password authentication is needed. >
:Gist -d
<
- Fork the gist (you need to have opened the gist buffer first).
Password authentication is needed. >
:Gist -f
<
- Star the gist (you need to have opened the gist buffer first).
Password authentication is needed.
>
:Gist +1
<
- Unstar the gist (you need to have opened the gist buffer first).
Password authentication is needed.
>
:Gist -1
<
- Get gist XXXXX. >
:Gist XXXXX
<
- Get gist XXXXX and add to clipboard. >
:Gist -c XXXXX
<
- List your public gists. >
:Gist -l
<
- List gists from user "mattn". >
:Gist -l mattn
<
- List everyone's gists. >
:Gist -la
<
- List gists from your starred gists.
>
:Gist -ls
<
==============================================================================
TIPS *gist-vim-tips*
If you set "g:gist_clip_command", gist.vim will copy the gist code with option
"-c".
- Mac: >
let g:gist_clip_command = 'pbcopy'
<
- Linux: >
let g:gist_clip_command = 'xclip -selection clipboard'
<
- Others (cygwin?): >
let g:gist_clip_command = 'putclip'
<
If you want to detect filetype from the filename: >
let g:gist_detect_filetype = 1
<
If you want to open the browser after the post: >
let g:gist_open_browser_after_post = 1
<
If you want to change the browser: >
let g:gist_browser_command = 'w3m %URL%'
<
or: >
let g:gist_browser_command = 'opera %URL% &'
<
On windows, this should work with your user settings.
If you want to show your private gists with ":Gist -l": >
let g:gist_show_privates = 1
<
If you want your gist to be private by default: >
let g:gist_post_private = 1
<
If you want to edit all files for gists containing more than one: >
let g:gist_get_multiplefile = 1
<
If you want to use on Github Enterprise: >
let g:github_api_url = 'http://your-github-enterprise-domain/api/v3'
<
If you want to update a gist, embed >
GistID: xxxxx
>
in your local file, then call >
:Gist
>
If you want to update a gist when only |:w!|: >
" :w and :w! update a gist.
let g:gist_update_on_write = 1
" Only :w! updates a gist.
let g:gist_update_on_write = 2
>
All other values are treated as 1.
This variable's value is 1 by default.
==============================================================================
LICENSE *gist-vim-license*
Copyright 2010 by Yasuhiro Matsumoto
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
==============================================================================
INSTALL *gist-vim-install*
Copy following files into your plugin directory.
rtp:
- autoload/gist.vim
- plugin/gist.vim
If you want to uninstall gist.vim, remember to also remove `~/.gist-vim`.
You need to install webapi-vim also:
http://www.vim.org/scripts/script.php?script_id=4019
If you want to use latest one:
https://github.com/mattn/webapi-vim
==============================================================================
REQUIREMENTS *gist-vim-requirements*
- curl command (http://curl.haxx.se/)
- webapi-vim (https://github.com/mattn/webapi-vim)
- and, if you want to use your git profile, the git command-line client.
==============================================================================
SETUP *gist-vim-setup*
This plugin uses github API v3. Setting value is stored in `~/.gist.vim`.
gist-vim have two ways to access APIs.
First, you need to set your Github username in global git config:
>
$ git config --global github.user Username
<
Then, gist.vim will ask for your password to create an authorization when you
first use it. The password is not stored and only the OAuth access token will
be kept for later use. You can revoke the token at any time from the list of
"Authorized applications" on Github's "Account Settings" page.
(https://github.com/settings/applications)
If you happen to have your password already written in ~/.gitconfig like
below:
>
[github]
password = xxxxx
<
Then, add following into your ~/.vimrc
>
let g:gist_use_password_in_gitconfig = 1
<
This is not secure at all, so strongly discouraged.
==============================================================================
THANKS *gist-vim-thanks*
AD7six
Bruno Bigras
c9s
Daniel Bretoi
Jeremy Michael Cantrell
Kien N
kongo2002
MATSUU Takuto
Matthew Weier O'Phinney
ornicar
Roland Schilter
steve
tyru
Will Gray
netj
vim:tw=78:ts=8:ft=help:norl:

View File

@ -0,0 +1,9 @@
:Gist gist-vim.txt /*:Gist*
Gist.vim gist-vim.txt /*Gist.vim*
gist-vim-install gist-vim.txt /*gist-vim-install*
gist-vim-license gist-vim.txt /*gist-vim-license*
gist-vim-requirements gist-vim.txt /*gist-vim-requirements*
gist-vim-setup gist-vim.txt /*gist-vim-setup*
gist-vim-thanks gist-vim.txt /*gist-vim-thanks*
gist-vim-tips gist-vim.txt /*gist-vim-tips*
gist-vim-usage gist-vim.txt /*gist-vim-usage*

View File

@ -0,0 +1,297 @@
script_name: Gist.vim
script_id: '2423'
script_type: utility
script_package: gist-vim.zip
script_version: '7.1'
required_vim_version: '7.0'
summary: vimscript for gist
detailed_description: |
This is vimscript for gist (http://gist.github.com)
Usage:
:Gist
post whole text to gist.
:'<,'>Gist
post selected text to gist.
:Gist -p
post whole text to gist with private.
if you got empty gist list, try :Gist --abandon
:Gist -a
post whole text to gist with anonymous.
:Gist -m
post multi buffer to gist.
:Gist -e
edit the gist. (shoud be work on gist buffer)
you can update the gist with :w command on gist buffer.
:Gist -e foo.js
edit the gist with name 'foo.js'. (shoud be work on gist buffer)
:Gist -d
delete the gist. (should be work on gist buffer)
authentication required.
:Gist -f
fork the gist. (should be work on gist buffer)
authentication required.
:Gist XXXXX
get gist XXXXX.
:Gist -c XXXXX.
get gist XXXXX and put to clipboard.
:Gist -l
list gists from mine.
:Gist -la
list gists from all.
Tips:
if set g:gist_clip_command, gist.vim will copy the gist code
with option '-c'.
# mac
let g:gist_clip_command = 'pbcopy'
# linux
let g:gist_clip_command = 'xclip -selection clipboard'
# others(cygwin?)
let g:gist_clip_command = 'putclip'
if you want to detect filetype from filename...
let g:gist_detect_filetype = 1
if you want to open browser after the post...
let g:gist_open_browser_after_post = 1
if you want to change the browser...
let g:gist_browser_command = 'w3m %URL%'
or
let g:gist_browser_command = 'opera %URL% &'
on windows, should work with original setting.
Require:
curl command (http://curl.haxx.se/)
and if you want to use profile of git, it require git command.
install_details: |
copy it to your plugin directory.
gist.vim leave cookie-jar file into runtimepath.
rtp:
plugin/gist.vim
cookies/github
See also: https://github.com/mattn/gist-vim/blob/master/README.mkd
versions:
- '7.1': |
This is an upgrade for Gist.vim: updated installation notes.
- '7.0': |
This is an upgrade for Gist.vim: fixed few bugs.
- '6.9': |
This is an upgrade for Gist.vim: fixed few bugs.
- '6.8': |
This is an upgrade for Gist.vim: changed authentication. removed password authentication. if you want to keep using password authentication, let gist_use_password_in_gitconfig to 1.
- '6.7': |
This is an upgrade for Gist.vim: fix behavior of g:gist_browser_command = ':OpenBrowser %URL%'.
- '6.6': |
This is an upgrade for Gist.vim: fixed detecting filetype.
- '6.5': |
This is an upgrade for Gist.vim: use webapi namespace. NOTE: please upgrade webapi-vim also.
- '6.4': |
This is an upgrade for Gist.vim: fixed updating with description.
- '6.3': |
This is an upgrade for Gist.vim: fixed typos.
- '6.2': |
This is an upgrade for Gist.vim: fixed some bugs.
- '6.1': |
This is an upgrade for Gist.vim: fixed opening browser.
- '6.0': |
This is an upgrade for Gist.vim: changed to use github APIs. Note to remove cookies directory if you used.
- '5.9': |
This is an upgrade for Gist.vim: add support anonymous post. fixed many bugs.
- '5.8': |
This is an upgrade for Gist.vim: add support for description. you can post description using -s option.
- '5.7': |
This is an upgrade for Gist.vim: post with filetype more cleverly.
- '5.6': |
This is an upgrade for Gist.vim: fix '--abandon'.
- '5.5': |
This is an upgrade for Gist.vim: fix: forgot to upload autoload/gist.vim.
- '5.4': |
This is an upgrade for Gist.vim: fix: does not work correctly with blockwize selection.
- '5.3': |
This is an upgrade for Gist.vim: upd: support autoload.
- '5.2': |
This is an upgrade for Gist.vim: add: support block-wise selection.
- '5.1': |
This is an upgrade for Gist.vim: fix: can't update privates.
- '5.0': |
This is an upgrade for Gist.vim: follow update of gist.github.com
- '4.9': |
fix: don't add new line after "Done: xxx".
fix: show WHY FAILED' when failed to post.
add: support for :OpenBrowser.
add: new option 'gist_curl_options'.
- '4.8': |
This is an upgrade for Gist.vim: fix: can't open private gist with ":Gist XXXXX".
- '4.7': |
This is an upgrade for Gist.vim: fix: filetype detection.
- '4.6': |
This is an upgrade for Gist.vim: fix: strange cookies folder.
- '4.5': |
This is an upgrade for Gist.vim: fix: use gist_clip_command for copying URL to clipboard. this fix strange behavior on Mac OSX.
- '4.4': |
This is an upgrade for Gist.vim: fix: gist is now only using https.
- '4.3': |
This is an upgrade for Gist.vim: add new option '-f' for fork.
- '4.2': |
This is an upgrade for Gist.vim: fixed code for login.
- '4.1': |
This is an upgrade for Gist.vim: fixed code cleanup.
- '4.0': |
This is an upgrade for Gist.vim: fixed deleting gist, listing privates.
- '3.9': |
This is an upgrade for Gist.vim: fixed :w handler in gist buffer.
- '3.8': |
This is an upgrade for Gist.vim: 'more...' on gist list.
- '3.7': |
This is an upgrade for Gist.vim: fix problem that break "gist list" window at twice.
- '3.6': |
This is an upgrade for Gist.vim: fix filetype detection for 'vimscript'.
- '3.5': |
This is an upgrade for Gist.vim: fix filetype detection.
- '3.4': |
This is an upgrade for Gist.vim: use '+' register on unix only if built with 'xterm_clipboard'. and some bug fixes.
- '3.3': |
This is an upgrade for Gist.vim: fix problem that append empty line when getting gist.
- '3.2': |
This is an upgrade for Gist.vim: added Gist header to recognize the gist. added script type header for Vimana.
- '3.1': |
This is an upgrade for Gist.vim: fix checking redirect url.
- '3.0': |
This is an upgrade for Gist.vim: fix for official changes(private button name was changed).
- '2.9': |
This is an upgrade for Gist.vim: fix for official changes(private button name was changed).
- '2.8': |
This is an upgrade for Gist.vim: be able to post multi buffer. currently updating or showing not supported. and ':Gist -d' delete the gist.
- '2.7': |
This is an upgrade for Gist.vim: be able to write the gist to local file with ':w foo.txt'.
- '2.6': |
This is an upgrade for Gist.vim: fixed problem that does not work 'Gist XXXX'.
- '2.5': |
This is an upgrade for Gist.vim: use existing buffer when open the list or gist.
- '2.4': |
This is an upgrade for Gist.vim: show error message when no any github settings.
- '2.3': |
This is an upgrade for Gist.vim: added :w BufWriteCmd for GistUpdate.
- '2.2': |
This is an upgrade for Gist.vim: fixed a bug for anonymous post. and new option '-a' for anonymous post.
- '2.1': |
This is an upgrade for Gist.vim: support changing gist filename.
- '2.0': |
This is an upgrade for Gist.vim: bugfix for listing gists in specified user.
- '1.9': |
This is an upgrade for Gist.vim: added support editing the gist. and bits bug fix.
- '1.8': |
This is an upgrade for Gist.vim: added new option g:gist_open_browser_after_post/g:gist_browser_command to open posted gist.
- '1.7': |
This is an upgrade for Gist.vim: now changed argument for putting clipboard as ':Gist -c XXXXX'.
- '1.6': |
This is an upgrade for Gist.vim: add gist's author in gist list.
- '1.5': |
This is an upgrade for Gist.vim: oops. bugfix for auto-detection.
- '1.4': |
This is an upgrade for Gist.vim: bugfix for auto-detection.
- '1.3': |
This is an upgrade for Gist.vim: more auto-detection for filetype.
- '1.2': |
This is an upgrade for Gist.vim: added new option for detect filetype from filename.
- '1.1': |
This is an upgrade for Gist.vim: calling StdinReadPost.
- '1.0': |
This is an upgrade for Gist.vim: treat literal "-" as part of username.
- '0.9': |
This is an upgrade for Gist.vim: added new option 'g:gist_clip_command' that copy the gist code.
# __END__
# vim: filetype=yaml

View File

@ -0,0 +1,16 @@
"=============================================================================
" File: gist.vim
" Author: Yasuhiro Matsumoto <mattn.jp@gmail.com>
" WebPage: http://github.com/mattn/gist-vim
" License: BSD
" GetLatestVimScripts: 2423 1 :AutoInstall: gist.vim
" script type: plugin
if &cp || (exists('g:loaded_gist_vim') && g:loaded_gist_vim)
finish
endif
let g:loaded_gist_vim = 1
command! -nargs=? -range=% Gist :call gist#Gist(<count>, <line1>, <line2>, <f-args>)
" vim:set et:

1
vim/bundle/vim-bundler/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/doc/tags

View File

@ -0,0 +1,2 @@
See the contribution guidelines for
[rails.vim](https://github.com/tpope/vim-rails/blob/HEAD/CONTRIBUTING.markdown).

View File

@ -0,0 +1,55 @@
# bundler.vim
This is a lightweight bag of Vim goodies for
[Bundler](http://gembundler.com), best accompanied by
[rake.vim](https://github.com/tpope/vim-rake) and/or
[rails.vim](https://github.com/tpope/vim-rails). Features:
* `:Bundle`, which wraps `bundle`.
* An internalized version of `bundle open`: `:Bopen` (and `:Bsplit`,
`:Btabedit`, etc.).
* `'path'` and `'tags'` are automatically altered to include all gems
from your bundle. (Generate those tags with
[gem-ctags](https://github.com/tpope/gem-ctags)!)
* Highlight Bundler keywords in `Gemfile`.
* Support for `gf` in `Gemfile.lock`, plus syntax highlighting that
distinguishes between installed and missing gems.
## Installation
If you don't have a preferred installation method, I recommend
installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and
then simply copy and paste:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-bundler.git
Once help tags have been generated, you can view the manual with
`:help bundler`.
## FAQ
> I installed the plugin and started Vim. Why don't any of the commands
> exist?
This plugin cares about the current file, not the current working
directory. Edit a file that's covered by a `Gemfile`.
> I opened a new tab. Why don't any of the commands exist?
This plugin cares about the current file, not the current working
directory. Edit a file that's covered by a `Gemfile`.
## Self-Promotion
Like bundler.vim? Follow the repository on
[GitHub](https://github.com/tpope/vim-bundler) and vote for it on
[vim.org](http://www.vim.org/scripts/script.php?script_id=4280). And if
you're feeling especially charitable, follow [tpope](http://tpo.pe/) on
[Twitter](http://twitter.com/tpope) and
[GitHub](https://github.com/tpope).
## License
Copyright (c) Tim Pope. Distributed under the same terms as Vim itself.
See `:help license`.

View File

@ -0,0 +1,26 @@
" Vim compiler file
if exists("current_compiler")
finish
endif
let current_compiler = "bundler"
let s:cpo_save = &cpo
set cpo-=C
CompilerSet makeprg=bundle
CompilerSet errorformat=
\%+E%f:%l:\ parse\ error,
\%W%f:%l:\ warning:\ %m,
\%E%f:%l:in\ %*[^:]:\ %m,
\%E%f:%l:\ %m,
\%-C%\tfrom\ %f:%l:in\ %.%#,
\%-Z%\tfrom\ %f:%l,
\%-Z%p^,
\%-G%.%#
let &cpo = s:cpo_save
unlet s:cpo_save
" vim: sw=2:

View File

@ -0,0 +1,68 @@
*bundler.txt* Support for Ruby's Bundler
Author: Tim Pope <http://tpo.pe/>
License: Same terms as Vim itself (see |license|)
This plugin is only available if 'compatible' is not set.
INTRODUCTION *bundler*
This lightweight companion to rails.vim and rake.vim provides support for
Bundler. In addition to the below commands, it also syntax highlights
Gemfile and Gemfile.lock, and alters 'path' and 'tags' to include bundled
gems. I recommend gem-ctags for generating tags for your gems.
COMMANDS *bundler-commands*
*bundler-:Bundle*
:Bundle[!] [args] Invoke `bundle` via |:make|.
*bundler-:Bopen*
:Bopen[!] [gem] With no argument, edits the Gemfile. Otherwise,
effectively does a `bundle open` of a gem inside of
Vim, including an |:lcd| to the gem's root directory.
Add ! to discard the current buffer's changes.
*bundler-:Bedit*
:Bedit[!] [gem] Like |:Bopen|, but don't |:lcd| afterwards.
*bundler-:Bsplit*
:Bsplit[!] [gem] Like |:Bopen|, but horizontally split. Add ! to
suppress the |:lcd|.
*bundler-:Bvsplit*
:Bvsplit[!] [gem] Like |:Bopen|, but vertically split. Add ! to
suppress the |:lcd|.
*bundler-:Btabedit*
:Btabedit[!] [gem] Like |:Bopen|, but use a new tab. Add ! to
suppress the |:lcd|.
*bundler-:Bpedit*
:Bpedit[!] [gem] Like |:Bopen|, but use a preview window. Add ! to
suppress the |:lcd|.
API *bundler-api*
Use bundler#project(root) to retrieve an object for the project at the given
root path. If no path is given, the current buffer's project root is used.
An empty object is returned if no project is found. Use |empty()| to check
for that.
On the bundler#project() object, versions() returns a dictionary mapping
between gem names and their locked versions, paths() returns a dictionary
mapping between gem names and their installation path (omitting gems which
aren't installed), and has(gem) returns true if the given gem name is in the
bundle (regardless of whether or not it is installed).
The original data structures are returned for performance reasons. Do not
mutate.
ABOUT *bundler-about*
Grab the latest version or report a bug on GitHub:
http://github.com/tpope/vim-bundler
vim:tw=78:et:ft=help:norl:

View File

@ -0,0 +1,581 @@
" bundler.vim - Support for Ruby's Bundler
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 2.0
if exists('g:loaded_bundler') || &cp || v:version < 700
finish
endif
let g:loaded_bundler = 1
" Utility {{{1
function! s:function(name) abort
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),''))
endfunction
function! s:sub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'')
endfunction
function! s:gsub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'g')
endfunction
function! s:shellesc(arg) abort
if a:arg =~ '^[A-Za-z0-9_/.-]\+$'
return a:arg
else
return shellescape(a:arg)
endif
endfunction
function! s:fnameescape(file) abort
if exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file," \t\n*?[{`$\\%#'\"|!<")
endif
endfunction
function! s:shellslash(path)
if exists('+shellslash') && !&shellslash
return s:gsub(a:path,'\\','/')
else
return a:path
endif
endfunction
function! s:completion_filter(results,A)
let results = sort(copy(a:results))
call filter(results,'v:val !~# "\\~$"')
let filtered = filter(copy(results),'v:val[0:strlen(a:A)-1] ==# 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 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:throw(string) abort
let v:errmsg = 'bundler: '.a:string
throw v:errmsg
endfunction
function! s:warn(str)
echohl WarningMsg
echomsg a:str
echohl None
let v:warningmsg = a:str
endfunction
function! s:add_methods(namespace, method_names) abort
for name in a:method_names
let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name)
endfor
endfunction
let s:commands = []
function! s:command(definition) abort
let s:commands += [a:definition]
endfunction
function! s:define_commands()
for command in s:commands
exe 'command! -buffer '.command
endfor
endfunction
augroup bundler_utility
autocmd!
autocmd User Bundler call s:define_commands()
augroup END
let s:abstract_prototype = {}
" }}}1
" Syntax highlighting {{{1
function! s:syntaxfile()
syntax keyword rubyGemfileMethod gemspec gem source path git group platforms env ruby
hi def link rubyGemfileMethod Function
endfunction
function! s:syntaxlock()
setlocal iskeyword+=-,.
syn match gemfilelockHeading '^[[:upper:]]\+$'
syn match gemfilelockKey '^\s\+\zs\S\+:'he=e-1 skipwhite nextgroup=gemfilelockRevision
syn match gemfilelockKey 'remote:'he=e-1 skipwhite nextgroup=gemfilelockRemote
syn match gemfilelockRemote '\S\+' contained
syn match gemfilelockRevision '[[:alnum:]._-]\+$' contained
syn match gemfilelockGem '^\s\+\zs[[:alnum:]._-]\+\%([ !]\|$\)\@=' contains=gemfilelockFound,gemfilelockMissing skipwhite nextgroup=gemfilelockVersions,gemfilelockBang
syn match gemfilelockVersions '([^()]*)' contained contains=gemfilelockVersion
syn match gemfilelockVersion '[^,()]*' contained
syn match gemfilelockBang '!' contained
if !empty(bundler#project())
exe 'syn match gemfilelockFound "\<\%(bundler\|' . join(keys(s:project().paths()), '\|') . '\)\>" contained'
exe 'syn match gemfilelockMissing "\<\%(' . join(keys(filter(s:project().versions(), '!has_key(s:project().paths(), v:key)')), '\|') . '\)\>" contained'
else
exe 'syn match gemfilelockFound "\<\%(\S*\)\>" contained'
endif
syn match gemfilelockHeading '^PLATFORMS$' nextgroup=gemfilelockPlatform skipnl skipwhite
syn match gemfilelockPlatform '^ \zs[[:alnum:]._-]\+$' contained nextgroup=gemfilelockPlatform skipnl skipwhite
hi def link gemfilelockHeading PreProc
hi def link gemfilelockPlatform Typedef
hi def link gemfilelockKey Identifier
hi def link gemfilelockRemote String
hi def link gemfilelockRevision Number
hi def link gemfilelockFound Statement
hi def link gemfilelockMissing Error
hi def link gemfilelockVersion Type
hi def link gemfilelockBang Special
endfunction
function! s:setuplock()
nnoremap <silent><buffer> gf :Bopen <C-R><C-F><CR>
nnoremap <silent><buffer> <C-W>f :Bsplit <C-R><C-F><CR>
nnoremap <silent><buffer> <C-W><C-F> :Bsplit <C-R><C-F><CR>
nnoremap <silent><buffer> <C-W>gf :Btabedit <C-R><C-F><CR>
endfunction
augroup bundler_syntax
autocmd!
autocmd BufNewFile,BufRead */.bundle/config set filetype=yaml
autocmd BufNewFile,BufRead Gemfile set filetype=ruby
autocmd Syntax ruby if expand('<afile>:t') ==? 'gemfile' | call s:syntaxfile() | endif
autocmd BufNewFile,BufRead [Gg]emfile.lock setf gemfilelock
autocmd FileType gemfilelock set suffixesadd=.rb
autocmd Syntax gemfilelock call s:syntaxlock()
autocmd FileType gemfilelock call s:setuplock()
autocmd User Rails/Gemfile.lock call s:setuplock()
augroup END
" }}}1
" Initialization {{{1
function! s:FindBundlerRoot(path) abort
let path = s:shellslash(a:path)
let fn = fnamemodify(path,':s?[\/]$??')
let ofn = ""
let nfn = fn
while fn != ofn
if filereadable(fn.'/Gemfile')
return s:sub(simplify(fnamemodify(fn,':p')),'[\\/]$','')
endif
let ofn = fn
let fn = fnamemodify(ofn,':h')
endwhile
return ''
endfunction
function! s:Detect(path)
if !exists('b:bundler_root')
let dir = s:FindBundlerRoot(a:path)
if dir != ''
let b:bundler_root = dir
endif
endif
if exists('b:bundler_root')
silent doautocmd User Bundler
endif
endfunction
augroup bundler
autocmd!
autocmd FileType * call s:Detect(expand('<afile>:p'))
autocmd BufNewFile,BufReadPost *
\ if empty(&filetype) |
\ call s:Detect(expand('<afile>:p')) |
\ endif
autocmd VimEnter * if expand('<amatch>')==''|call s:Detect(getcwd())|endif
augroup END
" }}}1
" Project {{{1
let s:project_prototype = {}
let s:projects = {}
function! bundler#project(...) abort
let dir = a:0 ? a:1 : (exists('b:bundler_root') && b:bundler_root !=# '' ? b:bundler_root : s:FindBundlerRoot(expand('%:p')))
if dir !=# ''
if has_key(s:projects,dir)
let project = get(s:projects,dir)
else
let project = {'root': dir}
let s:projects[dir] = project
endif
return extend(extend(project,s:project_prototype,'keep'),s:abstract_prototype,'keep')
endif
return {}
endfunction
function! s:project(...) abort
let project = a:0 ? bundler#project(a:1) : bundler#project()
if empty(project)
call s:throw('not a Bundler project: '.(a:0 ? a:1 : expand('%')))
else
return project
endif
endfunction
function! s:project_path(...) dict abort
return join([self.root]+a:000,'/')
endfunction
call s:add_methods('project',['path'])
function! s:project_locked() dict abort
let lock_file = self.path('Gemfile.lock')
let time = getftime(lock_file)
if time != -1 && time != get(self,'_lock_time',-1)
let self._locked = {'git': [], 'gem': [], 'path': []}
let self._versions = {}
for line in readfile(lock_file)
if line =~# '^\S'
let properties = {'versions': {}}
if has_key(self._locked, tolower(line))
call extend(self._locked[tolower(line)], [properties])
endif
elseif line =~# '^ \w\+: '
let properties[matchstr(line, '\w\+')] = matchstr(line, ': \zs.*')
elseif line =~# '^ [a-zA-Z0-9._-]\+\s\+(\d\+'
let name = split(line, ' ')[0]
let ver = substitute(line, '.*(\|).*', '', 'g')
let properties.versions[name] = ver
let self._versions[name] = ver
endif
endfor
let self._lock_time = time
endif
return get(self, '_locked', {})
endfunction
function! s:project_paths(...) dict abort
call self.locked()
let time = get(self, '_lock_time', -1)
if a:0 && a:1 ==# 'refresh' || time != -1 && time != get(self, '_path_time', -1)
let paths = {}
let chdir = exists("*haslocaldir") && haslocaldir() ? "lchdir" : "chdir"
let cwd = getcwd()
" Explicitly setting $PATH means /etc/zshenv on OS X can't touch it.
if executable('env')
let prefix = 'env PATH='.s:shellesc($PATH).' '
else
let prefix = ''
endif
let gem_paths = []
if exists('$GEM_PATH')
let gem_paths = split($GEM_PATH, has('win32') ? ';' : ':')
else
try
exe chdir s:fnameescape(self.path())
let gem_paths = split(system(prefix.'ruby -rubygems -e "print Gem.path.join(%(;))"'), ';')
finally
exe chdir s:fnameescape(cwd)
endtry
endif
let abi_version = matchstr(get(gem_paths, 0, '1.9.1'), '[0-9.]\+$')
for config in [expand('~/.bundle/config'), self.path('.bundle/config')]
if filereadable(config)
let body = join(readfile(config), "\n")
let bundle_path = matchstr(body, "\\C\\<BUNDLE_PATH: \\zs[^\n]*")
if !empty(bundle_path)
if body =~# '\C\<BUNDLE_DISABLE_SHARED_GEMS:'
let gem_paths = [self.path(bundle_path, 'ruby', abi_version)]
else
let gem_paths = [self.path(bundle_path)]
endif
endif
endif
endfor
for source in self._locked.git
for [name, ver] in items(source.versions)
for path in gem_paths
let dir = path . '/bundler/gems/' . matchstr(source.remote, '.*/\zs.\{-\}\ze\%(\.git\)\=$') . '-' . source.revision[0:11]
if isdirectory(dir)
let files = split(glob(dir . '/*/' . name . '.gemspec'), "\n")
if empty(files)
let paths[name] = dir
else
let paths[name] = files[0][0 : -10-strlen(name)]
endif
break
endif
endfor
endfor
endfor
for source in self._locked.path
for [name, ver] in items(source.versions)
if source.remote !~# '^/'
let local = simplify(self.path(source.remote))
else
let local = source.remote
endif
let files = split(glob(local . '/*/' . name . '.gemspec'), "\n")
if empty(files)
let paths[name] = local
else
let paths[name] = files[0][0 : -10-strlen(name)]
endif
endfor
endfor
for source in self._locked.gem
for [name, ver] in items(source.versions)
for path in gem_paths
let dir = path . '/gems/' . name . '-' . ver
if isdirectory(dir)
let paths[name] = dir
break
endif
endfor
if !has_key(paths, name)
for path in gem_paths
let dir = glob(path . '/gems/' . name . '-' . ver . '-*')
if isdirectory(dir)
let paths[name] = dir
break
endif
endfor
endif
endfor
endfor
let self._path_time = time
let self._paths = paths
let self._sorted = sort(values(paths))
let index = index(self._sorted, self.path())
if index > 0
call insert(self._sorted, remove(self._sorted,index))
endif
call self.alter_buffer_paths()
return paths
endif
return get(self,'_paths',{})
endfunction
function! s:project_sorted() dict abort
call self.paths()
return get(self, '_sorted', [])
endfunction
function! s:project_gems() dict abort
return self.paths()
endfunction
function! s:project_versions() dict abort
call self.locked()
return get(self, '_versions', {})
endfunction
function! s:project_has(gem) dict abort
call self.locked()
return has_key(self.versions(), a:gem)
endfunction
call s:add_methods('project', ['locked', 'gems', 'paths', 'sorted', 'versions', 'has'])
" }}}1
" Buffer {{{1
let s:buffer_prototype = {}
function! s:buffer(...) abort
let buffer = {'#': bufnr(a:0 ? a:1 : '%')}
let g:buffer = buffer
call extend(extend(buffer,s:buffer_prototype,'keep'),s:abstract_prototype,'keep')
if buffer.getvar('bundler_root') !=# ''
return buffer
endif
call s:throw('not a Bundler project: '.(a:0 ? a:1 : expand('%')))
endfunction
function! bundler#buffer(...) abort
return s:buffer(a:0 ? a:1 : '%')
endfunction
function! s:buffer_getvar(var) dict abort
return getbufvar(self['#'],a:var)
endfunction
function! s:buffer_setvar(var,value) dict abort
return setbufvar(self['#'],a:var,a:value)
endfunction
function! s:buffer_project() dict abort
return s:project(self.getvar('bundler_root'))
endfunction
call s:add_methods('buffer',['getvar','setvar','project'])
" }}}1
" Bundle {{{1
function! s:push_chdir()
if !exists("s:command_stack") | let s:command_stack = [] | endif
let chdir = exists("*haslocaldir") && haslocaldir() ? "lchdir " : "chdir "
call add(s:command_stack,chdir.s:fnameescape(getcwd()))
exe chdir.'`=s:project().path()`'
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:Bundle(bang,arg)
let old_makeprg = &l:makeprg
let old_errorformat = &l:errorformat
let old_compiler = get(b:, 'current_compiler', '')
try
compiler bundler
execute 'make! '.a:arg
if a:bang ==# ''
return 'if !empty(getqflist()) | cfirst | endif'
else
return ''
endif
finally
let &l:errorformat = old_errorformat
let &l:makeprg = old_makeprg
let b:current_compiler = old_compiler
if empty(b:current_compiler)
unlet b:current_compiler
endif
endtry
endfunction
function! s:BundleComplete(A,L,P)
if a:L =~# '^\S\+\s\+\%(show\|update\) '
return s:completion_filter(keys(s:project().paths()),a:A)
endif
return s:completion_filter(['install','update','exec','package','config','check','list','show','outdated','console','viz','benchmark'],a:A)
endfunction
function! s:SetupMake() abort
compiler bundler
endfunction
call s:command("-bar -bang -nargs=? -complete=customlist,s:BundleComplete Bundle :execute s:Bundle('<bang>',<q-args>)")
augroup bundler_make
autocmd FileType gemfilelock call s:SetupMake()
autocmd FileType ruby
\ if expand('<afile>:t') ==? 'gemfile' |
\ call s:SetupMake() |
\ endif
autocmd QuickFixCmdPre make,lmake
\ if &makeprg =~# '^bundle' && exists('b:bundler_root') |
\ call s:push_chdir() |
\ endif
autocmd QuickFixCmdPost make,lmake
\ if &makeprg =~# '^bundle' && exists('b:bundler_root') |
\ call s:pop_command() |
\ call s:project().paths("refresh") |
\ endif
augroup END
" }}}1
" Bopen {{{1
function! s:Open(cmd,gem,lcd)
if a:gem ==# '' && a:lcd
return a:cmd.' `=bundler#buffer().project().path("Gemfile")`'
elseif a:gem ==# ''
return a:cmd.' `=bundler#buffer().project().path("Gemfile.lock")`'
else
if !has_key(s:project().paths(), a:gem)
call s:project().paths('refresh')
endif
if !has_key(s:project().paths(), a:gem)
if has_key(s:project().versions(), a:gem)
let v:errmsg = "Gem \"".a:gem."\" is in bundle but not installed"
else
let v:errmsg = "Gem \"".a:gem."\" is not in bundle"
endif
return 'echoerr v:errmsg'
endif
let path = fnameescape(bundler#buffer().project().paths()[a:gem])
let exec = a:cmd.' '.path
if a:cmd =~# '^pedit' && a:lcd
let exec .= '|wincmd P|lcd '.path.'|wincmd p'
elseif a:lcd
let exec .= '|lcd '.path
endif
return exec
endif
endfunction
function! s:OpenComplete(A,L,P)
return s:completion_filter(keys(s:project().paths()),a:A)
endfunction
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Bopen :execute s:Open('edit<bang>',<q-args>,1)")
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Bedit :execute s:Open('edit<bang>',<q-args>,0)")
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Bsplit :execute s:Open('split',<q-args>,<bang>1)")
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Bvsplit :execute s:Open('vsplit',<q-args>,<bang>1)")
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Btabedit :execute s:Open('tabedit',<q-args>,<bang>1)")
call s:command("-bar -bang -nargs=? -complete=customlist,s:OpenComplete Bpedit :execute s:Open('pedit',<q-args>,<bang>1)")
" }}}1
" Paths {{{1
function! s:build_path_option(paths,suffix) abort
return join(map(copy(a:paths),'",".escape(s:shellslash(v:val."/".a:suffix),", ")'),'')
endfunction
function! s:buffer_alter_paths() dict abort
if self.getvar('&suffixesadd') =~# '\.rb\>'
let new = self.project().sorted()
let old = type(self.getvar('bundler_paths')) == type([]) ? self.getvar('bundler_paths') : []
for [option, suffix] in [['path', 'lib'], ['tags', 'tags']]
let value = self.getvar('&'.option)
if !empty(old)
let drop = s:build_path_option(old,suffix)
let index = stridx(value,drop)
if index > 0
let value = value[0:index-1] . value[index+strlen(drop):-1]
endif
endif
call self.setvar('&'.option,value.s:build_path_option(new,suffix))
endfor
call self.setvar('bundler_paths',new)
endif
endfunction
call s:add_methods('buffer',['alter_paths'])
function! s:project_alter_buffer_paths() dict abort
for bufnr in range(1,bufnr('$'))
if getbufvar(bufnr,'bundler_root') ==# self.path()
let vim_parsing_quirk = s:buffer(bufnr).alter_paths()
endif
if getbufvar(bufnr, '&syntax') ==# 'gemfilelock'
call setbufvar(bufnr, '&syntax', 'gemfilelock')
endif
endfor
endfunction
call s:add_methods('project',['alter_buffer_paths'])
augroup bundler_path
autocmd!
autocmd User Bundler call s:buffer().alter_paths()
augroup END
" }}}1
" vim:set sw=2 sts=2:

View File

@ -0,0 +1,267 @@
---
Title: Solarized Colorscheme for Vim
Description: Precision colors for machines and people
Author: Ethan Schoonover
Colors: light yellow
Created: 2011 Mar 15
Modified: 2011 Apr 16
---
Solarized Colorscheme for Vim
=============================
Developed by Ethan Schoonover <es@ethanschoonover.com>
Visit the [Solarized homepage]
------------------------------
See the [Solarized homepage] for screenshots,
details and colorscheme versions for Vim, Mutt, popular terminal emulators and
other applications.
Screenshots
-----------
![solarized dark](https://github.com/altercation/solarized/raw/master/img/solarized-vim.png)
Downloads
---------
If you have come across this colorscheme via the [Vim-only repository] on
github, or the [vim.org script] page see the link above to the Solarized
homepage or visit the main [Solarized repository].
The [Vim-only repository] is kept in sync with the main [Solarized repository]
and is for installation convenience only (with [Pathogen] or [Vundle], for
instance). Issues, bug reports, changelogs are centralized at the main
[Solarized repository].
[Solarized homepage]: http://ethanschoonover.com/solarized
[Solarized repository]: https://github.com/altercation/solarized
[Vim-only repository]: https://github.com/altercation/vim-colors-solarized
[vimorg-script]: http://vim.org/script
[Pathogen]: https://github.com/tpope/vim-pathogen
[Vundle]: https://github.com/gmarik/vundle
Installation
------------
### Option 1: Manual installation
1. Move `solarized.vim` to your `.vim/colors` directory. After downloading the
vim script or package:
$ cd vim-colors-solarized/colors
$ mv solarized.vim ~/.vim/colors/
### Option 2: Pathogen installation ***(recommended)***
1. Download and install Tim Pope's [Pathogen].
2. Next, move or clone the `vim-colors-solarized` directory so that it is
a subdirectory of the `.vim/bundle` directory.
a. **Clone:**
$ cd ~/.vim/bundle
$ git clone git://github.com/altercation/vim-colors-solarized.git
b. **Move:**
In the parent directory of vim-colors-solarized:
$ mv vim-colors-solarized ~/.vim/bundle/
### Modify .vimrc
After either Option 1 or Option 2 above, put the following two lines in your
.vimrc:
syntax enable
set background=dark
colorscheme solarized
or, for the light background mode of Solarized:
syntax enable
set background=light
colorscheme solarized
I like to have a different background in GUI and terminal modes, so I can use
the following if-then. However, I find vim's background autodetection to be
pretty good and, at least with MacVim, I can leave this background value
assignment out entirely and get the same results.
if has('gui_running')
set background=light
else
set background=dark
endif
See the [Solarized homepage] for screenshots which will help you
select either the light or dark background.
### IMPORTANT NOTE FOR TERMINAL USERS:
If you are going to use Solarized in Terminal mode (i.e. not in a GUI version
like gvim or macvim), **please please please** consider setting your terminal
emulator's colorscheme to used the Solarized palette. I've included palettes
for some popular terminal emulator as well as Xdefaults in the official
Solarized download available from [Solarized homepage]. If you use
Solarized *without* these colors, Solarized will need to be told to degrade its
colorscheme to a set compatible with the limited 256 terminal palette (whereas
by using the terminal's 16 ansi color values, you can set the correct, specific
values for the Solarized palette).
If you do use the custom terminal colors, solarized.vim should work out of the
box for you. If you are using a terminal emulator that supports 256 colors and
don't want to use the custom Solarized terminal colors, you will need to use
the degraded 256 colorscheme. To do so, simply add the following line *before*
the `colorschem solarized` line:
let g:solarized_termcolors=256
Again, I recommend just changing your terminal colors to Solarized values
either manually or via one of the many terminal schemes available for import.
Advanced Configuration
----------------------
Solarized will work out of the box with just the two lines specified above but
does include several other options that can be set in your .vimrc file.
Set these in your vimrc file prior to calling the colorscheme.
"
option name default optional
------------------------------------------------
g:solarized_termcolors= 16 | 256
g:solarized_termtrans = 0 | 1
g:solarized_degrade = 0 | 1
g:solarized_bold = 1 | 0
g:solarized_underline = 1 | 0
g:solarized_italic = 1 | 0
g:solarized_contrast = "normal"| "high" or "low"
g:solarized_visibility= "normal"| "high" or "low"
------------------------------------------------
### Option Details
* g:solarized_termcolors
This is set to *16* by default, meaning that Solarized will attempt to use
the standard 16 colors of your terminal emulator. You will need to set
those colors to the correct Solarized values either manually or by
importing one of the many colorscheme available for popular terminal
emulators and Xdefaults.
* g:solarized_termtrans
If you use a terminal emulator with a transparent background and Solarized
isn't displaying the background color transparently, set this to 1 and
Solarized will use the default (transparent) background of the terminal
emulator. *urxvt* required this in my testing; iTerm2 did not.
Note that on Mac OS X Terminal.app, solarized_termtrans is set to 1 by
default as this is almost always the best option. The only exception to
this is if the working terminfo file supports 256 colors (xterm-256color).
* g:solarized_degrade
For test purposes only; forces Solarized to use the 256 degraded color mode
to test the approximate color values for accuracy.
* g:solarized_bold | g:solarized_underline | g:solarized_italic
If you wish to stop Solarized from displaying bold, underlined or
italicized typefaces, simply assign a zero value to the appropriate
variable, for example: `let g:solarized_italic=0`
* g:solarized_contrast
Stick with normal! It's been carefully tested. Setting this option to high
or low does use the same Solarized palette but simply shifts some values up
or down in order to expand or compress the tonal range displayed.
* g:solarized_visibility
Special characters such as trailing whitespace, tabs, newlines, when
displayed using `:set list` can be set to one of three levels depending on
your needs. Default value is `normal` with `high` and `low` options.
Toggle Background Function
--------------------------
Solarized comes with a Toggle Background plugin that by default will map to
<F5> if that mapping is available. If it is not available you will need to
either map the function manually or change your current <F5> mapping to
something else.
To set your own mapping in your .vimrc file, simply add the following line to
support normal, insert and visual mode usage, changing the "<F5>" value to the
key or key combination you wish to use:
call togglebg#map("<F5>")
Note that you'll want to use a single function key or equivalent if you want
the plugin to work in all modes (normal, insert, visual).
Code Notes
----------
Use folding to view the `solarized.vim` script with `foldmethod=marker` turned
on.
I have attempted to modularize the creation of Vim colorschemes in this script
and, while it could be refactored further, it should be a good foundation for
the creation of any color scheme. By simply changing the sixteen values in the
GUI section and testing in gvim (or mvim) you can rapidly prototype new
colorschemes without diving into the weeds of line-item editing each syntax
highlight declaration.
The Values
----------
L\*a\*b values are canonical (White D65, Reference D50), other values are
matched in sRGB space.
SOLARIZED HEX 16/8 TERMCOL XTERM/HEX L*A*B sRGB HSB
--------- ------- ---- ------- ----------- ---------- ----------- -----------
base03 #002b36 8/4 brblack 234 #1c1c1c 15 -12 -12 0 43 54 193 100 21
base02 #073642 0/4 black 235 #262626 20 -12 -12 7 54 66 192 90 26
base01 #586e75 10/7 brgreen 240 #4e4e4e 45 -07 -07 88 110 117 194 25 46
base00 #657b83 11/7 bryellow 241 #585858 50 -07 -07 101 123 131 195 23 51
base0 #839496 12/6 brblue 244 #808080 60 -06 -03 131 148 150 186 13 59
base1 #93a1a1 14/4 brcyan 245 #8a8a8a 65 -05 -02 147 161 161 180 9 63
base2 #eee8d5 7/7 white 254 #d7d7af 92 -00 10 238 232 213 44 11 93
base3 #fdf6e3 15/7 brwhite 230 #ffffd7 97 00 10 253 246 227 44 10 99
yellow #b58900 3/3 yellow 136 #af8700 60 10 65 181 137 0 45 100 71
orange #cb4b16 9/3 brred 166 #d75f00 50 50 55 203 75 22 18 89 80
red #dc322f 1/1 red 160 #d70000 50 65 45 220 50 47 1 79 86
magenta #d33682 5/5 magenta 125 #af005f 50 65 -05 211 54 130 331 74 83
violet #6c71c4 13/5 brmagenta 61 #5f5faf 50 15 -45 108 113 196 237 45 77
blue #268bd2 4/4 blue 33 #0087ff 55 -10 -45 38 139 210 205 82 82
cyan #2aa198 6/6 cyan 37 #00afaf 60 -35 -05 42 161 152 175 74 63
green #859900 2/2 green 64 #5f8700 60 -20 65 133 153 0 68 100 60
License
-------
Copyright (c) 2011 Ethan Schoonover
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,55 @@
" Toggle Background
" Modified: 2011 Apr 29
" Maintainer: Ethan Schoonover
" License: OSI approved MIT license
if exists("g:loaded_togglebg")
finish
endif
let g:loaded_togglebg = 1
" noremap is a bit misleading here if you are unused to vim mapping.
" in fact, there is remapping, but only of script locally defined remaps, in
" this case <SID>TogBG. The <script> argument modifies the noremap scope in
" this regard (and the noremenu below).
nnoremap <unique> <script> <Plug>ToggleBackground <SID>TogBG
inoremap <unique> <script> <Plug>ToggleBackground <ESC><SID>TogBG<ESC>a
vnoremap <unique> <script> <Plug>ToggleBackground <ESC><SID>TogBG<ESC>gv
nnoremenu <script> Window.Toggle\ Background <SID>TogBG
inoremenu <script> Window.Toggle\ Background <ESC><SID>TogBG<ESC>a
vnoremenu <script> Window.Toggle\ Background <ESC><SID>TogBG<ESC>gv
tmenu Window.Toggle\ Background Toggle light and dark background modes
nnoremenu <script> ToolBar.togglebg <SID>TogBG
inoremenu <script> ToolBar.togglebg <ESC><SID>TogBG<ESC>a
vnoremenu <script> ToolBar.togglebg <ESC><SID>TogBG<ESC>gv
tmenu ToolBar.togglebg Toggle light and dark background modes
noremap <SID>TogBG :call <SID>TogBG()<CR>
function! s:TogBG()
let &background = ( &background == "dark"? "light" : "dark" )
if exists("g:colors_name")
exe "colorscheme " . g:colors_name
endif
endfunction
if !exists(":ToggleBG")
command ToggleBG :call s:TogBG()
endif
function! ToggleBackground()
echo "Please update your ToggleBackground mapping. ':help togglebg' for information."
endfunction
function! togglebg#map(mapActivation)
try
exe "silent! nmap <unique> ".a:mapActivation." <Plug>ToggleBackground"
exe "silent! imap <unique> ".a:mapActivation." <Plug>ToggleBackground"
exe "silent! vmap <unique> ".a:mapActivation." <Plug>ToggleBackground"
finally
return 0
endtry
endfunction
if !exists("no_plugin_maps") && !hasmapto('<Plug>ToggleBackground')
call togglebg#map("<F5>")
endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,254 @@
*solarized.vim* for Vim version 7.3 or newer. Modified: 2011 May 05
Solarized Vim Colorscheme by Ethan Schoonover ~
Solarized Colorscheme *solarized*
*solarized-help*
*solarized-colors*
*solarized-colorscheme*
*vim-colors-solarized*
Solarized is a carefully designed selective contrast colorscheme with dual
light and dark modes that runs in both GUI, 256 and 16 color modes.
See the homepage at http://ethanschoonover.com/solarized for screenshots and
details.
0. Install |solarized-install|
1. Solarized Menu |solarized-menu|
2. Options |solarized-options|
3. Toggle Background |solarized-togglebg|
4. Terminal Issues |solarized-term|
==============================================================================
0. Install *solarized-install*
Note: I recommend using Tim Pope's pathogen plugin to install this
colorscheme. See https://github.com/tpope/vim-pathogen . If you've installed
pathogen properly you can install Solarized with the following commands,
followed by the .vimrc configuration below.
$ cd ~/.vim/bundle
$ git clone https://github.com/altercation/vim-colors-solarized.git
If you aren't using pathogen, you can use the following three steps to install
Solarized:
1. Download the solarized distribution (available on the homepage above)
and unarchive the file.
2. Move `solarized.vim` to your `.vim/colors` directory.
3. Move each of the files in each subdirectories to the corresponding .vim
subdirectory (e.g. autoload/togglebg.vim goes into your .vim/autoload
directory as .vim/autoload/togglebg.vim).
After installation, place the following lines in your .vimrc:
syntax enable
set background=dark
colorscheme solarized
or, for the light background mode of Solarized:
syntax enable
set background=light
colorscheme solarized
==============================================================================
1. Solarized Menu *solarized-menu*
Solarized makes available a menu when used in Vim GUI mode (gvim, macvim).
This menu includes many of the options detailed below so that you can test out
different values quickly without modifying your .vimrc file. If you wish to
turn off this menu permanently, simply place the following line in your .vimrc
above the "colorscheme solarized" line.
let g:solarized_menu=0
==============================================================================
2. Toggle Background *solarized-togglebg*
*toggle-bg* *togglebg*
*toggle-background*
Solarized comes with Toggle Background, a simple plugin to switch between
light and dark background modes and reset the colorscheme. This is most useful
for colorschemes that support both light and dark modes and in terminals or
gui vim windows where the background will be properly set.
Toggle Background can be accessed by:
* the Solarized menu (in Vim gui mode)
* the Window menu (in Vim gui mode, even if the Solarized menu is off)
* the "yin/yang" toolbar button (in Vim gui mode)
* the default mapping of <F5>
* custom key mapping you set in your .vimrc (see below)
* command line via ":ToggleBG" (no quotes)
Toggle Background starts with a default mapping to function key <F5>. If you
are already using this in a mapping, Toggle Background will not map itself to
a default and you will have to map it manually in your .vimrc file, or
remove/change your existing <F5> mapping to another value. To customize the
keyboard mapping in your .vimrc file, use the following line, changing the
"<F5>" value to the key or key combination you wish to use:
call togglebg#map("<F5>")
Note that you'll want to use a single function key or equivalent if you want
the plugin to work in all modes (normal, insert, visual).
When using the plugin during normal, visual, or insert mode, there should be
no interruption in workflow. However, if you activate the plugin during
REPLACE mode, you will switch to standard insert mode (you will leave the
overwrite replace mode).
==============================================================================
3. Solarized Terminal Issues *solarized-term*
If you are going to use Solarized in Terminal mode (i.e. not in a GUI version
like gvim or macvim), **please please please** consider setting your terminal
emulator's colorscheme to used the Solarized palette. I've included palettes
for some popular terminal emulator as well as Xdefaults in the official
Solarized download available from the Solarized homepage listed at the top of
this help document. If you use Solarized *without* these colors, Solarized
will need to be told to degrade its colorscheme to a set compatible with the
limited 256 terminal palette (whereas by using the terminal's 16 ansi color
values, you can set the correct, specific values for the Solarized palette).
If you do use the custom terminal colors, solarized.vim should work out of
the box for you. If you are using a terminal emulator that supports 256
colors and don't want to use the custom Solarized terminal colors, you will
need to use the degraded 256 colorscheme. To do so, simply add the following
line *before* the `colorschem solarized` line:
let g:solarized_termcolors=256
Again, I recommend just changing your terminal colors to Solarized values
either manually or via one of the many terminal schemes available for import.
==============================================================================
4. Solarized Options *solarized-options*
AUTOGENERATE OPTIONS
You can easily modify and experiment with Solarized display options using the
Solarized menu when using Vim in gui mode. Once you have things set to your
liking, you can autogenerate the current option list in a format ready for
insertion into your .vimrc file using the Solarized menu "Autogenerate
Options" command or at the command line with:
:SolarizedOptions
OPTION LIST
Set these in your vimrc file prior to calling the colorscheme.
option name default optional
------------------------------------------------
g:solarized_termcolors= 16 | 256
g:solarized_termtrans = 0 | 1
g:solarized_degrade = 0 | 1
g:solarized_bold = 1 | 0
g:solarized_underline = 1 | 0
g:solarized_italic = 1 | 0
g:solarized_contrast = "normal"| "high" or "low"
g:solarized_visibility= "normal"| "high" or "low"
g:solarized_hitrail = 0 | 1
g:solarized_menu = 1 | 0
------------------------------------------------
OPTION DETAILS
------------------------------------------------
g:solarized_termcolors= 256 | 16 *'solarized_termcolors'*
------------------------------------------------
The most important option if you are using vim in terminal (non gui) mode!
This tells Solarized to use the 256 degraded color mode if running in a 256
color capable terminal. Otherwise, if set to `16` it will use the terminal
emulators colorscheme (best option as long as you've set the emulators colors
to the Solarized palette).
If you are going to use Solarized in Terminal mode (i.e. not in a GUI
version like gvim or macvim), **please please please** consider setting your
terminal emulator's colorscheme to used the Solarized palette. I've included
palettes for some popular terminal emulator as well as Xdefaults in the
official Solarized download available from:
http://ethanschoonover.com/solarized . If you use Solarized without these
colors, Solarized will by default use an approximate set of 256 colors. It
isn't bad looking and has been extensively tweaked, but it's still not quite
the real thing.
------------------------------------------------
g:solarized_termtrans = 0 | 1 *'solarized_termtrans'*
------------------------------------------------
If you use a terminal emulator with a transparent background and Solarized
isn't displaying the background color transparently, set this to 1 and
Solarized will use the default (transparent) background of the terminal
emulator. *urxvt* required this in my testing; iTerm2 did not.
Note that on Mac OS X Terminal.app, solarized_termtrans is set to 1 by
default as this is almost always the best option. The only exception to this
is if the working terminfo file supports 256 colors (xterm-256color).
------------------------------------------------
g:solarized_degrade = 0 | 1 *'solarized_degrade'*
------------------------------------------------
For test purposes only; forces Solarized to use the 256 degraded color mode
to test the approximate color values for accuracy.
------------------------------------------------
g:solarized_bold = 1 | 0 *'solarized_bold'*
------------------------------------------------
------------------------------------------------
g:solarized_underline = 1 | 0 *'solarized_underline'*
------------------------------------------------
------------------------------------------------
g:solarized_italic = 1 | 0 *'solarized_italic'*
------------------------------------------------
If you wish to stop Solarized from displaying bold, underlined or
italicized typefaces, simply assign a zero value to the appropriate
variable, for example: `let g:solarized_italic=0`
------------------------------------------------
g:solarized_contrast = "normal"| "high" or "low" *'solarized_contrast'*
------------------------------------------------
Stick with normal! It's been carefully tested. Setting this option to high
or low does use the same Solarized palette but simply shifts some values up
or down in order to expand or compress the tonal range displayed.
------------------------------------------------
g:solarized_visibility = "normal"| "high" or "low" *'solarized_visibility'*
------------------------------------------------
Special characters such as trailing whitespace, tabs, newlines, when
displayed using ":set list" can be set to one of three levels depending on
your needs.
------------------------------------------------
g:solarized_hitrail = 0 | 1 *'solarized_hitrail'*
------------------------------------------------
Visibility can make listchar entities more visible, but if one has set
cursorline on, these same listchar values standout somewhat less due to the
background color of the cursorline. g:solarized_hitrail enables highlighting
of trailing spaces (only one of the listchar types, but a particularly
important one) while in the cursoline in a different manner in order to make
them more visible. This may not work consistently as Solarized is using
a pattern match than can be overridden by a more encompassing syntax-native
match such as a comment line.
------------------------------------------------
g:solarized_menu = 1 | 0 *'solarized_menu'*
------------------------------------------------
Solarized includes a menu providing access to several of the above
display related options, including contrast and visibility. This allows
for an easy method of testing different values quickly before settling
on a final assignment for your .vimrc. If you wish to turn off this menu,
assign g:solarized_menu a value of 0.
vim:tw=78:noet:ts=8:ft=help:norl:

View File

@ -0,0 +1,27 @@
'solarized_bold' solarized.txt /*'solarized_bold'*
'solarized_contrast' solarized.txt /*'solarized_contrast'*
'solarized_degrade' solarized.txt /*'solarized_degrade'*
'solarized_hitrail' solarized.txt /*'solarized_hitrail'*
'solarized_italic' solarized.txt /*'solarized_italic'*
'solarized_menu' solarized.txt /*'solarized_menu'*
'solarized_termcolors' solarized.txt /*'solarized_termcolors'*
'solarized_termtrans' solarized.txt /*'solarized_termtrans'*
'solarized_underline' solarized.txt /*'solarized_underline'*
'solarized_visibility' solarized.txt /*'solarized_visibility'*
before solarized.txt /*before*
solarized solarized.txt /*solarized*
solarized-colors solarized.txt /*solarized-colors*
solarized-colorscheme solarized.txt /*solarized-colorscheme*
solarized-help solarized.txt /*solarized-help*
solarized-install solarized.txt /*solarized-install*
solarized-menu solarized.txt /*solarized-menu*
solarized-options solarized.txt /*solarized-options*
solarized-term solarized.txt /*solarized-term*
solarized-togglebg solarized.txt /*solarized-togglebg*
solarized.vim solarized.txt /*solarized.vim*
toggle-background solarized.txt /*toggle-background*
toggle-bg solarized.txt /*toggle-bg*
togglebg solarized.txt /*togglebg*
urxvt solarized.txt /*urxvt*
vim-colors-solarized solarized.txt /*vim-colors-solarized*
without solarized.txt /*without*

View File

@ -0,0 +1,15 @@
## Vim Colorscheme 'Elrodeo'
This is a dark low contrast vim color scheme influenced by colors used by Chris Granger (@ibdknox) for Clojure code, e.g., on the Noir web page (webnoir.org).
## Screenshot
![screenshot](https://github.com/chmllr/vim-colorscheme-elrodeo/raw/master/screenshot.png)
## Installation
The color scheme can be installed as a pathogen plugin, i.e., just check it out to `~/.vim/bundle`, or copy the content of `colors`to `~/.vim/colors`.
## Usage
In Vim: `:colorscheme elrodeo`.

View File

@ -0,0 +1,63 @@
" Vim color file
" Name: elrodeo
" Maintainer: Christian Müller (@chmllr)
" Version: 1.0
"
" Inspired by the color scheme used by ibdknox.
set background=dark
hi clear
if exists("syntax_on")
syntax reset
endif
let g:colors_name="elrodeo"
" the nexz block is copied from the wombat theme:
" Vim >= 7.0 specific colors
if version >= 700
hi CursorLine guibg=#2d2d2d
hi CursorColumn guibg=#2d2d2d
hi MatchParen guifg=#f6f3e8 guibg=#857b6f gui=bold
hi Pmenu guifg=#f6f3e8 guibg=#444444
hi PmenuSel guifg=#000000 guibg=#cae682
endif
" General colors
hi Normal guibg=#404040 guifg=#d0d0d0
hi Cursor guifg=#656565 guibg=#d0d0d0
hi NonText guifg=#808080 guibg=#404040
hi LineNr guifg=#666666 guibg=#383838
hi StatusLine guifg=#f6f3e8 guibg=#444444
hi StatusLineNC guifg=#857b6f guibg=#444444
hi VertSplit guifg=#444444 guibg=#444444
hi Folded guibg=#384048 guifg=#a0a8b0
hi Title guifg=#f6f3e8 guibg=NONE gui=bold
hi Visual guifg=#f6f3e8 guibg=#444444
hi SpecialKey guifg=#808080 guibg=#343434
" Syntax highlighting
hi Comment guifg=#677c99
hi Operator guifg=#a080f0
hi Todo guifg=#333333 guibg=#cccccc
hi Constant guifg=white
hi String guifg=#bbddff
hi Identifier guifg=#30c080
hi Define guifg=#30c080
hi Function guifg=#30c080
hi Macro guifg=#30c080
hi Number guifg=#319899
hi Special guifg=#30c080
hi Conditional guifg=#30c080
hi Boolean guifg=#99dd99
hi Delimiter guifg=#999999
hi Character guifg=#55d2ee
hi Search guifg=black guibg=#30c080
hi Visual guibg=#303030
" not used in Clojure (left as in wombat)
hi Type guifg=#cae682
hi Statement guifg=#8ac6f2
hi Keyword guifg=#8ac6f2
hi PreProc guifg=#e5786d

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

1
vim/bundle/vim-fugitive/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/doc/tags

View File

@ -0,0 +1,150 @@
fugitive.vim
============
I'm not going to lie to you; fugitive.vim may very well be the best
Git wrapper of all time. Check out these features:
View any blob, tree, commit, or tag in the repository with `:Gedit` (and
`:Gsplit`, `:Gvsplit`, `:Gtabedit`, ...). Edit a file in the index and
write to it to stage the changes. Use `:Gdiff` to bring up the staged
version of the file side by side with the working tree version and use
Vim's diff handling capabilities to stage a subset of the file's
changes.
Bring up the output of `git status` with `:Gstatus`. Press `-` to
`add`/`reset` a file's changes, or `p` to `add`/`reset` `--patch` that
mofo. And guess what `:Gcommit` does!
`:Gblame` brings up an interactive vertical split with `git blame`
output. Press enter on a line to reblame the file as it stood in that
commit, or `o` to open that commit in a split. When you're done, use
`:Gedit` in the historic buffer to go back to the work tree version.
`:Gmove` does a `git mv` on a file and simultaneously renames the
buffer. `:Gremove` does a `git rm` on a file and simultaneously deletes
the buffer.
Use `:Ggrep` to search the work tree (or any arbitrary commit) with
`git grep`, skipping over that which is not tracked in the repository.
`:Glog` loads all previous revisions of a file into the quickfix list so
you can iterate over them and watch the file evolve!
`:Gread` is a variant of `git checkout -- filename` that operates on the
buffer rather than the filename. This means you can use `u` to undo it
and you never get any warnings about the file changing outside Vim.
`:Gwrite` writes to both the work tree and index versions of a file,
making it like `git add` when called from a work tree file and like
`git checkout` when called from the index or a blob in history.
Use `:Gbrowse` to open the current file on GitHub, with optional line
range (try it in visual mode!). If your current repository isn't on
GitHub, `git instaweb` will be spun up instead.
Add `%{fugitive#statusline()}` to `'statusline'` to get an indicator
with the current branch in (surprise!) your statusline.
Last but not least, there's `:Git` for running any arbitrary command,
and `Git!` to open the output of a command in a temp file.
Screencasts
-----------
* [A complement to command line git](http://vimcasts.org/e/31)
* [Working with the git index](http://vimcasts.org/e/32)
* [Resolving merge conflicts with vimdiff](http://vimcasts.org/e/33)
* [Browsing the git object database](http://vimcasts.org/e/34)
* [Exploring the history of a git repository](http://vimcasts.org/e/35)
Installation
------------
If you don't have a preferred installation method, I recommend
installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and
then simply copy and paste:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-fugitive.git
Once help tags have been generated, you can view the manual with
`:help fugitive`.
If your Vim version is below 7.2, I recommend also installing
[vim-git](https://github.com/tpope/vim-git) for syntax highlighting and
other Git niceties.
FAQ
---
> I installed the plugin and started Vim. Why don't any of the commands
> exist?
Fugitive cares about the current file, not the current working
directory. Edit a file from the repository.
> I opened a new tab. Why don't any of the commands exist?
Fugitive cares about the current file, not the current working
directory. Edit a file from the repository.
> Why is `:Gbrowse` not using the right browser?
`:Gbrowse` delegates to `git web--browse`, which is less than perfect
when it comes to finding the right browser. You can tell it the correct
browser to use with `git config --global web.browser ...`. On OS X, for
example, you might want to set this to `open`. See `git web--browse --help`
for details.
> Here's a patch that automatically opens the quickfix window after
> `:Ggrep`.
This is a great example of why I recommend asking before patching.
There are valid arguments to be made both for and against automatically
opening the quickfix window. Whenever I have to make an arbitrary
decision like this, I ask what Vim would do. And Vim does not open a
quickfix window after `:grep`.
Luckily, it's easy to implement the desired behavior without changing
fugitive.vim. The following autocommand will cause the quickfix window
to open after any grep invocation:
autocmd QuickFixCmdPost *grep* cwindow
Contributing
------------
Before reporting a bug, you should try stripping down your Vim
configuration and removing other plugins. The sad nature of VimScript
is that it is fraught with incompatibilities waiting to happen. I'm
happy to work around them where I can, but it's up to you to isolate
the conflict.
If your [commit message sucks](http://stopwritingramblingcommitmessages.com/),
I'm not going to accept your pull request. I've explained very politely
dozens of times that
[my general guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
are absolute rules on my own repositories, so I may lack the energy to
explain it to you yet another time. And please, if I ask you to change
something, `git commit --amend`.
Beyond that, don't be shy about asking before patching. What takes you
hours might take me minutes simply because I have both domain knowledge
and a perverse knowledge of VimScript so vast that many would consider
it a symptom of mental illness. On the flip side, some ideas I'll
reject no matter how good the implementation is. "Send a patch" is an
edge case answer in my book.
Self-Promotion
--------------
Like fugitive.vim? Follow the repository on
[GitHub](https://github.com/tpope/vim-fugitive) and vote for it on
[vim.org](http://www.vim.org/scripts/script.php?script_id=2975). And if
you're feeling especially charitable, follow [tpope](http://tpo.pe/) on
[Twitter](http://twitter.com/tpope) and
[GitHub](https://github.com/tpope).
License
-------
Copyright (c) Tim Pope. Distributed under the same terms as Vim itself.
See `:help license`.

View File

@ -0,0 +1,313 @@
*fugitive.txt* A Git wrapper so awesome, it should be illegal
Author: Tim Pope <http://tpo.pe/>
License: Same terms as Vim itself (see |license|)
This plugin is only available if 'compatible' is not set.
INTRODUCTION *fugitive*
Whenever you edit a file from a Git repository, a set of commands is defined
that serve as a gateway to Git.
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-:Git!*
:Git! [args] Like |:Git|, but capture the output into a temp file,
and edit that temp file.
*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. The following maps, which work on the cursor
line file where sensible, are provided:
<C-N> next file
<C-P> previous file
<CR> |:Gedit|
- |:Git| add
- |:Git| reset (staged files)
cA |:Gcommit| --amend --reuse-message=HEAD
ca |:Gcommit| --amend
cc |:Gcommit|
cva |:Gcommit| --amend --verbose
cvc |:Gcommit| --verbose
D |:Gdiff|
ds |:Gsdiff|
dp |:Git!| diff (p for patch; use :Gw to apply)
dp |:Git| add --intent-to-add (untracked files)
dv |:Gvdiff|
O |:Gtabedit|
o |:Gsplit|
p |:Git| add --patch
p |:Git| reset --patch (staged files)
q close status
R reload status
S |:Gvsplit|
*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-:Glgrep*
:Glgrep [args] |:lgrep| 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
previous commits rather than previous file revisions
are loaded.
*fugitive-:Gllog*
:Gllog [args] Like |:Glog|, but use the location list instead of 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|.
:Gsplit! [args] *fugitive-:Gsplit!* *fugitive-:Gvsplit!*
:Gvsplit! [args] *fugitive-:Gtabedit!* *fugitive-:Gpedit!*
:Gtabedit! [args] Like |:Git!|, but open the resulting temp file in a
:Gpedit! [args] split, tab, or preview window.
*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! [args] Empty the buffer and |:read| the output of a Git
command. For example, :Gread! show HEAD:%.
:{range}Gread! [args] |:read| the output of a Git command after {range}.
*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-:Gwq*
:Gwq [path] Like |:Gwrite| followed by |:quit| if the write
succeeded.
:Gwq! [path] Like |:Gwrite|! followed by |:quit|! if the write
succeeded.
*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-:Gsdiff*
:Gsdiff [revision] Like |:Gdiff|, but split horizontally.
*fugitive-:Gvdiff*
:Gvdiff [revision] Identical to |:Gdiff|. For symmetry with |:Gsdiff|.
*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 ltfnsewMC as flags and they will be passed
along to git-blame. The following maps, which work on
the cursor line commit where sensible, are provided:
A resize to end of author column
C resize to end of commit column
D resize to end of date/time column
q close blame and return to blamed window
gq q, then |:Gedit| to return to work tree version
i q, then open commit
o open commit in horizontal split
O open commit in new tab
- reblame at commit
~ reblame at [count]th first grandparent
P reblame at [count]th parent (like HEAD^[count])
:[range]Gblame [flags] Run git-blame on the given range.
*fugitive-:Gbrowse*
:[range]Gbrowse If the remote for the current branch is on GitHub,
open the current file, blob, tree, commit, or tag
(with git-web--browse) on GitHub. Otherwise, open the
current file, blob, tree, commit, or tag in
git-instaweb (if you have issues, verify you can run
"git instaweb" from a terminal). If a range is given,
it is appropriately appended to the URL as an anchor.
To use with GitHub FI, point g:fugitive_github_domains
at a list of domains:
>
let g:fugitive_github_domains = ['git.example.com']
~
:[range]Gbrowse! Like :Gbrowse, but put the URL on the clipboard rather
than opening it.
:[range]Gbrowse {revision}
Like :Gbrowse, but for a given |fugitive-revision|. A
useful value here is -, which ties the URL to the
latest commit rather than a volatile branch.
:[range]Gbrowse [...]@{remote}
Force using the given remote rather than the remote
for the current branch. The remote is used to
determine which GitHub repository to link to.
MAPPINGS *fugitive-mappings*
These maps are available everywhere.
*fugitive-c_CTRL-R_CTRL-G*
<C-R><C-G> On the command line, recall the path to the current
object (that is, a representation of the object
recognized by |:Gedit|).
*fugitive-y_CTRL-G*
["x]y<C-G> Yank the commit SHA and path to the current object.
These maps are available in Git objects.
*fugitive-<CR>*
<CR> Jump to the revision under the cursor.
*fugitive-o*
o Jump to the revision under the cursor in a new split.
*fugitive-S*
S Jump to the revision under the cursor in a new
vertical split.
*fugitive-O*
O Jump to the revision under the cursor in a new tab.
*fugitive--*
- Go to the tree containing the current tree or blob.
*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
<
*fugitive#head(...)*
Use fugitive#head() to return the name of the current branch. If the current
HEAD is detached, fugitive#head() will return the empty string, unless the
optional argument is given, in which case the hash of the current commit will
be truncated to the given number of characters.
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:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
# vim-monokai
Monokai color scheme for Vim converted with [coloration](http://coloration.sickill.net) from Textmate theme with the same name.
## Screenshots
![Monokai in Vim](https://github.com/downloads/sickill/vim-monokai/vim-monokai.png)

View File

@ -0,0 +1,107 @@
" Vim color file
" Converted from Textmate theme Monokai using Coloration v0.3.2 (http://github.com/sickill/coloration)
set background=dark
highlight clear
if exists("syntax_on")
syntax reset
endif
let g:colors_name = "Monokai"
hi Cursor ctermfg=235 ctermbg=231 cterm=NONE guifg=#272822 guibg=#f8f8f0 gui=NONE
hi Visual ctermfg=NONE ctermbg=59 cterm=NONE guifg=NONE guibg=#49483e gui=NONE
hi CursorLine ctermfg=NONE ctermbg=237 cterm=NONE guifg=NONE guibg=#3c3d37 gui=NONE
hi CursorColumn ctermfg=NONE ctermbg=237 cterm=NONE guifg=NONE guibg=#3c3d37 gui=NONE
hi ColorColumn ctermfg=NONE ctermbg=237 cterm=NONE guifg=NONE guibg=#3c3d37 gui=NONE
hi LineNr ctermfg=102 ctermbg=237 cterm=NONE guifg=#90908a guibg=#3c3d37 gui=NONE
hi VertSplit ctermfg=241 ctermbg=241 cterm=NONE guifg=#64645e guibg=#64645e gui=NONE
hi MatchParen ctermfg=197 ctermbg=NONE cterm=underline guifg=#f92672 guibg=NONE gui=underline
hi StatusLine ctermfg=231 ctermbg=241 cterm=bold guifg=#f8f8f2 guibg=#64645e gui=bold
hi StatusLineNC ctermfg=231 ctermbg=241 cterm=NONE guifg=#f8f8f2 guibg=#64645e gui=NONE
hi Pmenu ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi PmenuSel ctermfg=NONE ctermbg=59 cterm=NONE guifg=NONE guibg=#49483e gui=NONE
hi IncSearch ctermfg=235 ctermbg=186 cterm=NONE guifg=#272822 guibg=#e6db74 gui=NONE
hi Search ctermfg=NONE ctermbg=NONE cterm=underline guifg=NONE guibg=NONE gui=underline
hi Directory ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi Folded ctermfg=242 ctermbg=235 cterm=NONE guifg=#75715e guibg=#272822 gui=NONE
hi Normal ctermfg=231 ctermbg=235 cterm=NONE guifg=#f8f8f2 guibg=#272822 gui=NONE
hi Boolean ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi Character ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi Comment ctermfg=242 ctermbg=NONE cterm=NONE guifg=#75715e guibg=NONE gui=NONE
hi Conditional ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi Constant ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi Define ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi DiffAdd ctermfg=231 ctermbg=64 cterm=bold guifg=#f8f8f2 guibg=#46830c gui=bold
hi DiffDelete ctermfg=88 ctermbg=NONE cterm=NONE guifg=#8b0807 guibg=NONE gui=NONE
hi DiffChange ctermfg=231 ctermbg=23 cterm=NONE guifg=#f8f8f2 guibg=#243955 gui=NONE
hi DiffText ctermfg=231 ctermbg=24 cterm=bold guifg=#f8f8f2 guibg=#204a87 gui=bold
hi ErrorMsg ctermfg=231 ctermbg=197 cterm=NONE guifg=#f8f8f0 guibg=#f92672 gui=NONE
hi WarningMsg ctermfg=231 ctermbg=197 cterm=NONE guifg=#f8f8f0 guibg=#f92672 gui=NONE
hi Float ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi Function ctermfg=148 ctermbg=NONE cterm=NONE guifg=#a6e22e guibg=NONE gui=NONE
hi Identifier ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=italic
hi Keyword ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi Label ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi NonText ctermfg=59 ctermbg=236 cterm=NONE guifg=#49483e guibg=#31322c gui=NONE
hi Number ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi Operator ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi PreProc ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi Special ctermfg=231 ctermbg=NONE cterm=NONE guifg=#f8f8f2 guibg=NONE gui=NONE
hi SpecialKey ctermfg=59 ctermbg=237 cterm=NONE guifg=#49483e guibg=#3c3d37 gui=NONE
hi Statement ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi StorageClass ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=italic
hi String ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi Tag ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi Title ctermfg=231 ctermbg=NONE cterm=bold guifg=#f8f8f2 guibg=NONE gui=bold
hi Todo ctermfg=95 ctermbg=NONE cterm=inverse,bold guifg=#75715e guibg=NONE gui=inverse,bold
hi Type ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi Underlined ctermfg=NONE ctermbg=NONE cterm=underline guifg=NONE guibg=NONE gui=underline
hi rubyClass ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi rubyFunction ctermfg=148 ctermbg=NONE cterm=NONE guifg=#a6e22e guibg=NONE gui=NONE
hi rubyInterpolationDelimiter ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi rubySymbol ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi rubyConstant ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=italic
hi rubyStringDelimiter ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi rubyBlockParameter ctermfg=208 ctermbg=NONE cterm=NONE guifg=#fd971f guibg=NONE gui=italic
hi rubyInstanceVariable ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi rubyInclude ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi rubyGlobalVariable ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi rubyRegexp ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi rubyRegexpDelimiter ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi rubyEscape ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi rubyControl ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi rubyClassVariable ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi rubyOperator ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi rubyException ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi rubyPseudoVariable ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi rubyRailsUserClass ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=italic
hi rubyRailsARAssociationMethod ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi rubyRailsARMethod ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi rubyRailsRenderMethod ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi rubyRailsMethod ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi erubyDelimiter ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi erubyComment ctermfg=95 ctermbg=NONE cterm=NONE guifg=#75715e guibg=NONE gui=NONE
hi erubyRailsMethod ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi htmlTag ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi htmlEndTag ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi htmlTagName ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi htmlArg ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi htmlSpecialChar ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi javaScriptFunction ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=italic
hi javaScriptRailsFunction ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi javaScriptBraces ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi yamlKey ctermfg=197 ctermbg=NONE cterm=NONE guifg=#f92672 guibg=NONE gui=NONE
hi yamlAnchor ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi yamlAlias ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE
hi yamlDocumentHeader ctermfg=186 ctermbg=NONE cterm=NONE guifg=#e6db74 guibg=NONE gui=NONE
hi cssURL ctermfg=208 ctermbg=NONE cterm=NONE guifg=#fd971f guibg=NONE gui=italic
hi cssFunctionName ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi cssColor ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi cssPseudoClassId ctermfg=148 ctermbg=NONE cterm=NONE guifg=#a6e22e guibg=NONE gui=NONE
hi cssClassName ctermfg=148 ctermbg=NONE cterm=NONE guifg=#a6e22e guibg=NONE gui=NONE
hi cssValueLength ctermfg=141 ctermbg=NONE cterm=NONE guifg=#ae81ff guibg=NONE gui=NONE
hi cssCommonAttr ctermfg=81 ctermbg=NONE cterm=NONE guifg=#66d9ef guibg=NONE gui=NONE
hi cssBraces ctermfg=NONE ctermbg=NONE cterm=NONE guifg=NONE guibg=NONE gui=NONE

1
vim/bundle/vim-obsession/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/doc/tags

View File

@ -0,0 +1 @@
See the [contribution guidelines for pathogen.vim](https://github.com/tpope/vim-pathogen/blob/master/CONTRIBUTING.markdown).

View File

@ -0,0 +1,47 @@
# obsession.vim
Vim features a `:mksession` command to write a file containing the current
state of Vim: window positions, open folds, stuff like that. For most of my
existence, I found the interface way too awkward and manual to be useful, but
I've recently discovered that the only thing standing between me and simple,
no-hassle Vim sessions is a few tweaks:
* Instead of making me remember to capture the session immediately before
exiting Vim, allow me to do it at any time, and automatically re-invoke
`:mksession` immediately before exit.
* Also invoke `:mksession` whenever the layout changes (in particular, on
`BufEnter`), so that even if Vim exits abnormally, I'm good to go.
* If I load an existing session, automatically keep it updated as above.
* If I try to create a new session on top of an existing session, don't refuse
to overwrite it. Just do what I mean.
* If I pass in a directory rather than a file name, just create a
`Session.vim` inside of it.
* Don't capture options and maps. Options are sometimes mutilated and maps
just interfere with updating plugins.
Use `:Obsess` (with optional file/directory name) to start recording to a
session file and `:Obsess!` to stop and throw it away. That's it. Load a
session in the usual manner: `vim -S`, or `:source` it.
## Installation
If you don't have a preferred installation method, I recommend
installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and
then simply copy and paste:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-obsession.git
## Self-Promotion
Like obsession.vim? Follow the repository on
[GitHub](https://github.com/tpope/vim-obsession) and vote for it on
[vim.org](http://www.vim.org/scripts/script.php?script_id=4472). And if
you're feeling especially charitable, follow [tpope](http://tpo.pe/) on
[Twitter](http://twitter.com/tpope) and
[GitHub](https://github.com/tpope).
## License
Copyright © Tim Pope. Distributed under the same terms as Vim itself.
See `:help license`.

View File

@ -0,0 +1,27 @@
*obsession.txt* Continuously updated session files
Author: Tim Pope <http://tpo.pe/>
Repo: https://github.com/tpope/vim-obsession
License: Same terms as Vim itself (see |license|)
USAGE *obsession* *:Obsession*
:Obsession {file} Invoke |:mksession| on {file} and continue to keep it
updated until Vim exits, triggering on the |BufEnter|
and |VimLeavePre| autocommands. If the file exists,
it will be overwritten if and only if it looks like a
session file.
:Obsession {dir} Invoke |:Obsession| on {dir}/Session.vim. Use "." to
write to a session file in the current directory.
:Obsession If session tracking is already in progress, pause it.
Otherwise, resume tracking or create a new session in
the current directory.
:Obsession! Stop obsession and delete the underlying session file.
Loading a session created with |:Obsession| automatically resumes updates to
that file.
vim:tw=78:et:ft=help:norl:

View File

@ -0,0 +1,71 @@
" obsession.vim - Continuously updated session files
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 1.0
if exists("g:loaded_obsession") || v:version < 700 || &cp
finish
endif
let g:loaded_obsession = 1
command! -bar -bang -complete=file -nargs=? Obsession execute s:dispatch(<bang>0, <q-args>)
function! s:dispatch(bang, file) abort
if a:bang && empty(a:file) && filereadable(get(g:, 'this_obsession', v:this_session))
echo 'Deleting session in '.fnamemodify(get(g:, 'this_obsession', v:this_session), ':~:.')
call delete(get(g:, 'this_obsession', v:this_session))
unlet! g:this_obsession
return ''
elseif empty(a:file) && exists('g:this_obsession')
echo 'Pausing session in '.fnamemodify(g:this_obsession, ':~:.')
unlet g:this_obsession
return ''
elseif empty(a:file) && !empty(v:this_session)
let file = v:this_session
elseif empty(a:file)
let file = getcwd() . '/Session.vim'
elseif isdirectory(a:file)
let file = fnamemodify(expand(a:file), ':p') . '/Session.vim'
else
let file = fnamemodify(expand(a:file), ':p')
endif
if !a:bang
\ && file !~# 'Session\.vim$'
\ && filereadable(file)
\ && getfsize(file) > 0
\ && readfile(file, '', 1)[0] !=# 'let SessionLoad = 1'
return 'mksession '.fnameescape(file)
endif
let g:this_obsession = file
let error = s:persist()
if empty(error)
echo 'Tracking session in '.fnamemodify(file, ':~:.')
let v:this_session = file
return ''
else
return error
endif
endfunction
function! s:persist()
if exists('g:this_obsession')
let sessionoptions = &sessionoptions
try
set sessionoptions-=options
execute 'mksession! '.fnameescape(g:this_obsession)
call writefile(insert(readfile(g:this_obsession), 'let g:this_obsession = v:this_session', -2), g:this_obsession)
catch
unlet g:this_obsession
return 'echoerr '.string(v:exception)
finally
let &sessionoptions = sessionoptions
endtry
endif
return ''
endfunction
augroup obsession
autocmd!
autocmd BufEnter,VimLeavePre * exe s:persist()
augroup END
" vim:set et sw=2:

3
vim/bundle/vim-rails/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/rails.zip
/rails.vba
/doc/tags

View File

@ -0,0 +1,16 @@
If your [commit message sucks][suck], I'm not going to accept your pull
request. I've explained very politely dozens of times that [my general
guidelines][guidelines] are absolute rules on my own repositories, so I may
lack the energy to explain it to you yet another time. And please, if I ask
you to change something, `git commit --amend` and `git push -f`.
If a feature idea is nontrivial, you should probably open an issue to [discuss
it][] before attempting a pull request. One of the biggest challenges in
maintaining rails.vim has been beating back the bloat, so do not assume that
your idea will make the cut. And if I like your idea, I'm generally amenable
to just knocking it out myself, rather than making you familiarize yourself
with a 4 thousand line code base.
[suck]: http://stopwritingramblingcommitmessages.com/
[guidelines]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
[discuss it]: http://www.igvita.com/2011/12/19/dont-push-your-pull-requests/

View File

@ -0,0 +1,135 @@
# rails.vim
Remember when everybody and their mother was using TextMate for Ruby on
Rails development? Well if it wasn't for rails.vim, we'd still be in
that era. So shut up and pay some respect. And check out these
features:
* Easy navigation of the Rails directory structure. `gf` considers
context and knows about partials, fixtures, and much more. There are
two commands, `:A` (alternate) and `:R` (related) for easy jumping
between files, including favorites like model to schema, template to
helper, and controller to functional test. Commands like `:Emodel`,
`:Eview`, `:Econtroller`, are provided to `:edit` files by type, along
with `S`, `V`, and `T` variants for `:split`, `:vsplit`, and
`:tabedit`. Throw a bang on the end (`:Emodel foo!`) to automatically
create the file with the standard boilerplate if it doesn't exist.
`:help rails-navigation`
* Enhanced syntax highlighting. From `has_and_belongs_to_many` to
`distance_of_time_in_words`, it's here. For easy completion of these
long method names, `'completefunc'` is set to enable syntax based
completion on CTRL-X CTRL-U.
* Interface to rake. Use `:Rake` to run the current test, spec, or
feature. Use `:.Rake` to do a focused run of just the method,
example, or scenario on the current line. `:Rake` can also run
arbitrary migrations, load individual fixtures, and more.
`:help rails-rake`
* Interface to the `rails` command. Generally, use `:Rails console` to
call `rails console`. Many commands have wrappers with additional features:
`:Rgenerate controller Blog` generates a blog controller and loads the
generated files into the quickfix list, and `:Rrunner` wraps `rails runner`
and doubles as a direct test runner. `:help rails-scripts`
* Partial and concern extraction. In a view, `:Rextract {file}`
replaces the desired range (typically selected in visual line mode)
with `render '{file}'`, which is automatically created with your
content. In a model or controller, a concern is created, with the
appropriate `include` declaration left behind.
`:help rails-:Rextract`
* Fully customizable. Define "projections" at the global, app, or gem
level to define navigation commands and override the alternate file,
default rake task, syntax highlighting, abbreviations, and more.
`:help rails-projections`.
* Integration with other plugins. If
[dbext.vim](http://www.vim.org/scripts/script.php?script_id=356) is
installed, it will be transparently configured to reflect
`database.yml`. Users of
[abolish.vim](https://github.com/tpope/vim-abolish) get pluralize and
tableize coercions, and users of
[bundler.vim](https://github.com/tpope/vim-bundler) get a smattering of
features. `:help rails-integration`
## Installation
If you don't have a preferred installation method, I recommend
installing [pathogen.vim](https://github.com/tpope/vim-pathogen), and
then simply copy and paste:
cd ~/.vim/bundle
git clone git://github.com/tpope/vim-rails.git
git clone git://github.com/tpope/vim-bundler.git
You don't strictly need [bundler.vim][], but it helps.
Once help tags have been generated, you can view the manual with
`:help rails`.
[bundler.vim]: https://github.com/tpope/vim-bundler
## FAQ
> I installed the plugin and started Vim. Why does only the `:Rails`
> command exist?
This plugin cares about the current file, not the current working
directory. Edit a file from a Rails application.
> I opened a new tab. Why does only the `:Rails` command exist?
This plugin cares about the current file, not the current working
directory. Edit a file from a Rails application. You can use the `:RT`
family of commands to open a new tab and edit a file at the same time.
> Can I use rails.vim to edit Rails engines?
It's not supported, but if you `touch config/environment.rb` in the root
of the engine, things should mostly work.
> Can I use rails.vim to edit other Ruby projects?
I wrote [rake.vim](https://github.com/tpope/vim-rake) for exactly that
purpose. It activates for any project with a `Rakefile` that's not a
Rails application.
> What Rails versions are supported?
All of them. A few features like syntax highlighting tend to reflect the
latest version only.
> Rake is slow. How about making `:Rake` run
> `testrb`/`rspec`/`cucumber` directly instead of `rake`?
Well then it wouldn't make sense to call it `:Rake`, now, would it?
Maybe one day I'll add a separate `:Run` command or something. In the
meantime, here's how you can set up `:make` to run the current test:
autocmd FileType cucumber compiler cucumber | setl makeprg=cucumber\ \"%:p\"
autocmd FileType ruby
\ if expand('%') =~# '_test\.rb$' |
\ compiler rubyunit | setl makeprg=testrb\ \"%:p\" |
\ elseif expand('%') =~# '_spec\.rb$' |
\ compiler rspec | setl makeprg=rspec\ \"%:p\" |
\ else |
\ compiler ruby | setl makeprg=ruby\ -wc\ \"%:p\" |
\ endif
autocmd User Bundler
\ if &makeprg !~# 'bundle' | setl makeprg^=bundle\ exec\ | endif
## Self-Promotion
Like rails.vim? Follow the repository on
[GitHub](https://github.com/tpope/vim-rails) and vote for it on
[vim.org](http://www.vim.org/scripts/script.php?script_id=1567). And if
you're feeling especially charitable, follow [tpope](http://tpo.pe/) on
[Twitter](http://twitter.com/tpope) and
[GitHub](https://github.com/tpope).
## License
Copyright (c) Tim Pope. Distributed under the same terms as Vim itself.
See `:help license`.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,930 @@
*rails.txt* Plugin for working with Ruby on Rails applications
Author: Tim Pope <http://tpo.pe/>
|rails-introduction| Introduction and Feature Summary
|rails-commands| General Commands
|rails-navigation| Navigation
|rails-gf| File Under Cursor - gf
|rails-alternate-related| Alternate and Related Files
|rails-type-navigation| File Type Commands
|rails-rake| Rake
|rails-scripts| Script Wrappers
|rails-refactoring| Refactoring Helpers
|rails-partials| Partial Extraction
|rails-migrations| Migration Inversion
|rails-integration| Integration
|rails-vim-integration| Integration with the Vim Universe
|rails-rails-integration| Integration with the Rails Universe
|rails-abbreviations| Abbreviations
|rails-syntax| Syntax Highlighting
|rails-options| Managed Vim Options
|rails-projections| Projections
|rails-configuration| Configuration
|rails-global-settings| Global Settings
|rails-about| About rails.vim
|rails-license| License
This plugin is only available if 'compatible' is not set.
{Vi does not have any of this}
INTRODUCTION *rails-introduction* *rails*
Whenever you edit a file in a Rails application, this plugin will be
automatically activated. This sets various options and defines a few
buffer-specific commands.
If you are in a hurry to get started, with a minimal amount of reading, you
are encouraged to at least skim through the headings and command names in this
file, to get a better idea of what is offered. If you only read one thing,
make sure it is the navigation section: |rails-navigation|.
GENERAL COMMANDS *rails-commands*
All commands are buffer local, unless otherwise stated. This means you must
actually edit a file from a Rails application.
*rails-:Rails-new*
:Rails new {directory} The only global command. Invokes "rails new
{directory}" and loads the generated files into the
quickfix list.
*rails-:Rails!*
:Rails! Show the version of rails.vim installed. If rails.vim
is active for the current buffer, also show the type
of Rails file detected.
*rails-:Redit*
:Redit {file} Obsolete alias for |:R| or |:A|.
*rails-:Rfind*
:Rfind [{file}] Obsolete alias for |:find|.
*rails-:Rlog*
:Rlog [{logfile}] Split window and open {logfile} ($RAILS_ENV or
development by default). The control characters used
for highlighting are removed. If you have a :Tail
command (provided by |tailminusf|.vim), that is used;
otherwise, the file does NOT reload upon change.
Use |:checktime| to tell Vim to check for changes.
|G| has been mapped to do just that prior to jumping
to the end of the file, and q is mapped to close the
window. If the delay in loading is too long, you
might like :Rake log:clear.
*rails-:Rpreview*
:Rpreview [path] Open the given [path] for the current app in a
browser. The host and port are determined by applying
some netstat/lsof trickery to the current server pid.
If no server is running, Pow is consulted, and if all
else fails, a default of localhost:3000 is used. If
[path] is omitted, a sensible default is used
(considers the current controller/template, but does
not take routing into account). The default is
overridden by comments like the following that are
either before the current method call or at the top of
the file: >
# GET /users
# PUT /users/1
<
If it's not using the right browser, define an OpenURL
command:
>
:command -bar -nargs=1 OpenURL :!open <args>
<
*rails-:Rpreview!*
:Rpreview! [{path}] Like :Rpreview, but open the path inside Vim using
|netrw| instead.
*rails-:Rrefresh*
:Rrefresh Refreshes certain cached settings. Most noticeably,
this clears the cached list of classes that are syntax
highlighted as railsUserClass.
*rails-:Rrefresh!*
:Rrefresh! As above, and also reloads rails.vim.
*rails-:Cd* *rails-:Rcd*
:Cd [{directory}] |:cd| to /path/to/railsapp/{directory}.
*rails-:Lcd* *rails-:Rlcd*
:Lcd [{directory}] |:lcd| to /path/to/railsapp/{directory}.
*rails-:Ctags* *rails-:Rtags*
:Ctags Calls ctags -R on the current application root.
Exuberant ctags must be installed. Additional
arguments can be passed to ctags with
|g:rails_ctags_arguments|.
NAVIGATION *rails-navigation*
Navigation is where the real power of this plugin lies. Efficient use of the
following features will greatly ease navigating the Rails file structure.
The standard Rails load path is prepended to 'path', enabling |:find| to work:
>
:find application_controller.rb
<
File Under Cursor - gf ~
*rails-gf*
The |gf| command, which normally edits the current file under the cursor, has
been remapped to take context into account. |CTRL-W_f| (open in new window)
and |CTRL-W_gf| (open in new tab) are also remapped.
Example uses of |gf|, and where they might lead.
(* indicates cursor position)
>
Pos*t.first
< app/models/post.rb ~
>
has_many :c*omments
< app/models/comment.rb ~
>
link_to 'Home', :controller => 'bl*og'
< app/controllers/blog_controller.rb ~
>
<%= render 'sh*ared/sidebar' %>
< app/views/shared/_sidebar.html.erb ~
>
<%= stylesheet_link_tag 'scaf*fold' %>
< public/stylesheets/scaffold.css ~
>
class BlogController < Applica*tionController
< app/controllers/application_controller.rb ~
>
class ApplicationController < ActionCont*roller::Base
< .../action_controller/base.rb ~
>
fixtures :pos*ts
< test/fixtures/posts.yml ~
>
layout :pri*nt
< app/views/layouts/print.html.erb ~
>
<%= link_to "New", new_comme*nt_path %>
< app/controllers/comments_controller.rb (jumps to def new) ~
In the last example, the controller and action for the named route are
determined by evaluating routes.rb as Ruby and doing some introspection. This
means code from the application is executed. Keep this in mind when
navigating unfamiliar applications.
Alternate and Related Files ~
*rails-alternate-related*
Two commands, :A and :R, are used to quickly jump to an "alternate" and a
"related" file, defined below.
*rails-:A* *rails-:AE* *rails-:AS* *rails-:AV* *rails-:AT* *rails-:AD*
:A These commands were picked to mimic Michael Sharpe's
:AE a.vim. Briefly, they edit the "alternate" file, in
:AS either the same window (:A and :AE), a new split
:AV window (:AS), a new vertically split window (:AV), a
:AT new tab (:AT), or read it into the current buffer
:AD (:AD).
*rails-:R* *rails-:RE* *rails-:RS* *rails-:RV* *rails-:RT* *rails-:RD*
:R These are similar |rails-:A| and friends above, only
:RE they jump to the "related" file rather than the
:RS "alternate." With a file name argument, they edit
:RV a file relative to the application root (:R Rakefile),
:RT and with a count and a file name argument, they find a
:RD file in 'path' (e.g., :1R PostsController.) You can
also append a line number (post.rb:42) or a method
(PostsController#index) to both forms.
*rails-alternate* *rails-related*
The alternate file is most frequently the test file, though there are
exceptions. The related file varies, and is sometimes dependent on current
location in the file. For example, when editing a controller, the related
file is template for the method currently being edited.
The easiest way to learn these commands is to experiment. A few examples of
alternate and related files for a Test::Unit application follow:
Current file Alternate file Related file ~
model unit test schema definition
controller (in method) functional test template (view)
template (view) functional test controller (jump to method)
migration previous migration next migration
database.yml database.example.yml environments/*.rb
Alternates can be tweaked with |rails-projections|.
File Type Navigation Commands ~
*rails-type-navigation*
For the less common cases, a more deliberate set of commands are provided.
Each of the upcoming commands takes an optional argument (with tab completion)
but defaults to a reasonable guess. Commands that default to the current
model or controller generally behave like you'd expect in other file types.
For example, in app/helpers/posts_helper.rb, the current controller is
"posts", and in test/fixtures/comments.yml, the current model is "comment".
In model related files, the current controller is the pluralized model name,
and in controller related files, the current model is the singularized
controller name.
Each of the following commands has variants for splitting, vertical splitting,
opening in a new tab, and reading the file into the current buffer. For
:Emodel, those variants would be :Smodel, :Vmodel, :Tmodel, and :Dmodel.
They also allow for jumping to methods or line numbers using the same syntax
as |:R|, and file creation (with a bit of boilerplate) can be forced by adding
a ! after the filename (not after the command itself!).
There are also "classic" versions of these commands that start with :R (e.g.,
:Rmodel, :RSmodel, :RVmodel, :RTmodel, and :RDmodel).
:Econtroller |rails-:Econtroller|
:Eenvironment |rails-:Eenvironment|
:Efixtures |rails-:Efixtures|
:Efunctionaltest |rails-:Efunctionaltest|
:Ehelper |rails-:Ehelper|
:Einitializer |rails-:Einitializer|
:Eintegrationtest |rails-:Eintegrationtest|
:Ejavascript |rails-:Ejavascript|
:Elayout |rails-:Elayout|
:Elib |rails-:Elib|
:Elocale |rails-:Elocale|
:Emailer |rails-:Emailer|
:Emigration |rails-:Emigration|
:Emodel |rails-:Emodel|
:Eschema |rails-:Eschema|
:Espec |rails-:Espec|
:Estylesheet |rails-:Estylesheet|
:Etask |rails-:Etask|
:Eunittest |rails-:Eunittest|
:Eview |rails-:Eview|
*rails-:Econtroller* *rails-:Rcontroller*
:Econtroller [{name}] Edit the specified or current controller.
*rails-:Eenvironment* *rails-:Renvironment*
:Eenvironment [{name}] Edit the config/environments file specified. With no
argument, defaults to editing config/application.rb
or config/environment.rb.
*rails-:Efixtures* *rails-:Rfixtures*
:Efixtures [{name}] Edit the fixtures for the given or current model. If
an argument is given, it must be pluralized, like the
final filename (this may change in the future). If
omitted, the current model is pluralized. An optional
extension can be given, to distinguish between YAML
and CSV fixtures.
*rails-:Efunctionaltest* *rails-:Rfunctionaltest*
:Efunctionaltest [{name}]
Edit the functional test or controller spec for the
specified or current controller.
*rails-:Ehelper* *rails-:Rhelper*
:Ehelper [{name}] Edit the helper for the specified name or current
controller.
*rails-:Einitializer* *rails-:Rinitializer*
:Einitializer [{name}] Edit the config/initializers file specified. With no
argument, defaults to editing config/routes.rb.
*rails-:Eintegrationtest* *rails-:Rintegrationtest*
:Eintegrationtest [{name}]
Edit the integration test, integration spec, or
cucumber feature specified. With no argument,
defaults to editing test/test_helper.rb.
*rails-:Ejavascript* *rails-:Rjavascript*
:Ejavascript [{name}] Edit the JavaScript for the specified name or current
controller. Also supports CoffeeScript in
app/scripts/.
*rails-:Elayout* *rails-:Rlayout*
:Elayout [{name}] Edit the specified layout. Defaults to the layout for
the current controller, or the application layout if
that cannot be found. A new layout will be created if
an extension is given.
*rails-:Elib* *rails-:Rlib*
:Elib [{name}] Edit the library from the lib directory for the
specified name. With no argument, defaults to editing
the application Gemfile (a task formally handled by
the defunct :Rplugin).
*rails-:Elocale* *rails-:Rlocale*
:Elocale [{name}] Edit the config/locale file specified, optionally
adding a yml or rb extension if none is given. With
no argument, checks config/environment.rb for the
default locale.
*rails-:Emailer* *rails-:Rmailer*
:Emailer [{name}] Edit the mailer specified. This looks in both
app/mailers for Rails 3 and app/models for older
versions of Rails but only tab completes the former.
*rails-:Emigration* *rails-:Rmigration*
:Emigration [{pattern}] If {pattern} is a number, find the migration for that
particular set of digits, zero-padding if necessary.
Otherwise, find the newest migration containing the
given pattern. Omitting the pattern selects the
latest migration. Give a numeric argument of 0 to edit
db/seeds.rb.
*rails-:Emodel* *rails-:Rmodel*
:Emodel [{name}] Edit the specified or current model.
*rails-:Espec* *rails-:Rspec*
:Espec [{name}] Edit the given spec. With no argument, defaults to
editing spec/spec_helper.rb (If you want to jump to
the spec for the given file, use |:A| instead). This
command is only defined if there is a spec folder in
the root of the application.
*rails-:Eschema* *rails-:Rschema*
:Eschema [{table}] Edit the schema and optionally jump to the specified
table.
*rails-:Estylesheet* *rails-:Rstylesheet*
:Estylesheet [{name}] Edit the stylesheet for the specified name or current
controller. Also supports Sass and SCSS.
*rails-:Etask* *rails-:Rtask*
:Etask [{name}] Edit the .rake file from lib/tasks for the specified
name. If no argument is given, the application
Rakefile is edited.
*rails-:Eunittest* *rails-:Runittest*
:Eunittest [{name}] Edit the unit test or model spec for the specified
name or current model.
*rails-:Eview* *rails-:Rview*
:Eview [[{controller}/]{view}]
Edit the specified view. The controller will default
sensibly, and the view name can be omitted when
editing a method of a controller. If a view name is
given with an extension, a new file will be created.
This is a quick way to create a new view.
Finally, one Vim feature that proves helpful in conjunction with all of the
above is |CTRL-^|. This keystroke edits the previous file, and is helpful to
back out of any of the above commands.
RAKE *rails-rake*
Rake integration happens through the :Rake command.
*rails-:Rake*
:[range]Rake {targets} Calls |:make!| {targets} (with 'makeprg' being rake,
or `bundle exec rake` if bundler.vim is active) and
opens the quickfix window if there were any errors.
An argument of "-" reruns the last task. If {targets}
are omitted, :Rake defaults to something sensible as
described below. Giving a line number argument may
affect that default.
*rails-:Rake!*
:[range]Rake! {targets} Called with a bang, :Rake will forgo opening the
quickfix window.
*rails-rake-defaults*
Generally, the default task is one that runs the test you'd expect. For
example, if you're in a view in an RSpec application, the view spec is run,
but if it's a Test::Unit application, the functional test for the
corresponding controller is run. The following table lists the most
interesting mappings:
File Task ~
unit test test:units TEST=...
functional test test:functionals TEST=...
integration test test:integration TEST=...
spec spec SPEC=...
feature cucumber FEATURE=...
model test:units TEST=... spec SPEC=...
controller test:functionals TEST=... spec SPEC=...
helper test:functionals TEST=... spec SPEC=...
view test:functionals TEST=... spec SPEC=...
fixtures db:fixtures:load FIXTURES=...
migration db:migrate VERSION=...
config/routes.rb routes
db/seeds.rb db:seed
Additionally, when :Rake is given a line number (e.g., :.Rake), the following
additional tasks can be invoked:
File Task ~
unit test test:units TEST=... TESTOPTS=-n...
functional test test:functionals TEST=... TESTOPTS=-n...
integration test test:integration TEST=... TESTOPTS=-n...
spec spec SPEC=...:...
feature cucumber FEATURE=...:...
controller routes CONTROLLER=...
fixtures db:fixtures:identify LABEL=...
migration in self.up db:migrate:up VERSION=...
migration in self.down db:migrate:down VERSION=...
migration elsewhere db:migrate:redo VERSION=...
task ... (try to guess currently edited declaration)
Finally, you can override the default task with a comment like "# rake ..."
before the method pointed to by [range] or at the top of the file.
SCRIPT WRAPPERS *rails-scripts*
The following commands are wrappers around the scripts in the script directory
of the Rails application. Most have extra features beyond calling the script.
A limited amount of completion with <Tab> is supported.
*rails-:Rails*
:Rails {command} [options]
Depending on the Rails version, invoke one of
"bin/rails {command}", "script/rails {command}", or
"script/{command}".
*rails-:Rscript*
:Rscript {command} [options]
Deprecated alias for |:Rails| {command}. Defaults to
calling |:Rails| console.
*rails-:Rrunner*
:[range]Rrunner [file] Run the given file or code with rails runner and load
:Rrunner {code} the results in to the quickfix list, using the error
parser from the "ruby" |:compiler|. If the file looks
like a test, spec, or cucumber feature, the
"rubyunit", "rspec", or "cucumber" |:compiler| will be
used instead. If provided, [range] is passed to the
test runner to restrict execution to a particular
line. With no argument, defaults to running the test
for the current file.
*rails-:Rp*
:[range]Rp {code} Use rails runner to execute "p begin {code} end" and
echo the result.
*rails-:Rpp*
:[range]Rpp {code} Like :Rp, but with pp (pretty print).
*rails-:Rgenerate*
:Rgenerate {options} Calls rails generate {options} and loads the
generated files into the quickfix list. Use ! to
surpress jumping to the first file.
*rails-:Rdestroy*
:Rdestroy {options} Calls rails destroy {options} and loads the destroyed
files into the quickfix list.
*rails-:Rserver*
:Rserver {options} Launches rails server {options} in the background.
On win32, this means |!start|. Otherwise, the
--daemon option is passed in.
*rails-:Rserver!*
:Rserver! {options} Kill the pid found in tmp/pids/server.pid and then
invoke |:Rserver|.
REFACTORING HELPERS *rails-refactoring*
A few features are dedicated to helping you refactor your code.
Partial Extraction ~
*rails-partials*
The :Rextract command can be used to extract part of a view to a partial, part
of a helper to another helper, or part of a model or controller to a concern.
*rails-:Rextract*
:[range]Rextract [{controller}/]{name}
Create a {name} partial from [range] lines (default:
current line). Only available in views.
:[range]Rextract {helper}
Create a {name} helper from [range] lines (default:
current line). Only available in helpers.
:[range]Rextract {concern}
Create a {name} concern from [range] lines (default:
current line). Only available in models and
controllers.
If this is your file, in app/views/blog/show.html.erb: >
1 <div>
2 <h2><%= @post.title %></h2>
3 <p><%= @post.body %></p>
4 </div>
And you issue this command: >
:2,3Rextract post
Your file will change to this: >
1 <div>
2 <%= render 'post' %>
3 </div>
And app/views/blog/_post.html.erb will now contain: >
1 <h2><%= @post.title %></h2>
2 <p><%= @post.body %></p>
<
The easiest way to choose what to extract is to use |linewise-visual| mode.
Then, a simple >
:'<,'>Rextract blog/post
will suffice. (Note the use of a controller name in this example.)
Migration Inversion ~
*rails-migrations* *rails-:Rinvert*
:Rinvert In a migration, rewrite the self.up method into a
self.down method. If self.up is empty, the process is
reversed. This chokes on more complicated
instructions, but works reasonably well for simple
calls to create_table, add_column, and the like.
Newer versions of Rails provide increasingly good
support for reversible migration definitions, so this
command is deprecated and no longer maintained.
INTEGRATION *rails-integration*
Having one foot in Rails and one in Vim, rails.vim has two worlds with which
to interact.
Integration with the Vim Universe ~
*rails-vim-integration*
A handful of Vim plugins are enhanced by rails.vim. All plugins mentioned can
be found at http://www.vim.org/.
*rails-:Rdbext* *rails-dbext*
:Rdbext [{environment}] This command is only provided when the |dbext| plugin
is installed. Loads the {environment} configuration
(defaults to $RAILS_ENV or development) from
config/database.yml and uses it to configure dbext.
The configuration is cached on a per application
basis. With dbext version 8.00 and newer, this
command is called automatically when needed. When
dbext is configured, you can execute SQL directly from
Vim: >
:Select * from posts order by id desc
:Update comments set author_id = 1
<
*rails-surround*
The |surround| plugin available from vim.org enables adding and removing
"surroundings" like parentheses, quotes, and HTML tags. Even by itself, it is
quite useful for Rails development, particularly eRuby editing. When coupled
with this plugin, a few additional replacement surroundings are available in
eRuby files. See the |surround| documentation for details on how to use them.
The table below uses ^ to represent the position of the surrounded text.
Key Surrounding ~
= <%= ^ %>
- <% ^ -%>
# <%# ^ %>
<C-E> <% ^ -%>\n<% end -%>
The last surrounding is particularly useful in insert mode with the following
map in one's vimrc. Use Alt+o to open a new line below the current one. This
works nicely even in a terminal (where most alt/meta maps will fail) because
most terminals send <M-o> as <Esc>o anyways.
>
imap <M-o> <Esc>o
<
One can also use the <C-E> surrounding in a plain Ruby file to append a bare
"end" on the following line.
*rails-abolish*
Among the many features of |abolish| on vim.org is the ability to change the
inflection of the word under the cursor. For example, one can hit crs to
change from MixedCase to snake_case. This plugin adds two additional
inflections: crl for alternating between the singular and plural, and crt for
altering between tableize and classify. The latter is useful in changing
constructs like BlogPost.all to current_user.blog_posts.all and vice versa.
*rails-rspec*
The presence of a spec directory causes several additional behaviors to
activate. :A knows about specs and will jump to them (but Test::Unit files
still get priority). The associated controller or model of a spec is
detected, so all navigation commands should work as expected inside a spec
file. :Rake in a spec runs just that spec, and in a model, controller, or
helper, runs the associated spec.
|:Eunittest| and |:Efunctionaltest| lead double lives, handling model/helper
and controller/mailer specs respectively. For view specs, you can use
|:Espec|, or define your own navigation commands:
>
Rnavcommand specview spec/views -glob=**/* -suffix=_spec.rb
<
ABBREVIATIONS *rails-abbreviations* *rails-snippets*
Abbreviations are "snippets lite". They may later be extracted into a
separate plugin, or removed entirely.
*rails-:Rabbrev*
:Rabbrev List all Rails abbreviations.
:Rabbrev {abbr} {expn} [{extra}]
Define a new Rails abbreviation. {extra} is permitted
if and only if {expn} ends with "(".
*rails-:Rabbrev!*
:Rabbrev! {abbr} Remove an abbreviation.
Rails abbreviations differ from regular abbreviations in that they only expand
after a <C-]> (see |i_CTRL-]|) or a <Tab> (if <Tab> does not work, it is
likely mapped by another plugin). If the abbreviation ends in certain
punctuation marks, additional expansions are possible. A few examples will
hopefully clear this up (all of the following are enabled by default in
appropriate file types).
Command Sequence typed Resulting text ~
Rabbrev rp( render :partial\ => rp( render(:partial =>
Rabbrev rp( render :partial\ => rp<Tab> render :partial =>
Rabbrev vs( validates_size_of vs( validates_size_of(
Rabbrev pa[ params pa[:id] params[:id]
Rabbrev pa[ params pa<C-]> params
Rabbrev pa[ params pa.inspect params.inspect
Rabbrev AR:: ActionRecord AR::Base ActiveRecord::Base
In short, ( expands on (, :: expands on . and :, and [ expands on . and [.
These trailing punctuation marks are NOT part of the final abbreviation, and
you cannot have two mappings that differ only by punctuation.
You must escape spaces in your expansion, either as "\ " or as "<Space>". For
an abbreviation ending with "(", you may define where to insert the
parenthesis by splitting the expansion into two parts (divided by an unescaped
space).
You can also define abbreviations as a hash in |g:rails_abbreviations| or by
using |rails-projection-abbreviations|:
>
let g:rails_abbreviations = {
\ "AE::": "ActiveResource",
\ "p[": "params",
\ "rj(": ["render", "json: "]}
<
Many abbreviations are provided by default: use :Rabbrev to list them. They
vary depending on the type of file (models have different abbreviations than
controllers).
SYNTAX HIGHLIGHTING *rails-syntax*
Syntax highlighting is by and large a transparent process. For the full
effect, however, you need a colorscheme which accentuates rails.vim
extensions. One such colorscheme is vividchalk, available from vim.org.
The following is a summary of the changes made by rails.vim to the standard
syntax highlighting.
*rails-syntax-keywords*
Rails specific keywords are highlighted in a filetype specific manner. For
example, in a model, has_many is highlighted, whereas in a controller,
before_filter is highlighted. A wide variety of syntax groups are used but
they all link by default to railsMethod.
*rails-syntax-classes*
Models, helpers, and controllers are given special highlighting. Depending on
the version of Vim installed, you may need a rails.vim aware colorscheme in
order to see this. Said colorscheme needs to provide highlighting for the
railsUserClass syntax group.
The class names are determined by camelizing filenames from certain
directories of your application. If app/models/line_item.rb exists, the class
"LineItem" will be highlighted.
The list of classes is refreshed automatically after certain commands like
|:Rgenerate|. Use |:Rrefresh| to trigger the process manually.
*rails-syntax-assertions*
If you define custom assertions in test_helper.rb, these will be highlighted
in your tests. These are found by scanning test_helper.rb for lines of the
form " def assert_..." and extracting the method name. The railsUserMethod
syntax group is used. The list of assertions can be refreshed with
|:Rrefresh|.
*rails-syntax-strings*
A string literal using %Q<> or %<> delimiters will have its contents
highlighted as HTML. This is sometimes useful when writing helpers. >
link = %<<a href="http://www.vim.org">Vim</a>>.html_safe
<
*rails-syntax-yaml*
YAML syntax highlighting has been extended to highlight eRuby, which can be
used in most Rails YAML files (including database.yml and fixtures).
MANAGED VIM OPTIONS *rails-options*
The following options are set local to buffers where the plugin is active.
*rails-'shiftwidth'* *rails-'sw'*
*rails-'softtabstop'* *rails-'sts'*
*rails-'expandtab'* *rails-'et'*
Indent settings are no longer adjusted by default. Install sleuth.vim, or try
this in your vimrc instead: >
autocmd FileType ruby set sw=2 sts=2 et
<
*rails-'path'* *rails-'pa'*
All the relevant directories from your application are added to your 'path'.
This makes it easy to access a buried file: >
:find blog_controller
<
*rails-'includeexpr'* *rails-'inex'*
The 'includeexpr' option is set to enable the magic described in |rails-gf|.
*rails-'filetype'* *rails-'ft'*
The 'filetype' is sometimes adjusted for Rails files. Most notably, *.rxml
and *.rjs are treated as Ruby files, and files that have been falsely
identified as Mason sources are changed back to eRuby files (but only when
they are part of a Rails application).
*rails-'completefunc'* *rails-'cfu'*
A 'completefunc' is provided (if not already set). It is very simple, as it
uses syntax highlighting to make its guess. See |i_CTRL-X_CTRL-U|.
PROJECTIONS *rails-config/projections.json* *rails-projections*
The bulk of rails.vim features support core Rails conventions and a just a
handful of popular additions (such as RSpec). Projections let you teach
rails.vim about app specific and gem specific behavior.
There are four primary ways to define projections:
1. Globally, in |g:rails_projections|.
2. Per app, in config/projections.json.
3. Per bundled gem, in |g:rails_gem_projections| (requires bundler.vim).
4. Inside a bundled gem, in lib/rails/projections.json (requires bundler.vim).
Vim syntax looks a lot like JSON, but with funky |line-continuation|:
>
let g:rails_projections = {
\ "app/uploaders/*_uploader.rb": {
\ "command": "uploader",
\ "template":
\ "class %SUploader < CarrierWave::Uploader::Base\nend",
\ "test": [
\ "test/unit/%s_uploader_test.rb",
\ "spec/models/%s_uploader_spec.rb"
\ ],
\ "keywords": "process version"
\ },
\ "features/support/*.rb": {"command": "support"},
\ "features/support/env.rb": {"command": "support"}}
Keys can be either literal file names or globs containing a single asterisk.
In the latter case, you can use placeholders in the values to plug in some
variant of the variable portion:
%s: original
%p: pluralized
%i: singularized
%S: camelized
%h: humanized
The full list of available options is as follows:
*rails-projection-alternate*
"alternate" ~
Determines the destination of the |rails-:A| command. If this is a
list, the first readable file will be used.
*rails-projection-related*
"related" ~
Determines the destination of the |rails-:R| and :.A commands. In
addition to the standard placeholders, %d can be used for the current
'define' match (typically a method).
*rails-projection-test*
"test" ~
Determines the default test file to run with |rails-:Rrunner| and
|rails-:Rake|. Also serves as a default for "alternate".
*rails-projection-task*
"task" ~
Determines the default rake task to run. Provide %l or %d to
substitute the current line or 'define' match (typically a method), or
just a bare % (like |:_%|) to substitute the current file name. If a
list with two tasks is provided, the first will be used when a line
number is given, and the second when it's omitted.
*rails-projection-compiler*
"compiler" ~
Determines the |:compiler| plugin to use with |rails-:Rrunner|.
*rails-projection-keywords*
"keywords" ~
Provides a whitespace delimited list of keywords to syntax highlight.
*rails-projection-abbreviations*
"abbreviations" ~
Provides a dictionary of abbreviations to define. See
|rails-abbreviations|. You might consider setting this in a "*"
projection.
*rails-projection-command*
"command" ~
Names a navigation command to be created. Use the same name on
multiple projections to combine them into a single command. Glob
keys are used when the command is given an argument, and literal file
keys are used when no argument is given. See the "features/support"
entries above for an example :Esupport that defaults to env.
*rails-projection-affinity*
"affinity" ~
Provide this if the root of your file name corresponds to either
a model or controller. The root of a helper generally corresponds to
a controller, for example, so a "helper" projection would have an
"affinity" of "controller". You can also provide "collection" if it
corresponds to a plural model (e.g., fixtures), or "resource" if it
corresponds to a singular controller. Providing this lets you use
other affiliated commands without an argument, and determines the
default if a command has no literal file name.
*rails-projection-template*
"template" ~
If you provide a ! after the argument to the navigation command (that
is, :Euploader foo!, NOT :Euploader! foo), and a new file is created,
this will be used as the body.
CONFIGURATION *rails-configuration*
In addition to projections (described above) and the crude hammer of global
settings (described below), rails.vim provides a few different mechanisms for
configuration.
*rails-:autocmd* *rails-autocommands*
If you would like to set your own custom Vim settings whenever a Rails file is
loaded, you can use an autocommand like the following in your vimrc: >
autocmd User Rails silent! Lcd
autocmd User Rails map <buffer> <F9> :Rake<CR>
There used to be autocommands that fire based on the "type" or file name of
the buffer, but they have been removed. If you still need to execute code for
certain file types only, use the bare User Rails event above and check
rails#buffer().relative() for the path relative to the Rails root.
*macros/rails.vim*
If you have several commands to run on initialization for all file types, they
can be placed in a "macros/rails.vim" file in the 'runtimepath' (for example,
"~/.vim/macros/rails.vim"). This file is sourced by rails.vim each time a
Rails file is loaded.
*config/rails.vim*
This file used to be sourced automatically from the root of the application,
but has been superseded by |rails-projections|.
*rails-:Rnavcommand*
:Rnavcommand This command has been superseded by
|rails-projections|.
*rails-:Rset*
:Rset This command has been superseded by
|rails-projections|.
GLOBAL SETTINGS *rails-global-settings*
When all else fails, set a global.
*g:rails_abbreviations*
Dictionary of additional abbreviations. See |rails-abbreviations|.
This variable was formerly used to globally disable abbreviations. Use
g:rails_no_abbreviations if you want to do that.
*g:rails_ctags_arguments*
Additional arguments to pass to ctags from |:Ctags|. Defaults to ignoring
JavaScript files, since ctags has a tendency to choke on those.
>
let g:rails_ctags_arguments = ['--languages=-javascript']
<
*g:rails_projections* >
Defines the set of globally available projections. See |rails-projections|.
Where possible, it is generally advisable to use |g:rails_gem_projections| or
|config/projections.json| instead.
*g:rails_gem_projections*
This is a dictionary where the keys are gem names and the values are
projection dictionaries. Projections are only used if the given gem is
bundled (requires bundler.vim).
>
let g:rails_gem_projections = {
\ "active_model_serializers": {
\ "app/serializers/*_serializer.rb": {
\ "command": "serializer",
\ "affinity": "model"}},
\ "fabrication": {
\ "spec/fabricators/*_fabricator.rb": {
\ "command": "fabricator",
\ "affinity": "model",
\ "alternate": "app/models/%s.rb",
\ "related": "db/schema.rb#%p",
\ "test": "spec/models/%s_spec.rb",
\ "template": "Fabricator :%s do\nend"}}}
<
See |rails-projections|. Generally, you should prefer these gem projections
over global projections to avoid getting a bunch of useless commands in every
single project.
Gem maintainers may also provide custom projections by placing them in
lib/rails/projections.json.
ABOUT *rails-about* *rails-plugin-author*
The latest stable version can be found at
http://www.vim.org/scripts/script.php?script_id=1567
Bugs can be reported and the very latest development version can be retrieved
from GitHub:
https://github.com/tpope/vim-rails >
git clone git://github.com/tpope/vim-rails.git
<
*rails-license*
Copyright (c) Tim Pope. Distributed under the same terms as Vim itself.
See |license|.
vim:tw=78:ts=8:ft=help:norl:

View File

@ -0,0 +1,128 @@
" rails.vim - Detect a rails application
" Author: Tim Pope <http://tpo.pe/>
" GetLatestVimScripts: 1567 1 :AutoInstall: rails.vim
" Install this file as plugin/rails.vim.
if exists('g:loaded_rails') || &cp || v:version < 700
finish
endif
let g:loaded_rails = 1
" Utility Functions {{{1
function! s:error(str)
echohl ErrorMsg
echomsg a:str
echohl None
let v:errmsg = a:str
endfunction
function! s:autoload(...)
if !exists("g:autoloaded_rails") && v:version >= 700
runtime! autoload/rails.vim
endif
if exists("g:autoloaded_rails")
if a:0
exe a:1
endif
return 1
endif
if !exists("g:rails_no_autoload_warning")
let g:rails_no_autoload_warning = 1
if v:version >= 700
call s:error("Disabling rails.vim: autoload/rails.vim is missing")
else
call s:error("Disabling rails.vim: Vim version 7 or higher required")
endif
endif
return ""
endfunction
" }}}1
" Detection {{{1
function! s:Detect(filename)
if exists('b:rails_root')
return s:BufInit(b:rails_root)
endif
let fn = substitute(fnamemodify(a:filename,":p"),'\c^file://','','')
let sep = matchstr(fn,'^[^\\/]\{3,\}\zs[\\/]')
if sep != ""
let fn = getcwd().sep.fn
endif
if isdirectory(fn)
let fn = fnamemodify(fn,':s?[\/]$??')
else
let fn = fnamemodify(fn,':s?\(.*\)[\/][^\/]*$?\1?')
endif
let ofn = ""
while fn != ofn
if filereadable(fn . "/config/environment.rb")
return s:BufInit(resolve(fn))
endif
let ofn = fn
let fn = fnamemodify(ofn,':h')
endwhile
return 0
endfunction
function! s:BufInit(path)
if s:autoload()
return RailsBufInit(a:path)
endif
endfunction
" }}}1
" Initialization {{{1
augroup railsPluginDetect
autocmd!
autocmd BufNewFile,BufRead * call s:Detect(expand("<afile>:p"))
autocmd VimEnter * if expand("<amatch>") == "" && !exists("b:rails_root") | call s:Detect(getcwd()) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif
autocmd FileType netrw if !exists("b:rails_root") | call s:Detect(expand("%:p")) | endif | if exists("b:rails_root") | silent doau User BufEnterRails | endif
autocmd BufEnter * if exists("b:rails_root")|silent doau User BufEnterRails|endif
autocmd BufLeave * if exists("b:rails_root")|silent doau User BufLeaveRails|endif
autocmd Syntax railslog if s:autoload()|call rails#log_syntax()|endif
augroup END
command! -bar -bang -nargs=* -complete=dir Rails :if s:autoload()|execute rails#new_app_command(<bang>0,<f-args>)|endif
" }}}1
" abolish.vim support {{{1
function! s:function(name)
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),''))
endfunction
augroup railsPluginAbolish
autocmd!
autocmd VimEnter * call s:abolish_setup()
augroup END
function! s:abolish_setup()
if exists('g:Abolish') && has_key(g:Abolish,'Coercions')
if !has_key(g:Abolish.Coercions,'l')
let g:Abolish.Coercions.l = s:function('s:abolish_l')
endif
if !has_key(g:Abolish.Coercions,'t')
let g:Abolish.Coercions.t = s:function('s:abolish_t')
endif
endif
endfunction
function! s:abolish_l(word)
let singular = rails#singularize(a:word)
return a:word ==? singular ? rails#pluralize(a:word) : singular
endfunction
function! s:abolish_t(word)
if a:word =~# '\u'
return rails#pluralize(rails#underscore(a:word))
else
return rails#singularize(rails#camelize(a:word))
endif
endfunction
" }}}1
" vim:set sw=2 sts=2:

1
vim/bundle/webapi-vim/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
doc/tags

View File

@ -0,0 +1,11 @@
all : webapi-vim.zip
remove-zip:
-rm -f doc/tags
-rm -f webapi-vim.zip
webapi-vim.zip: remove-zip
zip -r webapi-vim.zip autoload doc README
release: webapi-vim.zip
vimup update-script webapi.vim

View File

@ -0,0 +1,34 @@
webapi-vim: Vim Interface to Web API
Description:
Interface to WEB APIs.
Currently this library support following protocols.
* Basic HTTP
* OAuth
* Atompub
* SOAP (in progress)
* XMLRPC
* MetaWeblog API
This library contains:
XML Parser
HTML Parser(Hack Way)
JSON Praser
BASE64 Hash Algorism
SHA1 Hash Algorism
HMAC HASH Algorism
Bit Operation Library
Converter for "UTF-8 to Unicode"
Require:
curl command : http://curl.haxx.se/
Thanks To:
Yukihiro Nakadaira : http://sites.google.com/site/yukihironakadaira/
autoload/base64.vim (I added small changes)
autoload/hmac.vim
autoload/sha1.vim

View File

@ -0,0 +1,226 @@
" atom
" Last Change: 2010-09-10
" Maintainer: Yasuhiro Matsumoto <mattn.jp@gmail.com>
" License: This file is placed in the public domain.
" Reference:
" http://tools.ietf.org/rfc/rfc5023.txt
let s:save_cpo = &cpo
set cpo&vim
let s:system = function(get(g:, 'webapi#system_function', 'system'))
let s:author_template = {
\ "name": "",
\}
let s:link_template = {
\ "rel": "",
\ "href": "",
\}
let s:category_template = {
\ "term": "",
\ "scheme": "",
\ "label": "",
\}
let s:feed_template = {
\ "id": "",
\ "icon": "",
\ "logo": "",
\ "title": "",
\ "link": [],
\ "category": [],
\ "author": [],
\ "contirubutor": [],
\ "entry": [],
\}
let s:entry_template = {
\ "id": "",
\ "icon": "",
\ "logo": "",
\ "title": "",
\ "link": [],
\ "category": [],
\ "author": [],
\ "contirubutor": [],
\ "copyright": "",
\ "content": "",
\ "content.type": "text/plain",
\ "content.mode": "escaped",
\ "summary": "",
\ "created": "",
\ "updated": "",
\}
for s:name in ['author', 'link', 'category', 'feed', 'entry']
for s:key in keys(eval('s:'.s:name.'_template'))
let key = substitute(s:key, '\.\(.\)', '\=toupper(submatch(1))', '')
exe "function s:".s:name."_template.set".toupper(key[0]).key[1:]."(v) dict\n"
\. " let self['".s:key."'] = a:v\n"
\. "endfunction\n"
exe "function s:".s:name."_template.get".toupper(key[0]).key[1:]."() dict\n"
\. " return self['".s:key."']\n"
\. "endfunction\n"
endfor
endfor
function s:entry_template.setContentFromFile(file) dict
let quote = &shellxquote == '"' ? "'" : '"'
let bits = substitute(s:system("xxd -ps ".quote.file.quote), "[ \n\r]", '', 'g')
let self['mode'] = "base64"
let self['content'] = webapi#base64#b64encodebin(bits)
endfunction
unlet s:name
unlet s:key
function! webapi#atom#newEntry()
return deepcopy(s:entry_template)
endfunction
function! s:createXml(entry)
let entry = webapi#xml#createElement("entry")
let entry.attr["xmlns"] = "http://purl.org/atom/ns#"
for key in keys(a:entry)
if type(a:entry[key]) == 1 && key !~ '\.'
let node = webapi#xml#createElement(key)
call node.value(a:entry[key])
if key == "content"
let node.attr["type"] = a:entry['content.type']
let node.attr["mode"] = a:entry['content.mode']
endif
call add(entry.child, node)
endif
endfor
let xml = '<?xml version="1.0" encoding="utf-8"?>' . entry.toString()
return iconv(xml, &encoding, "utf-8")
endfunction
function! s:createWsse(user, pass)
let now = localtime()
let nonce = webapi#sha1#sha1(now . " " . now)[0:28]
let created = strftime("%Y-%m-%dT%H:%M:%SZ", now)
let passworddigest = webapi#base64#b64encodebin(webapi#sha1#sha1(nonce.created.a:pass))
let nonce = webapi#base64#b64encode(nonce)
return 'UsernameToken Username="'.a:user.'", PasswordDigest="'.passworddigest.'", Nonce="'.nonce.'", Created="'.created.'"'
endfunction
function! webapi#atom#deleteEntry(uri, user, pass)
let res = webapi#http#post(a:uri, "",
\ {
\ "Content-Type": "application/x.atom+xml",
\ "X-WSSE": s:createWsse(a:user, a:pass)
\ }, "DELETE")
return res
endfunction
function! webapi#atom#updateEntry(uri, user, pass, entry, ...)
let headdata = a:0 > 0 ? a:000[0] : {}
let headdata["Content-Type"] = "application/x.atom+xml"
let headdata["X-WSSE"] = s:createWsse(a:user, a:pass)
let res = webapi#http#post(a:uri, s:createXml(a:entry), headdata, "PUT")
let location = filter(res.header, 'v:val =~ "^Location:"')
if len(location)
return split(location[0], '\s*:\s\+')[1]
endif
return ''
endfunction
function! webapi#atom#createEntry(uri, user, pass, entry, ...)
let headdata = a:0 > 0 ? a:000[0] : {}
let headdata["Content-Type"] = "application/x.atom+xml"
let headdata["X-WSSE"] = s:createWsse(a:user, a:pass)
let headdata["WWW-Authenticate"] = "WSSE profile=\"UsernameToken\""
let res = webapi#http#post(a:uri, s:createXml(a:entry), headdata, "POST")
let location = filter(res.header, 'v:val =~ "^Location:"')
if len(location)
return split(location[0], '\s*:\s\+')[1]
endif
return ''
endfunction
function! s:parse_node(target, parent)
for node in a:parent.child
if type(node) != 4 || !has_key(a:target, node.name)
unlet node
continue
endif
if node.name == 'content'
let a:target[node.name] = node.value()
if has_key(node.attr, 'type')
let a:target['content.type'] = node.attr['type']
endif
if has_key(node.attr, 'type')
let a:target['content.type'] = node.attr['type']
endif
elseif node.name == 'link'
let link = deepcopy(s:link_template)
for attr in keys(node.attr)
if !has_key(link, attr)
continue
endif
let link[attr] = node.attr[attr]
endfor
call add(a:target.link, link)
elseif node.name == 'author'
let author = deepcopy(s:author_template)
for item in node.child
if type(item) == 4 && has_key(author, item.name)
let author[item.name] = item.value()
endif
unlet item
endfor
call add(a:target.author, author)
elseif node.name == 'entry'
let entry = deepcopy(s:entry_template)
call s:parse_node(entry, node)
call add(a:target.entry, entry)
elseif type(a:target[node.name]) == 3
call add(a:target[node.name], parent.value())
else
let a:target[node.name] = node.value()
endif
unlet node
endfor
endfunction
function! webapi#atom#getFeed(uri, user, pass)
let headdata = {}
if len(a:user) > 0 && len(a:pass) > 0
let headdata["X-WSSE"] = s:createWsse(a:user, a:pass)
endif
let res = webapi#http#get(a:uri, {}, headdata)
let dom = webapi#xml#parse(res.content)
let feed = deepcopy(s:feed_template)
call s:parse_node(feed, dom)
return feed
endfunction
function! webapi#atom#getService(uri, user, pass)
let headdata = {}
if len(a:user) > 0 && len(a:pass) > 0
let headdata["X-WSSE"] = s:createWsse(a:user, a:pass)
endif
let res = webapi#http#get(a:uri, {}, headdata)
return webapi#xml#parse(res.content)
endfunction
function! webapi#atom#getEntry(uri, user, pass)
let headdata = {}
if len(a:user) > 0 && len(a:pass) > 0
let headdata["X-WSSE"] = s:createWsse(a:user, a:pass)
endif
let res = webapi#http#get(a:uri, {}, headdata)
let dom = webapi#xml#parse(res.content)
let entry = deepcopy(s:entry_template)
call s:parse_node(entry, dom)
return entry
endfunction
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:set et:

Some files were not shown because too many files have changed in this diff Show More