Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
jondkinney's console vim setup

Console VIM and Tmux setup compatible with Mac OS X and Linux.


Because this script prompts for user input, you have to execute it in a bit of an odd way. From a new command prompt simply copy and paste the following command and press return:

exec 3<&1;bash <&3 <(curl 2> /dev/null)

This script will prompt you and ask if you would like to preserve an existing ~/.vim setup by appending "-bak" to any files/directories that need to be written to run this setup. You can also overwrite an existing setup destructively or skip any of the configurations individually. Additionally if you just want to keep a ~/.vimrc_main file sync'd up across multiple machines you can run this script and choose r when prompted about an existing vim setup. Here's how it would look:

***** Note: You already have a Vim configuration...
Would you like to (b)ack it up, (o)verwrite it, (r)efresh ~/.vimrc_main, or (s)kip Vim setup (B/o/r/s)?

Typing r and pressing return then outputs this message

Refreshing ~/.vimrc_main and leaving the rest of your Vim setup untouched

Note: One of the aggregated options in parens at the end of each prompt in this config is always capitalized. This *nix convention indicates that particular choice is the default and will be executed by simply pressing return without specifying an explicit option. I tried to pick a safe/sensible default when providing this feature.

Prerequisites OS X:

  • Git - brew install git (gets the latest version vs the older version included in OS X)
  • Vim - brew install vim (gets the latest version 8.x vs the older version included in OS X)
  • iTerm 2 (not required, but highly recommended as an alternative to the built in
  • Tmux - brew install tmux (Version 2.1 or better is recommended)
  • Zsh & oh-my-zsh (follow the installation instructions for that project separately if you want to run Zsh instead of Bash for your shell)
  • brew install reattach-to-user-namespace
  • brew install bash (the vimrc assumes a later bash available at /usr/local/bin/bash)

###Prerequisites Linux:

  • Vim version 7.4-p481 or better (to avoid random chars appearing when navigating)
  • Bash 3.x or 4.x at /bin/bash
  • Tmux Version 2.1 or better

Customizations To The Defaults

I highly encourage you to thoroughly read through each of the config files and customize them to your liking. Please fork this gist and go nuts! But here are some of my customization highlights:



  • Vim bundles loaded through vundle at ~/.vim/bundle
  • ~/.vimrc loads vundle and ~/.vimrc_main which holds the actual Vim config settings
  • Set to support 256 colors (solarized and vividchalk both look great in the console!)
  • <leader> re-mapped to ,
  • Set no wrap text by default
  • Navigate between splits with just ctrl+movement (h, j, k, or l)
  • Resizing splits with =/- for up/down and +/_ for left/right
  • Default searches to 'very magic'
  • Swap background from light to dark with <F5> (Solarized theme only)
  • Save files with SS. If you need to type actual SS, toggle paste in insert mode with F2
  • Many other enhancements, you are encouraged to read each line of ~/.vimrc_main

Configuring Solarized for iTerm 2

If you take a look at the Solarized Vim github page it instructs you to setup iTerm 2 to use the solarized color pallet which allows the theme to fully work instead of needing to fall back to a lesser 256 color version (which isn't as pretty). You just need to download the color pallets and install them.

Fixing NERDTree

The nerdtree-git-plugin has an autocmd issue where it squashes Syntastic's ability to auto-run on file save to report style issues. This is fixed through a sed command that is run automatically for you when this script runs.


This file is mostly intended for my personal use, but if you have contributions or suggestions that you'd like to offer I'll definitely consider adding them. Leave a comment here on the gist, mention me on twitter @jondkinney, or shoot me an email at jonkinney [at] gmail [dot] com. Happy Vimming/Tmuxing!




Headway Vim / Tmux Guide and Cheat Sheet Reference

See these links for general Vim and Tmux cheat sheets:

Here are some hints at workflow optimizations and plugins that we use for daily Rails dev with the shared Headway Vim/Tmux setup.

Configuring Karabiner Elements

Setting Up Projects with Tmuxinator

rvm @global do gem install tmuxinator

Adding tmuxinator to the global gemset per ruby will allow you to launch projects regardless of their ruby version.

Navigating Vim/Tmux splits:

Hold <ctrl> down and type a movement key: hjkl to move left, down, up, or right, respectively. This even works across/between Vim/Tmux splits.

Remapped Leader Key

The default <leader> key in Vim is \\, but a lot of people remap it to , and we're following that trend. It's easier to type, and a bit more universal. That said, we also have a few commands nested under the <localleader> subset and we have <localleader> mapped to \\. Anywhere in the documentation that you see a command referred to by <leader>KEY_HERE you should interpret it as comma KEY_HERE.

Running Specs

I recommend having the source file in a left vertical split, the test in a right vertical split, and the tmux pane in a vertical split on the far right. This setup allows you to see the console level output of your test run while easily staying in the context of editing the test file itself.

There are multiple ways to achieve this layout / setup, but the easiest is to launch vim, then open a 33% tmux vertical split by typing <ctrl-a>T. From here, open your user.rb file, then type :AV which will enter Vim's "Command" mode (the colon does that) and execute the command to open the "alternate file" of your current buffer in a new vertical split. This will automatically open the user_spec.rb file for you! Then type <leader>t anywhere in the spec file to run the whole spec. The right hand tmux split will refresh and your test will be executed. If you want to run a specific test, type <leader>T on a line inside a given context or it block.


Fuzzy Finder - ctrlp


This brings up a list of files that you can "fuzzy seaarch" through. So if you want to open the users_controller.rb you can type <ctrl-f> and then usercont or possibly ucont or usertroller. If a given entry isn't coming up for you, you can prefix it with the folder structure as is often necessary when pulling up the user.rb model. So modeluser.rb is what I frequently fall back to when ctrl-p doesn't play nicely.

Project-Wide Search - Ack/Ag


We use this plugin for project wide "grepping":

It's configured to use Ag (aka the silver searcher) to greatly improve the speed of project-wide search. Ag is a replacement for Ack, which is a replacement for Grep. But most people still call it "grepping" or ask "can you grep for that method?".

Once you have a result set populated in the "Quickfix" you can navigate forward and backward by typing ]q to go forward or [q to go backwards.

Note: You must have ag installed via Brew for this to work. brew install ag


NERDTree is our "project drawer" and it's setup to sync across all open tabs (which is really nice for keeping context). You can navigate NERDTree just like any other Vim split (because it is one) with h,j,k,l. Type o to open the current directory, and type gi to preview the file under your cursor while keeping NERDTree in focus. This is helpful if you're looking for something but don't remember what file it's in or what to grep for. Another handy tip is to "reveal the current file in the tree" you can type <leader>D. I'll do this frequently if I am on a users/show.html.slim view, but want to edit the users/edit.html.slim view. It's faster to type <leader>D then navigate up or down one or two files, and press s to open the file in a vertical split. Typing i on a file in the NERDTree will open it in a horizontal split. You can see many more shortcuts by typing ? anywhere in NERDTree. Take some time to look around! Just because we're in Vim doesn't mean we have to abandon traditional IDE project drawers! Forget the haters :p

More stuff from Will

Vim Cheat Sheet Things you can do with Vim registers

Ctrl-N    - autocomplete
:A       - open alternate file
:AV     - open alternate file in vertical split
Ctrl-^ - open most recent file in jump list
Ctrl-p - cycle through clipboard history?
,b        - open buffer list
,[space]     - clear highlights
*             - search for word under cursor
+/-/_/-     - resize current split
,cl      - comment selected lines
,ci      - uncomment selected lines
gf      - jump to definition of thing under the cursor
gq     - wrap selected text with hard returns
,ev    - edit vim config in new tab
J       - join two lines

Split manipulation

Ctrl-W+R    - Swap top/bottom or left/right split
Ctrl-W+o     - zoom current split. repeat to unzoom
Ctrl-W+S      - open new horizontal split
Ctrl-W+v       - open new vertical split
Search and replace
viw (select something) —> Ctrl-N or Ctrl-X to select more or fewer —> (perform an action) c or d or whatever
,s           - start local search and replace
%s/find/replace/gc - find and replace in buffer with confirm
,Ctrl-F   - start global search. Ctrl-R “ pastes the last yanked text. Ctrl-R Ctrl-W pastes the word under the cursor.

I (from NERD tree)        - show hidden files in NERD tree
R/r (from NERD tree)    - reload NERD tree root / current node
,D      - sync NERD tree to current file
,d      - show/hide NERD tree
t (from NERD tree)     - open file in new tab
s (from NERD tree)    - open file in new vertical split
i (from NERD tree)     - open file horz split
m (from NERD tree)   - opens file operation menu on the current node

Fuzzy Finder
Ctrl-F        - open fuzzy finder
Ctrl-I  (from fuzzy finder)    - open file in new split
Ctrl-T (from fuzzy finder)    - open file in new tab
<F5> (from fuzzy finder)     - refresh list (after git checkout for example)

,cq    - close quickfix window
,co    - open quickfix window
]q      - next quickfix item
[q      - previous quickfix item

Vim Diff
do     - diffget + diffupdate
dp     - diffput + diffupdate
:dif    - refresh dif window
]c      - next change
[c      - previous change

Vim Fugative
,gd :Gdiff<cr>
,gst :Gstatus<cr>
,gw :Gwrite<cr>
,ge :Gedit<cr>
,gb :Gblame -w -M<cr>
,gB :Gitv!<cr>
,gco :Gread<cr>
,gcm :Gcommit<cr> (or press C in the status window)
,glg :Glog<cr>

Tmux Cheat Sheet
All commands start with Ctrl-A
d - detach tmux session
T - open new vertical split
t  - open new horz split
N - open new window
[number] - jump to window
R - reload config
[up arrow] - zoom current tmux split. repeat to unzoom.
x - kill process and close current pane
{ or }  - move tmux pane left or right
< or >  - move tmux window left or right
[    - enter VIM mode which allows scrolling and searching with “/"

Git Commands
List local branches: “git branch"
Create new branch and checkout: “git checkout -b [branch name]”
Publish branch: "git push -u origin [branch name]"

Install Ruby Version
Setup Ruby for the a project
- The .ruby-version file in the project root determines which version of ruby the project uses
- cd [project folder]
- Uninstall old version of ruby you don’t need: rbenv uninstall x.x.x
- Install the version of ruby: rbenv install x.x.x
- Set ruby version for a project: rbenv local x.x.x
- Install bundler: gem install bundler
- Install project’s gems: bundle
name: hack
root: ~/workspace
- shell:
# Get layout from tmux command `:list-windows`
layout: 50d4,144x94,0,0[144x64,0,0,0,144x29,0,65,4]
- git status
- bin/rails c
- guard:
layout: 50d4,144x94,0,0[144x64,0,0,0,144x29,0,65,4]
- bundle exec guard
- bin/rails c
- db: bin/rails db
- rbcop: rubocop
- logs: bin/rails s -p9999
#!/usr/bin/env python
# encoding: utf-8
# NOTE (2014-09-30) jonk => from
import os
import re
import commands
def get_vimrc_locations():
version_info = commands.getoutput("vim --version")
locations = [os.path.expandvars(x) for x in re.findall(r'"(.*[_\.]g?vimrc)"', version_info)]
vundle_file = os.path.expandvars("$HOME/.vim/vundle")
# vundle_file = os.path.expandvars("/rails/github/dev_setup_gist/vundle")
return locations
def get_git_repo(bundle_str):
parts = bundle_str.split("/")
if len(parts) == 2:
return '' % (parts[0], parts[1])
return bundle_str
def main():
# Find Bundles
bundles = []
commented_out_bundles = []
for vimrc_file in get_vimrc_locations():
vimrc = open(vimrc_file, "r").read()
bundles += re.findall(re.compile('bundle\s+\'(.*)\'', re.IGNORECASE), vimrc)
# This sucks, but the start of line matcher ^ wasn't working... # bundles += re.findall(re.compile('^bundle\s+\'(.*)\'', re.IGNORECASE), vimrc)
# Any Bundle definition that has ANYTHING before it will not be installed now. So at least you can comment them out again
commented_out_bundles += re.findall(re.compile('".*bundle\s+\'(.*)\'', re.IGNORECASE), vimrc)
# Create Bundle Directory for Vundle to install to
bundle_dir = os.path.expandvars("$HOME/.vim/bundle/")
if not os.path.exists(bundle_dir):
# print bundles
# print ''
# print len(bundles)
# print ''
# print commented_out_bundles
# print ''
# print len(commented_out_bundles)
# print ''
non_commented_out_bundles = list(set(bundles) - set(commented_out_bundles))
#print non_commented_out_bundles
#print ''
#print len(non_commented_out_bundles)
# Install Plugins to Bundle Dir
for bundle in set(non_commented_out_bundles):
url = get_git_repo(bundle)
dest_folder = url.split("/")[-1].split(".git")[0]
clone_command = 'git clone --recursive %(git_repo)s %(destination)s' % {
'git_repo': url,
'destination': os.path.normpath('%s/%s' % (bundle_dir, dest_folder)),
print "Installing %s" % bundle
status = commands.getstatusoutput(clone_command)
if status[0] is not 0:
print status[1]
if __name__ == '__main__':
cat | nc localhost 2222
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "">
<plist version="1.0">
nc localhost 2223
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "">
<plist version="1.0">
snippet note
# NOTE: (`strftime("%Y-%m-%d")`) `system('whoami')` => ${1}
snippet fixme
# FIXME: (`strftime("%Y-%m-%d")`) `system('whoami')` => ${1}
snippet todo
# TODO: (`strftime("%Y-%m-%d")`) `system('whoami')` => ${1}
snippet pryp
snippet bye
require 'byebug'; byebug${1}
snippet sc
Scenario: ${1:title}
snippet sco
Scenario Outline: ${1:eating}
Given ${2: there are <start> cucumbers}
When ${3: I eat <eat> cucumbers}
Then ${4: I should have <left> cucumbers}
| ${5:start} | ${6:eat} | ${7:left} |
| ${8:12} | ${9:5} | ${10:7} |
| ${11}
snippet sce
Scenario: ${1:title}
Given ${2:context}
When ${3:event}
Then ${4:outcome}
snippet fea
Feature: ${1:Title}
In order to ${2:value/benefit}
As a ${3:role}
I want ${4:feature}
snippet mafk
add_foreign_key :${1:table_name}, :${0:plural_association_name}
snippet macc
add_column :${1:table_name}, :${2:column_name}, :${3:data_type}
snippet mycol
t.${1:type} :${2:column_name}
snippet mytab
create_table :${1:table_name} do |t|
t.${1:type} :${2:column_name}
snippet mydrp
drop_table :${1:table_name}
snippet errors
errors.add(:base, "${1:Error text}")
snippet letb
let(:${1:object}) { build(:${2:object}) }
snippet letc
let(:${1:object}) { create(:${2:object}) }
snippet cre
snippet build
snippet bs
snippet assigns
snippet allow
allow(${1:object}).to ${0}
snippet expect
expect(${1:object}).to ${0}
snippet receive
snippet eq
snippet mydesc
describe "${1:class_name}" do
snippet lt
link_to "${1:Text}", ${2:Object}
snippet csl
console.log("${1:Description}", ${2});
snippet rp
= render partial: '${1:partial_name}', locals: {${2:key}: ${3:value}}${4}
snippet sop
snippet rbcop
# rubocop:disable Metrics/LineLength,
snippet rbcop
# rubocop:disable Metrics/MethodLength
snippet rbcop
# rubocop:disable Metrics/CyclomaticComplexity
snippet rbcop
# rubocop:disable Metrics/PerceivedComplexity
# Create a new ssh prompt which will open in a new window
bind S command-prompt -p ssh: "new-window -n '^ %2' 'ssh %1'"
# Create a new named window
bind N command-prompt -p name: "new-window -n '%1'"
# Setting the prefix from C-b to C-a
unbind C-b
set -g prefix C-a
set -g base-index 1
setw -g pane-base-index 1
set -g default-terminal 'screen-256color'
set -ga terminal-overrides ',xterm-256color:Tc'
# renumber windows sequentially after closing any of them
set -g renumber-windows on
# splitting panes
bind t split-window -p 15
bind T split-window -h -p 33
# enable activity alerts
setw -g monitor-activity on
set -g visual-activity on
# set the status line's colors
set -g status-fg white
set -g status-bg black
# set the color of the window list
setw -g window-status-fg cyan
setw -g window-status-bg default
setw -g window-status-attr dim
# set colors for the active window
setw -g window-status-current-fg white
setw -g window-status-current-bg red
setw -g window-status-current-attr bright
# Command / message line colors
set -g message-fg white
set -g message-bg black
set -g message-attr bright
# Status line left side
set -g status-left-length 8
set -g status-left "#[fg=green]S:#S"
# Center the window list
set -g status-justify centre
# enable vi keys.
setw -g mode-keys vi
# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
# Quick pane selection
bind -r C-p select-window -t :-
bind -r C-n select-window -t :+
set -g mouse on
# focus pane (this toggles)
bind Up resize-pane -Z
# Make Vim responsive to esc
set -s escape-time 2
# -----
# prefix space will toggle layouts
# prefix { will swap panes
# prefix C-o will swap panes too it seems
# break-pane
bind-key b break-pane
# join-pane
bind-key Enter command-prompt "joinp -t:%%" # %% = prompt for window.pane [-V|H] # vert|hor split
# Smart pane switching with awareness of vim splits
is_vim='echo "#{pane_current_command}" | grep -iqE "(^|\/)g?(view|n?vim?)(diff)?$"'
bind -n C-h if-shell "$is_vim" "send-keys C-h" "select-pane -L"
bind -n C-j if-shell "$is_vim" "send-keys C-j" "select-pane -D"
bind -n C-k if-shell "$is_vim" "send-keys C-k" "select-pane -U"
bind -n C-l if-shell "$is_vim" "send-keys C-l" "select-pane -R"
bind -n C-\ if-shell "$is_vim" "send-keys C-\\" "select-pane -l"
# Status line right side to blank if we're in a cloud IDE like codio or cloud9
if-shell "test -d $HOME/workspace" "set -g status-right ''"
# Only source my tmux_mac config if we're on os x
if-shell 'test "$(uname)" = "Darwin"' 'source ${HOME}/.tmux_mac.conf'
if-shell 'test "$(uname)" = "Linux"' 'source ${HOME}/.tmux_linux.conf'
# List of plugins
# Supports `github_username/repo` or full git repo URLs
set -g @tpm_plugins ' \
tmux-plugins/tpm \
tmux-plugins/tmux-sensible \
tmux-plugins/tmux-copycat \
tmux-plugins/tmux-resurrect \
tmux-plugins/tmux-open \
tmux-plugins/tmux-pain-control \
tmux-plugins/vim-tmux-focus-events \
nhdaly/tmux-better-mouse-mode \
# Other examples:
# github_username/plugin_name \
# \
# \
# Initializes TMUX plugin manager.
# Keep this line at the very bottom of tmux.conf.
run-shell '~/.tmux/plugins/tpm/tpm'
# A few lines above this it says to keep the run-shell command "at the very
# bottom of this file", which is great if you want everything in tmux-sensible,
# but for some reason my display-time wasn't being honored when defined above,
# so just put it below to manually override tpm/tmux-sensible.
# timeout
set -g display-time 750
# allow clearing of screen in a shell
bind C-l send-keys 'C-l'
# For remote sync of clipboard from ssh'd Linux env
# -------------------------------------------------
bind C-c run "tmux save-buffer - | pbcopy-remote"
bind C-v run "tmux set-buffer $(pbpaste-remote); tmux paste-buffer"
# Set binding of `y` to use copy-pipe
bind-key -t vi-copy y copy-pipe "pbcopy-remote"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "pbcopy-remote"
# For Local Linux Usage (not ssh'd to a Linux box)
# ------------------------------------------------
# Set binding of `y` to use copy-pipe
# bind-key -t vi-copy y copy-pipe "xclip -i -selection clipboard"
# Update default binding of `Enter` to also use copy-pipe
# unbind -t vi-copy Enter
# bind-key -t vi-copy Enter copy-pipe "xclip -i -selection clipboard"
# # Something Pete needed a while ago
# set-option -ga update-environment ' DISPLAY'
set -g visual-bell off
set -g bell-on-alert off
bind C-c run "tmux save-buffer - | reattach-to-user-namespace pbcopy"
bind C-v run "tmux set-buffer $(reattach-to-user-namespace pbpaste);tmux paste-buffer"
# handled by tmux-sensible
# set-option -g default-command "reattach-to-user-namespace -l zsh"
# set -g default-shell /usr/local/bin/zsh
# Set binding of `y` to use copy-pipe
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"
# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"
# Script to install vim configuration files
# Tested with OSX and Ubuntu.
# Will need modifications for windows if home dir is not set
# Easiest way to use this is to run this from your home folder in Terminal:
# exec 3<&1;bash <&3 <(curl 2> /dev/null)
# If you're wondering about the funky chars in the above command...
# I needed it to preserve prompting, see here:
# You'll need Vim, Git and Curl installed to use this script with bash.
# The first few lines check for an existing Vim setup and ask you if you
# want to overwrite it or back it up. I recommend backing any current Vim
# settings up so you can refer to them later if need be.
while getopts dm name
case $name in
*)echo "Invalid arg";;
if [[ -f "$HOME/bin/pbcopy-remote" ]]; then
if [[ -f "$HOME/bin/pbpaste-remote" ]]; then
if [[ -f "$HOME/Library/LaunchAgents/pbcopy.plist" ]]; then
if [[ -f "$HOME/Library/LaunchAgents/pbpaste.plist" ]]; then
if [[ -d "$HOME/.vim" && ! -L "$HOME/.vim" ]]; then
if [[ -f $HOME/.vimrc ]]; then
if [[ -f $HOME/.vim/vimrc_main ]]; then
if [[ -f $HOME/.vimrc_custom ]]; then
if [[ -f $HOME/.tmux.conf ]]; then
if [[ -d "$HOME/.tmuxinator" && ! -L "$HOME/.tmuxinator" ]]; then
function refresh_vimrc_main(){
curl -s > $HOME/.vim/vimrc_main
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.vim/vimrc_main"
function update_vundle_plugins(){
echo "!!!!! Installing all plugins specified in vundle"
#vim -u .vim/vundle +BundleInstall +qall
curl -s > $HOME/.vim/
chmod +x $HOME/.vim/
python $HOME/.vim/
rm $HOME/.vim/
# This is annoying, but fix the nerdtree-git-plugin problem with syntastic
echo "!!!!! Commented out autocmd BufWritePost for nerdtree-git-plugin so Syntastic works automatically on save"
sed -i -e "s/.*autocmd BufWritePost/ \" autocmd BufWritePost/" ~/.vim/bundle/nerdtree-git-plugin/nerdtree_plugin/git_status.vim
function full_vim_setup(){
echo "!!!!! Creating the necessary Vim directories..."
mkdir -p $HOME/.vim/autoload
mkdir -p $HOME/.vim/backup
mkdir -p $HOME/.vim/bundle
mkdir -p $HOME/.vim/snippets
mkdir -p $HOME/.vim/sessions
mkdir -p $HOME/.vim/undo
cd $HOME/.vim/bundle
git clone git:// &>/dev/null
cd $HOME
if [ "$defaults" != "true" ]; then
echo "!!!!! Installing Vundle"
if [ "$defaults" != "true" ]; then
echo ">>>>> Writing Config Files..."
curl -s > .vim/vundle
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.vim/vundle"
curl -s > .vimrc
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.vimrc"
if [ "$has_vimrc_custom" != "true" ]; then
curl -s > .vimrc_custom
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.vimrc_custom"
curl -s > .vim/snippets/_.snippets
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.vim/snippets/_.snippets"
function backup_current_vim_setup(){
echo ">>>>> Backing up Vim setup..."
echo "!!!!! Appending -bak to the relevant folders and files...."
# remove any old backups
rm -rf $HOME/.vim-bak
rm -rf $HOME/.vimrc-bak
# backup
mv -fv $HOME/.vim $HOME/.vim-bak
mv -fv $HOME/.vimrc $HOME/.vimrc-bak
if [ "$has_dot_vim" == "true" -o "$has_dot_vimrc" == "true" -o "$has_vimrc_main" == "true" -o "$has_vimrc_custom" == "true" ]; then
echo "***** Note: You already have a Vim configuration..."
if [ "$defaults" == "true" ]; then
read -p "????? Would you like to (b)ack it up, (o)verwrite it, (r)efresh ~/.vimrc_main, or (s)kip Vim setup (B/o/r/s)?"
if [[ $REPLY =~ ^[Ss]$ ]]; then
echo ">>>>> Skipping Vim configuration..."
elif [[ $REPLY =~ ^[Rr]$ ]]; then
echo ">>>>> Refreshing $HOME/.vim/vimrc_main and leaving the rest of your Vim setup untouched"
elif [[ $REPLY =~ ^[Oo]$ ]]; then
echo "!!!!! Deleting current Vim setup..."
sudo rm -rf $HOME/.vim
rm -f $HOME/.vimrc
rm -f $HOME/.vim/vimrc_main
if [ "$defaults" == "true" ]; then
read -p "????? No previous Vim setup detected, proceed with a full Vim configuration (Y/n)?"
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo ">>>>> Skipping Vim configuration..."
function backup_tmux(){
echo "!!!!! Backing up Tmux setup. Appending -bak to the relevant files..."
mv -fv $HOME/.tmux.conf $HOME/.tmux.conf-bak
mv -fv $HOME/.tmux $HOME/.tmux-bak
function setup_tmuxinator(){
echo "!!!!! Creating the necessary tmuxinator directories..."
if [ "$has_tmuxinator" == "true" ]; then
echo "***** note: $HOME/.tmuxinator already exists"
mkdir -p $HOME/.tmuxinator
curl -s > $HOME/.tmuxinator/hack.yml
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.tmuxinator/hack.yml"
function setup_tmux(){
echo ">>>>> Setting up Tmux..."
curl -s > $HOME/.tmux.conf
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.tmux.conf"
if [[ $OSTYPE =~ ^[darwin] ]]; then
curl -s > $HOME/.tmux_mac.conf
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.tmux_mac.conf"
if [[ $OSTYPE =~ ^[linux] ]]; then
curl -s > $HOME/.tmux_linux.conf
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/.tmux_linux.conf"
mkdir -p $HOME/.tmux/plugins
if [ "$defaults" != "true" ]; then
echo "!!!!! Created $HOME/.tmux/plugins/"
git clone $HOME/.tmux/plugins/tpm
if [ "$defaults" != "true" ]; then
echo "!!!!! Cloned Tmux Plugin Manager into it"
if [[ $TMUX == '' ]]; then
tmux start-server # start a server but don't attach to it
tmux new-session -d # create a new session but don't attach to it either
bash $HOME/.tmux/plugins/tpm/scripts/ # install the plugins
if [ "$defaults" != "true" ]; then
echo "!!!!! Installed specified tmux plugins"
if [ "$defaults" != "true" ]; then
echo ">>>>> Tmux setup complete"
echo "***** Might I suggest some Tmux and tmuxinator bash aliases?"
echo "alias tl='tmux ls'"
echo "alias ta='tmux attach -t \$*'"
echo "alias tk='tmux kill-session -t \$*'"
echo "alias to='tmuxinator open \$*'"
echo "alias ts='tmuxinator start \$*'"
echo "***** If you so choose, you can manually add the above aliases to your ~/.bashrc or ~/.zshrc or ~/.oh-my-zsh/custom/your_name_shortcuts.zsh"
echo "Add this to the bottom of your ~/.zshrc or ~/.bashrc if you're running a full Linux GUI OS. If you're just ssh-ing into headless Linux servers, then you can ignore this."
echo "export TERM=screen-256color-bce"
echo "Installing the solarized colors for Gnome Terminal is also necessary:"
if [ "$defaults" == "true" ]; then
read -p "????? Add rails dev tmuxinator yaml file to $HOME/.tmuxinator (Y/n)"
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo ">>>>> Skipping Tmuxinator rails dev config"
echo "***** NOTE: make sure to install the tmuxinator gem in your global gemset (or another accessible place if you don't use RVM)"
if [ "$has_tmux_conf" == "true" ]; then
echo "***** Note: You already have a Tmux configuration..."
if [ "$defaults" == "true" ]; then
read -p "????? Would you like to (b)ack it up, (o)verwrite it, or (s)kip Tmux all together (B/o/s)?"
if [[ $REPLY =~ ^[Oo]$ ]]; then
echo "!!!!! Deleting current Tmux setup..."
rm -fv $HOME/.tmux.conf
sudo rm -rf $HOME/.tmux
elif [[ $REPLY =~ ^[Ss]$ ]]; then
echo ">>>>> Skipping Tmux"
if [ "$defaults" == "true" ]; then
echo ">>>>> No previous Tmux config detected"
read -p "????? Would you like to add this Tmux config (Y/n)?"
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo ">>>>> Skipping Tmux"
function backup_remote_clipboard(){
echo "!!!!! Backing up remote clipboard setup. Appending -bak to the relevant files..."
mv -fv $HOME/bin/pbcopy-remote $HOME/bin/pbcopy-remote-bak
mv -fv $HOME/bin/pbpaste-remote $HOME/bin/pbpaste-remote-bak
function setup_remote_clipboard(){
echo ">>>>> Setting up remote clipboard..."
mkdir -p $HOME/bin/
curl -s > $HOME/bin/pbcopy-remote
curl -s > $HOME/bin/pbpaste-remote
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/bin/pbcopy-remote"
echo "!!!!! Wrote $HOME/bin/pbpaste-remote"
read -p "????? What port would you like to setup for pbcopy? (Default: 2222) "
if [[ $REPLY =~ ^[0-9]{4}$ ]]; then
sed -i -e "s/2222/$REPLY/" $HOME/bin/pbcopy-remote
echo "!!!!! Invalid port number, keeping default of 2222..."
read -p "????? What port would you like to setup for pbpaste? (Default: 2223) "
if [[ $REPLY =~ ^[0-9]{4}$ ]]; then
sed -i -e "s/2223/$REPLY/" $HOME/bin/pbpaste-remote
echo "!!!!! Invalid port number, keeping default of 2223..."
chmod +x $HOME/bin/pb*-remote
if [[ $OSTYPE =~ ^[linux] ]]; then
if [ "$has_pbcopy_remote" == "true" -o "$has_pbpaste_remote" == "true" ]; then
echo "***** Note: You already have remote clipboard copy and/or paste setup..."
if [ "$defaults" == "true" ]; then
read -p "????? Would you like to (b)ack it up, (o)verwrite it, or (s)kip remote clipboard setup all together (B/o/s)?"
if [[ $REPLY =~ ^[Oo]$ ]]; then
echo "!!!!! Deleting current remote clipboard setup..."
rm -fv $HOME/bin/pbpaste-remote
rm -fv $HOME/bin/pbcopy-remote
elif [[ $REPLY =~ ^[Ss]$ ]]; then
echo ">>>>> Skipping Remote Clipboard Setup"
if [ "$defaults" == "true" ]; then
echo ">>>>> No previous remote clipboard setup detected"
read -p "????? Would you like to add remote clipboard capabilities (Y/n)?"
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo ">>>>> Skipping Remote Clipboard"
function backup_local_clipboard(){
echo "!!!!! Backing up local clipboard setup. Appending -bak to the relevant files..."
mv -fv $HOME/Library/LaunchAgents/pbcopy.plist $HOME/Library/LaunchAgents/pbcopy.plist-bak
mv -fv $HOME/Library/LaunchAgents/pbpaste.plist $HOME/Library/LaunchAgents/pbpaste.plist-bak
function setup_local_clipboard(){
echo ">>>>> Setting up local clipboard..."
curl -s > $HOME/Library/LaunchAgents/pbcopy.plist
curl -s > $HOME/Library/LaunchAgents/pbpaste.plist
if [ "$defaults" != "true" ]; then
echo "!!!!! Wrote $HOME/Library/LaunchAgents/pbcopy.plist"
echo "!!!!! Wrote $HOME/Library/LaunchAgents/pbpaste.plist"
read -p "????? What port would you like to setup for pbcopy? (Default: 2222) "
if [[ $REPLY =~ ^[0-9]{4}$ ]]; then
sed -i -e "s/2222/$REPLY/" $HOME/Library/LaunchAgents/pbcopy.plist
echo "!!!!! Invalid port number, keeping default of 2222..."
read -p "????? What port would you like to setup for pbpaste? (Default: 2223) "
if [[ $REPLY =~ ^[0-9]{4}$ ]]; then
sed -i -e "s/2223/$REPLY/" $HOME/Library/LaunchAgents/pbpaste.plist
echo "!!!!! Invalid port number, keeping default of 2223..."
echo "!!!!! Setting up pbcopy and pbpaste for launchctl"
launchctl unload $HOME/Library/LaunchAgents/pbcopy.plist
launchctl unload $HOME/Library/LaunchAgents/pbpaste.plist
launchctl load $HOME/Library/LaunchAgents/pbcopy.plist
launchctl load $HOME/Library/LaunchAgents/pbpaste.plist
if [[ $OSTYPE =~ ^[darwin] ]]; then
if [ "$has_pbcopy_local" == "true" -o "$has_pbpaste_local" == "true" ]; then
echo "***** Note: You already have local clipboard copy and/or paste setup..."
if [ "$defaults" == "true" ]; then
read -p "????? Would you like to (b)ack it up, (o)verwrite it, or (s)kip local clipboard setup all together (B/o/s)?"
if [[ $REPLY =~ ^[Oo]$ ]]; then
echo "!!!!! Deleting current local clipboard setup..."
rm -fv $HOME/Library/LaunchAgents/pbcopy.plist
rm -fv $HOME/Library/LaunchAgents/pbpaste.plist
elif [[ $REPLY =~ ^[Ss]$ ]]; then
echo ">>>>> Skipping Local Clipboard Setup"
if [ "$defaults" == "true" ]; then
echo ">>>>> No previous local clipboard setup detected"
read -p "????? Would you like to add local clipboard capabilities (Y/n)?"
if [[ $REPLY =~ ^[Nn]$ ]]; then
echo ">>>>> Skipping Local Clipboard"
# Put this at the bottom so if it errors out (like it does on codio) the rest
# of the script still will have run
if [ "$should_update_vundle_plugins" == "true" ]; then
if [ "$local_clipboard_was_setup" == "true" ]; then
echo "!!!!! Please add the following configuration to your ~/.ssh/config file"
echo "
Host nickname_here
HostName ip_address_or_hostname_here
User your_username_here
# Pick something other than 3000 to avoid port collisions in a shared environment
LocalForward 3000 localhost:3000
RemoteForward $pbcopy_local_port$pbcopy_local_port
RemoteForward $pbpaste_local_port$pbpaste_local_port
ForwardAgent yes
!!!!! You will then be able to ssh to the host using the above preferences automatically: ssh nickname_here
!!!!! NOTE: For pbcopy-remote & pbpaste-remote to work properly, make sure ~/bin is in your PATH on the remote machine!!
" this is the configuration file for linux and mac systems
" symlink this to your home folder as .vimrc
" It loads ~/.vim/vundle and loads all modules from ~/.vim/bundle.
" It then loads ~/.vim/vimrc_main which has the main
" configuration that works across all systems.
if has('nvim')
runtime! python_setup.vim
source ~/.vim/vundle
source ~/.vim/vimrc_main
source ~/.vimrc_custom
" Put platform specific stuff here.
" User customizations here
set nocompatible "Don't need to keep compatibility with Vi
set shell=/bin/bash "Set it for default Linux setup
if has("unix")
let s:uname = system("uname")
if s:uname == "Darwin\n"
set shell=/usr/local/bin/bash "I think I need this because I'm running ZSH actually... set it to homebrew version here 4.x
filetype plugin indent on "enable detection, plugins and indenting in one step
syntax on "Turn on syntax highlighting
" set synmaxcol=8000 "Don't try to highlight lines longer than 8000 characters
set showcmd "show incomplete cmds down the bottom
set noshowmode "don't show current mode down the bottom (set showmode does the opposite)
set showmatch "Set show matching parenthesis
set noexrc "Don't use the local config
set virtualedit=all "Allow the cursor to go in to 'invalid' places
set incsearch "Find the next match as we type the search
set hlsearch "Hilight searches by default
set ignorecase "Ignore case when searching
set smartcase " ...unless they contain at least one capital letter
set shiftwidth=2 "Number of spaces to use in each autoindent step
set shiftround "When at 3 spaces, and I hit > ... go to 4, not 5
set tabstop=2 "Two tab spaces
set softtabstop=2 "Number of spaces to skip or insert when <BS>ing or <Tab>ing
set expandtab "Spaces instead of tabs for better cross-editor compatibility
set smarttab "Use shiftwidth and softtabstop to insert or delete (on <BS>) blanks
set nowrap "No wrapping
set copyindent "Copy the previous indentation on autoindenting
set backspace=indent,eol,start "Allow backspacing over everything in insert mode
set noerrorbells "Don't make noise
set visualbell "Do blink the screen
set wildmenu "Make tab completion act more like bash
set wildmode=list:longest "Tab complete to longest common string, like bash
" set mouse-=a "Disable mouse automatically entering visual mode
set mouse=a "Enable mouse support in the terminal VIM and activate visual mode with dragging
set bs=2 "This influences the behavior of the backspace option. See :help 'bs' for more details
set number "Show line numbers
set cmdheight=2 "Make the command line a little taller to hide 'press enter to viem more' text
set ttyfast "Improves screen redraw
set lazyredraw
set splitbelow "New splits will be created below the current split
set splitright "New splits will be created to the right of the current split
set confirm "Ask to save changes
set encoding=utf-8 "Set utf-8 encoding
set pastetoggle=<F2> "Press F2 in insert mode to preserve tabs when pasting from clipboard into terminal
set updatetime=750 "Should 'fix' git-gutter weird highlighting issues
set notimeout ttimeout ttimeoutlen=10 "Quckly time out on keycodes, but never time out on mappings
if has("unix")
let s:uname = system("uname")
if s:uname != "Darwin\n"
set t_Co=256 "256 colors support
let g:solarized_termcolors=16
if has('termguicolors') && !has('gui_running')
set termguicolors
if &term =~ '256color'
" disable Background Color Erase (BCE) so that color schemes
" render properly when inside 256-color tmux and GNU screen.
set t_ut=
set background=dark
colorscheme solarized8_dark
let &t_8f = "\<Esc>[38;2;%lu;%lu;%lum"
let &t_8b = "\<Esc>[48;2;%lu;%lu;%lum"
" Toggles the background from dark to light
" call togglebg#map("<F5>")
hi SpellBad ctermfg=009 ctermbg=001 guifg=#ff0000 guibg=#ffffff
hi SpellCap ctermfg=009 ctermbg=001 guifg=#ff0000 guibg=#ffffff
set wildignore+=*/production_data/*,*/db/dumps/*,*/coverage/*,*/accredited_investor_questionnaires/*,*/accredited_verification_pdfs/*,*/HTML_DEMOS/*,*/docusign_docs/*,*/cookbooks/*,*/public/uploads/*,*/public/images/*,*/vim_sessions/*,*/node_modules/*,*/bower_components/*,*/tmp/*,*.so,*.swp,*.zip " MacOSX/Linux
runtime macros/matchit.vim "Extend % for matching brackets, if/end, and more
" Display images in vim
autocmd BufEnter *.png,*.jpg,*gif exec "! imgcat ".expand("%") | :bw
" autoread and autowrite
augroup save
au FocusLost * wall
augroup END
set nohidden
set nobackup
set noswapfile
set nowritebackup
set autoread
set autowrite
set autowriteall
" persistent-undo
set undodir=$HOME/.vim/undo
set undofile
" Resize splits when the window is resized
au VimResized * :wincmd =
let mapleader = "," "remap leader to ',' which is much easier than '\'
let maplocalleader = "\\" "add a local leader of '\'
if has("gui_macvim")
set guifont=Monaco\ for\ Powerline:h12
" toggle hide numbers
map <leader>1 :set nonumber! number?<CR>
" Open NERDTree with [<leader>d]
map <Leader>d :NERDTreeMirrorToggle<CR>
" Show current file in the NERDTree hierarchy
map <Leader>D :NERDTreeFind<CR>
let NERDTreeMinimalUI=1
let NERDTreeDirArrows=1
let NERDTreeWinSize = 51
let NERDTreeShowLineNumbers=1
let g:nerdtree_tabs_focus_on_files=1
let g:nerdtree_tabs_open_on_console_startup=1
let g:nerdtree_tabs_smart_startup_focus=2
" list of file types I don't want to auto-open nerdtree for
autocmd FileType vim,tmux,gitcommit,gitconfig,gitrebase let g:nerdtree_tabs_open_on_console_startup=0
autocmd BufNewFile,BufRead vundle let g:nerdtree_tabs_open_on_console_startup=0
" With tmux-plugins/vim-tmux-focus-events, vim will load up a file on focus so write the file when switching away
let g:tmux_navigator_save_on_switch = 1
let g:eighties_bufname_additional_patterns = ['fugitiveblame','locationlist'] " Don't try to auto-resize a fugitive blame split to 80 chars
let NERDSpaceDelims=1 " For nerdcommenter, add one space after comment char
" swap current with next word
nnoremap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<CR><c-o><c-l>:noh<CR>
" CodeClimate Bindings
nmap <Leader>aa :CodeClimateAnalyzeProject<CR>
nmap <Leader>ao :CodeClimateAnalyzeOpenFiles<CR>
nmap <Leader>af :CodeClimateAnalyzeCurrentFile<CR>
" CtrlP
" --------------
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$' " Exclude files from ctrl-p finder
" let g:ctrlp_custom_ignore = {
" \ 'dir': '\v[\/]\.(git|hg|svn)$',
" \ 'file': '\v\.(exe|so|dll)$',
" \ }
let g:ctrlp_map = '<c-f>' " Change default mapping
" allows opening a split from ctrlp with <c-i>, since using 'i' from NERDTree
" is how to open a horizontal split there. Keep em the same.
let g:ctrlp_prompt_mappings = {
\ 'AcceptSelection("h")': ['<c-x>', '<c-cr>', '<c-s>', '<c-i>']
\ }
let g:ctrlp_cache_dir = $HOME . '/.cache/ctrlp'
if executable('ag')
let g:ctrlp_user_command = 'ag %s -l --nocolor --hidden --follow --ignore .git --ignore node_modules -g ""'
let g:ctrlp_clear_cache_on_exit = 0
" let g:ctrlp_lazy_update = 175
let g:ctrlp_lazy_update = 475
" Open splits from quickfix window like you can in ctrlp
let g:qfenter_vopen_map = ['<C-v>']
let g:qfenter_hopen_map = ['<C-CR>', '<C-s>', '<C-x>', '<C-i>']
let g:qfenter_topen_map = ['<C-t>']
" let g:ctrlp_show_hidden = 1
" Find in project (async!)
" let agrep_win_sp_mod = 'botright vert'
" nnoremap <Leader><C-f> :Agrep -r <space>.<C-Left><Left>
" Ack in Project. AckG matches file names in the project, regular Ack looks inside those files
map <Leader><C-t> :AckG<space>
" map <Leader><C-f> :Ack!<space>
" map <Leader><C-f> :Ag<space>
let g:ackprg = 'ag'
" Split rightward so as not to displace a left NERDTree
let g:ack_mappings = {
\ 'v': '<C-W><CR><C-W>L<C-W>p<C-W>J<C-W>p',
\ 'gv': '<C-W><CR><C-W>L<C-W>p<C-W>J',
\ '<cr>': ':NERDTreeMirrorToggle<CR><CR>:NERDTreeMirrorToggle<CR><C-W>l' }
nnoremap <Leader><C-f> :tabnew <Bar> Ack!<Space>
" Navigate quickfix of found items
" look in ~/.vim/after/plugin/mystuff.vim - needed to override unimpaired
" vimwiki
let wiki0 = {}
let wiki0.path = '~/vimwiki/'
let wiki0.path_html = '~/vimwiki_html/'
let wiki0.auto_toc = 1
let wiki1 = {}
let wiki1.path = '~/vimwiki_headway/'
let wiki1.path_html = '~/vimwiki_headway_html/'
let wiki1.auto_toc = 1
" Run multiple wikis
let g:vimwiki_list = [wiki0, wiki1]
au BufRead,BufNewFile *.wiki set filetype=vimwiki
" Open diary with \d
:autocmd FileType vimwiki map <localleader>d :VimwikiMakeDiaryNote<CR>:Calendar<CR>
au! BufRead ~/vimwiki_headway/ !cd ~/vimwiki_headway;git pull
" au! BufWritePost ~/vimwiki_headway/* !cd ~/vimwiki_headway;git add -A;git commit -m "Auto commit + push.";git push
" let g:vimwiki_folding='expr'
set statusline=%F%m%r%h%w[%L][%{&ff}]%y[%p%%][%04l,%04v]
" | | | | | | | | | | |
" | | | | | | | | | | + current
" | | | | | | | | | | column
" | | | | | | | | | +-- current line
" | | | | | | | | +-- current % into file
" | | | | | | | +-- current syntax in
" | | | | | | | square brackets
" | | | | | | +-- current fileformat
" | | | | | +-- number of lines
" | | | | +-- preview flag in square brackets
" | | | +-- help flag in square brackets
" | | +-- readonly flag in square brackets
" | +-- modified flag in square brackets
" +-- full path to file in the buffer
"Shortcut to toggle `set list` which turns on and off the whitespace markers
nmap <leader>il :set list!<CR>
"Use the same symbols as TextMate for tabstops and EOLs
set listchars=tab:▸\ ,eol:¬
let g:StripperIgnoreFileTypes = []
"Right margin settings for vim 7.2 or greater
if version > 702
set colorcolumn=81
au BufNewFile,BufRead COMMIT_EDITMSG setlocal colorcolumn=51
" Better split management, kept in sync with tmux' mappings of (<prefix>| and <prefix>-)
noremap <leader>- :sp<CR><C-w>j
noremap <leader>\| :vsp<CR><C-w>l
" Allow resizing splits with =/- for up/down and +/_ right/left (repeatable w/hold too)
if bufwinnr(1)
map = <C-W>+
map - <C-W>-
map _ <C-W>>
map + <C-W><
function! NumberToggle()
if(&relativenumber == 1)
set norelativenumber
set number
set relativenumber
nnoremap <leader>l :call NumberToggle()<CR>
let g:debugMode = 0
" reload current top window/tab of chrome
map <leader>rr :ChromeReload<CR>
let g:returnApp = "iTerm"
" Indent guides turned on with <leader>ig
let g:indent_guides_start_level=1
let g:indent_guides_guide_size=1
"Search and replace the word under the cursor with whatever you type in
nnoremap <Leader>s :%s/\<<C-r><C-w>\>/
"Search and replace only within a given selection. This DOES NOT replace all
" instances on the line that the highlight is on, which is why it's awesome.
vnoremap <Leader>S :s/\%V//g<Left><Left><Left>
" Better search with insearch
map / <Plug>(incsearch-forward)
map ? <Plug>(incsearch-backward)
map g/ <Plug>(incsearch-stay)
" Allow for typing various quit cmds while accidentally capitalizing a letter
command! -bar Q quit "Allow quitting using :Q
command! -bar -bang Q quit<bang> "Allow quitting without saving using :Q!
command! -bar QA qall "Quit all buffers
command! -bar Qa qall "Quit all buffers
command! -bar -bang QA qall<bang> "Allow quitting without saving using :Q!
command! -bar -bang Qa qall<bang> "Allow quitting without saving using :Q!
" NOTE - the above has nothing to do with the quit commands below
" Make Q useful and avoid the confusing Ex mode.
" Pressing Q with this mapping does nothing intentionally
noremap Q <nop>
" Close window.
noremap QQ :q<CR>
" close and write
noremap WQ :wq<CR>
" Close all.
noremap QA :qa<CR>
" Close, damn you!
noremap Q! :q!<CR>
"I never much liked the S command in normal mode. Substitutes the whole line after a motion. So we'll disable it here.
nmap S <nop>
" Session management
" -----------------
" Create new session
nmap SC :Obsess ~/.vim/sessions/
" Open the last saved session
nmap SO :so ~/.vim/sessions/
nmap SQ :Obsess!<CR>
" Save
" Hit SS in insert or normal mode to save
" noremap SS :w<CR>:SyntasticCheck<CR>
" inoremap SS <Esc>:w<CR>:SyntasticCheck<CR>
noremap SS :w<CR>
inoremap SS <Esc>:w<CR>
"Save the current file even if you don't have permission to do so
map W!! :w !sudo tee % > /dev/null<CR>
cmap w!! w !sudo tee % >/dev/null
" This switches the cursor into a pipe when in insert mode tmux will only
" forward escape sequences to the terminal if surrounded by a DCS sequence
if has('nvim')
if exists('$TMUX')
let &t_SI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=1\x7\<Esc>\\"
let &t_EI = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=0\x7\<Esc>\\"
let &t_SI = "\<Esc>]50;CursorShape=1\x7"
let &t_EI = "\<Esc>]50;CursorShape=0\x7"
if has("unix")
let s:uname = system("uname")
if s:uname == "Linux\n"
" Remote Clipboard
function! PropagatePasteBufferToOSX()
let @n=getreg('"')
call system('pbcopy-remote', @n)
echo "done"
function! PopulatePasteBufferFromOSX()
let @" = system('pbpaste-remote')
echo "done"
nnoremap <leader>3 :call PopulatePasteBufferFromOSX()<cr>
nnoremap <leader>2 :call PropagatePasteBufferToOSX()<cr>
nnoremap yy yy:call PropagatePasteBufferToOSX()<cr>
function! YRRunAfterMaps()
nnoremap Y :<C-U>YRYankCount 'y$'<CR> <bar> :call PropagatePasteBufferToOSX()<CR>
vnoremap y y:call PropagatePasteBufferToOSX()<CR>
" Indent pastes properly
nnoremap <leader>pi p`[v`]=
"Update CTags
nnoremap <silent> <leader>ct :!$(.git/hooks/ctags &)<cr> <bar> :redraw!<cr>
" ExCTags window (requires
nmap <F8> :TagbarToggle<CR>
let g:tagbar_left = 1
let g:tagbar_autofocus = 1
let g:tagbar_compact = 1
let g:tagbar_autoclose = 1
" open ctag in tab/vertical split
map <leader><C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
map <C-\> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>
" NOTE: Jump to previous file with <leader><C-^>
" set text wrapping toggles
nmap <silent> <leader><Leader>tw :set invwrap<CR>:set wrap?<CR>
" Adjust viewports to the same size
map <Leader>= <C-w>=
"" Move by visual screen lines instead of file lines. (aka when navigating wrapped text)
" TODO: Determine if this is still necessary
noremap [A gk
noremap [B gj
inoremap [B <C-o>gj
inoremap [A <C-o>gk
" mapping to make movements operate on 1 screen line in wrap mode
" TODO: See if pencil works fine with this commented out
function! ScreenMovement(movement)
if &wrap
return "g" . a:movement
return a:movement
onoremap <silent> <expr> j ScreenMovement("j")
onoremap <silent> <expr> k ScreenMovement("k")
onoremap <silent> <expr> 0 ScreenMovement("0")
onoremap <silent> <expr> ^ ScreenMovement("^")
onoremap <silent> <expr> $ ScreenMovement("$")
nnoremap <silent> <expr> j ScreenMovement("j")
nnoremap <silent> <expr> k ScreenMovement("k")
nnoremap <silent> <expr> 0 ScreenMovement("0")
nnoremap <silent> <expr> ^ ScreenMovement("^")
nnoremap <silent> <expr> $ ScreenMovement("$")
" Tab/shift-tab to indent/outdent in visual mode.
vnoremap <Tab> >gv
vnoremap <S-Tab> <gv
" Keep selection when indenting/outdenting.
vnoremap > >gv
vnoremap < <gv
"arrow keys, up=A, down=B, right=C and left=D
"<C-Up> == <Esc>[A
" ----
" Load up all buffers into tabs
nmap <localleader>bt :tab sball<CR>
" previous tab(shift-9), next tab (shift-0)
nnoremap ( :tabp<CR>
nnoremap ) :tabn<CR>
" switch tab order with Ctrl+<left>/<right>
map <Esc>[C :tabm +1<Esc>
map <Esc>[D :tabm -1<Esc>
function! MoveToPrevTab()
"there is only one window
if tabpagenr('$') == 1 && winnr('$') == 1
"preparing new window
let l:tab_nr = tabpagenr('$')
let l:cur_buf = bufnr('%')
if tabpagenr() != 1
if l:tab_nr == tabpagenr('$')
exe "0tabnew"
"opening current buffer in new window
exe "b".l:cur_buf
function! MoveToNextTab()
"there is only one window
if tabpagenr('$') == 1 && winnr('$') == 1
"preparing new window
let l:tab_nr = tabpagenr('$')
let l:cur_buf = bufnr('%')
if tabpagenr() < tab_nr
if l:tab_nr == tabpagenr('$')
"opening current buffer in new window
exe "b".l:cur_buf
" switch tab order with Ctrl+<up>/<down>
map <Esc>[B :call MoveToNextTab()<CR>
map <Esc>[A :call MoveToPrevTab()<CR>
if has('nvim')
" Use unnamed registers for clipboard
set clipboard+=unnamedplus
" This allows you to share Vim's clipboard with OS X.
set clipboard=unnamed
" Alignment stuff
"if exists(":Tabularize")
nmap <Leader>a= :Tabularize /=<CR>
vmap <Leader>a= :Tabularize /=<CR>
nmap <Leader>a: :Tabularize /:\zs<CR>
vmap <Leader>a: :Tabularize /:\zs<CR>
" Triggers align of cucumber tables when you close it out with a | and have at
" least two lines. Thanks tpope :)
function! s:align()
let p = '^\s*|\s.*\s|\s*$'
if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
normal! 0
call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
inoremap <silent> <Bar> <Bar><Esc>:call <SID>align()<CR>a
" Hashrocket mappings
" ------------------
" inserts hashrocket in insert mode
inoremap <c-l> =>
" converts visually selected hashrockets to 1.9 syntax
vnoremap <c-l> :s/\:\([a-zA-Z_]*\)\s=>/\1\:/g<cr>:noh<cr>
"fold settings
" ------------
" toggle folding with za.
" fold everything with zM
" unfold everything with zR.
" zm and zr can be used too
" set foldmethod=syntax "fold based on syntax (except for haml below)
" set foldnestmax=10 "deepest fold is 10 levels
" set nofoldenable "dont fold by default
autocmd BufNewFile,BufRead *.haml setl foldmethod=indent nofoldenable
autocmd! FileType nofile setl foldmethod=indent nofoldenable
set foldlevelstart=99
" Space to toggle folds.
nnoremap <Space> za
vnoremap <Space> za
" Toggles folds being enabled for this vim session
function! FoldToggle()
if(&foldenable == 1)
au WinEnter * set nofen
au WinLeave * set nofen
au BufEnter * set nofen
au BufLeave * set nofen
:set nofen
au WinEnter * set fen
au WinLeave * set fen
au BufEnter * set fen
au BufLeave * set fen
:set fen
nnoremap <Leader>nf :call FoldToggle()<CR>
" Buffrgator settings
let g:buffergator_viewport_split_policy="B"
let g:buffergator_split_size=10
let g:buffergator_suppress_keymaps=1
let g:buffergator_sort_regime = "mru"
map <Leader>b :BuffergatorToggle<cr>
" go to the 81th column
noremap <leader>8 81\|
" commands from insert mode
inoremap II <Esc>I
inoremap AA <Esc>A
" Pull up the TODO And NOTE and FIXME definitions from the whole app
let g:TagmaTasksPrefix = '<localleader><localleader>t'
let g:TagmaTasksHeight = 10
map <Leader><Leader>tt :TagmaTasks * app/** config/** db/** doc/** features/** lib/** public/** spec/** test/** vendor/**<CR>
" Coverage via Cadre/
let g:legend_active_auto = 0
let g:legend_hit_color = "ctermfg=64 cterm=bold gui=bold guifg=Green"
let g:legend_ignored_sign = "◌"
let g:legend_ignored_color = "ctermfg=234"
let g:legend_mapping_toggle = '<Leader>cv'
let g:legend_mapping_toggle_line = '<localleader>cv'
" vim-rspec & cucumber test runner mappings <leader>T
let VimuxHeight = "33" "this is percentage
let VimuxOrientation = "h"
let VimuxUseNearestPane = 1
function! DetermineSpecRunString(focus, coverage)
let test_kind = (&filetype == 'cucumber' ? 'bin/cucumber' : 'bin/rspec')
let coverage = (a:coverage == 'coverage' ? 'COVERAGE=true bundle exec ' : ' ')
let focus = (a:focus == 'focus' ? ':' . line('.') : '')
return 'clear; ' . coverage . test_kind . " " . expand('%') . focus
function! RunCurrentSpec(focus, coverage)
let spec_run_string = DetermineSpecRunString(a:focus, a:coverage)
call VimuxRunCommand(spec_run_string)
"""""""""" This is crazy, but keep it around in does work
" :autocmd FileType jasmine.javascript map <leader>t :call VimuxRunCommand('clear; npm test')<CR>
" :autocmd FileType jasmine.javascript map <leader>T :s/it(/fit(<CR>:w<CR>:noh<CR>:call VimuxRunCommand('clear; npm test')<CR>:sleep 1<CR>:s/fit(/it(<CR>:sleep 500m<CR>:w<CR>:noh<CR>
"""""""""" This is crazy, but keep it around in does work
let test#strategy = "vimux"
let test#javascript#jasmine#executable = 'node_modules/.bin/babel-node ./node_modules/.bin/jasmine'
autocmd FileType jasmine.javascript nmap <silent> <leader>T :TestNearest<CR>
autocmd FileType jasmine.javascript nmap <silent> <leader>t :TestFile<CR>
" :autocmd FileType jasmine.javascript nmap <silent> <leader>a :TestSuite<CR>
autocmd FileType jasmine.javascript nmap <silent> <leader>l :TestLast<CR>
" :autocmd FileType jasmine.javascript nmap <silent> <leader>g :TestVisit<CR>
map <Leader>t :call RunCurrentSpec('all', '')<CR>
map <Leader>C :call RunCurrentSpec('all', 'coverage')<CR>
map <Leader>T :call RunCurrentSpec('focus', '')<CR>
map <leader>u :call VimuxRunCommand('clear; cucumber --profile syntastic --dry-run ' . expand('%'))<CR>
map <leader>U :call VimuxRunCommand('clear; cucumber --profile syntastic --dry-run ' . expand('%') . ':' . line('.'))<CR>
" for rspec.vim (syntax highlighting enhancements for rspec)
autocmd BufReadPost,BufNewFile *_spec.rb set syntax=rspec
" ,q to toggle quickfix window (where you have stuff like GitGrep)
" ,oq to open it back up (rare)
nmap <silent> ,cq :cclose<CR>
nmap <silent> ,co :copen<CR>
" Set super tab to start completion with ctrl+j and move down the list with
" more j's, move back with ctrl+k
let g:SuperTabMappingForward = '<c-k>'
let g:SuperTabMappingBackward = '<c-j>'
" Toggle spellcheck with F6 (highlighted and underlined in stark WHITE)
" -----------------
" z= - view spelling suggestions for a misspelled word
" zg - add word to dictionary
" zug - undo add word to dict
hi SpellBad cterm=underline ctermfg=white
nn <F6> :setlocal spell! spell?<CR>
map <F11> "dyiw:call MacDict(@d)<CR>
" YankRing plugin to manage yanked/deleted buffers
nnoremap <silent> <F7> :YRShow<CR>
let g:yankring_history_file = '.yankring-history'
" let g:yankring_zap_keys = 'f F t T / ?'
" STOP the help from being so... HELPFULL ;)
inoremap <F1> <ESC>
nnoremap <F1> <ESC>
vnoremap <F1> <ESC>
" Exit out of insert with jj
inoremap jj <ESC>
" Dig through the tree of undo possibilities for your current file
nnoremap <F3> :GundoToggle<CR>
let g:gundo_right = 1
let g:gundo_preview_bottom=1
let g:gundo_preview_height = 40
" Disable some built in commands I don't like
" map K <Nop>
" Load up the vimrc_main file (this file) in vim to edit it
nnoremap <Leader>ev :tabnew ~/.vim/vimrc_main<CR> :NERDTreeClose<CR>
" Load up the ~/.tmux.conf file in vim to edit it
nnoremap <Leader>et :tabnew ~/.tmux.conf<CR>
" Automatically source this file after it's saved
autocmd! BufWritePre vimrc_main :NERDTreeClose
autocmd! BufWritePost vimrc_main source %
"From Gary Bernhardt
function! ShowRoutes()
" Requires 'scratch' plugin
:topleft 40 :split __Routes__
" Make sure Vim doesn't write __Routes__ as a file
:set buftype=nofile
" set a filetype so we can fold the output (to avoid the error / warning)
:set filetype=nofile
" Delete everything
:normal 1GdG
" Put routes output in buffer (NOTE: (2013-09-10) jonk => changed to " bin/rake)
:0r! bin/rake -s routes
" Size window to number of lines (1 plus rake output length)
" :exec ":normal " . line("$") . "_ "
" Move cursor to bottom
:normal 1GG
" Delete empty trailing line
:normal dd
" Expand all folds
:normal zR
map <leader>gR :call ShowRoutes()<cr>
map <leader>gr :topleft 40 :split config/routes.rb<cr>
map <leader>gg :topleft 40 :split Gemfile<cr>
" turn highlighting off after a search (and / or turn off highlights)
noremap <silent> <leader><space> :noh<cr>:call clearmatches()<cr>
" keeps cursor on star search highlight
let g:indexed_search_dont_move=1
nnoremap <silent> <F4> :call <SID>SearchMode()<CR>
function! s:SearchMode()
" if !exists('s:searchmode') || s:searchmode == 0
if !exists('s:searchmode') || s:searchmode == 2
echo 'Search next: scroll hit to middle if not on same page'
nnoremap <silent> n n:call <SID>MaybeMiddle()<CR>
nnoremap <silent> N N:call <SID>MaybeMiddle()<CR>
let s:searchmode = 1
" elseif s:searchmode == 1
echo 'Search next: scroll hit to middle'
nnoremap n nzz
nnoremap N Nzz
let s:searchmode = 2
" else
" echo 'Search next: normal'
" nunmap n
" nunmap N
" let s:searchmode = 0
" If cursor is in first or last line of window, scroll to middle line.
function! s:MaybeMiddle()
if winline() == 1 || winline() == winheight(0)
normal! zz
augroup searchmode
au BufRead * call s:SearchMode()
augroup END
" pretty up JSON data
nnoremap <Leader>j !!python -m json.tool<CR>
nnoremap <Leader>J :%!python -m json.tool<CR>
vnoremap <Leader>j :!python -m json.tool<CR>
" Easy filetype switching (good for commenting code in haml filters)
nnoremap _md :set ft=markdown<CR>
nnoremap _hm :set ft=haml<CR>
nnoremap _eb :set ft=eruby<CR>
nnoremap _js :set ft=javascript<CR>
nnoremap _cs :set ft=coffee<CR>
nnoremap _d :set ft=diff<CR>
" Gist stuff for mattn/gist-vim
let g:gist_clip_command = 'pbcopy'
let g:gist_detect_filetype = 1
let g:gist_open_browser_after_post = 1
let g:gist_post_private = 1
" Make sure Vim returns to the same line when you reopen a file.
augroup line_return
au BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ execute 'normal! g`"zvzz' |
\ endif
augroup END
" -------------------
" <m-j> and <m-k> to drag lines in any mode (m is alt/option)
" this is the textmate move lines around thing that I used to do do with arrow
" keys but less fragile because it works in tmux or not
noremap ∆ :m+<CR>
noremap ˚ :m-2<CR>
inoremap ∆ <Esc>:m+<CR>
inoremap ˚ <Esc>:m-2<CR>
vnoremap ∆ :m'>+<CR>gv
vnoremap ˚ :m-2<CR>gv
" markdown
map <localleader>m :MarkedOpen!<CR>
let g:marked_app = "Marked" " Need to specify v1 of the app
let g:vim_markdown_folding_disabled = 1
" let g:vim_markdown_conceal = 0
let g:vim_markdown_frontmatter = 1
" Syntax highlight code in markdown files
let g:markdown_fenced_languages = ['javascript', 'js=javascript', 'json=javascript', 'ruby']
let g:vim_markdown_emphasis_multiline = 0
let g:vim_markdown_toc_autofit = 1
" Disable ]c for move to current header of vim-markdown
nmap <Plug>Markdown_MoveToCurHeader <Plug>Markdown_MoveToCurHeader
function! s:Toc()
if &filetype == 'markdown'
:normal SS
autocmd VimEnter *.m* call s:Toc()
autocmd BufReadPost *.m* call s:Toc()
autocmd BufWinEnter *.m* call s:Toc()
augroup ft_markdown
au BufNewFile,BufRead *.m*down setlocal filetype=markdown foldlevel=1
" Use <localleader>1/2/3 to add headings.
au Filetype markdown nnoremap <buffer> <localleader>1 mzI# <ESC>
au Filetype markdown nnoremap <buffer> <localleader>2 mzI## <ESC>
au Filetype markdown nnoremap <buffer> <localleader>3 mzI### <ESC>
" au FileType markdown nnoremap <leader>al <Esc>`<i[<Esc>`>la](<Esc>"*]pa)<Esc>
" Create a Markdown-link structure for the current word or visual selection
" with leader 3. Paste in the URL later. Or use leader 4 to insert the
" current system clipboard as an URL.
au FileType markdown nnoremap <Leader>al ciw[<C-r>"]()<Esc>
au FileType markdown vnoremap <Leader>al c[<C-r>"]()<Esc>
" au FileType markdown nnoremap <Leader>ai <Esc>`<i[<Esc>`>la](<Esc>"*]pa)<Esc>
au FileType markdown vnoremap <Leader>ai <Esc>`<i[<Esc>`>la](<Esc>"*]pa)<Esc>
" au FileType markdown nnoremap <Leader>ai ciw[<C-r>"](<Esc>"*pli)<Esc>
" au FileType markdown vnoremap <Leader>ai c[<C-r>"](<Esc>"*]pa)<Esc>
" Use formd to transfer markdown from inline [to reference](to reference) links and vice versa
" see:
au FileType markdown nmap <leader>fr :%! /usr/local/bin/formd/formd -r<CR>
au FileType markdown nmap <leader>fi :%! /usr/local/bin/formd/formd -i<CR>
" For some reason saving causes the Toc to go blank. Call it again to solve this for now. Then put cursor back.
au FileType markdown noremap SS :w<CR>:Toc<CR><C-w>h
au FileType markdown inoremap SS <Esc>:w<CR>:Toc<CR><C-w>h
augroup END
augroup textobj_quote
autocmd FileType markdown call textobj#quote#init({'educate': 0})
autocmd FileType html call textobj#quote#init({'educate': 0})
autocmd FileType textile call textobj#quote#init({'educate': 0})
autocmd FileType text call textobj#quote#init({'educate': 0})
autocmd FileType vimwiki call textobj#quote#init({'educate': 0})
augroup END
let g:pencil#mode_indicators = {'hard': '✐ hard', 'soft': '✎ soft', 'off': '✎ off',}
let g:airline_section_x = '%{PencilMode()}'
let g:pencil#map#suspend_af = 'K' " default is no mapping
augroup pencil
autocmd FileType markdown,md,vimwiki
\ call pencil#init({'wrap': 'soft', 'textwidth': 80})
\ | call litecorrect#init()
\ | call lexical#init()
\ | call textobj#sentence#init()
\ | setl spell spl=en_us
\ | setl fdo+=search
autocmd Filetype git,gitsendemail,*commit*,*COMMIT*
\ call pencil#init({'wrap': 'soft', 'textwidth': 72})
\ | call litecorrect#init()
\ | call lexical#init()
\ | call textobj#sentence#init()
\ | setl spell spl=en_us et sw=2 ts=2 noai
autocmd Filetype html,xml call pencil#init({'wrap': 'soft'})
\ | call litecorrect#init()
\ | setl spell spl=en_us et sw=2 ts=2
augroup END
" Vimwiki override to not check spelling when launching
autocmd FileType vimwiki setl nospell
" Find what Syntax you're in
" map <F9> :echo "hi<" . synIDattr(synID(line("."),col("."),1),"name") . '> trans<'
" \ . synIDattr(synID(line("."),col("."),0),"name") . "> lo<"
" \ . synIDattr(synIDtrans(synID(line("."),col("."),1)),"name") . ">"<CR>
" Fugitive
set diffopt+=vertical
nnoremap <leader>gd :Gdiff<cr>
nnoremap <leader>gst :Gstatus<cr>
nnoremap <leader>gw :Gwrite<cr>
nnoremap <leader>ge :Gedit<cr>
nnoremap <leader>gb :Gblame -w -M<cr>
nnoremap <leader>gB :Gitv!<cr>
nnoremap <leader>gco :Gread<cr>
nnoremap <leader>gcm :Gcommit<cr>
nnoremap <leader>glg :Glog<cr>
" Numbers
" Motion for numbers. Great for CSS. Lets you do things like this:
" margin-top: 200px; -> ciN -> margin-top: px;
" ^ ^
" TODO: Handle floats.
onoremap N :<c-u>call <SID>NumberTextObject(0)<cr>
xnoremap N :<c-u>call <SID>NumberTextObject(0)<cr>
onoremap aN :<c-u>call <SID>NumberTextObject(1)<cr>
xnoremap aN :<c-u>call <SID>NumberTextObject(1)<cr>
onoremap iN :<c-u>call <SID>NumberTextObject(1)<cr>
xnoremap iN :<c-u>call <SID>NumberTextObject(1)<cr>
function! s:NumberTextObject(whole)
normal! v
while getline('.')[col('.')] =~# '\v[0-9]'
normal! l
if a:whole
normal! o
while col('.') > 1 && getline('.')[col('.') - 2] =~# '\v[0-9]'
normal! h
let g:airline#extensions#tabline#enabled = 1
let g:airline_powerline_fonts = 1
let g:airline_detect_iminsert = 1
" tmux plugin for vim-airline
let g:tmuxline_preset = 'full'
let g:InteractiveReplace_map = 'X'
"let g:signify_sign_color_guibg = '#032b36'
let g:signify_sign_color_inherit_from_linenr = 1
let g:signify_sign_weight = 'NONE'
let g:signify_update_on_bufenter = 1
" Reveal in Finder - opens finder to folder of the file that is currently open
command! Rif execute '!open %:p:h'
" -------------- SURROUND SETTINGS -------------------
" ,# Surround a word with #{ruby interpolation}
vmap ,# c#{<C-R>"}<ESC>
" ," Surround a word with "quotes"
map ," ysiw"
vmap ," c"<C-R>""<ESC>
" ,' Surround a word with 'single quotes'
map ,' ysiw'
vmap ,' c'<C-R>"'<ESC>
" ,) or ,( Surround a word with (parens)
" The difference is in whether a space is put in
map ,( ysiw(
map ,) ysiw)
vmap ,( c( <C-R>" )<ESC>
vmap ,) c(<C-R>")<ESC>
" ,[ Surround a word with [brackets]
map ,] ysiw]
map ,[ ysiw[
vmap ,[ c[ <C-R>" ]<ESC>
vmap ,] c[<C-R>"]<ESC>
" ,{ Surround a word with {braces}
map ,} ysiw}
map ,{ ysiw{
vmap ,} c{ <C-R>" }<ESC>
vmap ,{ c{<C-R>"}<ESC>
map ,` ysiw`
" -------------- END SURROUND SETTINGS ---------------
" TODO: (2016-11-05) jonk => experiment with this more
" xmpfilter (need to: `gem install rcodetools` into each global gemset for each version of ruby that you want to use this with)
" map <F11> <Plug>(xmpfilter-mark)
" map <F12> <Plug>(xmpfilter-run)
" slim template detection, the plugin didn't get me goin... FIXME
" autocmd BufNewFile,BufRead *.slim set ft=slim
au BufNewFile,BufRead *.js.erb setlocal filetype=javascript
au BufNewFile,BufRead *.ejs set filetype=xml
if has("unix")
let s:uname = system("uname")
if s:uname == "Darwin\n"
" Do Mac stuff here
" Dash
"let g:dash_map = {
" \ 'ruby' : 'rails'
" \ }
au BufNewFile,BufRead *.rb :DashKeywords rails ruby<cr>
nmap <silent> <LocalLeader>d <Plug>DashSearch
nmap <silent> <LocalLeader>D <Plug>DashGlobalSearch
" quote, quotation, apostrophe, curly
map <silent> <leader>qc <Plug>ReplaceWithCurly
map <silent> <leader>qs <Plug>ReplaceWithStraight
let g:mustache_abbreviations = 1
let g:syntastic_shell = '/bin/sh'
let g:syntastic_mode_map = { 'mode': 'active' }
let g:syntastic_ruby_checkers = ['mri', 'rubocop', 'haml_lint']
let g:syntastic_cucumber_cucumber_args="--profile syntastic"
let g:syntastic_cucumber_cucumber_exe='cucumber'
let g:syntastic_ruby_rubocop_args = '--force-exclusion'
" let g:syntastic_debug = 1
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_loc_list_height = 5
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 1
let g:syntastic_javascript_checkers = ['eslint']
if executable('node_modules/.bin/eslint')
let g:syntastic_javascript_eslint_exec = 'node_modules/.bin/eslint'
" let g:ale_sign_error = '✗'
" let g:ale_sign_warning = '❱'
let g:syntastic_error_symbol = '✗'
let g:syntastic_style_error_symbol = '⁉️'
" let g:syntastic_warning_symbol = '❱'
let g:syntastic_warning_symbol = '⚠'
let g:syntastic_style_warning_symbol = '💩'
" let g:syntastic_error_symbol = 'x'
" let g:syntastic_style_error_symbol = '!!'
" let g:syntastic_warning_symbol = '!!'
" let g:syntastic_style_warning_symbol = '!!'
" highlight link SyntasticErrorSign SignColumn
" highlight link SyntasticWarningSign SignColumn
" highlight link SyntasticStyleErrorSign SignColumn
" highlight link SyntasticStyleWarningSign SignColumn
hi SyntasticWarn guifg=#b58900 guibg=#073642
hi SyntasticError guifg=#dc322f guibg=#073642
hi link SyntasticErrorSign SyntasticError
hi link SyntasticWarningSign SyntasticWarn
hi link SyntasticStyleErrorSign SyntasticError
hi link SyntasticStyleWarningSign SyntasticWarn
" Ensures color scheme works for the gutter diff indicators
hi clear SignColumn "Show the gutter color the same as the number column color
" OpenChangedFiles COMMAND
" Open a split for each dirty (or new) file in git
" Shamelessly stolen from Gary Bernhardt:
function! OpenChangedFiles()
only " Close all windows, unless they're modified
let modified_status = system('git status -s | grep "^ \?\(M\|A\)" | cut -d " " -f 3')
let added_status = system('git status -s | grep "^ \?\(??\)" | cut -d " " -f 2')
let status = modified_status . added_status
let filenames = split(status, "\n")
if len(filenames) > 0
exec "edit " . filenames[0]
for filename in filenames[1:]
exec "tabedit " . filename
command! OpenChangedFiles :call OpenChangedFiles()
" nnoremap ,em :NERDTreeMirrorToggle<CR>:OpenChangedFiles<CR>:NERDTreeMirrorToggle<CR>
nnoremap ,em :OpenChangedFiles<CR>
function! DoPrettyXML()
" save the filetype so we can restore it later
let l:origft = &ft
set ft=
" delete the xml header if it exists. This will
" permit us to surround the document with fake tags
" without creating invalid xml.
1s/<?xml .*?>//e
" insert fake tags around the entire document.
" This will permit us to pretty-format excerpts of
" XML that may contain multiple top-level elements.
0put ='<PrettyXML>'
$put ='</PrettyXML>'
silent %!xmllint --format -
" xmllint will insert an <?xml?> header. it's easy enough to delete
" if you don't want it.
" delete the fake tags
" restore the 'normal' indentation, which is one extra level
" too deep due to the extra tags we wrapped around the document.
silent %<
" back to home
" restore the filetype
exe "set ft=" . l:origft
command! PrettyXML call DoPrettyXML()
"autocmd VimEnter,BufNewFile,BufReadPost * silent! call HardMode()
" nnoremap <leader>h <Esc>:call ToggleHardMode()<CR>
" Easymotion
let g:EasyMotion_startofline = 0 "keep cursor colum JK motion
" change the default shading to something more readable with Solarized
hi EasyMotionTarget guifg=red guibg=NONE ctermfg=red ctermbg=NONE
hi EasyMotionTarget2First guifg=red guibg=NONE ctermfg=red ctermbg=NONE
hi EasyMotionTarget2Second guifg=red guibg=NONE ctermfg=red ctermbg=NONE
hi link EasyMotionShade Comment
"let g:EasyMotion_do_shade = 0
set switchbuf=useopen,usetab "Attempt to edit currently open files instead of opening multiple buffers. FIXME: Not sure if this is working.
nmap <localleader>h :%!html2haml --erb 2> /dev/null<CR>:set ft=haml<CR>
vmap <localleader>h :!html2haml --erb 2> /dev/null<CR>
" Insert a newline after each specified string (or before if use '!').
" If no arguments, use previous search.
command! -bang -nargs=* -range LineBreakAt <line1>,<line2>call LineBreakAt('<bang>', <f-args>)
function! LineBreakAt(bang, ...) range
let save_search = @/
if empty(a:bang)
let before = ''
let after = '\ze.'
let repl = '&\r'
let before = '.\zs'
let after = ''
let repl = '\r&'
let pat_list = map(deepcopy(a:000), "escape(v:val, '/\\.*$^~[')")
let find = empty(pat_list) ? @/ : join(pat_list, '\|')
let find = before . '\%(' . find . '\)' . after
" Example: 10,20s/\%(arg1\|arg2\|arg3\)\ze./&\r/ge
execute a:firstline . ',' . a:lastline . 's/'. find . '/' . repl . '/ge'
let @/ = save_search
nmap <localleader>. :LineBreakAt! .<CR>
nmap <localleader>, :LineBreakAt ,<CR>
let g:rails_projections = {
\ "config/projections.json": {
\ "command": "projections"
\ },
\ "app/serializers/*_serializer.rb": {
\ "command": "serializer",
\ "affinity": "model",
\ "test": "spec/serializers/%s_spec.rb",
\ "related": "app/models/%s.rb",
\ "template": "class %SSerializer < ActiveModel::Serializer\nend"
\ },
\ "app/services/*.rb": {
\ "command": "service",
\ "affinity": "model",
\ "alternate": ["spec/services/%s_spec.rb", "unit/services/%s_spec.rb"],
\ "template": "class %S\n\n def perform\n end\nend"
\ },
\ "app/presenters/*_presenter.rb": {
\ "command": "presenter",
\ "affinity": "model",
\ "alternate": ["spec/presenters/%s_presenter_spec.rb", "unit/presenters/%s_presenter_spec.rb"],
\ "related": "app/models/%s.rb",
\ "template": "class %SPresenter < SimpleDelegator\n def self.wrap(collection)\n{open} |object| new object {close}\n end\n\nend"
\ },
\ "spec/presenters/*_presenter.rb": {
\ "command": "specpresenter",
\ "affinity": "presenter",
\ "alternate": ["app/presenters/%s_presenter.rb"],
\ "related": "app/models/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %SPresenter, type: :presenter do\n\nend"
\ },
\ "features/cukes/*.feature": {
\ "alternate": ["features/step_definitions/%s_steps.rb", "features/steps/%s_steps.rb"],
\ },
\ "spec/factories/*s.rb": {
\ "command": "factory",
\ "affinity": "model",
\ "related": "app/models/%s.rb",
\ "template": "FactoryGirl.define do\n factory :%s do\n end\nend"
\ },
\ "spec/controllers/*_controller_spec.rb": {
\ "command": "speccontroller",
\ "affinity": "controller",
\ "related": "app/controllers/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %SController, type: :controller do\n\nend"
\ },
\ "spec/serializers/*_serializer_spec.rb": {
\ "command": "specserializer",
\ "affinity": "serializer",
\ "related": "app/serializers/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %SSerializer, type: :serializer do\n\nend"
\ },
\ "spec/models/*_spec.rb": {
\ "command": "spec",
\ "affinity": "model",
\ "related": "app/models/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %S, type: :model do\n\nend"
\ },
\ "spec/services/*_spec.rb": {
\ "command": "specservice",
\ "affinity": "service",
\ "related": "app/services/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %S do\n\nend"
\ },
\ "spec/workers/*_spec.rb": {
\ "command": "specworker",
\ "affinity": "worker",
\ "related": "app/workers/%s.rb",
\ "template": "require 'rails_helper'\n\nRSpec.describe %S, type: :worker do\n\nend"
\ },
\ "spec/features/*_spec.rb": {
\ "command": "specfeature",
\ "template": "require 'rails_helper'\n\nRSpec.feature '%S', type: :feature do\n\nend"
\ },
\ "spec/helpers/*_helper_spec.rb": {
\ "command": "spechelper",
\ "related": "app/helpers/%_helper.rb",
\ "affinity": "helper",
\ "template": "require 'rails_helper'\n\nRSpec.describe ApplicationHelper, type: :helper do\n\nend"
\ },
\ "lib/tasks/*.rake": {
\ "command": "rake",
\ "template": ["namespace :%s do\n desc '%s'\n task %s: :environment do\n\n end\nend"],
\ },
\ "config/*.rb": { "command": "config" },
\ "spec/support/*.rb": { "command": "support" },
\ }
let g:rails_gem_projections = {
\ "carrierwave": {
\ "app/uploaders/*_uploader.rb": {
\ "command": "uploader",
\ "template": "class %SUploader < CarrierWave::Uploader::Base\nend"
\ }
\ },
\ "resque": {
\ "app/workers/*_job.rb": {
\ "command": "worker",
\ "template": "class %SJob\n\n \n@queue = :main\ndef self.perform\n end\nend"
\ }
\ },
\ }
let g:projectionist_heuristics = {
\ ".ember-cli": {
\ "app/adapters/*.js": {
\ "command": "adapter",
\ "template": [
\ "\// export default DS.{capitalize}Adapter.extend();",
\ ]
\ },
\ "app/components/*.js": {
\ "command": "component",
\ "template": [
\ "import Ember from 'ember';",
\ "",
\ "export default Ember.Component.extend({",
\ "",
\ "});",
\ ],
\ "alternate": "tests/unit/components/{}-test.js"
\ },
\ "app/controllers/*.js": {
\ "command": "controller",
\ "template": [
\ "export default Ember.Controller.extend({",
\ "",
\ "});",
\ ],
\ "alternate": "tests/unit/controllers/{}-test.js"
\ },
\ "app/helpers/*.js": {
\ "command": "helper",
\ "template": [
\ "\// Please note that Handlebars helpers will only be found automatically by the",
\ "\// resolver if their name contains a dash (reverse-word, translate-text, etc.)",
\ "\// For more details:",
\ "import Ember from 'ember';",
\ "",
\ "function {camelcase}(text) {",
\ " if (!text) {open} return ''; {close}",
\ " return text.htmlSafe();",
\ "}",
\ "",
\ "export default Ember.Handlebars.makeBoundHelper({camelcase}, 'dependentKey');",
\ ],
\ "alternate": "tests/unit/helpers/{}-test.js"
\ },
\ "app/models/*.js": {
\ "command": "model",
\ "template": [
\ "import DS from 'ember-data';",
\ "",
\ "var attr = DS.attr;",
\ "\// hasMany = DS.hasMany;",
\ "",
\ "export default DS.Model.extend({",
\ "",
\ "});",
\ ],
\ "alternate": "tests/unit/models/{}-test.js"
\ },
\ "app/mixins/*.js": {
\ "command": "mixin",
\ "alternate": "tests/unit/mixins/{}-test.js"
\ },
\ "app/serializers/*.js": {
\ "command": "serializer",
\ "alternate": "tests/unit/serializers/{}-test.js"
\ },
\ "app/services/*.js": {
\ "command": "service",
\ "template": [
\ "import Ember from 'ember';",
\ "",
\ "export default Ember.Service.extend({",
\ "",
\ "});",
\ ],
\ "alternate": "tests/unit/services/{}-test.js"
\ },
\ "app/initializers/*.js": { "command": "initializer" },
\ "app/router.js": {
\ "command": "router"
\ },
\ "app/routes/*.js": {
\ "command": "route",
\ "template": [
\ "import Ember from 'ember';",
\ "",
\ "export default Ember.Route.extend({",
\ " model: function() {",
\ " ",
\ " }",
\ "});",
\ ],
\ "alternate": "app/controllers/{}.js"
\ },
\ "app/styles/*.sass": {
\ "command": "style",
\ "template": ["/* {}.sass */", ' ']
\ },
\ "app/styles/*.css": {
\ "command": "css",
\ "template": ["/* {}.css */", ' ']
\ },
\ "app/templates/*.hbs": {
\ 'command': 'template',
\ 'template': ["{open}{open}outlet{close}{close}", " "],
\ 'alternate': "app/controllers/{}.js"
\ },
\ "app/utils/*.js": {
\ "command": "util"
\ },
\ "app/views/*.js": {
\ "command": "view",
\ "template": [
\ "export default Ember.View.extend({",
\ "",
\ "});",
\ ],
\ "alternate": "tests/unit/views/{}-test.js"
\ },
\ "bower.json": { "command": "bower" },
\ "package.json": { "command": "package" },
\ "": { "command": "readme" }
\ }
\ }
set formatoptions=1
set linebreak
set breakat=\ ^I!@*-+;:,./?\(\[\{
set nocompatible " be iMproved
filetype off " required!
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()
autocmd! bufwritepost vundle source ~/.vim/vundle
" let Vundle manage Vundle
" required!
Bundle 'gmarik/vundle'
" project wide search
Bundle 'mileszs/ack.vim'
" Bundle 'rking/ag.vim'
" Yaml stuff
Bundle 'avakhov/vim-yaml'
" cmd-t replacement
Bundle 'ctrlpvim/ctrlp.vim'
" open splits from quickfix
Bundle 'yssl/QFEnter'
" comment multiple lines
Bundle 'scrooloose/nerdcommenter'
" project drawer
Bundle 'scrooloose/nerdtree'
Bundle 'Xuyuanp/nerdtree-git-plugin'
" makes NERDTree awesome if you use tabs
Bundle 'jistr/vim-nerdtree-tabs'
" tab completion like textmate for snippets
Bundle 'garbas/vim-snipmate'
" vim-snipmate dependency
Bundle 'tomtom/tlib_vim'
" vim-snipmate dependency
Bundle 'MarcWeber/vim-addon-mw-utils'
" vim-snipmate dependency
Bundle 'honza/vim-snippets'
" TODO think about removing this
Bundle 'ervandew/supertab'
" syntax checking on save
Bundle 'scrooloose/syntastic'
" aligning => stuff
" Bundle 'junegunn/vim-easy-align'
Bundle 'godlygeek/tabular'
" drawer showing ctags
Bundle 'majutsushi/tagbar'
" easily switch between buffers
Bundle 'jeetsukumaran/vim-buffergator'
" enabled .feature files
Bundle 'jondkinney/vim-cucumber'
" <leader><leader>w jump to highlighted word
Bundle 'Lokaltog/vim-easymotion'
" auto adds end to method definitions, blocks, etc
Bundle 'tpope/vim-endwise'
" git wrapper
Bundle 'tpope/vim-fugitive'
" some vim runtime files that are more up to date than those distributed with vim itself
Bundle 'tpope/vim-git'
" enabled .haml extension
Bundle 'tpope/vim-haml'
" show indent guides to the left of the methods
Bundle 'nathanaelkane/vim-indent-guides'
" some nice text wrappers for editing erb or html, ctrl+x in insert mode then type = or - or @ or #,etc
Bundle 'tpope/vim-ragtag'
" essential rails plugin for navigating a rails proj
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-projectionist'
" easily change what something is surrounded by
Bundle 'tpope/vim-surround'
" repeat surround (and other) changes with .
Bundle 'tpope/vim-repeat'
" allows for moving blocks of text up and down in place like you could in textmate
Bundle 'tpope/vim-unimpaired'
" Smart selection between pairs
Bundle 'gorkunov/smartpairs.vim'
" theme
" Bundle 'altercation/vim-colors-solarized'
Bundle 'lifepillar/vim-solarized8'
" lets you ctrl+w+o to toggle out a split to it's own buffer (easily can go back with the same command)
Bundle 'vim-scripts/ZoomWin'
" Proper syntax highlighting and commenting capabilities inside a tmux conf file
Bundle 'tmux-plugins/vim-tmux'
" Regain focus events for terminal vim
Bundle 'tmux-plugins/vim-tmux-focus-events'
" show project wide list of TODO, NOTE, FIXME
Bundle 'LStinson/TagmaTasks'
" strip trailing whitespace on save
Bundle 'itspriddle/vim-stripper'
" enable coffeescript
Bundle 'kchmck/vim-coffee-script'
" highlights Gemfile and wraps bundle open
Bundle 'tpope/vim-bundler'
" tig inside of vim with more power to traverse file history
Bundle 'gregsexton/gitv'
" cycle through yanks/deletes in a visual window or after pasting
Bundle 'vim-scripts/YankRing.vim'
" undo tree history navigation
Bundle 'sjl/gundo.vim'
" Gist things
Bundle 'mattn/gist-vim'
" dependency of gist-vim
Bundle 'mattn/webapi-vim'
" better vertical column selection / changing (vic will visual in column)
Bundle 'coderifous/textobj-word-column.vim'
" show diff in the left gutter
Bundle 'airblade/vim-gitgutter'
" Bundle 'mhinz/vim-signify'
" gives a count of the number of matches and which one you're on
" I added the ability to not jump to the next item immediately, but it has since been merged back.
Bundle 'henrik/vim-indexed-search'
" Project wide find and replace
Bundle 'henrik/vim-qargs'
" Don't jump to the next search, stay on current one
Bundle 'bronson/vim-visual-star-search'
" ensures windows are at least 80 chars wide (my PR added the ability to ignore a list of additional bufnames)
Bundle 'justincampbell/vim-eighties'
" better incremental search, highlights in realtime everywhere as you type
Bundle 'haya14busa/incsearch.vim'
" navigate with C-h/j/k/l in tmux and vim
Bundle 'christoomey/vim-tmux-navigator'
" like sublime multiple cursors
Bundle 'terryma/vim-multiple-cursors'
Bundle 'vim-airline/vim-airline'
Bundle 'vim-airline/vim-airline-themes'
Bundle 'edkolev/tmuxline.vim'
" Tabs
" Bundle 'gcmt/taboo.vim'
" For writing Prose
Bundle 'kana/vim-textobj-user'
Bundle 'reedes/vim-pencil'
Bundle 'reedes/vim-lexical'
Bundle 'reedes/vim-litecorrect'
Bundle 'reedes/vim-textobj-sentence'
Bundle 'reedes/vim-textobj-quote'
Bundle 'jonhiggs/MacDict.vim'
" Execute lines of code in Vim and show the results
Bundle 't9md/vim-ruby-xmpfilter'
Bundle 'metakirby5/codi.vim'
" Select ruby blocks
Bundle 'nelstrom/vim-textobj-rubyblock'
" Ruby fun
Bundle 'vim-ruby/vim-ruby'
Bundle 'tpope/vim-rake'
" RSpec syntax highlighting improvements
Bundle 'jondkinney/rspec.vim'
" Markdown
" Bundle 'tpope/vim-markdown'
Bundle 'plasticboy/vim-markdown'
Bundle 'itspriddle/vim-marked'
Bundle 'suan/vim-instant-markdown'
" Slim template syntax highlighting
Bundle 'igas/vim-slim'
" Dash docs
if has("unix")
let s:uname = system("uname")
if s:uname == "Darwin\n"
" Do Mac stuff here
Bundle 'rizzatti/funcoo.vim'
Bundle 'rizzatti/dash.vim'
" Browser Reloading from Vim
Bundle 'tell-k/vim-browsereload-mac'
Bundle 'Shougo/vimproc.vim'
" Handlebars templates
Bundle 'mustache/vim-mustache-handlebars'
" refactor model names
Bundle 'ecomba/vim-ruby-refactoring'
" Dependency of vim-ruby-refactoring
Bundle 'tpope/vim-abolish'
" Parses and displays x or check in the gutter for covered lines through cadre
" You need to install the cadre gem and have it all setup like I do for Bolstr.
Bundle 'killphi/vim-legend'
" Auto-fold files upon open. Disable session-wide with: <leader>nf
Bundle 'bruno-/vim-ruby-fold'
" Bundle 'othree/yajs.vim'
" Bundle 'othree/javascript-libraries-syntax.vim'
Bundle 'pangloss/vim-javascript'
Bundle 'glanotte/vim-jasmine'
" Less good than sass... so, yea
Bundle 'groenewege/vim-less'
" .env file editing in vim (syntax highlighting, mostly)
Bundle 'tpope/vim-dotenv'
" Personal wiki in vim! I keep a lot of client notes in here.
Bundle 'vimwiki/vimwiki'
Bundle 'mattn/calendar-vim'
" Brewfile syntax
Bundle 'bfontaine/Brewfile.vim'
" thoughtbot vim-rspec send to tmux, vim-dispatch, etc
Bundle 'thoughtbot/vim-rspec'
Bundle 'benmills/vimux'
" vim-react-snippets:
Bundle 'justinj/vim-react-snippets'
Bundle 'mxw/vim-jsx'
" CodeClimage
Bundle 'wfleming/vim-codeclimate'
" Test runner
Bundle 'janko-m/vim-test'
" Bundle 'ramele/agrep'
" Async, but slow. Try again soon-ish though.
Bundle 'KurtPreston/vim-autoformat-rails'
Bundle 'chrisbra/csv.vim'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment