Full Code of mhinz/dotfiles for AI

master 4f868c1f9c00 cached
110 files
225.9 KB
76.1k tokens
9 symbols
1 requests
Download .txt
Showing preview only (250K chars total). Download the full file or copy to clipboard to get everything.
Repository: mhinz/dotfiles
Branch: master
Commit: 4f868c1f9c00
Files: 110
Total size: 225.9 KB

Directory structure:
gitextract_0vxcr2cu/

├── .Xdefaults
├── .Xmodmap
├── .bash_profile
├── .bashrc
├── .config/
│   ├── git/
│   │   ├── config
│   │   ├── config.colors.dark
│   │   ├── config.colors.light
│   │   └── template/
│   │       └── hooks/
│   │           ├── post-applypatch
│   │           ├── post-checkout
│   │           ├── post-commit
│   │           ├── post-merge
│   │           ├── post-rewrite
│   │           └── pre-commit
│   ├── karabiner/
│   │   └── assets/
│   │       └── complex_modifications/
│   │           ├── any.json
│   │           └── keychron-k6.json
│   └── rg/
│       └── rgrc
├── .ctags
├── .emacs.d/
│   ├── configs/
│   │   ├── erlang.el
│   │   └── haskell.el
│   └── init.el
├── .gemrc
├── .gitignore
├── .gnupg/
│   ├── gpg-agent.conf
│   └── gpg.conf
├── .hgrc
├── .iex.exs
├── .inputrc
├── .irbrc
├── .lldbinit
├── .macos
├── .misc/
│   ├── YellowLight.itermcolors
│   └── neovim-local.mk
├── .profile
├── .pryrc
├── .psqlrc
├── .pypirc
├── .rtorrent.rc
├── .shrc
├── .tmux.conf
├── .travis.yml
├── .vim/
│   ├── autoload/
│   │   └── mhi.vim
│   ├── colors/
│   │   └── fnord.vim
│   ├── lua/
│   │   └── config.lua
│   └── vimrc
├── .weechat/
│   └── weechat.conf
├── .xinitrc
├── .yarnrc
├── .zsh/
│   ├── .zlogout
│   ├── .zprofile
│   ├── .zshrc
│   ├── completion/
│   │   └── _mix
│   ├── dircolors.dark
│   └── dircolors.light
├── .zshenv
├── README.md
├── bin/
│   ├── battery
│   ├── book
│   ├── book.erl
│   ├── book.go
│   ├── bootstrap-homebrew
│   ├── bootstrap-host
│   ├── bootstrap-ruby
│   ├── bootstrap-vim
│   ├── build-angband
│   ├── build-elixir
│   ├── build-erlang
│   ├── build-git
│   ├── build-go
│   ├── build-htop
│   ├── build-tmux
│   ├── build-vim
│   ├── build-zsh
│   ├── busy
│   ├── c_rocks
│   ├── dotfiles
│   ├── ec
│   ├── english
│   ├── english-notification
│   ├── fix-term
│   ├── gem-info
│   ├── git-ctags
│   ├── git-neck
│   ├── git-standup
│   ├── git-to
│   ├── git-trail
│   ├── git-whereami
│   ├── itb
│   ├── man
│   ├── markov
│   ├── mhi
│   ├── mhi-fix
│   ├── mhi-net
│   ├── numsys
│   ├── s3cp
│   ├── s3ls
│   ├── s3rm
│   ├── s3screenshot
│   ├── shell_function_missing
│   ├── svn-clean
│   ├── svn-stats
│   ├── task
│   ├── tips
│   ├── twump
│   ├── unbook
│   ├── unixsniff
│   ├── vm
│   ├── weasel
│   ├── wlan
│   └── zproc
└── english.yaml

================================================
FILE CONTENTS
================================================

================================================
FILE: .Xdefaults
================================================
!!!  MISC  !!!
Xcursor.theme:            redglass
Xcursor.size:             28

Eclipse*fontList:         -*-terminus-*-*-*-*-*-*-*-*-*-*-*-*
gitk*font:                -*-terminus-medium-*-*-*-12-*-*-*-*-*-*-*

xpdf*background:          #eeeeec
xpdf*fontList:            -*-terminus-medium-*-*-*-12-*-*-*-*-*-*-*
xpdf*foreground:          #2e3436
xpdf*initialZoom:         width
xpdf*shadowThickness:     1

urxvt*foreground:         #bebebe
urxvt*background:         #202020
!urxvt*background:         #412e21
urxvt*boldMode:           false
urxvt*meta8:              false
!urxvt*letterSpace: +1
!urxvt*font:               xft:Inconsolata:pixelsize=12:dpi=96
!urxvt*font:               -xos4-terminus-medium-r-normal--14-*-*-*-*-*-iso10646-*
urxvt*font:               xft:DejaVu Sans Mono:pixelsize=12
!urxvt*font:               xft:Ubuntu Mono:style=Regular:pixelsize=14
!urxvt*font:               xft:Droid Sans Mono:style=Regular:pixelsize=13


!!!  URXVT  !!!
urxvt*cursorColor:        #ffaa77
urxvt*matcher.button:     1
urxvt*matcher.pattern.1:  \\bwww\\.[\\w-]+\\.[\\w./?&@#-=]*[\\w/-]
urxvt*matcher.pattern.2:  \\bhttps?:\/\/[\\w-.]*\/[\\w./?&@#-=]*.(jpg|jpeg|png)
urxvt*matcher.launcher.2: feh $0
urxvt*perl-lib:           .urxvt
urxvt*perl-ext-common:    default,matcher,font-size
urxvt*urlLauncher:        firefox
urxvt*pointerColor:       yellow
urxvt*saveLines:          10000
urxvt*scrollBar:          false
urxvt*termName:           rxvt-256color
urxvt*tripleclickwords:   true
urxvt*underlineColor:     #CC6666
urxvt.keysym.C-Up:        perl:font-size:increase
urxvt.keysym.C-Down:      perl:font-size:decrease
!urxvt*fading:            20
!urxvt*shading:           5
!urxvt*transparent:       true

! black
urxvt*color0:   #000000
urxvt*color8:   #505050
! red
urxvt*color1:   #ff669d
urxvt*color9:   #d04c63
! green
urxvt*color2:   #B3D38C
urxvt*color10:  #93D6A9
! yellow
urxvt*color3:   #efaf7f
urxvt*color11:  #f4a45f
! blue
urxvt*color4:   #344863
urxvt*color12:  #80c0d9
! magenta
urxvt*color5:   #CCA3B3
urxvt*color13:  #AA66AA
! cyan
urxvt*color6:   #0b94a0
urxvt*color14:  #96cccc
! white
urxvt*color7:   white
urxvt*color15:  darkgray

! black
urxvt2*color0:   #000000
urxvt2*color8:   #505050
! red
urxvt2*color1:   #ff669d
urxvt2*color9:   #d04c63
! green
urxvt2*color2:   #B3D38C
urxvt2*color10:  #93D6A9
! yellow
urxvt2*color3:   #efaf7f
urxvt2*color11:  #f4a45f
! blue
urxvt2*color4:   #344863
urxvt2*color12:  #80c0d9
! magenta
urxvt2*color5:   #CCA3B3
urxvt2*color13:  #AA66AA
! cyan
urxvt2*color6:   #0b94a0
urxvt2*color14:  #96cccc
! white
urxvt2*color7:   white
urxvt2*color15:  darkgray

! Pnevma 2
!urxvt*color0:  #2F2E2D
!urxvt*color8:  #4A4845
!urxvt*color1:  #A36666
!urxvt*color9:  #D78787
!urxvt*color2:  #8FA57E
!urxvt*color10: #A9BA9C
!urxvt*color3:  #D7AF87
!urxvt*color11: #E4C9AF
!urxvt*color4:  #7FA5BD
!urxvt*color12: #A1BDCE
!urxvt*color5:  #C79EC4
!urxvt*color13: #D7BEDA
!urxvt*color6:  #8ADBB4
!urxvt*color14: #B1E7DD
!urxvt*color7:  #D0D0D0
!urxvt*color15: #EFEFEF

!urxvt2*font:               -xos4-terminus-medium-r-normal--18-140-72-72-c-80-iso10646-1
!urxvt2*font:               -*-terminus-medium-r-*-*-24-*-*-*-*-*-*-*
urxvt2*foreground:         #222
!urxvt2*background:         #f5f5f0
urxvt2*background:         #ccc
!urxvt2*font:               xft:DejaVu Sans Mono:pixelsize=16:style=bold
urxvt2*font:               xft:DejaVu Sans Mono:pixelsize=12
!urxvt2*font:               xft:DejaVu Sans Mono:pixelsize=16
!urxvt2*foreground:         #000
!urxvt2*background:         #eee
!urxvt2*cursorColor:        #000

urxvt2*cursorColor:        #2069ff
urxvt2*boldMode:           true
urxvt2*matcher.button:     1
urxvt2*matcher.launcher.2: feh $0
urxvt2*matcher.pattern.1:  \\bwww\\.[\\w-]+\\.[\\w./?&@#-]*[\\w/-]
urxvt2*matcher.pattern.2:  \\bhttps?:\/\/[\\w-.]*\/[\\w./?&@#=-]*.(jpg|jpeg|png)
urxvt2*perl-ext-common:    default,matcher
urxvt2*pointerColor:       yellow
urxvt2*saveLines:          10000
urxvt2*scrollBar:          false
urxvt2*termName:           rxvt-256color
urxvt2*tripleclickwords:   true
urxvt2*underlineColor:     #CC6666
urxvt2*urlLauncher:        iceweasel


!!!  XTERM  !!!
xterm*allowWindowOps:     true
!xterm*background:         #eee
xterm*boldMode:           true
xterm*colorMode:          true
xterm*cursorColor:        #f77
xterm*dynamicColors:      true
xterm*eightBitInput:      false
!xterm*faceName:           DejaVu Sans Mono:pixelsize=12:style=bold
!xterm*foreground:         #000
xterm*printAtrributes:    2
xterm*utf8:               true

xterm*foreground:         #bebebe
xterm*background:         #202020

xft*dpi:                  96
xft*antialias:            true
xft*rgba:                 rgb
xft*hinting:              true

!black
!*color0: #1B1D1E
!*color8: #505354
!*color0: #262729
!*color8: #554444
!red
!*color1: #F92672
!*color9: #FF669D
!green
!*color2: #A6E22E
!*color10: #BEED5F
!yellow
!*color3: #FD971F
!*color11: #E6DB74
!blue
!*color4: #66D9EF
!*color12: #66D9EF
!magenta
!*color5: #9E6FFE
!*color13: #9E6FFE
!cyan
!*color6: #5E7175
!*color14: #A3BABF
!white
!*color7: #CCCCC6
!*color15: #F8F8F2


================================================
FILE: .Xmodmap
================================================
remove Lock = Caps_Lock
keysym Caps_Lock = Control_L
add Control = Control_L

keycode 94 = parenleft parenright bar brokenbar bar brokenbar
keycode 92 = Multi_key


================================================
FILE: .bash_profile
================================================
if [[ -r ~/.profile ]]; then
  . $HOME/.profile
else
  echo 'No ~/.profile found.'
fi

# bashrc doesn't get sourced for login shells; do it here.

if [[ $- == *i* ]]; then
  if [[ -r ~/.bashrc ]]; then
    . $HOME/.bashrc
  else
    echo 'No ~/.bashrc found.'
  fi
fi


================================================
FILE: .bashrc
================================================
if [[ -r $HOME/.shrc ]]; then
  . $HOME/.shrc
else
  echo 'No .shrc found.'
fi

shopt -s globstar

stty werase undef
bind '\C-w:unix-filename-rubout'

PROMPT_COMMAND=_prompt

[[ -n $KITTY_WINDOW_ID ]] && trap 'printf "\033]0;%s\007" "${BASH_COMMAND/_prompt/bash}"' DEBUG


================================================
FILE: .config/git/config
================================================
; Config {{{1
[user]
  name       = Marco Hinz
  email      = mh.codebro@gmail.com
  signingKey = D56EA60F557FD8B6
[core]
  editor       = nvr --remote-wait-silent
  excludesfile = ~/.config/git/ignore
  autocrlf     = false
  filemode     = false
[init]
  templatedir = ~/.config/git/template
  defaultBranch = main
[commit]
  gpgsign = true
[fetch]
  prune = true
  writeCommitGraph = true
[pull]
  ff = only
[push]
  default = current
  followTags = true
[rebase]
  autosquash = true
  autostash  = true
[tag]
  sort = version:refname
[rerere]
  enabled = true
[advice]
  detachedHead = no
  statusHints = no
[pack]
  writeReverseIndex = true
[diff]
  tool                = nvr
  algorithm           = patience
  mnemonicPrefix      = true
  compactionHeuristic = true
[difftool "nvr"]
  cmd = nvr -sd $LOCAL $REMOTE
[merge]
  tool = nvr
  conflictstyle = diff3
[mergetool]
  keepBackup = false
[mergetool "nvr"]
  cmd           = nvr -sd $LOCAL $BASE $REMOTE $MERGED -c 'winc J | winc ='
  trustExitCode = true

; Aliases {{{1
[alias]
  a        = add
  b        = branch
  bi       = bisect
  bl       = blame
  c        = commit
  ca       = commit --amend
  caa      = commit --amend --no-edit
  cf       = commit --fixup
  cl       = clone
  co       = checkout
  codate   = "!f() { git checkout `git rev-list -n1 --before \"$@\" HEAD`; }; f"
  cp       = cherry-pick
  d        = diff --color --no-ext-diff
  dc       = !git d --cached
  dcs      = !git d --cached --stat
  des      = describe --contains
  ds       = !git d --stat
  dt       = difftool
  dw       = !git d --word-diff=color
  f        = fetch
  g        = grep
  h        = help
  lfp      = !git l --first-parent
  ln       = !git l @{1}..
  ls       = "!f() { git ls-files | grep "${@:-''}"; }; f"
  lso      = ls-files --others --exclude-standard
  lsr      = ls-remote
  m        = merge
  ma       = merge --abort
  mt       = mergetool
  n        = name-rev --name-only
  p        = push
  pl       = pull --ff-only
  plr      = pull --rebase origin master
  r        = reset
  ra       = rebase --abort
  rc       = rebase --continue
  re       = rebase
  rem      = remote
  ri       = rebase -i --keep-empty
  rs       = rebase --skip
  ru       = remote update
  s        = status --short --branch --untracked-files=no
  sh       = show
  shs      = show --stat
  st       = stash
  stl      = stash list
  sts      = stash show -p
  t        = tag
  tr       = trail
  unmerged = branch --no-merged master
  wt       = worktree

  rehook = "!f() { cd \"$(git rev-parse --show-toplevel)\"; rm -r .git/hooks; git init; }; f"

  description = !git config --get "branch.$(git rev-parse --abbrev-ref HEAD).description"

  snapshot = !git stash push "snapshot: $(date)" && git stash apply "stash@{0}"

  ours   = !git checkout --ours $@ && git add $@
  theirs = !git checkout --theirs $@ && git add $@

  rank    = shortlog -sn --no-merges
  authors = "!f() { git log --no-merges --pretty='format:%<(26)%an <%ae>' --author \"$*\" | sort | uniq; }; f"
  by      = "!f() { IFS=$'\n'; select a in `git authors \"$*\"`; do git l --no-merges --author \"${a%%  *<*}\"; break; done; }; f"

  upstream = !git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD)
  upstream-remote = !git upstream | sed -e 's/\\/.*$//g'

; Colors {{{1
[color]
  branch      = auto
  diff        = auto
  interactive = auto
  status      = auto
  ui          = auto
[include]
  path = config.colors


================================================
FILE: .config/git/config.colors.dark
================================================
[alias]
    l = log --graph --pretty='%C(242)%h %C(156)%s %C(248)%an%C(242), %C(248)%ar%C(222)%d' --decorate --date=relative

[color "diff"]
    frag       = 104
    func       = 74
    meta       = 137 bold
    new        = 114
    old        = 167
    plain      = 240
    whitespace = 24 24

[color "status"]
    header = 240
    branch = yellow


================================================
FILE: .config/git/config.colors.light
================================================
[alias]
    l = log --graph --pretty='%C(245)%h %C(16)%s %C(reset)%C(ul 245)%an%C(reset), %C(248)%ar%C(124)%d' --decorate --date=relative

[color "diff"]
    new        = 28
    old        = 124
    context    = 248
    commit     = 16 bold
    frag       = 16
    func       = 16
    meta       = 16 bold
    whitespace = 27 27

[color "status"]
    header = 240
    branch = yellow


================================================
FILE: .config/git/template/hooks/post-applypatch
================================================
#!/usr/bin/env bash

if [[ "$(uname -s)" = Darwin ]]; then
    osascript <<EOF
    display notification "git-ctags: `pwd`" with title "post-applypatch"
EOF
fi

~/bin/git-ctags &>/dev/null &


================================================
FILE: .config/git/template/hooks/post-checkout
================================================
#!/usr/bin/env bash

if [[ "$(uname -s)" = Darwin ]]; then
    osascript <<EOF
    display notification "git-ctags: `pwd`" with title "post-checkout"
EOF
fi

~/bin/git-ctags &>/dev/null &

if [[ $1 != 0000000000000000000000000000000000000000 ]] \
    && [[ $3 -eq 1 ]] \
    && git diff --name-only $1 $2 | egrep -q '^Gemfile|\.gemspec$' \
    && command -v bundle &>/dev/null
then
    exec bundle
fi


================================================
FILE: .config/git/template/hooks/post-commit
================================================
#!/usr/bin/env bash

if [[ "$(uname -s)" = Darwin ]]; then
    osascript <<EOF
    display notification "git-ctags: `pwd`" with title "post-commit"
EOF
fi

~/bin/git-ctags &>/dev/null &


================================================
FILE: .config/git/template/hooks/post-merge
================================================
#!/usr/bin/env bash

if [[ "$(uname -s)" = Darwin ]]; then
    osascript <<EOF
    display notification "git-ctags: `pwd`" with title "post-merge"
EOF
fi

~/bin/git-ctags &>/dev/null &


================================================
FILE: .config/git/template/hooks/post-rewrite
================================================
#!/usr/bin/env bash

case "$1" in
    rebase)
        if [[ "$(uname -s)" = Darwin ]]; then
            osascript <<EOF
            display notification "git-ctags: `pwd`" with title "post-rewrite"
EOF
        fi
        ~/bin/git-ctags &>/dev/null &
        ;;
esac


================================================
FILE: .config/git/template/hooks/pre-commit
================================================
#!/usr/bin/env bash

if git rev-parse --verify HEAD &>/dev/null; then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

exec git diff-index --check --cached $against --


================================================
FILE: .config/karabiner/assets/complex_modifications/any.json
================================================
{
  "title": "Any",
  "rules": [
    {
      "manipulators": [
        {
          "description": "(Any) caps_lock > left_control, caps_lock alone > escape",
          "from": {
            "key_code": "caps_lock"
          },
          "to": [
            {
              "key_code": "left_control",
              "lazy": true
            }
          ],
          "to_if_alone": [
            {
              "key_code": "escape"
            }
          ],
          "type": "basic"
        }
      ]
    }
  ]
}


================================================
FILE: .config/karabiner/assets/complex_modifications/keychron-k6.json
================================================
{
  "title": "Keychron K6",
  "rules": [
    {
      "description": "(Keychron K6) left_shift alone > `",
      "manipulators": [
        {
          "conditions": [
            {
              "type": "device_if",
              "identifiers": [
                {
                  "product_id": 591,
                  "vendor_id": 1452
               }
              ]
            }
          ],
          "from": {
            "key_code": "left_shift"
          },
          "to": [
            {
              "key_code": "left_shift"
            }
          ],
          "to_if_alone": [
            {
              "key_code": "grave_accent_and_tilde"
            }
          ],
          "type": "basic"
        }
      ]
    },
    {
      "description": "(Keychron K6) right_shift alone > ~",
      "manipulators": [
        {
          "conditions": [
            {
              "type": "device_if",
              "identifiers": [
                {
                  "product_id": 591,
                  "vendor_id": 1452
                }
              ]
            }
          ],
          "from": {
            "key_code": "right_shift"
          },
          "to": [
            {
              "key_code": "right_shift"
            }
          ],
          "to_if_alone": [
            {
              "key_code": "grave_accent_and_tilde",
              "modifiers": [
                "left_shift"
              ]
            }
          ],
          "type": "basic"
        }
      ]
    }
  ]
}


================================================
FILE: .config/rg/rgrc
================================================
--hidden
--no-ignore
--smart-case


================================================
FILE: .ctags
================================================
--regex-ruby=/(^|[:;])[ \t]*([A-Z][[:alnum:]_]+) *=/\2/c,class,constant/
--regex-ruby=/^[ \t]*attr_(reader|writer|accessor) (:[a-z0-9_]+, )*:([a-z0-9_]+)/\3/A,attr/

--langdef=elixir
--langmap=elixir:.ex.exs
--regex-elixir=/^[ \t]*def(p?)[ \t]+([a-z_][a-zA-Z0-9_?!]*)/\2/f,functions,functions (def ...)/
--regex-elixir=/^[ \t]*defcallback[ \t]+([a-z_][a-zA-Z0-9_?!]*)/\1/c,callbacks,callbacks (defcallback ...)/
--regex-elixir=/^[ \t]*defdelegate[ \t]+([a-z_][a-zA-Z0-9_?!]*)/\1/d,delegates,delegates (defdelegate ...)/
--regex-elixir=/^[ \t]*defexception[ \t]+([A-Z][a-zA-Z0-9_]*\.)*([A-Z][a-zA-Z0-9_?!]*)/\2/e,exceptions,exceptions (defexception ...)/
--regex-elixir=/^[ \t]*defimpl[ \t]+([A-Z][a-zA-Z0-9_]*\.)*([A-Z][a-zA-Z0-9_?!]*)/\2/i,implementations,implementations (defimpl ...)/
--regex-elixir=/^[ \t]*defmacro(p?)[ \t]+([a-z_][a-zA-Z0-9_?!]*)\(/\2/a,macros,macros (defmacro ...)/
--regex-elixir=/^[ \t]*defmacro(p?)[ \t]+([a-zA-Z0-9_?!]+)?[ \t]+([^ \tA-Za-z0-9_]+)[ \t]*[a-zA-Z0-9_!?!]/\3/o,operators,operators (e.g. "defmacro a <<< b")/
--regex-elixir=/^[ \t]*defmodule[ \t]+([A-Z][a-zA-Z0-9_]*\.)*([A-Z][a-zA-Z0-9_?!]*)/\2/m,modules,modules (defmodule ...)/
--regex-elixir=/^[ \t]*defprotocol[ \t]+([A-Z][a-zA-Z0-9_]*\.)*([A-Z][a-zA-Z0-9_?!]*)/\2/p,protocols,protocols (defprotocol...)/
--regex-elixir=/^[ \t]*Record\.defrecord[ \t]+:([a-zA-Z0-9_]+)/\1/r,records,records (defrecord...)/


================================================
FILE: .emacs.d/configs/erlang.el
================================================
(setq erlang-root-dir "~/local/erlang/lib/erlang/erts-6.3.1")
(setq exec-path (cons "~/local/erlang/lib/erlang/erts-6.3.1/bin" exec-path))
(require 'erlang-start)


================================================
FILE: .emacs.d/configs/haskell.el
================================================
(require 'haskell-mode-autoloads)

(custom-set-variables
 '(haskell-process-auto-import-loaded-modules t)
 '(haskell-process-log t)
 '(haskell-process-suggest-remove-import-lines t)
 '(haskell-process-type (quote cabal-repl))
 '(haskell-tags-on-save t))

(add-to-list 'Info-default-directory-list "~/.emacs.d/packages/haskell-mode")

(eval-after-load 'haskell-mode '(progn
				  (interactive-haskell-mode)
				  (define-key haskell-mode-map [f8] 'haskell-navigate-imports)
				  (define-key haskell-mode-map (kbd "C-c C-l") 'haskell-process-load-or-reload)
				  (define-key haskell-mode-map (kbd "C-c C-z") 'haskell-interactive-switch)
				  (define-key haskell-mode-map (kbd "C-c C-n C-t") 'haskell-process-do-type)
				  (define-key haskell-mode-map (kbd "C-c C-n C-i") 'haskell-process-do-info)
				  (define-key haskell-mode-map (kbd "C-c C-n C-c") 'haskell-process-cabal-build)
				  (define-key haskell-mode-map (kbd "C-c C-n c") 'haskell-process-cabal)
				  (define-key haskell-mode-map (kbd "C-c SPC") 'haskell-mode-contextual-space)))

(let ((my-cabal-path (expand-file-name "~/.cabal/bin")))
  (setenv "PATH" (concat my-cabal-path ":" (getenv "PATH")))
  (add-to-list 'exec-path my-cabal-path))

(eval-after-load 'haskell-cabal '(progn
				   (define-key haskell-cabal-mode-map (kbd "C-c C-c") 'haskell-process-cabal-build)
				   (define-key haskell-cabal-mode-map (kbd "C-c c") 'haskell-process-cabal)
				   (define-key haskell-cabal-mode-map (kbd "C-c C-k") 'haskell-interactive-mode-clear)))
;;				   (define-key haskell-cabal-mode-map (bkd "C-c C-z") 'haskell-interactive-switch)))


================================================
FILE: .emacs.d/init.el
================================================
(when (< emacs-major-version 24)
  (princ "Install at least Emacs 24.\n" #'external-debugging-output)
  (kill-emacs))

(when (member "Source Code Pro" (font-family-list))
  (set-default-font "Source Code Pro-13"))

(if (fboundp 'tool-bar-mode)     (tool-bar-mode 0))
(if (fboundp 'toggle-scroll-bar) (toggle-scroll-bar 0))
(menu-bar-mode 0)

(setq ring-bell-function 'ignore)
(setq inhibit-splash-screen t)
(setq inhibit-startup-message t)
(setq custom-file "~/.emacs.d/custom.el")

(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/") t)
(add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/") t)
(package-initialize)

(unless (package-installed-p 'use-package)
  (package-refresh-contents)
  (package-install 'use-package))

(eval-and-compile
  (defvar use-package-verbose t)
  (require 'cl)
  (require 'use-package)
  (require 'bind-key)
  (setq use-package-always-ensure t))

(defalias 'yes-or-no-p 'y-or-n-p)

(setq backup-directory-alist
      `((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
      `((".*" ,temporary-file-directory t)))

(let ((week (* 60 60 24 7))
      (current (float-time (current-time))))
  (dolist (file (directory-files temporary-file-directory t))
    (when (and (backup-file-name-p file)
               (> (- current (float-time (fifth (file-attributes file))))
                  week))
      (message "%s" file)
      (delete-file file))))

(delete-selection-mode +1)

(setq-default tab-width 2)
(setq-default indent-tabs-mode nil)

(when (display-graphic-p)
  (use-package subatomic-theme)
  (toggle-frame-maximized))

(use-package ace-window
  :bind (("M-q" . ace-window)))

(use-package git-gutter
  :config (global-git-gutter-mode 1))

(use-package avy
  :bind* ("C-," . avy-goto-char-2))

(use-package slime
  :init
  (setq inferior-lisp-program "sbcl")
  (setq slime-contribs '(slime-fancy)))

(unless (and (fboundp 'server-running-p)
             (server-running-p))
  (server-start))

(if (file-readable-p custom-file)
    (load custom-file))


================================================
FILE: .gemrc
================================================
:update_sources: true
:bulk_threshold: 1000
:verbose: true
:benchmark: false
:backtrace: false
gem: --no-document


================================================
FILE: .gitignore
================================================
/*/
!/bin/
!.*
/.git/


================================================
FILE: .gnupg/gpg-agent.conf
================================================
pinentry-program /usr/local/bin/pinentry-mac
default-cache-ttl 7200


================================================
FILE: .gnupg/gpg.conf
================================================
personal-digest-preferences SHA256
cert-digest-algo SHA256
default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed
keyid-format long

keyserver hkps://hkps.pool.sks-keyservers.net
keyserver-options no-honor-keyserver-url


================================================
FILE: .hgrc
================================================
[ui]
username = Marco Hinz <mh.codebro@gmail.com>
color = always

[pager]
pager = LESS='FRX' less

[alias]
a    = add
b    = branch
bi   = bisect
bm   = bookmark
c    = commit
cl   = clone
co   = checkout
d    = diff
g    = grep
h    = help
l    = !hg log -G | LESS=FRX less
m    = merge
p    = push
pl   = pull
r    = revert
rank = !hg churn -t '{author}' -c | less -FRX
s    = status
u    = update

[extensions]
color =
pager =
churn =

[color]
diff.trailingwhitespace = bold red_background


================================================
FILE: .iex.exs
================================================
IEx.configure [
  colors: [
    eval_info:       [:yellow, :bright],
    eval_error:      [:red],
    eval_interrupt:  [:red],
    stack_info:      [:blue],
    doc_code:        [:blue],
    doc_inline_code: [:blue],
    doc_headings:    [:red, :bright],
  ],
  width: 100,
  default_prompt: [
    "\e[G",
    :blue,
    :bright,
    "%prefix(%counter)>",
  ] |> IO.ANSI.format |> IO.chardata_to_string
]

defmodule Mex do
  defp expand_all(n, env) do
    Macro.prewalk(n, &Macro.expand(&1, env))
  end

  defmacro mex(do: block) do
    block
    |> expand_all(__CALLER__)
    |> Macro.to_string
    |> IO.puts

    quote do: :ok
  end
end


================================================
FILE: .inputrc
================================================
set show-all-if-ambiguous on

Control-p: history-search-backward
Control-k: history-search-backward
Control-n: history-search-forward


================================================
FILE: .irbrc
================================================
begin
  require 'pry'
  Pry.start
  exit
rescue LoadError
  require 'irb/completion'
  IRB.conf[:PROMPT_MODE] = :SIMPLE
  warn 'not installed: pry'
end


================================================
FILE: .lldbinit
================================================
command alias ptype target modules lookup -t %1
command alias reload command source -s 1 ~/.lldbinit

settings set target.x86-disassembly-flavor intel
settings set frame-format "frame #${frame.index}: ${frame.pc}{ \x1b\x5b36m${module.file.basename}\x1b\x5b39m{` \x1b\x5b32m${function.name-with-args} \x1b\x5b39m${function.pc-offset}}}{ at \x1b\x5b31m${line.file.basename}\x1b\x5b0m ${line.number}}\n"


================================================
FILE: .macos
================================================
#!/usr/bin/env bash

sudo -v

# Cron {{{1
# This needs full disk access enabled for the calling terminal emulator.
# E.g. Security & Privacy -> Full Disk Access -> iTerm.app
# Reference: https://gitlab.com/gnachman/iterm2/wikis/fulldiskaccess
if crontab -l 2>&1 | grep -qv english; then
  { crontab -l 2>/dev/null; echo "*/30 * * * * ~/bin/english-notification"; } | crontab -
fi

# Defaults {{{1
defaults write ApplePressAndHoldEnabled -bool true
defaults write NSGlobalDomain InitialKeyRepeat -int 20
defaults write NSGlobalDomain KeyRepeat -int 1
defaults write NSRequiresAquaSystemAppearance  -bool true
defaults write com.apple.finder AppleShowAllFiles -boolean true
defaults write com.google.Keystone.Agent checkInterval 172800

# Defaults (need disabled SIP) {{{1
if [[ "$(csrutil status)" =~ enabled ]]; then
  echo 'Disable System Integrity Protection (rootless mode):'
  echo '  * restart'
  echo '  * hold cmd+R to boot into Recovery System'
  echo '  * Utilities -> Terminal'
  echo '  * $ csrutil disable'
  echo '  * restart'
else
  defaults write /System/Library/LaunchAgents/com.apple.mdworker.single LowPriorityBackgroundIO -int 1
  defaults write /System/Library/LaunchAgents/com.apple.mdworker.shared LowPriorityBackgroundIO -int 1
fi

# vim: et sts=2 sw=2


================================================
FILE: .misc/YellowLight.itermcolors
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Ansi 0 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.0</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Ansi 1 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.10676553100347519</real>
		<key>Red Component</key>
		<real>0.789775550365448</real>
	</dict>
	<key>Ansi 10 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.40609359741210938</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.98006147146224976</real>
		<key>Red Component</key>
		<real>0.37424531579017639</real>
	</dict>
	<key>Ansi 11 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.40395939350128174</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.98757272958755493</real>
		<key>Red Component</key>
		<real>0.99950331449508667</real>
	</dict>
	<key>Ansi 12 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.44485551118850708</real>
		<key>Red Component</key>
		<real>0.40937519073486328</real>
	</dict>
	<key>Ansi 13 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.46518981456756592</real>
		<key>Red Component</key>
		<real>1</real>
	</dict>
	<key>Ansi 14 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.99263292551040649</real>
		<key>Red Component</key>
		<real>0.37597531080245972</real>
	</dict>
	<key>Ansi 15 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>1</real>
		<key>Red Component</key>
		<real>0.99999600648880005</real>
	</dict>
	<key>Ansi 2 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.76266151666641235</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Ansi 3 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.76959484815597534</real>
		<key>Red Component</key>
		<real>0.78058648109436035</real>
	</dict>
	<key>Ansi 4 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.78216177225112915</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.14576995372772217</real>
		<key>Red Component</key>
		<real>0.0096152340993285179</real>
	</dict>
	<key>Ansi 5 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.78154844045639038</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.18891248106956482</real>
		<key>Red Component</key>
		<real>0.79022186994552612</real>
	</dict>
	<key>Ansi 6 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.78166204690933228</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.77425903081893921</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Ansi 7 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.78104829788208008</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.78105825185775757</real>
		<key>Red Component</key>
		<real>0.7810397744178772</real>
	</dict>
	<key>Ansi 8 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.4078223705291748</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.40782788395881653</real>
		<key>Red Component</key>
		<real>0.40781760215759277</real>
	</dict>
	<key>Ansi 9 Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.40569943189620972</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.43035173416137695</real>
		<key>Red Component</key>
		<real>1</real>
	</dict>
	<key>Background Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.918487548828125</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.99384576082229614</real>
		<key>Red Component</key>
		<real>1</real>
	</dict>
	<key>Badge Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>0.5</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.1491314172744751</real>
		<key>Red Component</key>
		<real>1</real>
	</dict>
	<key>Bold Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>1</real>
		<key>Red Component</key>
		<real>0.99999600648880005</real>
	</dict>
	<key>Cursor Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.78104829788208008</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.78105825185775757</real>
		<key>Red Component</key>
		<real>0.7810397744178772</real>
	</dict>
	<key>Cursor Guide Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>0.25</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.9268307089805603</real>
		<key>Red Component</key>
		<real>0.70213186740875244</real>
	</dict>
	<key>Cursor Text Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>1</real>
		<key>Red Component</key>
		<real>0.99999600648880005</real>
	</dict>
	<key>Foreground Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.0</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Link Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.73423302173614502</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.35916060209274292</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Selected Text Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>0.0</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.0</real>
		<key>Red Component</key>
		<real>0.0</real>
	</dict>
	<key>Selection Color</key>
	<dict>
		<key>Alpha Component</key>
		<real>1</real>
		<key>Blue Component</key>
		<real>1</real>
		<key>Color Space</key>
		<string>sRGB</string>
		<key>Green Component</key>
		<real>0.86970102787017822</real>
		<key>Red Component</key>
		<real>0.75813239812850952</real>
	</dict>
</dict>
</plist>


================================================
FILE: .misc/neovim-local.mk
================================================
CMAKE_BUILD_TYPE  := Debug
CMAKE_EXTRA_FLAGS := -DCMAKE_INSTALL_PREFIX=${HOME}/local/nvim
USE_BUNDLED       := ON

# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_GETTEXT=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_GPERF=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LIBICONV=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LIBTERMKEY=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LUA=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_MSGPACK=OFF
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_UNIBILIUM=OFF

# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LIBUV=ON
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_BUSTED=ON
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LUAJIT=ON
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LUAROCKS=ON

# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LIBVTERM=ON
# DEPS_CMAKE_FLAGS  += -DUSE_BUNDLED_LUV=ON

.PHONY: all
default: all

.PHONY: info
info:
	@awk -F = '/BUILD_TYPE:/ { print "BUILD_TYPE:", $$2 }' build/CMakeCache.txt
	@awk -F = '/C_COMPILER:/ { print "C_COMPILER:", $$2 }' build/CMakeCache.txt

.PHONY: release
release:
	$(MAKE) CMAKE_BUILD_TYPE=RelWithDebInfo

rebuild-%:
	rm -f .deps/build/src/$*-stamp/$*-build
	DEBUG=1 $(MAKE) deps

.PHONY: cl
cl:
	rm -f errors.json
	wget https://raw.githubusercontent.com/neovim/doc/gh-pages/reports/clint/errors.json
	$(eval FILES = $(shell git diff-tree --name-only --no-commit-id -r master..))
	src/clint.py --suppress-errors=errors.json ${FILES}


================================================
FILE: .profile
================================================
# This file gets sourced by every login shell.

# PATH {{{1
newpath=(
    # homebrew (keg-only)
    /usr/local/sbin
    /usr/local/opt/coreutils/libexec/gnubin
    /usr/local/opt/ncurses/bin
    /usr/local/opt/ruby/bin
    /usr/local/lib/ruby/gems/*/bin
    /usr/local/opt/llvm/bin

    ~/data/go/bin  # $GOPATH
    ~/.npm/bin
    ~/.asdf/bin
    ~/.asdf/shims
    ~/.cargo/bin
    ~/local/*/bin
    ~/bin
)

# Apple's path_helper gets called from /etc/profile and
# /etc/zprofile and mangles $PATH. Work around it.
if [[ -x /usr/libexec/path_helper ]]; then
    PATH=
    eval "$(/usr/libexec/path_helper -s)"
fi

# Only unique elements, please.
for dir in "${newpath[@]}"; do
    case $PATH in
        *:"$dir":*) ;;
        *) [[ -d $dir ]] && PATH="$dir:$PATH" ;;
    esac
done

export PATH
unset newpath dir
# }}}

export ME=$HOME/data
export LANG=en_US.UTF-8

export FZF_DEFAULT_COMMAND="rg --files --hidden --glob '!.git'"
export FZF_DEFAULT_OPTS='--inline-info --color=light'

export RIPGREP_CONFIG_PATH="$HOME/.config/rg/rgrc"

export ELIXIR_EDITOR='ec +__LINE__ __FILE__'

export GOPATH=$ME/go
export GOARCH=amd64
export GOOS="$(uname -s | tr '[:upper:]' '[:lower:]')"

export PGDATA=/usr/local/var/postgres

if   command -v nvim  1>/dev/null; then export EDITOR='nvim'
elif command -v vim   1>/dev/null; then export EDITOR='vim'
elif command -v vi    1>/dev/null; then export EDITOR='vi'
elif command -v emacs 1>/dev/null; then export EDITOR='emacs -nw'
elif command -v nano  1>/dev/null; then export EDITOR='nano'
else echo 'Install a proper editor.'
fi

export MANPATH=/usr/local/opt/coreutils/libexec/gnuman:"$MANPATH"
export MANPATH=/usr/local/opt/erlang/lib/erlang/man:"$MANPATH"
export MANPATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/share/man:"$MANPATH"
export MANWIDTH=82

case "$EDITOR" in
    nvim) export MANPAGER="nvim +'set ft=man' -" ;;
    vim)  export MANPAGER="/bin/sh -c \"col -b | vim -c 'set ft=man ro nomod nolist' -\"" ;;
    *)    export MANPAGER='less' ;;
esac


================================================
FILE: .pryrc
================================================
def line(obj, depth, indent=true)
  print indent ? obj.rjust(depth.to_i + obj.length) : obj
end

def ppp(obj, depth=0, indent=true)
  if obj.is_a? Array
    line "[\n", depth, indent
    obj.each { |v| ppp v, depth+2 }
    line "],\n", depth
  elsif obj.is_a? Hash
    line "{\n", depth, indent
    obj.each do |k,v|
      line "#{k} => ", depth+2
      ppp v, depth+2, false
    end
    line "},\n", depth
  else
    line "#{':' if obj.is_a? Symbol}#{obj},\n", depth, indent
  end
end

# vim: ft=ruby


================================================
FILE: .psqlrc
================================================
\set PROMPT1 '%[%033[0;34m%]%/%R%x%#%[%033[0m%] '
\set PROMPT2 '%[%033[0;33m%]%R%x →%[%033[0m%] '
\x auto


================================================
FILE: .pypirc
================================================
[distutils]
index-servers = pypi

[pypi]
username:mhinz


================================================
FILE: .rtorrent.rc
================================================
directory  = /data/torrent/download
session    = /data/torrent/session

schedule   = low_diskspace,5,60,close_low_diskspace=50M
encryption = allow_incoming,try_outgoing,enable_retry,prefer_plaintext

ip = 127.0.0.1

port_range   = 32537-32537
port_random  = yes

dht           = disable
peer_exchange = false


================================================
FILE: .shrc
================================================
# This file gets sourced by .bashrc and .zshrc.

os="$(uname -s)"

stty discard undef

if [[ -z $THEME ]]; then
    if [[ -n $ITERM_PROFILE  ]]; then
        export THEME=$ITERM_PROFILE
    elif [[ -n $KITTY_WINDOW_ID ]]; then
        export THEME=Light
    else
        export THEME=Dark
    fi
fi

if [[ $THEME = Dark ]]; then
    eval $(dircolors ~/.zsh/dircolors.dark)
    ln -fs \
        ~/.config/git/config.colors.dark \
        ~/.config/git/config.colors
else
    eval $(dircolors ~/.zsh/dircolors.light)
    ln -fs \
        ~/.config/git/config.colors.light \
        ~/.config/git/config.colors
fi

# Prompt {{{1
if [[ -n ${ZSH_VERSION-} ]]; then
    _p_pink='%F{161}'
    _p_red='%F{9}'
    _p_green='%F{46}' # 77
    _p_blue='%F{67}'
    _p_clear='%f%k%b%u'
    _p_bold='%B'
    _p_underline='%U'
    _p_user='%F{19}'
    _p_host='%F{32}'
else
    _p_pink='\[\e[38;5;161m\]'
    _p_red='\[\e[38;5;9m\]'
    _p_green='\[\e[38;5;46m\]'
    _p_blue='\[\e[38;5;67m\]'
    _p_clear='\[\e[0m\]'
    _p_bold='\[\e[1m\]'
    _p_underline='\[\e[4m\]'
    _p_user='\[\e[38;5;19m\]'
    _p_host='\[\e[38;5;32m\]'
fi

[[ $THEME = Dark ]] && _p_main=$_p_green || _p_main=$_p_pink

_prompt() {
    local exitval=$?
    local jobs="$(jobs | wc -l | tr -d '\n')"
    local gittop="$(git rev-parse --show-toplevel 2>/dev/null)"
    local pwd="$(pwd -P)"
    local p

    # this directory might be below a git repo but not part of it
    [[ -n $gittop && -z $(git ls-files) ]] && gittop=

    # root!
    [[ $UID -eq 0 ]] && p+="${_p_red}${_p_underline}ROOT${_p_clear} "

    # show user and host on remote systems
    if [[ -n $SSH_CONNECTION ]]; then
        [[ $UID -ne 0 ]] && p+="${_p_user}${USER}${_p_clear} "
        p+="${_p_host}$(hostname) "
    fi

    p+=$_p_main

    if [[ -z $gittop ]]; then
        p+="$pwd "
    else
        local parentdir="${gittop%/*}"
        local front="${parentdir/#${HOME}/~}"
        local middle="${_p_underline}${_p_bold}${gittop##*/}${_p_clear}"
        local back="${_p_main}${pwd#${gittop}}"
        p+="${front}/${middle}${back}${_p_clear} "

        # branch name or short SHA if detached
        local branch=$(git symbolic-ref --short -q HEAD || git rev-parse --short HEAD)
        [[ -n $branch ]] && p+="${_p_bold}${branch}"

        # dirty working tree
        git diff --no-ext-diff --quiet 2>/dev/null || p+="$_p_bold *"

        # staged changes
        git diff-index --cached --quiet HEAD 2>/dev/null || p+="$_p_bold ✓"

        local gitdir="${gittop}/.git"

        [[ -f "${gitdir}/refs/stash" ]] && p+=' [stash]'

        if [[ -f "${gitdir}/MERGE_HEAD" ]]; then
            p+=' [merge]'
        elif [[ -f "${gitdir}/CHERRY_PICK_HEAD" ]]; then
            p+=' [cherry]'
        elif [[ -f "${gitdir}/REVERT_HEAD" ]]; then
            p+=' [revert]'
        elif [[ -f "${gitdir}/rebase-merge/interactive" ]]; then
            p+=' [rebase-i]'
        elif [[ -d "${gitdir}/rebase-apply" ]]; then
            p+=' [rebase]'
        fi
    fi

    p+="${_p_clear}"$'\n'

    (( $jobs )) && p+="[${_p_blue}${_p_bold}${jobs}${_p_clear}]"
    (( $exitval )) && p+="[${_p_red}${_p_bold}${exitval}${_p_clear}]"

    PS1="${p}❯ "
}

# Aliases {{{1
alias d='docker'
alias dc='docker-compose'
alias g='git'
alias m='mhi'

alias t='task'
alias tf='task -f'
alias tn='task | head -n 1'

alias pip3up="pip3 list --outdated | sed -e '1,2d; s/ .*//' | xargs pip3 --no-cache-dir install -U"
alias gemup="gem update --system && gem update && gem cleanup"
alias npmup="npm install npm@latest -g && npm -g update"
if [[ $os = Darwin ]]; then
    alias brewup='brew update && brew upgrade && brew upgrade --cask --greedy && brew cleanup --prune 1'
    alias allup="pip3up; gemup; npmup; brewup"
elif [[ $os = Linux ]]; then
    alias aptup='sudo apt update && sudo apt upgrade && sudo apt autoremove'
    alias allup="pip3up; gemup; npmup; aptup"
fi

alias stripcolors='sed -r "s/\x1b\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"'
alias mirror='wget --mirror --no-parent --continue'
alias myip='dig +short myip.opendns.com @resolver1.opendns.com'
alias val='valgrind -v --leak-check=full --show-reachable=yes'
alias yt2mp3='youtube-dl -x --audio-format mp3 --audio-quality 0 -o "%(title)s.%(ext)s"'
alias yt2mp3-chapters='yt-dlp -x --audio-format mp3 --audio-quality 0 --split-chapters -o "%(title)s - %(chapter_number)s. %(chapter)s.%(ext)s"'
alias yt2mp3-playlist='yt-dlp -x --audio-format mp3 --audio-quality 0 --yes-playlist -o "%(title)s - %(playlist_index)s. %(playlist)s.%(ext)s"'

if [[ $os = FreeBSD ]]; then
    alias ls='gnuls --color=auto -N'
else
    alias ls='ls --color=auto -Nv'
fi
alias l='ls -1h --group-directories-first'
alias ll='ls -lh --group-directories-first'
alias la='ll -A'

alias grep='grep --color=auto'

alias 1='fg %1'
alias 2='fg %2'
alias 3='fg %3'
alias 11='bg %1'
alias 22='bg %2'
alias 33='bg %3'

if [[ $os = Darwin ]]; then
    alias chrome='open -a Google\ Chrome'
    alias preview='open -a Preview'
    alias vlc='open -a VLC'
    alias xcode='open -a Xcode'

    if [[ -x /Applications/LuLu.app/Contents/Resources/Netiquette.app/Contents/MacOS/Netiquette ]]; then
        alias objsee-netiquette='/Applications/LuLu.app/Contents/Resources/Netiquette.app/Contents/MacOS/Netiquette -list'
    fi

    if [[ -x /Applications/FileMonitor.app/Contents/MacOS/FileMonitor ]]; then
        alias objsee-filemonitor='sudo /Applications/FileMonitor.app/Contents/MacOS/FileMonitor'
    fi

    if [[ -x /Applications/ProcessMonitor.app/Contents/MacOS/ProcessMonitor ]]; then
        alias objsee-processmonitor='sudo /Applications/ProcessMonitor.app/Contents/MacOS/ProcessMonitor'
    fi
fi

# Functions {{{1
dsf() {
    git diff --no-index --color "$@" | diff-so-fancy | less -RFXx2
}

s() {
    if (( $# )); then
        ps -eo pid,ppid,user,%cpu,%mem,state,command | grep -i "$@" | grep -v "grep.*$@" | grep "$@"
    else
        ps -eo pid,ppid,user,%cpu,%mem,state,command
    fi
}

r() {
  exec $SHELL
}

md() {
  command mkdir -p $1 && builtin cd $1
}

rd() {
  dir=$PWD
  builtin cd ..
  if command rmdir "$dir" 2>/dev/null; then
    echo 'Removed empty directory:' $dir
  else
    builtin cd "$dir"
    echo 'Directory is not empty:'
    ls -A
  fi
  unset dir
}

lookup() {
  open "https://sks-keyservers.net/pks/lookup?search=${*}"
}

oman() {
    open "https://man.openbsd.org/${*}"
}

camusedby() {
  echo 'Recent camera uses:'
  local usedby=$(lsof | grep -w "AppleCamera\|USBVDC\|iSight" | awk '{printf $2"\n"}' | xargs ps)
  echo $usedby
}

fix-perm() {
  [[ $1 = -h ]] && {
    echo 'usage: fix-perm [dirs:700] [files:600]'
    return 1
  } 1>&2
  find . -type d -exec chmod ${1-700} {} +
  find . -type f -exec chmod ${2-600} {} +
}

angband() {
    save_stty="$(stty --save)"
    # Disable flow control and delayed suspend, since we need ^S and ^Y.
    stty -ixon dsusp undef
    command angband
    stty "$save_stty"
}

_() {
    for file in "$@"; do
        if [[ ${file:0:1} = _ ]]; then
            mv -nv "$file" "${file:1}"
        else
            mv -nv "$file" _"$file"
        fi
    done
}

fsed() {
    [[ $# -lt 2 ]] && { echo 'usage: fsed <sed cmd> <files>' 2>&1; return 1; }
    for file in "${@:2}"; do mv -nv "$file" "$(sed "$1" <<< "$file")"; done
}

asn() {
    (( !$# )) && { echo 'usage: asn <host>' 2>&1; return 1; }
    local ip="$1"
    grep ':' 1>/dev/null <<< "$ip" && ip="$(dig -x "$ip" +short)"     # IPv6 to domain
    grep '[g-z]' 1>/dev/null <<< "$ip" && ip="$(dig "$ip" A +short)"  # domain to IPv4
    local rr="$(printf '%s' "$ip." | tac -s.)"origin.asn.cymru.com
    dig "$rr" TXT +short
    whois -h whois.cymru.com -- "$ip"
}

hex() {
    { echo 'obase=16'; seq "$1" "$2"; } | bc | paste -s -d ' '
}

mount() {
    command mount | sed -e 's/^\(.*\) on \([^ ]*\)/\1\t\2\t/' | sort -t$'\t' -k2 -f | column -s$'\t' -t
}
# }}}

# Chrome {{{1
ch() {
  export CONF_COLS=$[ COLUMNS/2 ]
  export CONF_SEP='{::}'

  cp -f ~/Library/Application\ Support/Google/Chrome/Default/History /tmp/h

  sqlite3 -separator $CONF_SEP /tmp/h 'select title, url from urls order by last_visit_time desc' \
      | ruby -ne '
  cols = ENV["CONF_COLS"].to_i
  title, url = $_.split(ENV["CONF_SEP"])
  puts "\x1b[33m#{title.ljust(cols)}\x1b[0m #{url}"' \
      | fzf --ansi --multi --no-hscroll --tiebreak=index \
      | grep --color=never -o 'https\?://.*' \
      | xargs open

  unset CONF_COLS CONF_SEP
}

# FZF {{{1
url() {
    tmux capture-pane -pJS - \
        | grep -oE '\b(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]' \
        | fzf-tmux --multi --tac --exit-0 \
        | while read url; do open "$url"; done
}

f() {
  local file="$(fzf-tmux -1 --tac --tiebreak=index)"
  [[ -n $file ]] && cd "$(dirname "$file")"
}

p() {
  local dirs=(
    $ME/github/*
    $HOME/.vim/bundle
  )
  local dir="$(find "${dirs[@]}" -type d -mindepth 1 -maxdepth 1 | fzf-tmux -1 --tac)"
  [[ -n $dir ]] && cd "$dir" && clear
}

c() {
  local configs=(
    ~/.bash_profile
    ~/.bashrc
    ~/.config/git/config
    ~/.profile
    ~/.shrc
    ~/.tmux.conf
    ~/.vim/autoload/mhi.vim
    ~/.vim/lua/config.lua
    ~/.vim/magic.vim
    ~/.vim/vimrc
    ~/.zsh/.zprofile
    ~/.zsh/.zshrc
    ~/.zshenv
  )
  local IFS=$'\n'
  local files=($(echo "${configs[*]}" | fzf-tmux -m -1 --tac --tiebreak=index))
  [[ -n $files ]] && v "${files[@]}"
}

book() {
    local book="$(rg --files $ME/books | fzf -1 --tac)"
    [[ -z $book ]] && return 1
    cd "${book%/*}"
    clear
    ls -1 --group-directories-first
}

# Git {{{1
pr() {
    local origin pr
    if [[ $# -eq 0 ]]; then
        echo "usage: pr [remote] <ref>"
        return 1
    elif [[ $# -eq 1 ]]; then
        origin=$(git config branch.master.remote || echo origin)
        pr=$1
    else
        origin=$1
        pr=$2
    fi
    git fetch $origin refs/pull/${pr}/head || return
    git checkout -q FETCH_HEAD
}

prpush() {
    local pr=$1
    local local_branch=$(git rev-parse --abbrev-ref HEAD)
    [[ $local_branch == pr[[:digit:]]* ]] && pr=${local_branch#??}

    local url=$(git config remote.$(git config branch.master.remote).url)
    local slug=${${url#*github.com?}%.git}
    local repo="${slug#*/}"

    local url=https://api.github.com/repos/${slug}/pulls/${pr}
    local label=$(curl -s "$url" | jq -r '.head.label')
    local author=${label%%:*}
    local remote_branch=${label#*:}

    local cmd="git push -f git@github.com:${author}/${repo} ${local_branch}:${remote_branch}"
    echo "$cmd"
    eval "$cmd"
}

changed() {
    local files=$(git diff -U0 --no-prefix --relative "$@" 2>/dev/null | quickfix_diff_to_hunk)
    [[ -z $files ]] && { echo '¯\_(ツ)_/¯'; return 1; }
    v -q <(echo $files)
}

quickfix_diff_to_hunk() {
    ruby -ne  '
    (file = $1; next) if $_ =~ /^\+\+\+ (.*)/;
    next if file.nil?;
    (linenr = $1; next) if $_ =~ /^@@ .*\+(\d+)/;
    next if linenr.nil?;
    puts "#{file}:#{linenr}: #{$1}" if $_ =~ /^[+-](.*)/;
    linenr = nil
    '
}

b() {
    git checkout $(git branch -a | fzf -1 | cut -c3-)
}

gho() {
  local prefix
  prefix=$(git rev-parse --show-prefix)
  (( $? )) && return 1
  local branch=$(git symbolic-ref -q --short HEAD)
  local remote=$(git config branch.master.remote || echo origin)
  local url=$(git config remote.${remote}.url)
  url=${url/git\@github\.com:/https:\/\/github.com/}
  url=${url%\.git}
  open ${url}/tree/${branch}/${prefix}${1:-}
}

gl() {
    nvim +'Gclog'
}

# iTerm2 {{{1
proftoggle() {
    if [[ -z $ITERM_PROFILE ]]; then
        print "Not in iTerm" 1>&2
        return
    fi
    tmup
    if [[ $ITERM_PROFILE == Light ]]; then
        export ITERM_PROFILE=Dark
        eval $(dircolors ~/.zsh/dircolors.dark)
        ln -fs \
            ~/.config/git/config.colors.dark \
            ~/.config/git/config.colors
    else
        export ITERM_PROFILE=Light
        eval $(dircolors ~/.zsh/dircolors.light)
        ln -fs \
            ~/.config/git/config.colors.light \
            ~/.config/git/config.colors
    fi
    local seq="\e]1337;SetProfile=${ITERM_PROFILE}\x7"
    if [[ -n $TMUX ]]; then
        seq="\ePtmux;\e${seq}\e\\"
        tmux setenv -g ITERM_PROFILE $ITERM_PROFILE
    fi
    printf $seq
    clear
}

# Tmux {{{1
tm() {
    if (( $# )); then
        tmux has-session -t "$*" && tmux attach -t "$*" || tmux new-session -s "$*"
    else
        tmux attach || tmux new-session -s default
    fi
}

tmup() {
    [[ -n $TMUX ]] && export "$(tmux showenv -s)"
}

# Vim {{{1
v() {
 if [[ -x $ME/github/neovim/neovim/build/bin/nvim ]]; then
     VIMRUNTIME=$ME/github/neovim/neovim/runtime $ME/github/neovim/neovim/build/bin/nvim "$@"
 else
     $EDITOR "$@"
 fi
}

vd() {
    VIMRUNTIME=$ME/github/neovim/neovim/runtime lldb -- $ME/github/neovim/neovim/build/bin/nvim "$@"
}

all() {
    git rev-parse --is-inside-work-tree &>/dev/null && tool=git || tool=ag
    nvim +"Grepper -tool $tool -highlight -jump -open -noswitch -query $1"
}

va() {
    nvim -q <(ag --vimgrep "$@")
}

vg() {
    nvim -q <(git grep -nI "$@")
}

test -r ~/.shenv && . ~/.shenv

# vim: ft=sh fdm=marker


================================================
FILE: .tmux.conf
================================================
# tmux.conf

#  bindings  {{{1
bind-key a               send-prefix
bind-key r               source-file ~/.tmux.conf \; display-message 'Reloaded ~/tmux.conf'
bind-key G               set status
bind-key T               run-shell 'for i in {1..$(tmux list-windows | wc -l)}; do tmux next-window; done'
bind-key ,               command-prompt "rename-window '%%'"

bind-key s               command-prompt -p 'Send pane to:'   'join-pane -ht "%%"'
bind-key j               command-prompt -p 'Join pane from:' 'join-pane -hs "%%"'
bind-key B               break-pane

bind-key c               new-window
bind-key C               new-window      -c "#{pane_current_path}"
bind-key |               split-window -h -c "#{pane_current_path}"
bind-key -               split-window -v -c "#{pane_current_path}"

bind-key -r n            next-window
bind-key -r p            previous-window
bind-key -r o            last-window
bind-key -r Left         swap-window -t {previous}
bind-key -r Right        swap-window -t {next}

bind-key h               select-pane -L
bind-key j               select-pane -D
bind-key k               select-pane -U
bind-key l               select-pane -R

bind-key -n M-h          if-shell '[[ #{pane_current_command} =~ vim ]]' 'send-keys M-h' 'select-pane -L'
bind-key -n M-j          if-shell '[[ #{pane_current_command} =~ vim ]]' 'send-keys M-j' 'select-pane -D'
bind-key -n M-k          if-shell '[[ #{pane_current_command} =~ vim ]]' 'send-keys M-k' 'select-pane -U'
bind-key -n M-l          if-shell '[[ #{pane_current_command} =~ vim ]]' 'send-keys M-l' 'select-pane -R'

bind-key -r C-h          resize-pane -L 3
bind-key -r C-j          resize-pane -D 3
bind-key -r C-k          resize-pane -U 3
bind-key -r C-l          resize-pane -R 3

bind-key +               choose-buffer "delete-buffer -b '%%'"
bind-key >               save-buffer ~/.tmux-exchange \; display-message 'tmux: buffer saved'
bind-key <               load-buffer ~/.tmux-exchange \; display-message 'tmux: buffer loaded'

bind-key v               copy-mode
bind-key -r P            paste-buffer

bind-key -T copy-mode-vi y    send -X copy-pipe-and-cancel pbcopy
bind-key -T copy-mode-vi v    send -X begin-selection
bind-key -T copy-mode-vi C-v  send -X rectangle-toggle

#  options  {{{1
set-option -g  prefix             C-a
set-option -g  default-terminal   'tmux-256color'
set-option -ga update-environment ' ITERM_PROFILE'

set-option -ga terminal-overrides ',xterm-256color:Tc'
set-option -ga terminal-overrides ',*:Setulc=\E[58::2::%p1%{65536}%/%d::%p1%{256}%/%{255}%&%d::%p1%{255}%&%d%;m'  # underscore colors in kitty

set-option -g  mode-keys          vi
set-option -g  mouse              on

set-option -gs escape-time        1
set-option -g  repeat-time        1000

set-option -g  base-index         1
set-option -g  focus-events       on
set-option -g  history-limit      1000
set-option -g  status-position    top
set-option -g  monitor-activity   off
set-option -g  renumber-windows   on
set-option -g  set-titles         on
set-option -g  visual-activity    off

#  statusline  {{{1
set-option -g status-justify   centre
set-option -g status-interval  60

set-option -g window-status-current-format  ' #W '
set-option -g window-status-format          ' #W '

set-option -g  status-left   ''

set-option -g  status-right  '#{?window_zoomed_flag, #[fg=colour16]#[bg=colour214] ZOOM ,}#[default] '
set-option -ga status-right  '#[fg=colour15]#[bg=colour245] '
# set-option -ga status-right  '#(cat ~/todo)'
set-option -ga status-right  "#(pmset -g batt | awk 'NR==2 { gsub(/;/, \"\"); print $3 }') #[default]"
set-option -ga status-right  ' #[bg=colour245] %H:%M '

#  colors  {{{1
set-option -g status-style                 fg=colour15,bg=default
set-option -g window-status-current-style  fg=colour15,bg=colour161
set-option -g window-status-style          fg=colour15,bg=colour24

set-option -g pane-border-style            fg=colour240
set-option -g pane-active-border-style     fg=colour240

set-option -g window-status-activity-style fg=colour111

set-option -g message-style                fg=colour15,bg=colour161
set-option -g message-command-style        fg=colour15,bg=colour24


================================================
FILE: .travis.yml
================================================
sudo: false
dist: trusty

addons:
  apt:
    packages: shellcheck

script: shellcheck bin/mhi* bin/build* bin/bootstrap*


================================================
FILE: .vim/autoload/mhi.vim
================================================
"
" Show the commit that touched the current line last.
"
function! mhi#git_blame_current_line() abort
  let gitdir = finddir('.git', expand('%:p').';')
  if empty(gitdir)
    echo 'no git'
    return
  endif
  let sha = matchstr(systemlist(printf('git blame --porcelain -lL%d,+1 %s',
        \ line('.'), expand('%')))[0], '\x\+')
  new
  execute 'silent file fugitive://'.gitdir.'//'.sha
  edit
  silent! %foldopen
  set bufhidden=wipe
  nnoremap <silent><buffer> q :quit<cr>
endfunction

"
" Show evolution of current line
"
function mhi#git_log_evolution(startline, endline, file) abort
  let cmd = printf('git log -L %s,%s:%s', a:startline, a:endline, a:file)
  enew
  set buftype=nofile
  setfiletype git
  let &l:statusline = cmd
  nnoremap <silent><buffer> q :bd<cr>
  execute 'silent! %!' cmd
endfunction

"
" Close nearest open bracket.
"
function! mhi#close_bracket() abort
  highlight BracketRange cterm=underline
  let pos = [0, 0]
  let pairs = {}
  for [open, close] in map(split(&matchpairs, ','), 'split(v:val, ":")')
    let pairs[open] = close
    let m = searchpairpos(escape(open, '['), '', close, 'bnW')
    if m[0] > pos[0]
      let pos = m
    elseif m[1] > pos[1] && m[0] == pos[0]
      let pos[1] = m[1]
    endif
  endfor
  if pos != [0, 0]
    let cur = getcurpos()[1:2]
    call clearmatches()
    call matchadd('BracketRange',
          \ '\%'.pos[0].'l\%'.pos[1].'c.*\_.\+\%'.cur[0].'l\%'.cur[1].'c')
    call timer_start(&matchtime * 100, {-> clearmatches()})
    return pairs[matchstr(getline(pos[0]), '.', pos[1]-1)]
  endif
  return ''
endfunction

"
" GitHub
"
function! mhi#github_open_issue() abort
  if !exists('b:git_dir')
    return
  endif
  let issue = matchstr(expand('<cWORD>'), '\d\+')
  if empty(issue)
    return
  endif
  let remote = systemlist('git config branch.master.remote || echo origin')[0]
  let url = systemlist(printf('git config remote.%s.url', remote))[0]
  let slug = substitute(matchstr(url, '\v[/:]\zs.*'), '\.git', '', '')
  let url = 'https://github.com/'. slug .'/issues/'. issue
  silent execute '!open -a Google\ Chrome' url
endfunction

function! mhi#github_open_slug() abort
  let old_isk = &iskeyword
  let &iskeyword = 'a-z,A-z,48-57,-,_,/,.'
  let slug = expand('<cword>')
  let &iskeyword = old_isk
  call system('open https://github.com/'. slug)
endfunction

"
" Tmux
"
function! mhi#tmux_navigate(direction) abort
  let oldwin = winnr()
  execute 'wincmd' a:direction
  if !empty($TMUX) && winnr() == oldwin
    let sock = split($TMUX, ',')[0]
    let direction = tr(a:direction, 'hjkl', 'LDUR')
    silent execute printf('!tmux -S %s select-pane -%s', sock, direction)
  endif
endfunction

"
" Smarter jumping.
"
function! mhi#jump()
  if (&filetype ==# 'vim' && &buftype ==# 'nofile') || &buftype ==# 'quickfix'
    execute "normal! \<cr>"
  elseif &filetype ==# 'vim'
    call lookup#lookup()
  elseif &filetype ==# 'man'
    execute "normal \<c-]>"
  elseif has_key(get(g:, 'ls#servers', {}), &filetype)
    call ls#feature#definition()
  else
    let word = expand('<cword>')
    if empty(word)
      return
    endif
    try
      execute 'tag' word
    catch
      echoerr substitute(v:exception, '.\{-}:', '', '')
      return
    endtry
    call halo#run()
  endif
  " normal! zvzt
endfunction

"
" Showing [+1 -2 ~3] in statusline.
"
function! mhi#sy_stats_wrapper()
  let symbols = ['+', '-', '~']
  let [added, modified, removed] = sy#repo#get_stats()
  let stats = [added, removed, modified]  " reorder
  let hunkline = ''
  for i in range(3)
    if stats[i] > 0
      let hunkline .= printf('%s%s ', symbols[i], stats[i])
    endif
  endfor
  if !empty(hunkline)
    let hunkline = '%3*[%5*'. hunkline[:-2] .'%3*]%*'
  endif
  return hunkline
endfunction

"
" Verbatim matching for *.
"
function! mhi#search() abort
  let regsave = @@
  normal! gvy
  let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
  let @@ = regsave
endfunction

"
" Jump forward/backward to next match and highlight it.
"
function! mhi#search_highlight_next_match(cmd) abort
  silent! call matchdelete(s:match)
  try
    execute 'normal!' a:cmd.'zvzz'
  catch /E486/  " pattern not found
    echohl ErrorMsg | echo substitute(v:exception, '^.\{-}:', '', '') | echohl NONE
  endtry
  let line = line('.')
  let col = col('.')
  call search(@/, 'zce', line, 100)
  let len = col('.') - col + 1
  call cursor(line, col)
  let s:match = matchaddpos('IncSearch', [[line, col, len]])
endfunction

"
" For 'foldtext'.
"
function! mhi#foldy()
  let linelen = &tw ? &tw : 80
  let marker  = strpart(&fmr, 0, stridx(&fmr, ',')) . '\d*'
  let range   = foldclosedend(v:foldstart) - foldclosed(v:foldstart) + 1

  let left    = substitute(getline(v:foldstart), marker, '', '')
  let leftlen = len(left)

  let right    = range . ' [' . v:foldlevel . ']'
  let rightlen = len(right)

  let tmp    = strpart(left, 0, linelen - rightlen)
  let tmplen = len(tmp)

  if leftlen > len(tmp)
    let left    = strpart(tmp, 0, tmplen - 4) . '... '
    let leftlen = tmplen
  endif

  let fill = repeat(' ', linelen - (leftlen + rightlen))

  return left . fill . right . repeat(' ', 100)
endfunction

"
" Switch to VCS root, if there is one.
"
function! mhi#cd() abort
  if &buftype =~# '\v(nofile|terminal)' || expand('%') =~# '^fugitive'
    return
  endif
  if !exists('s:cache')
    let s:cache = {}
  endif
  let dirs   = [ '.git', '.hg', '.svn' ]
  let curdir = mhi#normalize(resolve(expand('%:p:h')))
  if !isdirectory(curdir)
    echohl WarningMsg | echo 'No such directory: '. curdir | echohl NONE
    return
  endif
  if has_key(s:cache, curdir)
    execute 'lcd' fnameescape(s:cache[curdir])
    return
  endif
  for dir in dirs
    let founddir = finddir(dir, curdir .';')
    if !empty(founddir)
      break
    endif
  endfor
  let dir = empty(founddir) ? curdir : mhi#normalize(resolve(fnamemodify(founddir, ':p:h:h')))
  let s:cache[curdir] = dir
  execute 'lcd' fnameescape(dir)
endfunction

"
" Capture output of any command in a new window.
"
function! mhi#scratch(cmd) abort
  let more = &more
  set nomore
  try
    let lines = 1
    redir => lines
    silent execute a:cmd
  finally
    redir END
    let &more = more
  endtry
  noautocmd new
  setlocal buftype=nofile bufhidden=hide noswapfile
  silent put =lines
  1
  nnoremap <buffer> q :q<cr>
endfunction

"
" Make <tab> a little bit more useful. Stolen from junegunn.
"
function! s:can_complete(func, prefix)
  if empty(a:func) || a:func(1, '') < 0
    return 0
  endif
  let result = a:func(0, matchstr(a:prefix, '\k\+$'))
  return !empty(type(result) == type([]) ? result : result.words)
endfunction

function! mhi#tab_yeah()
  if pumvisible()
    return "\<c-n>"
  endif
  let line = getline('.')
  let col = col('.') - 2
  if empty(line) || line[col] !~ '\k\|[/~.]' || line[col + 1] =~ '\k'
    return "\<tab>"
  endif
  let prefix = expand(matchstr(line[0:col], '\S*$'))
  if prefix =~ '^[~/.]'
    return "\<c-x>\<c-f>"
  endif
  if !empty(&completefunc) && s:can_complete(function(&completefunc), prefix)
    return "\<c-x>\<c-u>"
  endif
  if !empty(&omnifunc) && s:can_complete(function(&omnifunc), prefix)
    return "\<c-x>\<c-o>"
  endif
  return "\<c-n>"
endfunction

"
" Get syntax group information. Stolen from jamessan.
"
function! s:synnames()
  let syn                 = {}
  let [lnum, cnum]        = [line('.'), col('.')]
  let [effective, visual] = [synID(lnum, cnum, 0), synID(lnum, cnum, 1)]
  let syn.effective       = synIDattr(effective, 'name')
  let syn.effective_link  = synIDattr(synIDtrans(effective), 'name')
  let syn.visual          = synIDattr(visual, 'name')
  let syn.visual_link     = synIDattr(synIDtrans(visual), 'name')
  return syn
endfunction

function! mhi#syninfo()
  let syn = s:synnames()
  let info = ''
  if syn.visual != ''
    let info .= printf('visual: %s', syn.visual)
    if syn.visual != syn.visual_link
      let info .= printf(' (as %s)', syn.visual_link)
    endif
  endif
  if syn.effective != syn.visual
    if syn.visual != ''
      let info .= ', '
    endif
    let info .= printf('effective: %s', syn.effective)
    if syn.effective != syn.effective_link
      let info .= printf(' (as %s)', syn.effective_link)
    endif
  endif
  return info
endfunction

"
" Run Exercism tests
"
function! mhi#run_exercism_tests() abort
  if expand('%:e') == 'vim'
    let testfile = printf('%s/%s.vader', expand('%:p:h'),
          \ tr(expand('%:p:h:t'), '-', '_'))
    if !filereadable(testfile)
      echoerr 'File does not exist: '. testfile
      return
    endif
    source %
    execute 'Vader' testfile
  else
    let sourcefile = printf('%s/%s.vim', expand('%:p:h'),
          \ tr(expand('%:p:h:t'), '-', '_'))
    if !filereadable(sourcefile)
      echoerr 'File does not exist: '. sourcefile
      return
    endif
    execute 'source' sourcefile
    Vader
  endif
endfunction

"
" Find and source project-specific Vim configs
"
function! mhi#source_project_config() abort
  let projectfile = findfile('.project.vim', expand('%:p').';')
  if filereadable(projectfile)
    execute 'source' projectfile
  endif
endfunction

"
" Cycle through completion functions.
"
function! mhi#next_completion() abort
  let compls = [ 'emoji#complete', 'tmuxcomplete#complete' ]
  let &cfu = compls[(index(compls, &cfu) + 1) % len(compls)]
  echomsg 'Using '. &cfu
endfunction

"
" Wrapper for :terminal
"
function! mhi#terminal(bang, mods, cmd) abort
  let terms = filter(map(tabpagebuflist(), 'getbufvar(v:val, ''terminal_job_id'')'), '!empty(v:val)')
  if empty(terms)
    execute a:mods 'new'
    let g:terminal = termopen($SHELL)
    $
    if a:bang | wincmd p | endif
  endif
  call chansend(g:terminal, a:cmd."\n")
endfunction

"
" Switch buffer. Skip buffers already shown in another window.
"
function! mhi#switch_buffer(cmd) abort
  try
    execute a:cmd
  catch /E85/  " There is no listed buffer
    return
  endtry
  let bufs = tabpagebuflist()
  while !empty(bufs)
    let buf = bufnr('')
    if count(bufs, buf) == 1 | break | endif
    execute a:cmd
    call filter(bufs, 'v:val != '.buf)
  endwhile
  stopinsert
  call halo#run()
endfunction

"
" :cd chokes on UNC paths with two backslashes. Use one backslash instead.
"
" Bad:  :cd z:\\share
" Good: :cd z:\share
"
function! mhi#normalize(path) abort
  return has('win32') && &shellslash == 0
        \ ? substitute(a:path, '\v^(\w):\\\\', '\1:\\', '')
        \ : a:path
endfunction

"
" Highlight the '123' in 'ctermfg=123' according to its number.
"
function! mhi#vim_highlight_groups()
  for c in range(256)
    execute 'syntax match CtermFg'.c '/\<\%(ctermfg=\)\@<='.c.'\>/ display containedin=vimHiNmbr'
    execute 'syntax match CtermBg'.c '/\<\%(ctermbg=\)\@<='.c.'\>/ display containedin=vimHiNmbr'
    execute 'highlight CtermFg'.c 'ctermfg='.c 'cterm=NONE'
    execute 'highlight CtermBg'.c 'ctermfg='.c 'cterm=NONE'
  endfor
endfunction

" vim: fdm=syntax


================================================
FILE: .vim/colors/fnord.vim
================================================
let g:colors_name = 'fnord'

if !has('gui_running') || &termguicolors == 0
  if exists('+termguicolors')
    let &termguicolors = 1
  else
    echohl Error
    echomsg "vim-fnord requires a Vim supporting the 'termguicolors' option."
    echohl NONE
    finish
  endif
endif

" highlight clear
" syntax reset

function! s:hi(group, fg, bg, gui, guisp)
  let config = a:group
  if !empty(a:fg)    | let config .= ' guifg='.a:fg                    | endif
  if !empty(a:bg)    | let config .= ' guibg='.a:bg                    | endif
  if !empty(a:gui)   | let config .= ' gui='  .a:gui . ' cterm='.a:gui | endif
  if !empty(a:guisp) | let config .= ' guisp='.a:guisp                 | endif
  execute 'highlight' config
endfunction

let s:blue0   = '#35d4d9'
let s:blue1   = '#25909c'
let s:blue2   = '#013969'
let s:blue3   = '#05224a'
let s:blue4   = '#68b3da'
let s:blue5   = '#00c2f4'
let s:blue6   = '#5879bd'
let s:blue7   = '#124a7b'
let s:gray0   = '#afb8c4'
let s:gray1   = '#eeeeee'
let s:gray2   = '#555588'
let s:yellow0 = '#e5e568'
let s:purple  = '#5e50ba'
let s:orange  = '#d69a66'
let s:orange2 = '#e3c08e'
let s:orange3 = '#d2a500'
" let s:red     = '#772d26'
let s:green   = '#97dd7b'
let s:green2  = '#103850'
let s:red     = '#d2554f'
let s:red2    = '#d42a60'
let s:red3    = '#fb6c89'
let s:pink    = '#d371e3'

call s:hi('Normal', s:gray0, s:blue2, 'NONE', '')

call s:hi('NormalFloat', '', s:blue3,  'NONE', '')
call s:hi('FloatBorder', s:red3, s:blue3, 'NONE', '')

" call s:hi('StatusLine', 'black', s:blue0, 'NONE', '')
call s:hi('StatusLine', s:gray0, s:blue7, 'bold', '')
call s:hi('StatusLineNC', s:gray0, s:blue7, 'NONE', '')

call s:hi('User1', '#6acdef', s:blue7, 'bold', '')  " main/master branch
call s:hi('User2', s:yellow0, s:blue7, 'bold', '')  " other branch
call s:hi('User3', s:blue7,   s:blue7, '',     '')  " hunkline brackets
call s:hi('User4', s:green,   s:blue7, 'bold', '')  " filename
call s:hi('User5', '#ef8a55', s:blue7, '',     '')  " hunkline
call s:hi('User6', s:blue6,   s:blue7, '',     '')  " separators

call s:hi('TabLineSel', 'black', s:blue5, 'NONE', '')
call s:hi('TabLine', s:gray0, s:blue7, 'NONE', '')
call s:hi('TabLineFill', s:gray1, s:blue2, 'NONE', '')

call s:hi('Visual', s:blue2, s:green, 'NONE', 'NONE')
call s:hi('CursorLine', '', s:blue7, 'NONE', 'NONE')

call s:hi('Special', s:gray0, '', 'NONE', '')
call s:hi('Statement' , s:pink, '' , 'NONE', '')
call s:hi('Function', s:yellow0, '', 'NONE', '')
call s:hi('Identifier', s:blue0, '', 'NONE', '')
call s:hi('PreProc', s:blue0, '', 'NONE', '')
call s:hi('String', s:green, '', 'NONE', '')
call s:hi('Type', s:blue0, '', 'bold', '')
call s:hi('VertSplit', '', s:blue7, 'NONE', '')
call s:hi('Comment', s:blue4, '', 'NONE', '')
call s:hi('Folded', s:gray1, s:blue1, 'NONE', '')
call s:hi('EndOfBuffer', s:blue4, '', 'NONE', '')
call s:hi('Constant', s:orange, '', 'NONE', '')
call s:hi('NonText', s:blue6, '', 'NONE', '')

call s:hi('LineNr', s:blue6, s:blue2, 'NONE', '')
call s:hi('CursorLineNr', s:yellow0, s:blue2, 'NONE', '')
call s:hi('SignColumn', s:orange, s:blue2, 'NONE', '')

call s:hi('DiffAdd', s:green, s:blue2, 'NONE', '')
call s:hi('DiffChange', s:orange, s:blue2, 'NONE', '')
call s:hi('DiffDelete', s:red3, s:blue2, 'NONE', '')

call s:hi('Pmenu', s:blue4, s:blue3, 'NONE', '')
call s:hi('PmenuSel', 'black', s:orange, 'NONE', '')
call s:hi('PmenuSbar', 'black', s:blue3, 'NONE', '')
call s:hi('PmenuThumb', 'black', s:blue2, 'NONE', '')

call s:hi('RFCType', s:blue6, '', 'NONE', '')
call s:hi('RFCID', s:blue4, '', 'NONE', '')
call s:hi('RFCDelim', s:blue6, '', 'NONE', '')

call s:hi('ErrorMsg', s:red3, s:blue2, 'bold', '')
call s:hi('Todo', s:yellow0, s:blue2, 'bold', '')
call s:hi('Question', s:pink, s:blue2, 'bold', '')

call s:hi('QuickFixLine', s:orange2, '', 'bold', '')

call s:hi('Search', 'black', s:yellow0, 'NONE', '')
call s:hi('IncSearch', 'black', s:red3, 'NONE', '')

highlight default link diffAdded     DiffAdd
highlight default link diffRemoved   DiffDelete
highlight default link diffFile      Comment
highlight default link diffNewFile   Comment
highlight default link diffLine      Comment
highlight default link diffIndexLine Comment
highlight default link diffSubname   Comment


================================================
FILE: .vim/lua/config.lua
================================================
local mapopts = { noremap = true, silent = true }

-- lsp {{{1
local function default_lsp_settings(_client, _bufnr)
  vim.api.nvim_buf_set_keymap(0, 'n', '<cr>',       '<cmd>lua vim.lsp.buf.definition()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', 'gd',         '<cmd>lua vim.lsp.buf.declaration()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', 'K',          '<cmd>lua vim.lsp.buf.hover()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>jc', '<cmd>lua vim.lsp.buf.code_action()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>jn', '<cmd>lua vim.lsp.buf.rename()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>jr', '<cmd>lua vim.lsp.buf.references()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>jt', '<cmd>lua vim.lsp.buf.type_definition()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>js', '<cmd>lua vim.lsp.buf.signature_help()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '<leader>jd', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics({show_header = false, border = "single"})<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', '[d',         '<cmd>lua vim.lsp.diagnostic.goto_prev()<cr>', mapopts)
  vim.api.nvim_buf_set_keymap(0, 'n', ']d',         '<cmd>lua vim.lsp.diagnostic.goto_next()<cr>', mapopts)

  vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
  -- if client.resolved_capabilities.document_formatting then
  --   buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts)
  -- end
  -- if client.resolved_capabilities.document_range_formatting then
  --   buf_set_keymap("v", "<space>f", "<cmd>lua vim.lsp.buf.range_formatting()<CR>", opts)
  -- end
end

vim.fn.sign_define('LspDiagnosticsSignError',       {text = '', texthl = 'LspDiagnosticsSignError'})
vim.fn.sign_define('LspDiagnosticsSignWarning',     {text = '', texthl = 'LspDiagnosticsSignWarning'})
vim.fn.sign_define('LspDiagnosticsSignHint',        {text = '', texthl = 'LspDiagnosticsSignHint'})
vim.fn.sign_define('LspDiagnosticsSignInformation', {text = '', texthl = 'LspDiagnosticsSignInformation'})

vim.cmd('highlight! link FloatBorder NormalFloat')
vim.cmd('command! LspLog :lua vim.cmd("edit" .. vim.lsp.get_log_path())')

-- https://en.wikipedia.org/wiki/Box-drawing_character
vim.lsp.handlers['textDocument/hover'] = vim.lsp.with(
  vim.lsp.handlers.hover, {
    -- border = 'double'
    border = {
      {"╭", "NormalFloat"},
      {"─", "NormalFloat"},
      {"╮", "NormalFloat"},
      {"│", "NormalFloat"},
      {"╯", "NormalFloat"},
      {"─", "NormalFloat"},
      {"╰", "NormalFloat"},
      {"│", "NormalFloat"},
    }
  }
)

vim.lsp.handlers['textDocument/publishDiagnostics'] = vim.lsp.with(
  vim.lsp.diagnostic.on_publish_diagnostics, {
    signs = { priority = 11 },
    underline = true,
    virtual_text = true,
    update_in_insert = false,
  }
)

local lspconfig = require('lspconfig')

lspconfig.util.default_config = vim.tbl_extend('force', lspconfig.util.default_config, {
  autostart = false,
  on_attach = default_lsp_settings,
})

for _, v in pairs({'gopls', 'pyright', 'rust_analyzer'}) do
  lspconfig[v].setup({})
end

lspconfig.clangd.setup({
  cmd = {'/Library/Developer/CommandLineTools/usr/bin/clangd', '--background-index'},
  autostart = true,
})

local sumneko_root_path = '/Users/mhi/data/lua/lua-language-server'
local sumneko_bin = '/bin/macos/lua-language-server'

lspconfig.sumneko_lua.setup({
   cmd = {sumneko_root_path .. sumneko_bin, '-E', sumneko_root_path .. '/main.lua'},
   settings = {
      Lua = {
         runtime = {
            version = 'LuaJIT',
            -- path = vim.split(package.path, ';'),
         },
         workspace = {
            library = {
               -- ['/Users/mhi/data/github/neovim/neovim/runtime/lua'] = true,
               -- ['/Users/mhi/data/github/neovim/neovim/runtime/lua/vim/lsp'] = true,
               -- ['/Users/mhi/data/github/neovim/neovim/.deps/usr/share/lua/busted'] = true,
            },
            -- preloadFileSize = 50;
            -- ignoreDir = { 'data' }
         },
         diagnostics = {
            globals = {'vim', 'describe', 'it', 'before_each', 'after_each', 'pending',
                       'teardown'},
            -- disable = {'lowercase-global', 'unused-function'},
         },
         -- completion = {
         --    keywordSnippet = "Disable",
         -- },
      },
   },
})

-- treesitter {{{1
require('nvim-treesitter.configs').setup({
  highlight = {
    enable = {'c', 'lua', 'javascript', 'typescript'}
  },
  textobjects = {
    select = {
      enable = true
    }
  }
})

-- telescope {{{1
-- require('telescope').load_extension('spotlight')

vim.api.nvim_set_keymap('n', '<leader>ff', '<cmd>Telescope find_files<cr>', mapopts)
vim.api.nvim_set_keymap('n', '<leader>fg', '<cmd>Telescope live_grep<cr>', mapopts)
vim.api.nvim_set_keymap('n', '<leader>fb', '<cmd>Telescope buffers<cr>', mapopts)
vim.api.nvim_set_keymap('n', '<leader>fh', '<cmd>Telescope help_tags<cr>', mapopts)

-- hop {{{1
require('hop').setup({ teasing = false })

vim.api.nvim_set_keymap('n', '<space>',   '<cmd>HopChar2<cr>', mapopts)
vim.api.nvim_set_keymap('n', '<c-space>', '<cmd>HopWord<cr>', mapopts)

-- colorizer {{{1
if vim.o.termguicolors then
  require('colorizer').setup({'vim'})
end

-- vim: nowrap


================================================
FILE: .vim/vimrc
================================================
"
"                         ███████████████████████████
"                         ███████▀▀▀░░░░░░░▀▀▀███████
"                         ████▀░░░░░░░░░░░░░░░░░▀████
"                         ███│░░░░░░░░░░░░░░░░░░░│███
"                         ██▌│░░░░░░░░░░░░░░░░░░░│▐██
"                         ██░└┐░░░░░░░░░░░░░░░░░┌┘░██
"                         ██░░└┐░░░░░░░░░░░░░░░┌┘░░██
"                         ██░░┌┘▄▄▄▄▄░░░░░▄▄▄▄▄└┐░░██
"                         ██▌░│██████▌░░░▐██████│░▐██
"                         ███░│▐███▀▀░░▄░░▀▀███▌│░███
"                         ██▀─┘░░░░░░░▐█▌░░░░░░░└─▀██
"                         ██▄░░░▄▄▄▓░░▀█▀░░▓▄▄▄░░░▄██
"                         ████▄─┘██▌░░░░░░░▐██└─▄████
"                         █████░░▐█─┬┬┬┬┬┬┬─█▌░░█████
"                         ████▌░░░▀┬┼┼┼┼┼┼┼┬▀░░░▐████
"                         █████▄░░░└┴┴┴┴┴┴┴┘░░░▄█████
"                         ███████▄░░░░░░░░░░░▄███████
"                         ██████████▄▄▄▄▄▄▄██████████
"                         ███████████████████████████
"
"   You are about to experience a potent dosage of Vim. Watch your steps.
"
"                ╔══════════════════════════════════════════╗
"                ║           ⎋ HERE BE VIMPIRES ⎋           ║
"                ╚══════════════════════════════════════════╝

let s:is_win = has('win32')
let $v = $HOME.(s:is_win ? '\vimfiles' : '/.vim')

if s:is_win
  set shell=cmd.exe
  set shellcmdflag=/c
  set encoding=utf-8
endif

" Plug {{{1
let s:bundle_dir = $v.'/bundle'

let g:plug_shallow = 0
let g:plug_window  = 'enew'
let g:plug_pwindow = 'vertical rightbelow new'

call plug#begin(s:bundle_dir)
  Plug 'jonathanfilip/vim-lucius'
  Plug 'arcticicestudio/nord-vim'
  Plug 'mhartington/oceanic-next'
  Plug 'joshdick/onedark.vim'

  Plug 'AndrewRadev/splitjoin.vim'
  Plug 'chrisbra/unicode.vim', {'on': ['UnicodeName', 'UnicodeTable']}
  Plug 'godlygeek/csapprox', {'for': 'fugitiveblame' }
  Plug 'junegunn/fzf', has('win32') ? {} : {'on': 'FZF', 'dir': '~/local/fzf', 'do': './install --bin'}
  Plug 'junegunn/vim-easy-align', {'on': '<plug>(LiveEasyAlign)'}
  Plug 'junegunn/vim-plug'
  Plug 'tpope/vim-commentary'
  Plug 'tpope/vim-endwise'
  Plug 'tpope/vim-fugitive'
  Plug 'tpope/vim-repeat'
  Plug 'tpope/vim-rhubarb'
  Plug 'tpope/vim-rsi'
  Plug 'tpope/vim-scriptease'
  Plug 'tpope/vim-surround'

  if has('nvim-0.5')
    Plug 'neovim/nvim-lspconfig'
    Plug 'nvim-treesitter/nvim-treesitter', {'do': ':TSUpdate'}
    Plug 'nvim-treesitter/nvim-treesitter-refactor'
    Plug 'nvim-treesitter/nvim-treesitter-textobjects'
    Plug 'nvim-treesitter/playground'
    Plug 'norcalli/nvim-colorizer.lua'
    Plug 'nvim-lua/plenary.nvim'
    Plug 'nvim-telescope/telescope.nvim'
    Plug 'mhinz/telescope-spotlight.nvim'
    Plug 'bfredl/luarefvim'
    Plug 'phaazon/hop.nvim'
  endif

  let g:plug_url_format = 'git@github.com:%s.git'
  Plug 'mhinz/vim-crates'
  Plug 'mhinz/vim-grepper'
  Plug 'mhinz/vim-halo'
  Plug 'mhinz/vim-janah'
  Plug 'mhinz/vim-lookup'
  Plug 'mhinz/vim-mix-format'
  Plug 'mhinz/vim-rfc'
  Plug 'mhinz/vim-sayonara', {'on': 'Sayonara'}
  Plug 'mhinz/vim-signify'
  Plug 'mhinz/vim-startify'
  Plug 'mhinz/vim-tree'
  unlet! g:plug_url_format
call plug#end()

if has('nvim-0.5')
  lua require 'config'
  lua require 'tree'
endif

" Init {{{1
if has('nvim')
  let $GIT_EDITOR = 'nvr -cc split --remote-wait'
  let $ELIXIR_EDITOR = 'nvr -l +__LINE__ __FILE__'
  if v:progpath =~# 'build/bin/nvim$'
    " for build/runtime/syntax/vim/generated.vim
    let &runtimepath .= ','.$VIM.'/build/runtime'
  endif
else
  filetype plugin indent on
  syntax on
  packadd! matchit
endif

let g:vimsyn_embed   = 'l'
let g:vimsyn_folding = 'f'
let g:is_bash        = 1
let g:lisp_rainbow   = 1

let g:markdown_fenced_languages = ['vim']

let g:loaded_2html_plugin     = 1
let g:loaded_getscriptPlugin  = 1
let g:loaded_gzip             = 1
let g:loaded_logipat          = 1
" let g:loaded_matchit          = 1
" let g:loaded_matchparen       = 1
let g:loaded_rrhelper         = 1
let g:loaded_spellfile_plugin = 1
let g:loaded_tarPlugin        = 1
let g:loaded_vimballPlugin    = 1
let g:loaded_zipPlugin        = 1

augroup vimrc
  autocmd!
augroup END

" Option {{{1
" indent settings
set autoindent
set cinoptions    =l1,p0,)50,*50,t0
set expandtab
set smarttab
set softtabstop   =2
set shiftwidth    =2
set shiftround

" backup/swap/info/undo settings
set nobackup
set nowritebackup
set undofile
set swapfile
if has('nvim')
  set backupdir  -=.
  set shada       ='100
else
  set backupdir   =$v/files/backup
  set directory   =$v/files/swap//
  set undodir     =$v/files/undo
  set viewdir     =$v/files/view
  set viminfo     ='100,n$v/files/info/viminfo
endif

" better navigation
set cursorline
set foldmethod    =marker
set foldopen     -=hor
set foldopen     +=jump
set foldtext      =mhi#foldy()
set hlsearch
set incsearch
set mouse         =a
set scrolloff     =4
set sidescroll    =5
set ignorecase
set smartcase
set tagcase       =match

" misc settings
set autoread
set backspace     =indent,eol,start
set clipboard     =unnamed
set complete     -=i
set completeopt  +=noselect
set diffopt      +=vertical,foldcolumn:0,indent-heuristic,algorithm:patience
set fileformats   =unix,dos,mac
set hidden
set history       =1000
set lazyredraw
set more
set mousemodel    =popup
set noautowrite
set noautowriteall
set noequalalways
set noerrorbells
set nofsync
set nojoinspaces
set wrapscan
set nrformats     =hex
set pastetoggle   =<F5>
set norelativenumber
set report        =0
set sessionoptions-=options
set sessionoptions+=localoptions
set showfulltag
set showtabline   =1
set splitbelow
set splitright
set switchbuf     =
set synmaxcol     =200
set tags         ^=./.git/tags;
set timeout
set timeoutlen    =1000
set titlestring   =VIM:\ %f
set ttimeout
set ttimeoutlen   =10
set ttyfast
set virtualedit   =onemore,block
set whichwrap     =h,l

" wild stuff
set suffixes     +=.a,.1,.class
set wildignore   +=*.o,*.so,*.zip,*.png
set wildmenu
set wildoptions   =tagfile
if has('nvim')
  set wildoptions+=pum
else
  set wildmode=list:longest,full
endif

" display settings
set display      +=lastline
set laststatus    =2
set list
set modeline
set modelines     =1
set nostartofline
set numberwidth   =1
set ruler
set shortmess     =aoOTI
set showcmd
set showmatch
set showmode

" spelling
set spellfile     =~/.vim/spell/en.utf-8.add,~/.vim/spell/de.utf-8.add
set spelllang     =en,de

" breaking
set wrap
set nolinebreak
set breakindent
set breakindentopt=min:40
"set highlight    +=@:SpecialKey

set cpoptions     =aABcefFqsZ
set formatoptions =tcrqnj

if has('multi_byte') && &encoding ==# 'utf-8'
  let &listchars = 'tab:▸ ,extends:❯,precedes:❮,nbsp:±,trail:⣿'
  let &fillchars = 'vert: ,diff: '  " ▚
  let &showbreak = '↪ '
  highlight VertSplit ctermfg=242
  " augroup vimrc
  "   autocmd InsertEnter * set listchars-=trail:⣿
  "   autocmd InsertLeave * set listchars+=trail:⣿
  " augroup END
else
  let &listchars = 'tab:> ,extends:>,precedes:<,nbsp:.'
  let &fillchars = 'vert: ,stlnc:#'
  let &showbreak = '-> '
  augroup vimrc
    autocmd InsertEnter * set listchars-=trail:.
    autocmd InsertLeave * set listchars+=trail:.
  augroup END
endif

if has('nvim')
  set signcolumn=auto:2
endif

" Mapping {{{1
let mapleader = ';'
nnoremap \ ;

inoremap jf <esc>

nnoremap gh :call mhi#github_open_issue()<cr>
nnoremap gH :call mhi#github_open_slug()<cr>

inoremap <expr> <tab> mhi#tab_yeah()
inoremap <expr> <c-]> mhi#close_bracket()

nnoremap <silent> <tab> <c-w>w:call halo#run()<cr>
nnoremap <silent> <c-p> :call mhi#switch_buffer('bprevious')<cr>
nnoremap <silent> <c-n> :call mhi#switch_buffer('bnext')<cr>
nnoremap <silent> [b    :call mhi#switch_buffer('bprevious')<cr>
nnoremap <silent> ]b    :call mhi#switch_buffer('bnext')<cr>
nnoremap <silent> [q    :cprevious<bar>call halo#run()<cr>
nnoremap <silent> ]q    :cnext<bar>call halo#run()<cr>
nnoremap <silent> [l    :lprevious<bar>call halo#run()<cr>
nnoremap <silent> ]l    :lnext<bar>call halo#run()<cr>
nnoremap <silent> [t    :tabprevious<bar>call halo#run()<cr>
nnoremap <silent> ]t    :tabnext<bar>call halo#run()<cr>

nnoremap [<space>  :<c-u>put! =repeat(nr2char(10), v:count1)<cr>'[
nnoremap ]<space>  :<c-u>put =repeat(nr2char(10), v:count1)<cr>

nnoremap [e  :<c-u>execute 'move -1-'. v:count1<cr>
nnoremap ]e  :<c-u>execute 'move +'. v:count1<cr>

" switch comma-separated arguments
nnoremap [w  :normal F,h]w2w<cr>
nnoremap ]w  :let s=&isk \| setl isk+=\",' \| exe "norm diwmmebgPdw'mP" \| let &isk=s<cr>

nnoremap }   }zz
nnoremap {   {zz
nnoremap ]]  ]]zz
nnoremap [[  [[zz
nnoremap []  []zz
nnoremap ][  ][zz

nnoremap g;  g;zvzz
nnoremap g,  g,zvzz

nnoremap <left>   <c-w>>
nnoremap <right>  <c-w><
nnoremap <up>     <c-w>-
nnoremap <down>   <c-w>+

nnoremap <silent><a-h>  :<c-u>call mhi#tmux_navigate('h')<cr>
nnoremap <silent><a-j>  :<c-u>call mhi#tmux_navigate('j')<cr>
nnoremap <silent><a-k>  :<c-u>call mhi#tmux_navigate('k')<cr>
nnoremap <silent><a-l>  :<c-u>call mhi#tmux_navigate('l')<cr>

xnoremap <  <gv
xnoremap >  >gv

onoremap gv  :<c-u>normal! gv<cr>

nnoremap Q  gqap

nnoremap <leader>ev  :edit $MYVIMRC<cr>
nnoremap <leader>em  :edit ~/.vim/autoload/mhi.vim<cr>

nnoremap <leader>si  :echo mhi#syninfo()<cr>
nnoremap <leader>ss  :echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')<cr>

nnoremap <leader>m  :Messages<cr>
nnoremap <leader>M  :<c-u><c-r><c-r>='let @'. v:register .' = '. string(getreg(v:register))<cr><c-f><left>
" nnoremap <leader>o  :!echo `git url`/blob/`git rev-parse --abbrev-ref HEAD`/%\#L<C-R>=line('.')<cr> \| xargs open<cr><cr>
nnoremap <leader>o  :silent !open <c-r>=fnameescape('<c-r><c-a>')<cr><cr>
nnoremap <leader>w  :update<cr>
nnoremap <leader>x  :xit<cr>
nnoremap <leader>l  :noh<bar>diffupdate<bar>call clearmatches()<bar>syntax sync fromstart<cr><c-l>
nnoremap <leader>v  :Runtime<cr>
nnoremap <leader>t  :Tree<cr>
nnoremap <silent> <leader>d  :Dirview<cr>
" nnoremap <silent> <leader>d  :exe 'sil !open' fnameescape(printf('https://devdocs.io/#q=%s%%20%s', &ft, expand('<cword>')))<cr>

nnoremap <silent><leader>b  :call mhi#git_blame_current_line()<cr>

nnoremap '  `
nnoremap `  '

nnoremap <bs>  <c-t>
nnoremap <silent><cr>  :call mhi#jump()<cr>

cnoremap <expr> <c-n> wildmenumode() ? "\<c-n>" : "\<down>"
cnoremap <expr> <c-p> wildmenumode() ? "\<c-p>" : "\<up>"

cnoremap <leader>r   $VIMRUNTIME/
cnoremap <leader>ft  ~/.vim/after/ftplugin/

nnoremap <silent> n  :call mhi#search_highlight_next_match('Nn'[v:searchforward])<cr>
nnoremap <silent> N  :call mhi#search_highlight_next_match('nN'[v:searchforward])<cr>

xnoremap *  :<c-u>call mhi#search()<cr>//<cr>
xnoremap #  :<c-u>call mhi#search()<cr>??<cr>

if has('nvim')
  nnoremap <leader>T      :vsplit +terminal<cr>
  tnoremap <esc>          <c-\><c-n>
  tnoremap <silent><a-h>  <c-\><c-n>:<c-u>call mhi#tmux_navigate('h')<cr>
  tnoremap <silent><a-j>  <c-\><c-n>:<c-u>call mhi#tmux_navigate('j')<cr>
  tnoremap <silent><a-k>  <c-\><c-n>:<c-u>call mhi#tmux_navigate('k')<cr>
  tnoremap <silent><a-l>  <c-\><c-n>:<c-u>call mhi#tmux_navigate('l')<cr>
endif

if !has('nvim')
  if empty($TMUX)
    let &t_SI = "\<Esc>]50;CursorShape=1\x7"
    let &t_EI = "\<Esc>]50;CursorShape=0\x7"
    let &t_SR = "\<Esc>]50;CursorShape=2\x7"
  else
    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_SR = "\<Esc>Ptmux;\<Esc>\<Esc>]50;CursorShape=2\x7\<Esc>\\"
  endif
endif

" Autocmd {{{1
augroup vimrc
  " foldopen=hor sucks
  autocmd BufWinEnter * normal! zvzz

  if has('nvim')
    autocmd TermOpen,BufEnter term://* startinsert
  endif

  autocmd BufReadPost *
        \ if line("'\"") > 1 && line("'\"") <= line("$") |
        \   execute 'normal! g`"' |
        \ endif

  autocmd WinEnter    * set cursorline
  autocmd WinLeave    * set nocursorline
  autocmd InsertEnter * set nocursorline
  autocmd InsertLeave * set cursorline

  autocmd FocusGained * call halo#run()

  autocmd CompleteDone * pclose
augroup END

" Command {{{1
command! -nargs=1 -complete=command Scratch call mhi#scratch(<f-args>)
command! CleanSpell  runtime! spell/cleanadd.vim
command! Cd call mhi#cd()
command! -range Evo call mhi#git_log_evolution(<line1>, <line2>, expand('%'))
command! Changed exe 'args' join(map(systemlist('git diff --name-only --relative "$@" 2>/dev/null'), 'fnameescape(v:val)'))
command! -nargs=1 -bang T call mhi#terminal(<bang>0, <f-mods>, <f-args>)
command! Signs PP sign_getplaced('.', {'lnum': line('.'), 'group': '*'})

if has('nvim')
  command! LuaG lua print(vim.inspect(_G))
  command! LspClients lua print(vim.inspect(vim.lsp.buf_get_clients()))
endif

" Color {{{1
function! s:colors_default() abort
  " highlight Comment cterm=italic
  highlight link User1 StatusLine   " master branch
  highlight link User2 StatusLine   " other branch
  highlight link User3 StatusLine   " separators
  highlight link User4 StatusLine   " filename at beginning
  highlight link User5 StatusLine   " ~changes
  " highlight SignifySignAdd ctermfg=151 ctermbg=NONE cterm=NONE
  " highlight SignifySignDelete ctermfg=181 ctermbg=NONE cterm=NONE
  " highlight SignifySignChange ctermfg=187 ctermbg=NONE cterm=NONE
  " highlight Halo guifg=white guibg=#F92672 ctermfg=white ctermbg=197
endfunction

function! s:colors_fnord() abort
  highlight link StartifyPath Identifier
  highlight link StartifyFile Directory
endfunction

function! s:colors_janah() abort
  highlight User1  ctermfg=192 ctermbg=237 cterm=NONE
  highlight User2  ctermfg=167 ctermbg=237 cterm=NONE
  highlight User3  ctermfg=245 ctermbg=237 cterm=NONE
  highlight User4  ctermfg=215 ctermbg=237 cterm=NONE
  highlight User5  ctermfg=111 ctermbg=237 cterm=NONE
endfunction

function! s:colors_lucius() abort
  if &background ==# 'light'
    highlight Normal                  ctermbg=NONE guibg=NONE
    highlight CursorLine              ctermbg=255
    highlight User1      ctermfg=84   ctermbg=237  cterm=NONE
    highlight User2      ctermfg=222  ctermbg=237  cterm=NONE
    highlight User3      ctermfg=237  ctermbg=237  cterm=NONE
    highlight User4      ctermfg=255  ctermbg=237  cterm=NONE
    highlight User5      ctermfg=255  ctermbg=237  cterm=NONE
    highlight StatusLine              ctermbg=237  cterm=NONE
    highlight SignColumn ctermfg=NONE ctermbg=NONE cterm=NONE
    highlight Question   ctermfg=24   ctermbg=255  cterm=NONE
    highlight Search     ctermfg=fg   ctermbg=222  cterm=NONE
    highlight Folded                  ctermbg=253  cterm=NONE
    " highlight NormalFloat ctermfg=231 ctermbg=240  cterm=NONE
    highlight NormalFloat ctermfg=0   ctermbg=223  cterm=NONE
    highlight DirviewArchive    ctermfg=31
    highlight DirviewDirectory  ctermfg=88
    highlight DirviewImage      ctermfg=29
    highlight DirviewVideo      ctermfg=115
  endif
endfunction

augroup vimrc
  autocmd ColorScheme *      call s:colors_default()
  autocmd ColorScheme janah  call s:colors_janah()
  autocmd ColorScheme lucius call s:colors_lucius()
  autocmd ColorScheme fnord  call s:colors_fnord()
augroup END

if has('gui_running')
  set background=light
  colorscheme lucius
  set guioptions=a
  set mousehide
  if s:is_win
    autocmd GUIEnter * simalt ~x
    let &guifont = 'Consolas:h10:b'
  elseif has('gui_macvim')
    set macmeta
    let &guifont = 'Source Code Pro:h13'
  endif
  command! Bigger  let &guifont = substitute(&guifont, '\d\+', '\=submatch(0)+1', '')
  command! Smaller let &guifont = substitute(&guifont, '\d\+', '\=submatch(0)-1', '')
else
  set termguicolors
  if !has('nvim')
    let &t_8f = "\<Esc>[38:2:%lu:%lu:%lum"
    let &t_8b = "\<Esc>[48:2:%lu:%lu:%lum"
  endif
  if $TERM =~ 'alacritty'
    set background=dark
    color janah
    highlight Normal ctermbg=236
  elseif $ITERM_PROFILE == 'Light'
    set background=light
    colorscheme lucius
  else
    set background=dark
    colorscheme fnord
  endif
endif

" Statusline {{{1
command! -bar ToggleStatusline let b:stl_location  = !get(b:, 'stl_location')
command! -bar ToggleHighlight  let b:stl_highlight = !get(b:, 'stl_highlight')

nnoremap <silent><f10> :ToggleStatusline<cr>
nnoremap <silent><f11> :ToggleHighlight<cr>

set statusline=%!SetStatusline()

function! SetStatusline()
  let stl = ' %4*%<%f%*'

  if exists('b:git_dir')
    let stl    .= '%3*:%*'
    let branch  = fugitive#head(8)
    let stl    .= ((branch =~# 'master\|main') ? '%1*' : '%2*'). branch .'%*'
    let stl    .= mhi#sy_stats_wrapper()
  endif

  let stl .= '%m%r%h%w '

  " right side
  let stl .=
        \   '%= '
        \ . '%#ErrorMsg#%{&paste ? " paste " : ""}%*'
        \ . '%#WarningMsg#%{&ff != "unix" ? " ".&ff." ":""}%* '
        \ . '%#warningmsg#%{&fenc != "utf-8" && &fenc != "" ? " ".&fenc." " :""}%* '

  if get(b:, 'stl_highlight')
    let id = synID(line('.'), col('.'), 1)
    let stl .=
          \   '%#WarningMsg#['
          \ . '%{synIDattr('.id.',"name")} as '
          \ . '%{synIDattr(synIDtrans('.id.'),"name")}'
          \ . ']%* '
  endif

  if get(b:, 'stl_location')
    let stl .=
          \   '%3*[%*%v%3*,%*%l%3*/%*%L%3*]%* '
          \ . '%p%3*%%%* '
  endif

  return stl
endfunction
" }}}1

" Plugin {{{1
" Plugin: fzf {{{2
set runtimepath+=~/local/fzf

let g:fzf_layout = {'down': '40%'}

nnoremap <leader><leader> :Buffers<cr>
nnoremap <leader>C        :Colorschemes<cr>
nnoremap <leader>P        :Plugins<cr>
nnoremap <leader>S        :Scriptnames<cr>
nnoremap <leader>f        :FZF<cr>

function! s:buflist()
  return map(filter(range(1, bufnr('$')),
        \ 'bufloaded(v:val)'), 'printf("%s: %s", v:val, bufname(v:val))')
endfunction

function! s:bufopen(lines)
  if len(a:lines) < 2 | return | endif
  let cmd = get({
        \ 'ctrl-s': 'split',
        \ 'ctrl-v': 'vsplit',
        \ 'ctrl-t': 'tabedit'
        \ }, a:lines[0], 'edit')
  execute cmd '+b'.matchstr(a:lines[1], '^\d\+')
endfunction

function! s:plugopen(entry)
  execute 'Dirvish' expand(s:bundle_dir) .'/'. a:entry
  execute 'lcd' expand('%')
endfunction

command! Buffers let bl = reverse(s:buflist()) | call fzf#run({
      \ 'source':  bl,
      \ 'sink*':   function('<sid>bufopen'),
      \ 'options': '+m --expect=ctrl-s,ctrl-v,ctrl-t',
      \ 'down':    len(bl) + 2,
      \ }) | unlet bl

command! Plugins call fzf#run({
      \ 'source':  reverse(sort(map(globpath(s:bundle_dir, '*', 0, 1), 'fnamemodify(v:val, ":t")'))),
      \ 'sink':    function('<sid>plugopen'),
      \ 'options': '+m',
      \ 'left':    30
      \ })

command! Colorschemes call fzf#run({
      \ 'source':  reverse(sort(map(globpath(&rtp, 'colors/*.vim', 0, 1), 'fnamemodify(v:val, ":t:r")'))),
      \ 'sink':    'colorscheme',
      \ 'options': '+m',
      \ 'left':    30
      \ })

" Plugin: netrw {{{2
" let g:loaded_netrwPlugin = 1
let g:netrw_banner       = 0
let g:netrw_bufsettings  = 'relativenumber'
let g:netrw_keepdir      = 0
let g:netrw_liststyle    = 1
let g:netrw_sort_options = 'i'

" Plugin: surround {{{2
let g:surround_indent = 1
let g:surround_{char2nr('k')} = "<kbd>\r</kbd>"

" Plugin: tagbar {{{2
nnoremap <f2> :TagbarToggle<cr>

let g:tagbar_width     = 40
let g:tagbar_autoclose = 0
let g:tagbar_autofocus = 1
let g:tagbar_compact   = 1

" Plugin: vim-easy-align {{{2
xmap <cr> <plug>(LiveEasyAlign)

" Plugin: vim-grepper {{{2
nnoremap <leader>g :Grepper<cr>
nmap gs <plug>(GrepperOperator)
xmap gs <plug>(GrepperOperator)

highlight GrepperSideFile ctermfg=161 cterm=reverse
highlight Conceal ctermfg=NONE ctermbg=250

let g:grepper = {}
let g:grepper.dir = 'repo,filecwd'
let g:grepper.tools = ['git', 'rg', 'rubocop']
let g:grepper.rubocop = {
      \ 'grepprg': 'rubocop -femacs',
      \ 'grepformat': '%f:%l:%c: %t: %m' }

command! Todo Grepper -noprompt -tool rg -query '(TODO|FIX|FIXME|XXX|NOTE|HACK|OPTIMIZE):'

" Plugin: vim-sayonara {{{2
nnoremap <silent><leader>q  :Sayonara<cr>
nnoremap <silent><leader>Q  :Sayonara!<cr>

let g:sayonara_confirm_quit = 0

" Plugin: vim-startify {{{2
nnoremap <leader>st :Startify<cr>

let g:startify_change_to_dir       = 0
" let g:startify_custom_header       = 'startify#pad(startify#fortune#boxed())'
let g:startify_enable_special      = 0
let g:startify_fortune_use_unicode = 1
let g:startify_update_oldfiles     = 1
let g:startify_use_env             = 1

" Filetype {{{1
augroup vimrc
  " Filetype: Assembly {{{2
  let g:asmsyntax = 'nasm'
  " vim-commentary uses 'commentstring', not 'comments'
  autocmd FileType nasm let &commentstring = '; %s'

  " Filetype: C {{{2
  autocmd FileType c,cpp setl com=sO:*\ -,mO:*\ \ ,exO:*/,s1:/*,mb:*,ex:*/
  autocmd BufLeave *.{c,cpp} mark C
  autocmd BufLeave *.h       mark H

  " Filetype: cmake {{{2
  autocmd FileType cmake setlocal commentstring=#\ %s

  " Filetype: crontab {{{2
  autocmd FileType crontab setlocal nobackup nowritebackup

  " Filetype: Erlang {{{2
  autocmd FileType erlang setl com-=:%

  " Filetype: Go {{{2
  let g:go_bin_path    = $v.'/vendor/go'
  let g:go_fmt_command = 'goimports'
  let g:gofmt_on_save  = 0

  autocmd FileType go setlocal noet sts& sw& com-=:// isk-=. lcs+=tab:\ \ 

  " Filetype: Help {{{2
  autocmd FileType help
        \  setl noet
        \| execute 'silent wincmd' 'TL'[winnr('$') == 2]

  " Filetype: HTML {{{2
  autocmd FileType html setl et sts=2 sw=2

  " Filetype: Lua {{{2
  autocmd FileType lua setl com-=:# sts=2 sw=2

  " Filetype: Perl {{{2
  let perl_include_pod = 1

  autocmd FileType perl
        \  setlocal com-=:# kp=perldoc\ -f
        \| compiler perl

  autocmd BufRead,BufNewFile *.html.ep{,l} set ft=html.epl

  " Filetype: Python {{{2
  let python_highlight_all = 1

  autocmd FileType python
        \  setlocal kp=pydoc mp=./%
        \| compiler pyunit

  " Filetype: Ruby {{{2
  let g:ruby_operators                 = 1
  let g:ruby_space_errors              = 1
  let g:rubycomplete_buffer_loading    = 1
  let g:rubycomplete_classes_in_global = 1
  let g:rubycomplete_rails             = 1

  function! s:ruby()
    command! -buffer -bang Rubocop exe 'Grepper -tool rubocop -noprompt' ['-buffer',''][<bang>0]
    command! -buffer -nargs=* -bang Rspec exe '<mods> T clear; bundle exec rspec <args>' expand('%:p').['', ':'.line('.')][<bang>0]
    nnoremap <buffer> <leader>rs :vertical Rspec!<cr>
  endfunction

  autocmd BufNewFile *.rb call append(0, ['#!/usr/bin/env ruby', ''])
  autocmd FileType ruby call s:ruby()

  " -> after/ftplugin/ruby.vim

  " Filetype: Rust {{{2
  if has('nvim')
    autocmd BufRead Cargo.toml call crates#toggle()
  endif

  " Filetype: Sh, Zsh {{{2
  au FileType zsh,sh setl com-=:# sts=4 sw=4
        \| com! -buffer Lint Grepper -noprompt -buffer -grepprg shellcheck -fgcc

  " Filetype: Text, Mail, Markdown {{{2
  let g:instant_markdown_autostart = 0
  let g:instant_markdown_slow      = 1

  autocmd FileType mail     setl tw=72 wrap lbr
  autocmd FileType markdown setl tw=80 mp=gomali\ %
  autocmd FileType text     setl tw=80 fo+=t

  " Filetype: VCS {{{2
  autocmd FileType git,gitcommit setl tw=80 fo+=t

  " fugitive
  autocmd BufReadPost fugitive:// setlocal bufhidden=delete
  autocmd FileType fugitiveblame nmap q gq
  autocmd User fugitive
        \  if get(b:, 'fugitive_type', '') =~# '\v^%(tree|blob)$'
        \|   nnoremap <buffer> .. :edit %:h<cr>
        \| endif

  " signify
  let g:signify_sign_show_text = 1
  let g:signify_sign_add = '▊'
  let g:signify_sign_change = '▊'
  let g:signify_sign_delete = '▊'
  omap ic <plug>(signify-motion-inner-pending)
  xmap ic <plug>(signify-motion-inner-visual)
  omap ac <plug>(signify-motion-outer-pending)
  xmap ac <plug>(signify-motion-outer-visual)
  nnoremap <silent><leader>p :SignifyHunkDiff<cr>
  nnoremap <silent><leader>u :SignifyHunkUndo<cr>
  autocmd User SignifyAutocmds autocmd! signify CursorHold,CursorHoldI

  " Filetype: Vim, Vader {{{2
  autocmd FileType vim nnoremap <buffer><silent> <bs> :call lookup#pop()<bar>call halo#run()<cr>
  autocmd FileType vim setl sts=2 sw=2 isk-=#
" }}}2
augroup END
" }}}1

if filereadable($v.'/magic.vim')
  source $v/magic.vim
endif

" vim: sw=2 sts=2 tw=0 fdm=marker


================================================
FILE: .weechat/weechat.conf
================================================
#
# weechat -- weechat.conf
#
# WARNING: It is NOT recommended to edit this file by hand,
# especially if WeeChat is running.
#
# Use /set or similar command to change settings in WeeChat.
#
# For more info, see: https://weechat.org/doc/quickstart
#

[debug]

[startup]
command_after_plugins = ""
command_before_plugins = ""
display_logo = on
display_version = on
sys_rlimit = ""

[look]
align_end_of_lines = message
align_multiline_words = on
bar_more_down = "++"
bar_more_left = "<<"
bar_more_right = ">>"
bar_more_up = "--"
bare_display_exit_on_input = on
bare_display_time_format = "%H:%M"
buffer_auto_renumber = on
buffer_notify_default = all
buffer_position = end
buffer_search_case_sensitive = off
buffer_search_force_default = off
buffer_search_regex = off
buffer_search_where = prefix_message
buffer_time_format = "%H:%M"
color_basic_force_bold = off
color_inactive_buffer = on
color_inactive_message = on
color_inactive_prefix = on
color_inactive_prefix_buffer = on
color_inactive_time = off
color_inactive_window = on
color_nick_offline = off
color_pairs_auto_reset = 5
color_real_white = off
command_chars = ""
command_incomplete = off
confirm_quit = off
confirm_upgrade = off
day_change = on
day_change_message_1date = "-- %a, %d %b %Y --"
day_change_message_2dates = "-- %%a, %%d %%b %%Y (%a, %d %b %Y) --"
eat_newline_glitch = off
emphasized_attributes = ""
highlight = ""
highlight_regex = ""
highlight_tags = ""
hotlist_add_conditions = "${away} || ${buffer.num_displayed} == 0"
hotlist_buffer_separator = ", "
hotlist_count_max = 2
hotlist_count_min_msg = 2
hotlist_names_count = 3
hotlist_names_length = 0
hotlist_names_level = 12
hotlist_names_merged_buffers = off
hotlist_prefix = "H: "
hotlist_remove = merged
hotlist_short_names = on
hotlist_sort = group_time_asc
hotlist_suffix = ""
hotlist_unique_numbers = on
input_cursor_scroll = 20
input_share = none
input_share_overwrite = off
input_undo_max = 32
item_away_message = on
item_buffer_filter = "*"
item_buffer_zoom = "!"
item_mouse_status = "M"
item_time_format = "%H:%M"
jump_current_to_previous_buffer = on
jump_previous_buffer_when_closing = on
jump_smart_back_to_buffer = on
key_bind_safe = on
key_grab_delay = 800
mouse = on
mouse_timer_delay = 100
nick_color_force = ""
nick_color_hash = djb2
nick_color_stop_chars = "_|["
nick_prefix = ""
nick_suffix = ""
paste_auto_add_newline = on
paste_bracketed = on
paste_bracketed_timer_delay = 10
paste_max_lines = 1
prefix_action = " *"
prefix_align = right
prefix_align_max = 0
prefix_align_min = 0
prefix_align_more = "+"
prefix_align_more_after = on
prefix_buffer_align = right
prefix_buffer_align_max = 0
prefix_buffer_align_more = "+"
prefix_buffer_align_more_after = on
prefix_error = "=!="
prefix_join = "-->"
prefix_network = "--"
prefix_quit = "<--"
prefix_same_nick = ""
prefix_suffix = "|"
quote_nick_prefix = "<"
quote_nick_suffix = ">"
quote_time_format = "%H:%M:%S"
read_marker = line
read_marker_always_show = off
read_marker_string = "-"
save_config_on_exit = on
save_config_with_fsync = off
save_layout_on_exit = none
scroll_amount = 3
scroll_bottom_after_switch = off
scroll_page_percent = 100
search_text_not_found_alert = on
separator_horizontal = "-"
separator_vertical = ""
tab_width = 1
time_format = "%a, %d %b %Y %T"
window_auto_zoom = off
window_separator_horizontal = on
window_separator_vertical = on
window_title = "WeeChat ${info:version}"
word_chars_highlight = "!\u00A0,-,_,|,alnum"
word_chars_input = "!\u00A0,-,_,|,alnum"

[palette]

[color]
bar_more = lightmagenta
chat = default
chat_bg = default
chat_buffer = white
chat_channel = red
chat_day_change = cyan
chat_delimiters = 245
chat_highlight = 231
chat_highlight_bg = 167
chat_host = cyan
chat_inactive_buffer = default
chat_inactive_window = default
chat_nick = lightcyan
chat_nick_colors = "27,39,41,71,94,103,111,131,143,181"
chat_nick_offline = default
chat_nick_offline_highlight = default
chat_nick_offline_highlight_bg = blue
chat_nick_other = cyan
chat_nick_prefix = green
chat_nick_self = 63
chat_nick_suffix = green
chat_prefix_action = white
chat_prefix_buffer = brown
chat_prefix_buffer_inactive_buffer = default
chat_prefix_error = yellow
chat_prefix_join = lightgreen
chat_prefix_more = lightmagenta
chat_prefix_network = magenta
chat_prefix_quit = lightred
chat_prefix_suffix = 245
chat_read_marker = 245
chat_read_marker_bg = default
chat_server = brown
chat_tags = red
chat_text_found = yellow
chat_text_found_bg = lightmagenta
chat_time = 245
chat_time_delimiters = 252
chat_value = cyan
chat_value_null = blue
emphasized = yellow
emphasized_bg = magenta
input_actions = lightgreen
input_text_not_found = red
item_away = yellow
nicklist_away = cyan
nicklist_group = green
separator = 245
status_count_highlight = magenta
status_count_msg = brown
status_count_other = 245
status_count_private = green
status_data_highlight = lightmagenta
status_data_msg = yellow
status_data_other = 245
status_data_private = lightgreen
status_filter = green
status_more = yellow
status_mouse = green
status_name = white
status_name_ssl = lightgreen
status_nicklist_count = 245
status_number = yellow
status_time = 245

[completion]
base_word_until_cursor = on
command_inline = on
default_template = "%(nicks)|%(irc_channels)"
nick_add_space = on
nick_case_sensitive = off
nick_completer = ":"
nick_first_only = off
nick_ignore_chars = "[]`_-^"
partial_completion_alert = on
partial_completion_command = off
partial_completion_command_arg = off
partial_completion_count = on
partial_completion_other = off
partial_completion_templates = "config_options"

[history]
display_default = 5
max_buffer_lines_minutes = 0
max_buffer_lines_number = 4096
max_commands = 100
max_visited_buffers = 50

[proxy]

[network]
connection_timeout = 60
gnutls_ca_file = "/etc/ssl/certs/ca-certificates.crt"
gnutls_handshake_timeout = 30
proxy_curl = ""

[plugin]
autoload = "*,!xfer,!perl,!ruby,!python,!aspell"
debug = off
extension = ".so,.dll"
path = "%h/plugins"
save_config_on_unload = on

[bar]
buflist.color_bg = default
buflist.color_delim = default
buflist.color_fg = default
buflist.conditions = ""
buflist.filling_left_right = vertical
buflist.filling_top_bottom = columns_vertical
buflist.hidden = off
buflist.items = "buflist"
buflist.position = left
buflist.priority = 0
buflist.separator = on
buflist.size = 0
buflist.size_max = 0
buflist.type = root
fset.color_bg = default
fset.color_delim = cyan
fset.color_fg = default
fset.conditions = "${buffer.full_name} == fset.fset"
fset.filling_left_right = vertical
fset.filling_top_bottom = horizontal
fset.hidden = off
fset.items = "fset"
fset.position = top
fset.priority = 0
fset.separator = on
fset.size = 3
fset.size_max = 3
fset.type = window
input.color_bg = default
input.color_delim = 245
input.color_fg = default
input.conditions = ""
input.filling_left_right = vertical
input.filling_top_bottom = horizontal
input.hidden = off
input.items = "[input_prompt]+(away),[input_search],[input_paste],input_text"
input.position = bottom
input.priority = 1000
input.separator = off
input.size = 1
input.size_max = 0
input.type = window
nicklist.color_bg = default
nicklist.color_delim = cyan
nicklist.color_fg = 245
nicklist.conditions = "${nicklist}"
nicklist.filling_left_right = vertical
nicklist.filling_top_bottom = columns_vertical
nicklist.hidden = on
nicklist.items = "buffer_nicklist"
nicklist.position = right
nicklist.priority = 200
nicklist.separator = on
nicklist.size = 0
nicklist.size_max = 0
nicklist.type = window
status.color_bg = black
status.color_delim = 241
status.color_fg = 231
status.conditions = ""
status.filling_left_right = vertical
status.filling_top_bottom = horizontal
status.hidden = off
status.items = "buffer_plugin> +buffer_name +buffer_modes +buffer_zoom,scroll,[lag],completion"
status.position = bottom
status.priority = 500
status.separator = off
status.size = 1
status.size_max = 0
status.type = window
title.color_bg = black
title.color_delim = cyan
title.color_fg = 231
title.conditions = ""
title.filling_left_right = vertical
title.filling_top_bottom = horizontal
title.hidden = off
title.items = "buffer_title"
title.position = top
title.priority = 500
title.separator = off
title.size = 1
title.size_max = 0
title.type = window

[layout]

[notify]

[filter]
irc_smart = on;*;irc_smart_filter;*

[key]
ctrl-? = "/input delete_previous_char"
ctrl-A = "/input move_beginning_of_line"
ctrl-B = "/input move_previous_char"
ctrl-C_ = "/input insert \x1F"
ctrl-Cb = "/input insert \x02"
ctrl-Cc = "/input insert \x03"
ctrl-Ci = "/input insert \x1D"
ctrl-Co = "/input insert \x0F"
ctrl-Cv = "/input insert \x16"
ctrl-D = "/input delete_next_char"
ctrl-E = "/input move_end_of_line"
ctrl-F = "/input move_next_char"
ctrl-H = "/input delete_previous_char"
ctrl-I = "/input complete_next"
ctrl-J = "/input return"
ctrl-K = "/input delete_end_of_line"
ctrl-L = "/window refresh"
ctrl-M = "/input return"
ctrl-N = "/buffer +1"
ctrl-P = "/buffer -1"
ctrl-R = "/input search_text_here"
ctrl-Sctrl-U = "/input set_unread"
ctrl-T = "/input transpose_chars"
ctrl-U = "/input delete_beginning_of_line"
ctrl-W = "/input delete_previous_word"
ctrl-X = "/input switch_active_buffer"
ctrl-Y = "/input clipboard_paste"
meta-meta-OP = "/bar scroll buflist * b"
meta-meta-OQ = "/bar scroll buflist * e"
meta-meta2-11~ = "/bar scroll buflist * b"
meta-meta2-12~ = "/bar scroll buflist * e"
meta-meta2-1~ = "/window scroll_top"
meta-meta2-23~ = "/bar scroll nicklist * b"
meta-meta2-24~ = "/bar scroll nicklist * e"
meta-meta2-4~ = "/window scroll_bottom"
meta-meta2-5~ = "/window scroll_up"
meta-meta2-6~ = "/window scroll_down"
meta-meta2-7~ = "/window scroll_top"
meta-meta2-8~ = "/window scroll_bottom"
meta-meta2-A = "/buffer -1"
meta-meta2-B = "/buffer +1"
meta-meta2-C = "/buffer +1"
meta-meta2-D = "/buffer -1"
meta-- = "/filter toggle @"
meta-/ = "/input jump_last_buffer_displayed"
meta-0 = "/buffer *10"
meta-1 = "/buffer *1"
meta-2 = "/buffer *2"
meta-3 = "/buffer *3"
meta-4 = "/buffer *4"
meta-5 = "/buffer *5"
meta-6 = "/buffer *6"
meta-7 = "/buffer *7"
meta-8 = "/buffer *8"
meta-9 = "/buffer *9"
meta-< = "/input jump_previously_visited_buffer"
meta-= = "/filter toggle"
meta-> = "/input jump_next_visited_buffer"
meta-OA = "/input history_global_previous"
meta-OB = "/input history_global_next"
meta-OC = "/input move_next_word"
meta-OD = "/input move_previous_word"
meta-OF = "/input move_end_of_line"
meta-OH = "/input move_beginning_of_line"
meta-OP = "/bar scroll buflist * -100%"
meta-OQ = "/bar scroll buflist * +100%"
meta-Oa = "/input history_global_previous"
meta-Ob = "/input history_global_next"
meta-Oc = "/input move_next_word"
meta-Od = "/input move_previous_word"
meta2-11^ = "/bar scroll buflist * -100%"
meta2-11~ = "/bar scroll buflist * -100%"
meta2-12^ = "/bar scroll buflist * +100%"
meta2-12~ = "/bar scroll buflist * +100%"
meta2-15~ = "/buffer -1"
meta2-17~ = "/buffer +1"
meta2-18~ = "/window -1"
meta2-19~ = "/window +1"
meta2-1;3A = "/buffer -1"
meta2-1;3B = "/buffer +1"
meta2-1;3C = "/buffer +1"
meta2-1;3D = "/buffer -1"
meta2-1;3F = "/window scroll_bottom"
meta2-1;3H = "/window scroll_top"
meta2-1;3P = "/bar scroll buflist * b"
meta2-1;3Q = "/bar scroll buflist * e"
meta2-1;5A = "/input history_global_previous"
meta2-1;5B = "/input history_global_next"
meta2-1;5C = "/input move_next_word"
meta2-1;5D = "/input move_previous_word"
meta2-1;5P = "/bar scroll buflist * -100%"
meta2-1;5Q = "/bar scroll buflist * +100%"
meta2-1~ = "/input move_beginning_of_line"
meta2-200~ = "/input paste_start"
meta2-201~ = "/input paste_stop"
meta2-20~ = "/bar scroll title * -30%"
meta2-21~ = "/bar scroll title * +30%"
meta2-23;3~ = "/bar scroll nicklist * b"
meta2-23~ = "/bar scroll nicklist * -100%"
meta2-24;3~ = "/bar scroll nicklist * e"
meta2-24~ = "/bar scroll nicklist * +100%"
meta2-3~ = "/input delete_next_char"
meta2-4~ = "/input move_end_of_line"
meta2-5;3~ = "/window scroll_up"
meta2-5~ = "/window page_up"
meta2-6;3~ = "/window scroll_down"
meta2-6~ = "/window page_down"
meta2-7~ = "/input move_beginning_of_line"
meta2-8~ = "/input move_end_of_line"
meta2-A = "/input history_previous"
meta2-B = "/input history_next"
meta2-C = "/input move_next_char"
meta2-D = "/input move_previous_char"
meta2-F = "/input move_end_of_line"
meta2-G = "/window page_down"
meta2-H = "/input move_beginning_of_line"
meta2-I = "/window page_up"
meta2-Z = "/input complete_previous"
meta2-[E = "/buffer -1"
meta-_ = "/input redo"
meta-a = "/input jump_smart"
meta-b = "/input move_previous_word"
meta-d = "/input delete_next_word"
meta-f = "/input move_next_word"
meta-h = "/input hotlist_clear"
meta-jmeta-f = "/buffer -"
meta-jmeta-l = "/buffer +"
meta-jmeta-r = "/server raw"
meta-jmeta-s = "/server jump"
meta-j01 = "/buffer *1"
meta-j02 = "/buffer *2"
meta-j03 = "/buffer *3"
meta-j04 = "/buffer *4"
meta-j05 = "/buffer *5"
meta-j06 = "/buffer *6"
meta-j07 = "/buffer *7"
meta-j08 = "/buffer *8"
meta-j09 = "/buffer *9"
meta-j10 = "/buffer *10"
meta-j11 = "/buffer *11"
meta-j12 = "/buffer *12"
meta-j13 = "/buffer *13"
meta-j14 = "/buffer *14"
meta-j15 = "/buffer *15"
meta-j16 = "/buffer *16"
meta-j17 = "/buffer *17"
meta-j18 = "/buffer *18"
meta-j19 = "/buffer *19"
meta-j20 = "/buffer *20"
meta-j21 = "/buffer *21"
meta-j22 = "/buffer *22"
meta-j23 = "/buffer *23"
meta-j24 = "/buffer *24"
meta-j25 = "/buffer *25"
meta-j26 = "/buffer *26"
meta-j27 = "/buffer *27"
meta-j28 = "/buffer *28"
meta-j29 = "/buffer *29"
meta-j30 = "/buffer *30"
meta-j31 = "/buffer *31"
meta-j32 = "/buffer *32"
meta-j33 = "/buffer *33"
meta-j34 = "/buffer *34"
meta-j35 = "/buffer *35"
meta-j36 = "/buffer *36"
meta-j37 = "/buffer *37"
meta-j38 = "/buffer *38"
meta-j39 = "/buffer *39"
meta-j40 = "/buffer *40"
meta-j41 = "/buffer *41"
meta-j42 = "/buffer *42"
meta-j43 = "/buffer *43"
meta-j44 = "/buffer *44"
meta-j45 = "/buffer *45"
meta-j46 = "/buffer *46"
meta-j47 = "/buffer *47"
meta-j48 = "/buffer *48"
meta-j49 = "/buffer *49"
meta-j50 = "/buffer *50"
meta-j51 = "/buffer *51"
meta-j52 = "/buffer *52"
meta-j53 = "/buffer *53"
meta-j54 = "/buffer *54"
meta-j55 = "/buffer *55"
meta-j56 = "/buffer *56"
meta-j57 = "/buffer *57"
meta-j58 = "/buffer *58"
meta-j59 = "/buffer *59"
meta-j60 = "/buffer *60"
meta-j61 = "/buffer *61"
meta-j62 = "/buffer *62"
meta-j63 = "/buffer *63"
meta-j64 = "/buffer *64"
meta-j65 = "/buffer *65"
meta-j66 = "/buffer *66"
meta-j67 = "/buffer *67"
meta-j68 = "/buffer *68"
meta-j69 = "/buffer *69"
meta-j70 = "/buffer *70"
meta-j71 = "/buffer *71"
meta-j72 = "/buffer *72"
meta-j73 = "/buffer *73"
meta-j74 = "/buffer *74"
meta-j75 = "/buffer *75"
meta-j76 = "/buffer *76"
meta-j77 = "/buffer *77"
meta-j78 = "/buffer *78"
meta-j79 = "/buffer *79"
meta-j80 = "/buffer *80"
meta-j81 = "/buffer *81"
meta-j82 = "/buffer *82"
meta-j83 = "/buffer *83"
meta-j84 = "/buffer *84"
meta-j85 = "/buffer *85"
meta-j86 = "/buffer *86"
meta-j87 = "/buffer *87"
meta-j88 = "/buffer *88"
meta-j89 = "/buffer *89"
meta-j90 = "/buffer *90"
meta-j91 = "/buffer *91"
meta-j92 = "/buffer *92"
meta-j93 = "/buffer *93"
meta-j94 = "/buffer *94"
meta-j95 = "/buffer *95"
meta-j96 = "/buffer *96"
meta-j97 = "/buffer *97"
meta-j98 = "/buffer *98"
meta-j99 = "/buffer *99"
meta-k = "/input grab_key_command"
meta-l = "/window bare"
meta-m = "/mute mouse toggle"
meta-n = "/window scroll_next_highlight"
meta-p = "/window scroll_previous_highlight"
meta-r = "/input delete_line"
meta-s = "/mute aspell toggle"
meta-u = "/window scroll_unread"
meta-wmeta-meta2-A = "/window up"
meta-wmeta-meta2-B = "/window down"
meta-wmeta-meta2-C = "/window right"
meta-wmeta-meta2-D = "/window left"
meta-wmeta2-1;3A = "/window up"
meta-wmeta2-1;3B = "/window down"
meta-wmeta2-1;3C = "/window right"
meta-wmeta2-1;3D = "/window left"
meta-wmeta-b = "/window balance"
meta-wmeta-s = "/window swap"
meta-x = "/input zoom_merged_buffer"
meta-z = "/window zoom"
ctrl-_ = "/input undo"

[key_search]
ctrl-I = "/input search_switch_where"
ctrl-J = "/input search_stop_here"
ctrl-M = "/input search_stop_here"
ctrl-Q = "/input search_stop"
ctrl-R = "/input search_switch_regex"
meta2-A = "/input search_previous"
meta2-B = "/input search_next"
meta-c = "/input search_switch_case"

[key_cursor]
ctrl-J = "/cursor stop"
ctrl-M = "/cursor stop"
meta-meta2-A = "/cursor move area_up"
meta-meta2-B = "/cursor move area_down"
meta-meta2-C = "/cursor move area_right"
meta-meta2-D = "/cursor move area_left"
meta2-1;3A = "/cursor move area_up"
meta2-1;3B = "/cursor move area_down"
meta2-1;3C = "/cursor move area_right"
meta2-1;3D = "/cursor move area_left"
meta2-A = "/cursor move up"
meta2-B = "/cursor move down"
meta2-C = "/cursor move right"
meta2-D = "/cursor move left"
@item(buffer_nicklist):K = "/window ${_window_number};/kickban ${nick}"
@item(buffer_nicklist):b = "/window ${_window_number};/ban ${nick}"
@item(buffer_nicklist):k = "/window ${_window_number};/kick ${nick}"
@item(buffer_nicklist):q = "/window ${_window_number};/query ${nick};/cursor stop"
@item(buffer_nicklist):w = "/window ${_window_number};/whois ${nick}"
@chat:Q = "hsignal:chat_quote_time_prefix_message;/cursor stop"
@chat:m = "hsignal:chat_quote_message;/cursor stop"
@chat:q = "hsignal:chat_quote_prefix_message;/cursor stop"

[key_mouse]
@bar(buflist):ctrl-wheeldown = "hsignal:buflist_mouse"
@bar(buflist):ctrl-wheelup = "hsignal:buflist_mouse"
@bar(input):button2 = "/input grab_mouse_area"
@bar(nicklist):button1-gesture-down = "/bar scroll nicklist ${_window_number} +100%"
@bar(nicklist):button1-gesture-down-long = "/bar scroll nicklist ${_window_number} e"
@bar(nicklist):button1-gesture-up = "/bar scroll nicklist ${_window_number} -100%"
@bar(nicklist):button1-gesture-up-long = "/bar scroll nicklist ${_window_number} b"
@chat(fset.fset):button1 = "/window ${_window_number};/fset -go ${_chat_line_y}"
@chat(fset.fset):button2* = "hsignal:fset_mouse"
@chat(fset.fset):wheeldown = "/fset -down 5"
@chat(fset.fset):wheelup = "/fset -up 5"
@chat(script.scripts):button1 = "/window ${_window_number};/script go ${_chat_line_y}"
@chat(script.scripts):button2 = "/window ${_window_number};/script go ${_chat_line_y};/script installremove -q ${script_name_with_extension}"
@chat(script.scripts):wheeldown = "/script down 5"
@chat(script.scripts):wheelup = "/script up 5"
@item(buffer_nicklist):button1 = "/window ${_window_number};/query ${nick}"
@item(buffer_nicklist):button1-gesture-left = "/window ${_window_number};/kick ${nick}"
@item(buffer_nicklist):button1-gesture-left-long = "/window ${_window_number};/kickban ${nick}"
@item(buffer_nicklist):button2 = "/window ${_window_number};/whois ${nick}"
@item(buffer_nicklist):button2-gesture-left = "/window ${_window_number};/ban ${nick}"
@item(buflist):button1* = "hsignal:buflist_mouse"
@item(buflist):button2* = "hsignal:buflist_mouse"
@item(buflist2):button1* = "hsignal:buflist_mouse"
@item(buflist2):button2* = "hsignal:buflist_mouse"
@item(buflist3):button1* = "hsignal:buflist_mouse"
@item(buflist3):button2* = "hsignal:buflist_mouse"
@bar:wheeldown = "/bar scroll ${_bar_name} ${_window_number} +20%"
@bar:wheelup = "/bar scroll ${_bar_name} ${_window_number} -20%"
@chat:button1 = "/window ${_window_number}"
@chat:button1-gesture-left = "/window ${_window_number};/buffer -1"
@chat:button1-gesture-left-long = "/window ${_window_number};/buffer 1"
@chat:button1-gesture-right = "/window ${_window_number};/buffer +1"
@chat:button1-gesture-right-long = "/window ${_window_number};/input jump_last_buffer"
@chat:ctrl-wheeldown = "/window scroll_horiz -window ${_window_number} +10%"
@chat:ctrl-wheelup = "/window scroll_horiz -window ${_window_number} -10%"
@chat:wheeldown = "/window scroll_down -window ${_window_number}"
@chat:wheelup = "/window scroll_up -window ${_window_number}"
@*:button3 = "/cursor go ${_x},${_y}"


================================================
FILE: .xinitrc
================================================
#!/bin/sh

failsafe="xterm -ls -T failsafe -geometry 80x24-0-0"

trap "exec $failsafe" EXIT SIGHUP SIGINT SIGPIPE SIGTERM SIGIO

test -r ~/.Xdefaults  && xrdb ~/.Xdefaults
test -r ~/.Xresources && xrdb ~/.Xresources
test -r ~/.Xmodmap    && xmodmap ~/.Xmodmap

xset b off
xset m 2 5

#feh --bg-max /data/pics/wallpapers/github/octowhite.png
#feh --bg-max /data/pics/wallpapers/trigonometry.jpg
#feh --bg-max /data/pics/wallpapers/fp_is_the_right_way.jpg
#feh --bg-max /data/pics/wallpapers/steampunk2.jpg
feh --bg-fill /data/pics/wallpapers/haskell.png

pgrep urxvtd || urxvtd -f -q -o
pgrep ssh-agent || eval $(ssh-agent) && SSH_ASKPASS=ssh-askpass ssh-add < /dev/null

autocutsel -selection CLIPBOARD -fork &
autocutsel -selection PRIMRARY  -fork &

# Java Swing fix
wmname LG3D

while true; do
    xsetroot -name "$(date +'%d %b %R')"
    sleep 1m
done &

exec dwm
#xmonad


================================================
FILE: .yarnrc
================================================
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


cache-folder "/Users/mhi/.yarn/cache"
disable-self-update-check true
global-folder "/Users/mhi/.yarn/global"
prefix "/Users/mhi/.yarn"


================================================
FILE: .zsh/.zlogout
================================================
#!/usr/bin/zsh

which sudo &>/dev/null && sudo -k
clear

[[ -n $SSH_CONNECTION ]] && echo -n "Connection closed:  "; date


================================================
FILE: .zsh/.zprofile
================================================
# Opposed to Bash, Zsh doesn't source ~/.profile on its own.

if [[ -r ~/.profile ]]; then
  emulate sh -c 'source ~/.profile'
else
  echo 'No ~/.profile found.'
fi


================================================
FILE: .zsh/.zshrc
================================================
#!/usr/bin/env zsh

if [[ -r ~/.shrc ]]; then
    source ~/.shrc
else
    echo 'No .shrc found.'
fi

[[ -d $ZDOTDIR/completion ]] && fpath=($ZDOTDIR/completion $fpath)

zmodload -i zsh/complist

autoload -Uz compinit && compinit
autoload -Uz edit-command-line
autoload -Uz run-help

bindkey -e
umask 077

watch=all
logcheck=60
WATCHFMT="%n from %M has %a tty%l at %T %W"

alias -g G='| grep -i'
alias -g L='| less -r'
alias -g N='>/dev/null'
alias -g E='2>/dev/null'

alias j='ls -lhd -- *(D-/)'
alias k='ls -lhX -- *(D-^/)'
alias n='ls -lhS -- *(DOL[1,5]^/)'

# options {{{1

setopt cdablevars
setopt checkjobs
setopt completeinword
setopt correct
setopt globcomplete
setopt interactivecomments
setopt listpacked
setopt longlistjobs
setopt menucomplete
setopt no_autocd
setopt no_beep
setopt no_hist_beep
setopt no_listrowsfirst
setopt no_nomatch
setopt no_print_exit_value
setopt no_rm_star_silent
setopt nohup
setopt nolistambiguous
setopt nolog
setopt notify
setopt numericglobsort
setopt promptsubst
# setopt extendedglob

# history {{{1

HISTFILE=~/.zsh/history
HISTSIZE=2048
SAVEHIST=2048

setopt append_history
setopt bang_hist
setopt hist_ignore_all_dups
setopt hist_ignore_space
setopt hist_reduce_blanks
setopt hist_verify
setopt inc_append_history   # add commands as they're typed
setopt share_history        # share history between sessions

# prompt {{{1

autoload -U colors && colors

precmd() { _prompt }
SPROMPT="%R -> %r:%f "
PROMPT2="+%f "
PROMPT3="Select:%f "

# bindings {{{1

_zle_backward_kill_word() {
    LBUFFER="$({ sed -E 's#[^ _/\-]+[ _/\-]+$##' | sed -E 's#[^ _/\-]+$##' } <<< $LBUFFER)"
}

_zle_ctrl_z() {
    if [[ $#BUFFER -eq 0 ]]; then
        BUFFER=fg
        zle accept-line
    else
        zle push-input
        zle clear-screen
    fi
}

_zle_fancy_dot() {
    local -a split
    split=( ${=LBUFFER} )
    local dir=$split[-1]
    case $LBUFFER in
        .)
            LBUFFER='cd ../'
            RBUFFER=' && l'
            [[ -d $dir ]] && zle -M $dir(:a:h)
            ;;
        *.)
            zle self-insert
            LBUFFER+=/
            [[ -d $dir ]] && zle -M $dir(:a:h)
            ;;
        *../)
            zle self-insert
            zle self-insert
            LBUFFER+=/
            [[ -d $dir ]] && zle -M $dir(:a:h)
            ;;
        *)
            zle self-insert
    esac
}

_zle_insert_last_typed_word() {
        zle insert-last-word -- 0 -1
}

_zle_jump_after_first_word() {
    CURSOR=$#BUFFER[(w)1]
}

_zle_sudo() {
    LBUFFER="sudo $LBUFFER"
}

zle -N _zle_backward_kill_word
zle -N _zle_ctrl_z
zle -N _zle_fancy_dot
zle -N _zle_insert_last_typed_word
zle -N _zle_jump_after_first_word
zle -N _zle_sudo
zle -N edit-command-line

bindkey ''   up-line-or-search
bindkey ''   up-line-or-search
bindkey ''   down-line-or-search
bindkey ''   _zle_backward_kill_word
bindkey 'e'  edit-command-line
bindkey 'm'  expand-word
bindkey 'n'  list-expand
bindkey ''   _zle_ctrl_z
bindkey '.'    _zle_fancy_dot
bindkey ';f'   _zle_jump_after_first_word
bindkey ';g'   _zle_insert_last_typed_word
bindkey ';s'   _zle_sudo

bindkey -M menuselect 'h' backward-char
bindkey -M menuselect 'i' accept-and-menu-complete
bindkey -M menuselect 'j' down-line-or-history
bindkey -M menuselect 'k' up-line-or-history
bindkey -M menuselect 'l' forward-char

# completion {{{1

zstyle ':completion:*'                    matcher-list 'm:{a-z}={A-Z} r:|[-_.+,]=** r:|=*'
zstyle ':completion:*:default'            list-colors  ${(s.:.)LS_COLORS} 'ma=01;38;05;255;48;05;161'
zstyle ':completion:*:descriptions'       format       '→ %B%d%b%'
zstyle ':completion:*:approximate:*'      max-errors   '(( reply=($#PREFIX+$#SUFFIX)/3 ))'
zstyle ':completion::complete:*'          use-cache    true
zstyle ':completion:*'                    cache-path   ~/.zsh/cache
zstyle ':completion:*'                    verbose      true
zstyle ':completion:*'                    menu         select=2
zstyle ':completion:*'                    special-dirs ..
zstyle ':completion:*'                    group-name   ''

# zstyle ':completion:*:kill:*'             command      'ps f -u $USER -wo pid,ppid,state,%cpu,%mem,tty,cmd'
# zstyle ':completion:*:*:kill:*:processes' list-colors  '=(#b) #([0-9]#)*=0=01;31'

compctl -g '*.class'      java
compctl -g '*.(c|o|a)':   cc gcc
compctl -g '*.el'         erl erlc
compctl -g '*.(hs|hls)'   hugs ghci
compctl -g '*.java'       javac
compctl -g '*.pl'         perl
compctl -g '*.py'         python
compctl -g '*.rb'         ruby

compctl -g '*.pdf'        acrorad xpdf zathura z
compctl -g '*.chm'        chmsee c
compctl -g '*.djvu'       djview
compctl -g '*.lyx'        lyx
compctl -g '*.ps'         gs ghostview ps2pdf ps2ascii
compctl -g '*.tex'        tex latex slitex pdflatex
compctl -g '*.dvi'        dvips dvipdf xdvi dviselect dvitype

compctl -g '*.(bz2|tbz2)' tar bzip2 bunzip2
compctl -g '*.(gz|tgz)'   tar gzip gunzip
compctl -g '*.pax'        pax
compctl -g '*.rar'        rar unrar
compctl -g '*.zip'        zip unzip

compctl -g '*.(htm|html|php)' firefox iceweasel opera lynx w3m link2 dillo uzbl surf

compctl -fg '*.(avi|mp*g|mp4|wmv|ogm|mkv|xvid|divx)' mplayer gmplayer vlc
compctl -g '*.(jp*g|gif|xpm|png|bmp)'                display gimp feh geeqie fbsetbg
compctl -g '*.(mp3|m4a|ogg|au|wav)'                  cmus cmus-remote xmms cr

compctl -g '*.(rar|zip)' unbook

_completion_tmux_sessions() {
    local -a sessions=( ${(f)"$(command tmux list-sessions)"} )
    _describe -t sessions '' sessions "$@"
}

compdef _completion_tmux_sessions tm

# }}}

command_not_found_handler() { ~/bin/shell_function_missing $* }

# http://mika.l3ib.org/code/zsh-functions/backdoor
backdoor() {
    if [[ $1 == -f ]]; then
        shift
        local fifo
        exec {fifo}<>$1
        backdoor -i $fifo
    elif [[ $1 == -i ]]; then
        shift
        zle -F $1 backdoor
    elif [[ $1 == <-> ]]; then
        local line
        # can get DoSed by someone writing data without a newline,
        # but obviously that's the least of your problems if the
        # other end is not trusted
        if ! IFS= read -r line <&$1; then
            zle -F $1
            return 1
        fi
        eval $line
    else
        echo >&2 "Usage: backdoor -f [fifo]"
        echo >&2 "       backdoor -i [fd]"
        echo >&2
        echo >&2 "Will read lines from given fifo and eval them in the zle -F context"
        echo >&2 "You can also attach it to an fd yourself with backdoor -i fd, and"
        echo >&2 "it will run all lines read from FD."
    fi
}

# vim: fdm=marker


================================================
FILE: .zsh/completion/_mix
================================================
#compdef mix

_arguments \
  '1:task names:->tasks' \
  '*:task arguments:->arguments'

local candidates

case $state in
  tasks)
    candidates=(${(f)"$(mix help | tail -n+2 | grep '^mix ' | cut -b5-)"})
    candidates=(${candidates/ *\# /:})
    _describe 'tasks' candidates
    return
esac

case $words[2] in
  archive.install)
    case $words[3] in
      hex)
        if [[ -z $words[4] ]]; then
          _message 'enter query for searching remote hex packges'
        else
          candidates=(${(f)"$(mix hex.search $words[4] | tail -n+2 | sed 's/  http.*$//')"})
          candidates=(${candidates/[[:space:]]##/:})
          _describe 'remote hex archives' candidates
        fi
        ;;
    esac
    ;;
  archive.uninstall)
    candidates=(${(f)"$(mix archive | grep '^* ' | cut -b3-)"})
    _describe 'local archives' candidates
    ;;
  help)
    candidates=(${(f)"$(mix help | tail -n+2 | grep '^mix ' | cut -b5-)"})
    candidates=(${candidates/ *\# /:})
    _describe 'tasks' candidates
    ;;
  *)
    _files
    ;;
esac


================================================
FILE: .zsh/dircolors.dark
================================================
# Thanks, https://github.com/trapd00r/LS_COLORS/blob/master/LS_COLORS

# core {{{1
BLK                   38;5;68
CAPABILITY            38;5;17
CHR                   38;5;113;1
DIR                   38;5;117;1
DOOR                  38;5;127
EXEC                  38;5;208;1
FIFO                  38;5;126
FILE                  0
LINK                  target
MULTIHARDLINK         38;5;222;1
# "NORMAL don't reset the bold attribute -
# https://github.com/trapd00r/LS_COLORS/issues/11
#NORMAL                38;5;254
NORMAL                0
ORPHAN                48;5;196;38;5;232;1
OTHER_WRITABLE        38;5;220;1
SETGID                48;5;3;38;5;0
SETUID                38;5;220;1;3;100;1
SOCK                  38;5;197
STICKY                38;5;86;48;5;234
STICKY_OTHER_WRITABLE 48;5;235;38;5;139;3

*LS_COLORS 48;5;89;38;5;197;1;3;4;7 # :-)
# }}}
# documents {{{1
*README               38;5;220;1
*README.rst           38;5;220;1
*README.md            38;5;220;1
*LICENSE              38;5;220;1
*COPYING              38;5;220;1
*INSTALL              38;5;220;1
*COPYRIGHT            38;5;220;1
*AUTHORS              38;5;220;1
*HISTORY              38;5;220;1
*CONTRIBUTORS         38;5;220;1
*PATENTS              38;5;220;1
*VERSION              38;5;220;1
*NOTICE               38;5;220;1
*CHANGES              38;5;220;1
.log                  38;5;190
# plain-text {{{2
.txt                  38;5;253
# markup {{{2
.adoc                 38;5;184
.asciidoc             38;5;184
.etx                  38;5;184
.info                 38;5;184
.markdown             38;5;184
.md                   38;5;184
.mkd                  38;5;184
.nfo                  38;5;184
.pod                  38;5;184
.rst                  38;5;184
.tex                  38;5;184
.textile              38;5;184
# key-value, non-relational data {{{2
.bib                  38;5;178
.json                 38;5;178
.jsonl                38;5;178
.jsonnet              38;5;178
.libsonnet            38;5;142
.ndjson               38;5;178
.msg                  38;5;178
.pgn                  38;5;178
.rss                  38;5;178
.xml                  38;5;178
.fxml                 38;5;178
.toml                 38;5;178
.yaml                 38;5;178
.yml                  38;5;178
.RData                38;5;178
.rdata                38;5;178
.xsd                  38;5;178
.dtd                  38;5;178
.sgml                 38;5;178
.rng                  38;5;178
.rnc                  38;5;178
# }}}
# binary {{{2
.cbr                  38;5;141
.cbz                  38;5;141
.chm                  38;5;141
.djvu                 38;5;141
.pdf                  38;5;141
.PDF                  38;5;141
.mobi                 38;5;141
.epub                 38;5;141
# words {{{3
.docm                 38;5;111;4
.doc                  38;5;111
.docx                 38;5;111
.odb                  38;5;111
.odt                  38;5;111
.rtf                  38;5;111
# presentation {{{3
.odp                  38;5;166
.pps                  38;5;166
.ppt                  38;5;166
.pptx                 38;5;166
#   Powerpoint show
.ppts                 38;5;166
#   Powerpoint with enabled macros
.pptxm                38;5;166;4
#   Powerpoint show with enabled macros
.pptsm                38;5;166;4
# spreadsheet {{{3
.csv                  38;5;78
.tsv                  38;5;78
#   Open document spreadsheet
.ods                  38;5;112
.xla                  38;5;76
#   Excel spreadsheet
.xls                  38;5;112
.xlsx                 38;5;112
#   Excel spreadsheet with macros
.xlsxm                38;5;112;4
#   Excel module
.xltm                 38;5;73;4
.xltx                 38;5;73
#   macOS office suite {{{3
.pages                38;5;111
.numbers              38;5;112
.key                  38;5;166
# }}}
# }}}
# configs {{{2
*config               1
*cfg                  1
*conf                 1
*rc                   1
*authorized_keys      1
*known_hosts          1
.ini                  1
.plist                1
#   vim
.viminfo              1
#   cisco VPN client configuration
.pcf                  1
#   adobe photoshop proof settings file
.psf                  1
#   Sublime Text config
.hidden-color-scheme  1
.hidden-tmTheme       1
.last-run             1
.merged-ca-bundle     1
.sublime-build        1
.sublime-commands     1
.sublime-keymap       1
.sublime-settings     1
.sublime-snippet      1
.sublime-project      1
.sublime-workspace    1
.tmTheme              1
.user-ca-bundle       1
# eclipse
.epf                  1
# }}}
# }}}
# code {{{1
# version control {{{2
.git                  38;5;197
.gitignore            38;5;240
.gitattributes        38;5;240
.gitmodules           38;5;240

# shell {{{2
.awk                  38;5;172
.bash                 38;5;172
.bat                  38;5;172
.BAT                  38;5;172
.sed                  38;5;172
.sh                   38;5;172
.zsh                  38;5;172
.vim                  38;5;172
.kak                  38;5;172

# interpreted {{{2
.ahk                  38;5;41
# python
.py                   38;5;41
.ipynb                38;5;41
# ruby
.rb                   38;5;41
.gemspec              38;5;41
# perl
.pl                   38;5;208
.PL                   38;5;160
.t                    38;5;114
# sql
.msql                 38;5;222
.mysql                38;5;222
.pgsql                38;5;222
.sql                  38;5;222
#   Tool Command Language
.tcl                  38;5;64;1
# R language
.r                    38;5;49
.R                    38;5;49
# GrADS script
.gs                   38;5;81
# Clojure
.clj                  38;5;41
.cljs                 38;5;41
.cljc                 38;5;41
# Clojure gorilla REPL worksheet
.cljw                 38;5;41
# Scala
.scala                38;5;41
.sc                   38;5;41
# Dart
.dart                 38;5;51

# compiled {{{2
#
#   assembly language
.asm                  38;5;81
#   LISP
.cl                   38;5;81
.lisp                 38;5;81
.rkt                  38;5;81
#   lua
.lua                  38;5;81
#   Moonscript
.moon                 38;5;81
#   C
.c                    38;5;81
.C                    38;5;81
.h                    38;5;110
.H                    38;5;110
.tcc                  38;5;110
#   C++
.c++                  38;5;81
.h++                  38;5;110
.hpp                  38;5;110
.hxx                  38;5;110
.ii                   38;5;110
#   method file for Objective C
.M                    38;5;110
.m                    38;5;110
#   Csharp
.cc                   38;5;81
.cs                   38;5;81
.cp                   38;5;81
.cpp                  38;5;81
.cxx                  38;5;81
#   Crystal
.cr                   38;5;81
#   Google golang
.go                   38;5;81
#   fortran
.f                    38;5;81
.F                    38;5;81
.for                  38;5;81
.ftn                  38;5;81
.f90                  38;5;81
.F90                  38;5;81
.f95                  38;5;81
.F95                  38;5;81
.f03                  38;5;81
.F03                  38;5;81
.f08                  38;5;81
.F08                  38;5;81
# Nim
.nim                  38;5;81
.nimble               38;5;81
#   pascal
.s                    38;5;110
.S                    38;5;110
#   Rust
.rs                   38;5;81
#   AppleScript
.scpt                 38;5;219
#   Swift
.swift                38;5;219
#   ?
.sx                   38;5;81
# Vala
.vala                 38;5;81
.vapi                 38;5;81
#   interface file in GHC - https://github.com/trapd00r/LS_COLORS/pull/9
.hi                   38;5;110
#   haskell
.hs                   38;5;81
.lhs                  38;5;81
#   agda
.agda                 38;5;81
.lagda                38;5;81
.lagda.tex            38;5;81
.lagda.rst            38;5;81
.lagda.md             38;5;81
.agdai                38;5;110
#   Zig
.zig                  38;5;81
# V
.v                    38;5;81

# binaries {{{2
# compiled apps for interpreted languages
.pyc                  38;5;240
# }}}
# orchestration {{{2
.tf                   38;5;168
.tfstate              38;5;168
.tfvars               38;5;168
# orchestration 2}}}
# html {{{2
.css                  38;5;125;1
.less                 38;5;125;1
.sass                 38;5;125;1
.scss                 38;5;125;1
.htm                  38;5;125;1
.html                 38;5;125;1
.jhtm                 38;5;125;1
.mht                  38;5;125;1
.eml                  38;5;125;1
.mustache             38;5;125;1
# }}}
# java {{{2
.coffee               38;5;074;1
.java                 38;5;074;1
.js                   38;5;074;1
.mjs                  38;5;074;1
.jsm                  38;5;074;1
.jsp                  38;5;074;1
# }}}
# php {{{2
.php                  38;5;81
#   CakePHP view scripts and helpers
.ctp                  38;5;81
#   Twig template engine
.twig                 38;5;81
# }}}
# vb/a {{{2
.vb                   38;5;81
.vba                  38;5;81
.vbs                  38;5;81
# 2}}}
# Build stuff {{{2
*Dockerfile           38;5;155
.dockerignore         38;5;240
*Makefile             38;5;155
*MANIFEST             38;5;243
*pm_to_blib           38;5;240
# Functional Configuration
.nix                  38;5;155
.dhall                38;5;178
# ruby rake
.rake                 38;5;155
# automake
.am                   38;5;242
.in                   38;5;242
.hin                  38;5;242
.scan                 38;5;242
.m4                   38;5;242
.old                  38;5;242
.out                  38;5;242
.SKIP                 38;5;244
# }}}
# patch files {{{2
.diff                 48;5;197;38;5;232
.patch                48;5;197;38;5;232;1
#}}}
# graphics {{{1
.bmp                  38;5;97
.dicom                38;5;97
.tiff                 38;5;97
.tif                  38;5;97
.TIFF                 38;5;97
.cdr                  38;5;97
.flif                 38;5;97
.gif                  38;5;97
.icns                 38;5;97
.ico                  38;5;97
.jpeg                 38;5;97
.JPG                  38;5;97
.jpg                  38;5;97
.nth                  38;5;97
.png                  38;5;97
.psd                  38;5;97
.pxd                  38;5;97
.pxm                  38;5;97
.xpm                  38;5;97
.webp                 38;5;97
# }}}
# vector {{{1
.ai                   38;5;99
.eps                  38;5;99
.epsf                 38;5;99
.drw                  38;5;99
.ps                   38;5;99
.svg                  38;5;99
# }}}
# video {{{1
.avi                  38;5;114
.divx                 38;5;114
.IFO                  38;5;114
.m2v                  38;5;114
.m4v                  38;5;114
.mkv                  38;5;114
.MOV                  38;5;114
.mov                  38;5;114
.mp4                  38;5;114
.mpeg                 38;5;114
.mpg                  38;5;114
.ogm                  38;5;114
.rmvb                 38;5;114
.sample               38;5;114
.wmv                  38;5;114
  # mobile/streaming {{{2
.3g2                  38;5;115
.3gp                  38;5;115
.gp3                  38;5;115
.webm                 38;5;115
.gp4                  38;5;115
.asf                  38;5;115
.flv                  38;5;115
.ts                   38;5;115
.ogv                  38;5;115
.f4v                  38;5;115
  # }}}
  # lossless {{{2
.VOB                  38;5;115;1
.vob                  38;5;115;1
# }}}
# subtitles {{{1
.ass                  38;5;117
.srt                  38;5;117
.ssa                  38;5;117
.sub                  38;5;117
.sup                  38;5;117 # bitmap image track
.vtt                  38;5;117
#}}}
# audio {{{1
.3ga                  38;5;137;1
.S3M                  38;5;137;1
.aac                  38;5;137;1
.amr                  38;5;137;1
.au                   38;5;137;1
.caf                  38;5;137;1
.dat                  38;5;137;1
.dts                  38;5;137;1
.fcm                  38;5;137;1
.m4a                  38;5;137;1
.mod                  38;5;137;1
.mp3                  38;5;137;1
.mp4a                 38;5;137;1
.oga                  38;5;137;1
.ogg                  38;5;137;1
.opus                 38;5;137;1
.s3m                  38;5;137;1
.sid                  38;5;137;1
.wma                  38;5;137;1
# lossless
.ape                  38;5;136;1
.aiff                 38;5;136;1
.cda                  38;5;136;1
.flac                 38;5;136;1
.alac                 38;5;136;1
.mid                  38;5;136;1
.midi                 38;5;136;1
.pcm                  38;5;136;1
.wav                  38;5;136;1
.wv                   38;5;136;1
.wvc                  38;5;136;1

# }}}
# fonts {{{1
.afm                  38;5;66
.fon                  38;5;66
.fnt                  38;5;66
.pfb                  38;5;66
.pfm                  38;5;66
.ttf                  38;5;66
.otf                  38;5;66
# Web Open Font Format
.woff                 38;5;66
.woff2                38;5;66
#   postscript fonts
.PFA                  38;5;66
.pfa                  38;5;66
# }}}
# archives {{{1
.7z                   38;5;40
.a                    38;5;40
.arj                  38;5;40
.bz2                  38;5;40
.cpio                 38;5;40
.gz                   38;5;40
.lrz                  38;5;40
.lz                   38;5;40
.lzma                 38;5;40
.lzo                  38;5;40
.rar                  38;5;40
.s7z                  38;5;40
.sz                   38;5;40
.tar                  38;5;40
.tgz                  38;5;40
.warc                 38;5;40
.WARC                 38;5;40
.xz                   38;5;40
.z                    38;5;40
.zip                  38;5;40
.zipx                 38;5;40
.zoo                  38;5;40
.zpaq                 38;5;40
.zst                  38;5;40
.zstd                 38;5;40
.zz                   38;5;40
  # packaged apps {{{2
.apk                  38;5;215
.ipa                  38;5;215
.deb                  38;5;215
.rpm                  38;5;215
.jad                  38;5;215
.jar                  38;5;215
.cab                  38;5;215
.pak                  38;5;215
.pk3                  38;5;215
.vdf                  38;5;215
.vpk                  38;5;215
.bsp                  38;5;215
.dmg                  38;5;215
.crx                  38;5;215 # Google Chrome extension
.xpi                  38;5;215 # Mozilla Firefox extension
  # }}}
  # segments from 0 to three digits after first extension letter {{{2
.r[0-9]{0,2}          38;5;239
.zx[0-9]{0,2}         38;5;239
.z[0-9]{0,2}          38;5;239
# partial files
.part                 38;5;239
  # }}}
# partition images {{{2
.iso                  38;5;124
.bin                  38;5;124
.nrg                  38;5;124
.qcow                 38;5;124
.sparseimage          38;5;124
.toast                38;5;124
.vcd                  38;5;124
.vmdk                 38;5;124
# }}}
# databases {{{2
.accdb                38;5;60
.accde                38;5;60
.accdr                38;5;60
.accdt                38;5;60
.db                   38;5;60
.fmp12                38;5;60
.fp7                  38;5;60
.localstorage         38;5;60
.mdb                  38;5;60
.mde                  38;5;60
.sqlite               38;5;60
.typelib              38;5;60
# NetCDF database
.nc                   38;5;60
# }}}
# tempfiles {{{1
# undo files
.pacnew               38;5;33
.un~                  38;5;241
.orig                 38;5;241
# backups
.BUP                  38;5;241
.bak                  38;5;241
.o                    38;5;241 #   *nix Object file (shared libraries, core dumps etc)
*core                 38;5;241 #   Linux user core dump file (from /proc/sys/kernel/core_pattern)
.mdump                38;5;241 #   Mini DuMP crash report
.rlib                 38;5;241 #   Static rust library
.dll                  38;5;241 #   dynamic linked library
# temporary files
.swp                  38;5;244
.swo                  38;5;244
.tmp                  38;5;244
.sassc                38;5;244
# state files
.pid                  38;5;248
.state                38;5;248
*lockfile             38;5;248
*lock                 38;5;248
# error logs
.err                  38;5;160;1
.error                38;5;160;1
.stderr               38;5;160;1
# state dumps
.aria2                38;5;241
.dump                 38;5;241
.stackdump            38;5;241
.zcompdump            38;5;241
.zwc                  38;5;241
# tcpdump, network traffic capture
.pcap                 38;5;29
.cap                  38;5;29
.dmp                  38;5;29
# macOS
.DS_Store             38;5;239
.localized            38;5;239
.CFUserTextEncoding   38;5;239
# }}}
# hosts {{{1
# /etc/hosts.{deny,allow}
.allow                38;5;112
.deny                 38;5;196
# }}}
# systemd {{{1
# http://www.freedesktop.org/software/systemd/man/systemd.unit.html
.service              38;5;45
*@.service            38;5;45
.socket               38;5;45
.swap                 38;5;45
.device               38;5;45
.mount                38;5;45
.automount            38;5;45
.target               38;5;45
.path                 38;5;45
.timer                38;5;45
.snapshot             38;5;45
# }}}
# metadata {{{1
.application          38;5;116
.cue                  38;5;116
.description          38;5;116
.directory            38;5;116
.m3u                  38;5;116
.m3u8                 38;5;116
.md5                  38;5;116
.properties           38;5;116
.sfv                  38;5;116
.theme                38;5;116
.torrent              38;5;116
.urlview              38;5;116
.webloc               38;5;116
.lnk                  38;5;39
# }}}
# macOS files {{{1
*CodeResources        38;5;239 # code signing apps
*PkgInfo              38;5;239 # app bundle id
.nib                  38;5;57  # UI
.car                  38;5;57  # asset catalog
.dylib                38;5;241 # shared lib
#   Xcode files {{{2
.entitlements         1
.pbxproj              1
.strings              1
.storyboard           38;5;196
.xcconfig             1
.xcsettings           1
.xcuserstate          1
.xcworkspacedata      1
.xib                  38;5;208
# }}}
# }}}
# encrypted data {{{1
.asc                  38;5;192;3
.bfe                  38;5;192;3
.enc                  38;5;192;3
.gpg                  38;5;192;3
.signature            38;5;192;3
.sig                  38;5;192;3
.p12                  38;5;192;3
.pem                  38;5;192;3
.pgp                  38;5;192;3
.p7s                  38;5;192;3
*id_dsa                38;5;192;3
*id_rsa                38;5;192;3
*id_ecdsa              38;5;192;3
*id_ed25519            38;5;192;3
# 1}}}
# emulators {{{1
.32x                  38;5;213
.cdi                  38;5;213
.fm2                  38;5;213
.rom                  38;5;213
.sav                  38;5;213
.st                   38;5;213
  # atari
.a00                  38;5;213
.a52                  38;5;213
.A64                  38;5;213
.a64                  38;5;213
.a78                  38;5;213
.adf                  38;5;213
.atr                  38;5;213
  # nintendo
.gb                   38;5;213
.gba                  38;5;213
.gbc                  38;5;213
.gel                  38;5;213
.gg                   38;5;213
.ggl                  38;5;213
.ipk                  38;5;213 # Nintendo (DS Packed Images)
.j64                  38;5;213
.nds                  38;5;213
.nes                  38;5;213
  # Sega
.sms                  38;5;213
# }}}
#   Texas Instruments Calculator files {{{1
# for more see http://tibasicdev.wikidot.com/file-extensions
.8xp                  38;5;121
.8eu                  38;5;121
.82p                  38;5;121
.83p                  38;5;121
.8xe                  38;5;121
# }}}
# 3D printing {{{1
.stl                  38;5;216
.dwg                  38;5;216
.ply                  38;5;216
.wrl                  38;5;216
# }}}
# unsorted {{{1
#
#   Portable Object Translation for GNU Gettext
.pot                  38;5;7
#   CAD files for printed circuit boards
.pcb                  38;5;7
#   groff (rendering app for texinfo)
.mm                   38;5;7
#   GIMP files
.gbr                  38;5;7
.scm                  38;5;7
.xcf                  38;5;7
# printer spool file
.spl                  38;5;7
# RStudio project file
.Rproj                38;5;11
#   Nokia Symbian OS files
.sis                  38;5;7

.1p                   38;5;7
.3p                   38;5;7
.cnc                  38;5;7
.def                  38;5;7
.ex                   38;5;7
.example              38;5;7
.feature              38;5;7
.ger                  38;5;7
.ics                  38;5;7 # calendar information
.map                  38;5;7
.mf                   38;5;7
.mfasl                38;5;7
.mi                   38;5;7
.mtx                  38;5;7
.pc                   38;5;7
.pi                   38;5;7
.plt                  38;5;7
.pm                   38;5;7
.rdf                  38;5;7
.ru                   38;5;7
.sch                  38;5;7
.sty                  38;5;7
.sug                  38;5;7
.tdy                  38;5;7
.tfm                  38;5;7
.tfnt                 38;5;7
.tg                   38;5;7
.vcard                38;5;7
.vcf                  38;5;7 #contact information
.xln                  38;5;7
#   AppCode files
.iml                  38;5;166
# }}}
# termcap {{{1
TERM ansi
TERM color-xterm
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28
TERM con80x30
TERM con80x43
TERM con80x50
TERM con80x60
TERM cons25
TERM console
TERM cygwin
TERM dtterm
TERM Eterm
TERM eterm-color
TERM gnome
TERM gnome-256color
TERM jfbterm
TERM konsole
TERM kterm
TERM linux
TERM linux-c
TERM mach-color
TERM mlterm
TERM putty
TERM rxvt
TERM rxvt-256color
TERM rxvt-cygwin
TERM rxvt-cygwin-native
TERM rxvt-unicode
TERM rxvt-unicode-256color
TERM rxvt-unicode256
TERM screen
TERM screen-256color
TERM screen-256color-bce
TERM screen-bce
TERM screen-w
TERM screen.linux
TERM screen.rxvt
TERM terminator
TERM vt100
TERM xterm
TERM xterm-16color
TERM xterm-256color
TERM xterm-88color
TERM xterm-color
TERM xterm-debian
TERM xterm-kitty
# }}}

# vim: ft=dircolors fdm=marker


================================================
FILE: .zsh/dircolors.light
================================================
# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option.
# Copyright (C) 1996-2014 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted provided the copyright notice and this notice are preserved.
# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
# slackware version of dircolors) are recognized but ignored.
# Below, there should be one TERM entry for each termtype that is colorizable
TERM Eterm
TERM ansi
TERM color-xterm
TERM con132x25
TERM con132x30
TERM con132x43
TERM con132x60
TERM con80x25
TERM con80x28
TERM con80x30
TERM con80x43
TERM con80x50
TERM con80x60
TERM cons25
TERM console
TERM cygwin
TERM dtterm
TERM eterm-color
TERM gnome
TERM gnome-256color
TERM hurd
TERM jfbterm
TERM konsole
TERM kterm
TERM linux
TERM linux-c
TERM mach-color
TERM mach-gnu-color
TERM mlterm
TERM putty
TERM putty-256color
TERM rxvt
TERM rxvt-256color
TERM rxvt-cygwin
TERM rxvt-cygwin-native
TERM rxvt-unicode
TERM rxvt-unicode-256color
TERM rxvt-unicode256
TERM screen
TERM screen-256color
TERM screen-256color-bce
TERM screen-bce
TERM screen-w
TERM screen.Eterm
TERM screen.rxvt
TERM screen.linux
TERM st
TERM st-256color
TERM terminator
TERM tmux-256color
TERM vt100
TERM xterm
TERM xterm-16color
TERM xterm-256color
TERM xterm-88color
TERM xterm-color
TERM xterm-debian
# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#NORMAL 00 # no color code at all
#FILE 00 # regular file: use no color at all
RESET 0 # reset to "normal" color
# DIR 38;5;150 # directory
DIR 38;5;31;1 # directory
# LINK 38;5;174 # symbolic link. (If you set this to 'target' instead of a
LINK 38;5;24 # symbolic link. (If you set this to 'target' instead of a
# ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file
ORPHAN 7 # symlink to nonexistent file, or non-stat'able file
MULTIHARDLINK 41;38;5;15 # regular file with more than one link
FIFO 01;38;5;161 # pipe
SOCK 01;38;5;161 # socket
DOOR 01;35 # door
BLK 01;38;5;161 # block device driver
CHR 01;38;5;161 # character device driver
SETUID 38;5;7;48;5;160 # file that is setuid (u+s)
SETGID 38;5;7;48;5;160 # file that is setgid (g+s)
CAPABILITY 38;5;7;26 # file with capability
STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
# This is for files with execute permission:
EXEC 4;38;5;16
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
# If you use DOS-style suffixes, you may want to uncomment the following:
#.cmd 01;32 # executables (bright green)
#.exe 01;32
#.com 01;32
#.btm 01;32
#.bat 01;32
# Or if you want to colorize scripts even if they do not have the
# executable bit actually set.
#.sh 01;32
#.csh 01;32
 # archives or compressed (bright red)
.tar 01;31
.tgz 01;31
.arc 01;31
.arj 01;31
.taz 01;31
.lha 01;31
.lz4 01;31
.lzh 01;31
.lzma 01;31
.tlz 01;31
.txz 01;31
.tzo 01;31
.t7z 01;31
.zip 01;31
.z 01;31
.Z 01;31
.dz 01;31
.gz 01;31
.lrz 01;31
.lz 01;31
.lzo 01;31
.xz 01;31
.bz2 01;31
.bz 01;31
.tbz 01;31
.tbz2 01;31
.tz 01;31
.deb 01;31
.rpm 01;31
.jar 01;31
.war 01;31
.ear 01;31
.sar 01;31
.rar 38;05;164
.alz 01;31
.ace 01;31
.zoo 01;31
.cpio 01;31
.7z 01;31
.rz 01;31
.cab 01;31
# image formats
.jpg  38;5;29
.jpeg 38;5;29
.gif  38;5;29
.bmp  38;5;29
.pbm  38;5;29
.pgm  38;5;29
.ppm  38;5;29
.tga  38;5;29
.xbm  38;5;29
.xpm  38;5;29
.tif  38;5;29
.tiff 38;5;29
.png  38;5;29
.svg  38;5;29
.svgz 38;5;115
.mng  38;5;115
.pcx  38;5;115
.mov  38;5;115
.mpg  38;5;115
.mpeg 38;5;115
.m2v  38;5;115
.mkv  38;5;115
.webm 38;5;115
.ogm  38;5;115
.mp4  38;5;115
.m4v  38;5;115
.mp4v 38;5;115
.vob  38;5;115
.qt   38;5;115
.nuv  38;5;115
.wmv  38;5;115
.asf  38;5;115
.rm   38;5;115
.rmvb 38;5;115
.flc  38;5;115
.avi  38;5;115
.fli  38;5;115
.flv  38;5;115
.gl   38;5;115
.dl   38;5;115
.xcf  38;5;115
.xwd  38;5;115
.yuv  38;5;115
.cgm  38;5;115
.emf  38;5;115
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
.axv  38;5;115
.anx  38;5;115
.ogv  38;5;115
.ogx  38;5;115
# audio formats
.aac 00;36
.au 00;36
.flac 00;36
.m4a 00;36
.mid 00;36
.midi 00;36
.mka 00;36
.mp3 00;36
.mpc 00;36
.ogg 00;36
.ra 00;36
.wav 00;36
# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions
.axa 00;36
.oga 00;36
.spx 00;36
.xspf 00;36
# misc
.conf 38;05;161
.log 38;05;161


================================================
FILE: .zshenv
================================================
#!/usr/bin/env zsh

# Always sourced first.

export ZDOTDIR=~/.zsh


================================================
FILE: README.md
================================================
[![Build Status](https://travis-ci.org/mhinz/dotfiles.svg?branch=master)](https://travis-ci.org/mhinz/dotfiles)

A few years ago I switched from Linux to macOS, but my workflow didn't change a
lot. I just need a browser and a terminal emulator. The majority of my work is
done in a shell with a handful of tools.

Everyday, I use [Nvim](.vim/vimrc), [git](.config/git/config),
[tmux](.tmux.conf), and [zsh](.zsh/.zshrc) ([profile](.profile), [shrc](.shrc))
and thus these config files are the most customized.

Have fun reading them and steal what you need.

_Disclaimer: No Reddit users were hurt during the creation of these
configuration files._

![Screenshot](https://raw.githubusercontent.com/mhinz/dotfiles/master/.github/screenshot.png)


================================================
FILE: bin/battery
================================================
#!/bin/sh

os="$(uname -o)"

if [ "$os" = Darwin ]; then
    pmset -g batt | awk 'NR==2 { gsub(/;/, ""); print $3 }'
    exit 0
fi

exit 1


================================================
FILE: bin/book
================================================
#!/usr/bin/env ruby

require 'find'

module Find
  def populate(*paths)
    matched = {}
    find(*paths) do |path|
      if File.file?(path) && yield(path)
        matched[File.basename(path, File.extname(path))] = path
      end
    end
    matched
  end
  module_function :populate
end

class Books
  def initialize(path, term = '')
    @books = find(path, term)
    if @books.empty?
      puts "No matches."
      return
    end
    select
  end

  def find(path, term)
    Find.populate(path) do |p|
      p =~ /#{term}/i
    end.sort
  end

  def select
    @books.each_with_index do |book, i|
      puts "\e[32m %-4d \e[33m%s" % [ i, book.flatten.first ]
    end

    print "\e[31m Select:\e[0m "
    begin
      choice = STDIN.gets
    rescue Interrupt
      # Catch CTRL-C.
    end
    return if choice.nil?
    choice = choice.chomp.to_i

    open @books[choice].flatten.last
  end

  def open(path)
    exec 'open', path
  end
end

Books.new('/data/books', ARGV.join(' '))


================================================
FILE: bin/book.erl
================================================
#!/usr/bin/env escript

-define(BOOKPATH, '/data/books').

list_files(RegExp) ->
    filelib:fold_files(?BOOKPATH, "((?i)" ++ RegExp ++ ")", true,
                       fun(File, Acc) -> [File|Acc] end, []).

% Returns [{Index, {File, Path}}]
process_paths(Paths) ->
    Sorted = lists:sort(fun({A,_}, {B,_}) -> A < B end,
                        [{filename:basename(P), P} || P <- Paths]),
    lists:zip(lists:seq(1, length(Sorted)), Sorted).

main(Args) ->
    Paths = process_paths(case length(Args) of
                              0 -> list_files("");
                              _ -> list_files(hd(Args))
                          end),
    case length(Paths) of
        0 ->
            io:format("Nothing found!~n");
        _ ->
            [io:format("\e[32m~3w \e[33m~s\n",
                       [Index, File]) || {Index, {File, _}} <- Paths],
            {ok, [Choice|_]} = io:fread("\e[32mOpen>\e[0m ", "~d"),
            {_, {_, Path}} = lists:nth(Choice, Paths),
            open_port({spawn_executable, "/usr/bin/open"}, [{args, [Path]}])
    end.


================================================
FILE: bin/book.go
================================================
//usr/bin/env go run $0 $@; exit

package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
)

type byBase []string

// Implement sort.Interface {{{1
func (b byBase) Len() int {
	return len(b)
}

func (b byBase) Less(i, j int) bool {
	return filepath.Base(b[i]) < filepath.Base(b[j])
}

func (b byBase) Swap(i, j int) {
	b[i], b[j] = b[j], b[i]
}

// scanDir() {{{1
func scanDir(fnames *[]string, arg string) {
	dir, err := os.Open(arg)
	if err != nil {
		log.Fatal(err)
	}
	defer dir.Close()

	fis, err := dir.Readdir(-1)
	if err != nil {
		log.Fatal(err)
	}

	r, err := regexp.Compile("(?i)" + os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	for _, fi := range fis {
		fname := fi.Name()

		if !fi.IsDir() && r.MatchString(fname) {
			*fnames = append(*fnames, arg+"/"+fname)
		} else if fi.IsDir() {
			scanDir(fnames, arg+"/"+fname)
		}
	}
}

// run() {{{1
func run(prog, bookpath string) {
	cmd := exec.Command(prog, bookpath)
	err := cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
}

// main() {{{1
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("usage: %s <regex>\n", os.Args[0])
		os.Exit(0)
	}

	var fnames []string
	scanDir(&fnames, "/data/books")

	if len(fnames) == 0 {
		fmt.Println("\033[31mNothing found!")
		return
	}

	sort.Sort(byBase(fnames))
	for i, v := range fnames {
		fmt.Printf(" \033[32m%-5d \033[33m%s\n", i, filepath.Base(v))
	}

	var input int
	fmt.Print("\033[32mSelect>\033[0m ")
	_, err := fmt.Scanf("%d", &input)
	if err != nil {
		log.Fatal(err)
	}

	run("open", fnames[input])
	// switch filepath.Ext(fnames[input]) {
	// case ".pdf":
	// 	run("zathura", fnames[input])
	// case ".chm":
	// 	run("xchm", fnames[input])
	// case ".djvu":
	// 	run("djview", fnames[input])
	// default:
	// 	fmt.Println("\033[31mI can't handle that file!")
	// }
}


================================================
FILE: bin/bootstrap-homebrew
================================================
#!/usr/bin/env bash

xcode-select --install

if ! command -v brew &>/dev/null; then
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi

brew analytics off

formulae=(
    asdf
    automake
    bash
    cmake
    coreutils
    curl-openssl
    git
    gnupg
    go
    jq
    libtool
    ncdu
    neovim
    netcat
    ninja
    nmap
    node
    openssl
    pinentry-mac
    pkg-config
    postgresql
    python
    ripgrep
    shellcheck
    socat
    sqlite
    ssh-copy-id
    tmux
    tree
    unbound
    wget
    youtube-dl
    zsh
)

brew install "${formulae[@]}"

brew install --HEAD universal-ctags/universal-ctags/universal-ctags

brew tap caskroom/cask
brew tap homebrew/services
brew tap homebrew/cask-fonts
brew tap homebrew/cask-versions

formulae=(
    brave-browser
    calibre
    dbeaver-community
    docker-edge
    flux
    font-dejavu
    font-fira-code
    font-juliamono
    gifox
    gimp
    iterm2
    karabiner-elements
    kitty
    magicavoxel
    rar
    tor-browser
    vienna
    virtualbox
    virtualbox-extension-pack
    vlc
    wireshark

    blockblock
    lulu
)

brew install --cask "${formulae[@]}"


================================================
FILE: bin/bootstrap-host
================================================
#!/bin/sh

list_ssh_hosts() {
    awk '$1 == "HostName" { print $2 }' ~/.ssh/config | \
        cut -d. -f1 | \
        sort
}

bootstrap() {
    cd || exit 1
    if [ ! -d .git ]; then
        git init
        git remote add -f origin https://github.com/mhinz/dotfiles
    fi
    # shellcheck disable=SC2006
    if sh=`grep '\<zsh\>' /etc/shells` && [ "$SHELL" != "$sh" ]; then
        chsh -s "$sh"
    fi
}

bootstrap_to_host() {
    ssh -T "$1" 'bash -s' < ~/bin/bootstrap-host .
}

if ! command -v git 1>/dev/null; then
    echo 'Install git.'
    exit 1
fi


if [ $# -eq 0 ]; then
    list_ssh_hosts
else
    if [ "$1" = . ]; then
        bootstrap
    elif list_ssh_hosts | grep -q "\\<$1\\>"; then
        bootstrap_to_host "$1"
    else
        list_ssh_hosts
    fi
fi


================================================
FILE: bin/bootstrap-ruby
================================================
#!/usr/bin/env bash

gem install rbenv gem-ctags
gem ctags

mkdir -p ~/.rbenv/plugins
git clone https://github.com/tpope/rbenv-ctags.git    ~/.rbenv/plugins/rbenv-ctags
git clone https://github.com/ianheggie/rbenv-binstubs ~/.rbenv/plugins/rbenv-binstubs
rbenv ctags


================================================
FILE: bin/bootstrap-vim
================================================
#!/usr/bin/env bash

set -ex

mkdir -p ~/.vim/files/{backup,info,swap,undo}
mkdir -p ~/.vim/bundle
mkdir -p ~/.config

git clone https://github.com/junegunn/vim-plug.git ~/.vim/bundle/vim-plug || true
ln -sf ~/.vim/bundle/vim-plug/plug.vim ~/.vim/autoload

vim +PlugInstall +qall

ln -sf ~/.vim ~/.config/nvim
cd ~/.vim && ln -sf vimrc init.vim


================================================
FILE: bin/build-angband
================================================
#!/usr/bin/env bash

repo='https://github.com/angband/angband'
dir="${ME}/repo/angband"

cd "$dir" 2>/dev/null || {
    cd "${dir%/*}" || exit 1
    git clone "$repo"
    cd "${repo##*/}" || exit 1
}

echo '[*] Cleaning directory..'
make distclean &>/dev/null

if [[ $1 = '-f' ]]; then
    echo '[!] Force building..'
else
    echo '[*] Pulling changes..'
    if git pull | grep 'Already up[ -]to[ -]date.' &>/dev/null; then
        echo '[!] No changes found.'
        exit 1
    fi
fi

export NCURSES_CONFIG=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/bin/ncurses5.4-config

./autogen.sh
./configure \
    --prefix="${HOME}/local/angband" \
    --bindir="${HOME}/local/angband/bin" \
    --with-ncurses-prefix=/usr/lib \
    --disable-ncursestest \
    --disable-x11
make
make install


================================================
FILE: bin/build-elixir
================================================
#!/usr/bin/env bash

set -e

dir="${ME}/github/elixir-lang/elixir"

if [[ ! -d $dir ]]; then
    mkdir -p "${ME}/github/elixir-lang"
    git clone https://github.com/elixir-lang/elixir "$dir"
fi

cd "$dir"

if [[ $1 != -f ]]; then
    git pull | grep 'Already up[ -]to[ -]date.' && exit 1
fi

make clean
make


================================================
FILE: bin/build-erlang
================================================
#!/usr/bin/env bash

set -e

dir="${ME}/github/erlang/otp"
prefix="${HOME}/local/erlang"

flags=(
    "--prefix=${prefix}"
    '--with-ssl=/usr/local/opt/openssl'
    '--without-javac'
)

cd "$dir"

if [[ $1 != -f ]]; then
    git pull | grep 'Already up[ -]to[ -]date.' && exit 1
fi

export LANG=C

if [[ ! -f ./configure ]]; then
    ./otp_build autoconf
    ./configure "${flags[@]}"
fi

make install


================================================
FILE: bin/build-git
================================================
#!/usr/bin/env bash

set -e
set -x

dir="${ME}/repo/git"
prefix="${HOME}/local/git"

# avoid "Document /<path>/git/Documentation/git-add.xml does not validate" errors
export XML_CATALOG_FILES=/usr/local/etc/xml/catalog
export CPPFLAGS=-I/usr/local/opt/openssl/include
export LDFLAGS=-L/usr/local/opt/openssl/lib

cd "$dir" || exit

if [[ $1 != -f ]]; then
    git pull | grep 'Already up[ -]to[ -]date.' && exit 1
fi

make distclean 1>/dev/null
make configure 1>/dev/null

./configure --prefix="${prefix}"
make install install-man

cd contrib/subtree
make install


================================================
FILE: bin/build-go
================================================
#!/usr/bin/env bash

set -e
set -x

[[ -z ${GOROOT:+nope} ]] && { echo "Export \$GOROOT first."; exit 1; }
[[ -z ${GOARCH:+nope} ]] && { echo "Export \$GOARCH first."; exit 1; }
[[ -z ${GOOS:+nope}   ]] && { echo "Export \$GOOS first.";   exit 1; }

if ! cd "${GOROOT}/src"; then
    mkdir -p "${GOROOT}/.."
    git clone https://github.com/golang/go.git "$GOROOT"
    cd "${GOROOT}/src"
else
    if [[ $1 != -f ]]; then
        git pull | grep 'Already up[ -]to[ -]date.' && exit 1
    fi
fi

# shellcheck disable=SC2155
export GOROOT_BOOTSTRAP=$(mktemp -dt go-bootstrap-XXX)

if [[ -x $GOROOT/bin/go ]]; then
    rsync -a "$GOROOT"/ "$GOROOT_BOOTSTRAP" --exclude .git
else
    echo '[*] No go binary found. Downloading Go 1.7.3..'
    curl -#L "https://storage.googleapis.com/golang/go1.7.3.${GOOS}-${GOARCH}.tar.gz" \
        | tar -C "$GOROOT_BOOTSTRAP" --strip-components=1 -x
fi

if [[ -z ${GOROOT_BOOTSTRAP+nope} ]]; then
    echo '[*] Building master..'
else
    echo "[*] Building master using bootstrap: $GOROOT_BOOTSTRAP"
fi

./make.bash


================================================
FILE: bin/build-htop
================================================
#!/usr/bin/env bash

dir="${ME}/repo/htop"
prefix="${HOME}/local/htop"

cd "$dir" || exit

if [[ $1 != -f ]]; then
    git pull | grep 'Already up[ -]to[ -]date.' && exit 1
fi

sh autogen.sh
./configure --prefix="${prefix}"
make install


================================================
FILE: bin/build-tmux
================================================
#!/usr/bin/env bash

cd "${ME}/repo/tmux" || exit

if git pull | grep 'Already up[ -]to[ -]date.' && [ "$1" != -f ]; then
    exit 0
fi

sh autogen.sh
./configure --prefix="${HOME}/local/tmux"
make install


================================================
FILE: bin/build-vim
================================================
#!/usr/bin/env bash

dir="${ME}/github/vim/vim"
prefix="${HOME}/local/vim"

# python3-config --configdir
flags=(
    "--prefix=${prefix}"
    '--with-compiledby=mhi'
    '--enable-rubyinterp=dynamic'
    '--enable-python3interp'
    '--with-python3-config-dir=/usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/config-3.9-darwin'
)

[[ $(uname) == Linux ]] && flags+=('--with-x')

current_vim_version() {
    local version patchlevel
    version=$(vim --version | head -1 | cut -d' ' -f5)
    patchlevel=$(vim --version | head -3 | tail -1 | cut -d'-' -f2)
    echo "${version}.${patchlevel}"
}

cd "$dir" || exit 1
if [[ $1 != -f ]]; then
    git pull | grep 'Already up[ -]to[ -]date.' && exit 1
fi

old_version=$(current_vim_version)

echo "Build log: ${dir}/build.log"

echo 'Cleaning...'
make distclean 1>/dev/null

echo 'Configure...'
./configure "${flags[@]}" >build.log

echo 'Compile...'
make >>build.log

echo 'Install...'
make install >>build.log

echo "New version: $old_version => $(current_vim_version)"


================================================
FILE: bin/build-zsh
================================================
#!/usr/bin/env bash

dir="${ME}/repo/zsh"
prefix="${HOME}/local/zsh"

cd "$dir" || exit
echo '[*] Cleaning directory..'
make distclean &>/dev/null

if [[ $1 = '-f' ]]; then
    echo '[!] Force building..'
else
    echo '[*] Pulling changes..'
    if git pull | grep 'Already up[ -]to[ -]date.' &>/dev/null; then
        echo '[!] No changes found.'
        exit 1
    fi
fi

echo "[*] Build log: ${dir}/build.log"

echo '[*] Run preconfig..'
./Util/preconfig >build.log

echo '[*] Configure..'
./configure --prefix="${prefix}" >>build.log

echo '[*] Compile sources..'
make >>build.log

echo '[*] Install..'
make install >>build.log


================================================
FILE: bin/busy
================================================
#!/usr/bin/env bash

# Just a hack to keep macOS from sleeping without having to fiddle with the
# energy saver settings or using apps like caffeine and amphetamine.

[[ $(uname -s) == Darwin ]] || exit 1

declare -A map=(
    [Apple_Terminal]=Terminal
    [iTerm.app]=iTerm
)

term=${map[$TERM_PROGRAM]}
[[ -z $term ]] && exit 2

time osascript <<EOF
tell application "System Events"
    keystroke "cat\n"
end tell
repeat
    tell application "$term"
        activate
        tell application "System Events"
            keystroke "yay\n"
        end tell
    end tell
    delay 10
end repeat
EOF


================================================
FILE: bin/c_rocks
================================================
#!/bin/bash

header[0]='      o__ __o                                            o                '
header[1]='     /v     v\                                          <|>               '
header[2]='    />       <\                                         / \               '
header[3]='  o/                 \o__ __o     o__ __o        __o__  \o/  o/      __o__'
header[4]=' <|                   |     |>   /v     v\      />  \    |  /v      />  \ '
header[5]='  \\                 / \   < >  />       <\   o/        / \/>       \o    '
header[6]='    \         /      \o/        \         /  <|         \o/\o        v\   '
header[7]='     o       o        |          o       o    \\         |  v\        <\  '
header[8]='     <\__ __/>       / \         <\__ __/>     _\o__</  / \  <\  _\o__</  '

draw_char()
{
    local voff_x=$1
    local voff_y=$2

    tput cup $[off_y + voff_y] $[off_x + voff_x]
    printf %c ${header[voff_y]:voff_x:1}
}

#
# check color support
#
if [[ $(tput colors) -ne 256 ]]; then
    echo "$0: This terminal does not support 256 colors." 2>&1
    exit 1
fi

#
# set trap handlers
#
trap 'tput cnorm; tput clear' EXIT
trap 'exit 1' INT TERM

#
# calculate header position
#
while getopts ':x:y:' opt; do
    [[ $opt =~ [\?:] ]] && continue
    case $opt in
        x)
            cols=$OPTARG
            ;;
        y)
            rows=$OPTARG
            ;;
        *)
            echo "usage: $0 [-t] [-x \$cols] [-y \$rows]" 2>&1
            exit 1
    esac
done

#
# if no cols or rows were set:
#   - try to determine them
#   - set default values otherwise
#
[[ -z $cols ]] && { cols=$(tput cols)  || cols=80; }
[[ -z $rows ]] && { rows=$(tput lines) || rows=24; }

#
# get width and height of the header
#
header_width=${#header[0]}
header_height=${#header[@]}

#
# check if header is bigger than the actual terminal size; truncate otherwise
#
[[ $cols -lt $header_width  ]] && { off_x=0; header_width=$cols;  } || off_x=$[ (cols - header_width)  / 2 ]
[[ $rows -lt $header_height ]] && { off_y=0; header_height=$rows; } || off_y=$[ (rows - header_height) / 2 ]

#
# prepare screen
#
tput civis
clear

#
# main loop
#
while :; do
    for c in {136..166}; do
        tput setaf $c
        for ((x = 0; x < $header_width; x++)); do
            for ((y = 0; y < $header_height; y++)); do
                draw_char $x $y
            done
        done
    done
done


================================================
FILE: bin/dotfiles
================================================
#!/bin/sh

red="\033[31m"
green="\033[32m"
yellow="\033[33m"
blue="\033[34m"
reset="\033[0m"

check_file() {
    if ! which "$1" >/dev/null; then
        echo " ${yellow}${1}${reset} % ${red}is not available${reset}"
    elif [ -e "$2" ]; then
        if [ -L "$2" ]; then
            echo " ${yellow}${2}${reset} % ${blue}is already symlinked${reset}"
        else
            echo " ${yellow}${2}${reset} % ${red}is no symlink${reset}"
        fi
    else
        ln -s "$3" "$2"
        echo " ${yellow}${2}${reset} % ${green}-> ${3}${reset}"
    fi
}

{
    check_file  bochs     ~/.bochsrc                       .dotfiles/bochs/bochsrc
    check_file  cmus      ~/.cmus/kuku.theme               ~/.dotfiles/cmus/kuku.theme
    check_file  conky     ~/.conkyrc                       .dotfiles/conky/conkyrc
    check_file  emacs     ~/.emacs.d                       .dotfiles/emacs.d
    check_file  firefox   ~/.mozilla                       .dotfiles/mozilla
    check_file  gdb       ~/.gdbinit                       .dotfiles/gdb/gdbinit
    check_file  gem       ~/.gemrc                         .dotfiles/gem/gemrc
    check_file  getmail   ~/.getmail                       .dotfiles/getmail
    check_file  git       ~/.git                           .dotfiles/git
    check_file  git       ~/.gitconfig                     .dotfiles/git/gitconfig
    check_file  gitk      ~/.gitk                          .dotfiles/git/gitk
    check_file  gpg       ~/.gnupg                         .dotfiles/gnupg
    check_file  hg        ~/.hgrc                          .dotfiles/hg/hgrc
    check_file  irssi     ~/.irssi                         .dotfiles/irssi
    check_file  liferea   ~/.liferea_1.8                   .dotfiles/liferea/liferea_1.8
    check_file  liferea   ~/feedlist.opml                  .dotfiles/liferea/feedlist.opml
    check_file  msmtp     ~/.msmtprc                       .dotfiles/msmtp/msmtprc
    check_file  mutt      ~/.muttrc                        .dotfiles/mutt/muttrc
    check_file  procmail  ~/.procmailrc                    .dotfiles/procmail/procmailrc
    check_file  rtorrent  ~/.rtorrent.rc                   .dotfiles/rtorrent/rtorrent.rc
    check_file  skype     ~/.Skype                         .dotfiles/skype
    check_file  slrn      ~/.slrn                          .dotfiles/slrn
    check_file  slrn      ~/.slrnrc                        .dotfiles/slrn/slrnrc
    check_file  ssh       ~/.ssh                           .dotfiles/ssh
    check_file  startx    ~/.Xdefaults                     .dotfiles/x/Xdefaults
    check_file  startx    ~/.Xmodmap                       .dotfiles/x/Xmodmap
    check_file  startx    ~/.config/fontconfig/fonts.conf  .dotfiles/fonts/fonts.conf
    check_file  startx    ~/.fonts                         .dotfiles/fonts/fonts
    check_file  startx    ~/.icons                         .dotfiles/icons
    check_file  startx    ~/.xinitrc                       .dotfiles/x/xinitrc
    check_file  tmux      ~/.tmux.conf                     .dotfiles/tmux/tmux.conf
    check_file  true      ~/.pentadactyl                   .dotfiles/pentadactyl
    check_file  true      ~/.pentadactylrc                 .dotfiles/pentadactyl/pentadactylrc
    check_file  true      ~/.terminfo                      .dotfiles/terminfo
    check_file  true      ~/bin                            .dotfiles/bin
    check_file  true      ~/mail                           /data/mail
    check_file  vim       ~/.vim                           .dotfiles/vim
    check_file  xmonad    ~/.xmonad                        .dotfiles/xmonad
    check_file  zsh       ~/.zsh                           .dotfiles/zsh
    check_file  zsh       ~/.zshenv                        .dotfiles/zsh/.zshenv
} | column -t -s %


================================================
FILE: bin/ec
================================================
#!/usr/bin/env bash

if emacsclient --eval t &>/dev/null; then
    if [[ -z $@ ]]; then
        emacsclient --eval "(dired \"${PWD}\")"
    else
        emacsclient --no-wait "$@"
    fi
else
    if [[ -z $@ ]]; then
        emacs --chdir "$PWD" --eval "(dired \"${PWD}\")" &
    else
        emacs --chdir "$PWD" "$@" &
    fi
fi


================================================
FILE: bin/english
================================================
#!/usr/bin/env ruby

require 'yaml'

words = YAML.load_file(File.expand_path('~/english.yaml'))

while words.any?
  word = words.keys.sample
  print "\n\x1b[1;36m#{word}\x1b[0m "
  begin
    gets
  rescue Interrupt
    exit
  end
  puts words[word]
  words.delete(word)
end


================================================
FILE: bin/english-notification
================================================
#!/usr/bin/env ruby

require 'YAML'

words = YAML.load_file(File.expand_path('~/english.yaml'))

english = words.keys.sample
german  = words[english].gsub('"', '\"').gsub("'", "''\\'''")

%x{ osascript <<< 'display notification "#{german}" with title "#{english}"' }


================================================
FILE: bin/fix-term
================================================
#!/bin/sh

# kbs        backspace key
# sitm/ritm  italic
# smso/rmso  standout
# smxx/rmxx  strikethrough
# Smulx      undercurl (https://sw.kovidgoyal.net/kitty/protocol-extensions.html#colored-and-styled-underlines)

os="$(uname -s)"
tinfo="$(mktemp)"

if [ "$os" = Darwin ]; then
    export TERMINFO=/usr/share/terminfo
fi

cat > "$tinfo" <<EOF
xterm-256color|xterm with 256 colors and italic,
    kbs=\177,
    sitm=\E[3m, ritm=\E[23m,
    smxx=\E[9m, rmxx=\E[29m,
    Smulx=\E[4\:%p1%dm,
    use=xterm-256color,
tmux-256color|tmux with 256 colors and italic,
    kbs=\177,
    sitm=\E[3m, ritm=\E[23m,
    smso=\E[7m, rmso=\E[27m,
    smxx=\E[9m, rmxx=\E[29m,
    Smulx=\E[4\:%p1%dm,
    use=screen-256color,
EOF

if [ "$os" = FreeBSD ]; then
    tcap="$(mktemp)"
    tic -CKr0x "$tinfo" > "$tcap"
    cap_mkdb -f ~/.termcap "$tcap"
else
    rm -rf ~/.terminfo
    tic -xo ~/.terminfo "$tinfo"
fi

# vim: nowrap


================================================
FILE: bin/gem-info
================================================
#!/bin/sh

curl -s https://rubygems.org/api/v1/gems/"${1}".json | jq


================================================
FILE: bin/git-ctags
================================================
#!/usr/bin/env bash

set -e

blacklist=(~ /usr/local/Homebrew)

for dir in "${blacklist[@]}"; do
    if [[ $PWD = $dir ]]; then
        echo 'nö' 1>&2
        exit 1
    fi
done

cd "$(git rev-parse --show-toplevel)"

echo 'Creating tags...'
git ls-files | ctags -L - --tag-relative=yes --fields=+S -f .git/tags.$$
mv .git/tags.$$ .git/tags


================================================
FILE: bin/git-neck
================================================
#!/bin/sh -e

# git neck [-r] [COMMIT] - show commits until first branching point
#
# Stolen from http://chneukirchen.org/blog/archive/2013/01/a-grab-bag-of-git-tricks.html

[ "$1" = -r ] && shift && R=-r
COMMIT=$(git rev-parse --no-flags --default HEAD "$@")
# skip first elements of trail
TORSO=$(git trail $R $COMMIT | cut -d' ' -f2 | uniq | sed -n 2p)
# fall back to initial commit on empty trail
: ${TORSO:=$(git rev-list --max-parents=0 HEAD)}
git log --oneline $(git rev-parse --no-revs "$@") $COMMIT...$TORSO


================================================
FILE: bin/git-standup
================================================
#!/usr/bin/env bash

standup() {
    dir=$1
    shift
    if git -C "$dir" rev-parse --git-dir &>/dev/null; then
        changes="$(git -C "$dir" log --all --author='Marco Hinz' --since='6am yesterday' --format=%s "$@")"
        if [[ -n $changes ]]; then
            echo -e "\e[31;3m⇒ ${dir}\e[0m"
            echo "$changes"
        fi
    fi
}

if git rev-parse --git-dir &>/dev/null; then
    standup "$PWD" "$@"
else
    for dir in *; do
        standup "$dir" "$@"
    done
fi


================================================
FILE: bin/git-to
================================================
#!/usr/bin/env bash
#
# usage: git to [ref]
#
# The number of commits between a given ref and HEAD. If no ref is given, the
# last tag (lightweight or annotated) is used.
#
# This works in both directions (the ref can appear before or after HEAD),
# hence "to" and not "since".

last_tag() {
    git describe --tags --exact-match "$(git rev-list --tags --max-count=1)"
}

number_of_commits_relative_to() {
    git log --oneline --no-merges ..."$1" | wc -l
}

ref="${1:-"$(last_tag)"}"

echo "$(number_of_commits_relative_to "$ref") commits to $ref"


================================================
FILE: bin/git-trail
================================================
#!/bin/sh -e

# git trail [-r] [-t] [COMMIT] - show all branching points in Git history
#
# Stolen from http://chneukirchen.org/blog/archive/2013/01/a-grab-bag-of-git-tricks.html

[ "$1" = -r ] && shift || REMOTES="-e refs/remotes/"
[ "$1" = -t ] && shift || TAGS="-e refs/tags/"
COMMIT=$(git rev-parse --no-flags --default HEAD "$@")

{ git for-each-ref | grep -v -e '^$' $TAGS $REMOTES
  git log --date=short --format="%cd %h %H" "$@"
} | awk '
    $2 == "commit" || $2 == "tag" {
      "git merge-base '$COMMIT' " $1 | getline mb
      merge[mb] = merge[mb] " " $3
    }
    {
      if ($3 in merge) {
        split(merge[$3], mbs, " ")
        for (i in mbs) {
          "git name-rev --name-only --refs=\"" mbs[i] "\" " $3 | getline nr
          if (nr != "undefined") print $1, $2, nr   # skip unreachable commits
        }
      }
    }' | git -p column   # paginate output


================================================
FILE: bin/git-whereami
================================================
#!/usr/bin/env ruby
#
# frozen_string_literal: true

# usage: git whereami [HEAD]
#
# Show next and previous tags from ref and their distance.

ref = !ARGV.empty? ? ARGV[0] : 'HEAD'

def out(title, tag, distance)
  printf("%-20s %-20s %d commits away\n", title, tag, distance)
end

def distance(tag)
  `git log --oneline --no-merges ...#{tag}`.lines.count
end

exact = `git describe --abbrev=0 --exact-match #{ref} 2>/dev/null`.rstrip

case $?.exitstatus
when 0
  prev_anno  = `git describe --abbrev=0        #{ref}^ 2>/dev/null`.rstrip
  prev_light = `git describe --abbrev=0 --tags #{ref}^ 2>/dev/null`.rstrip
  out('exact',            exact,      0)
  out('prev annotated',   prev_anno,  distance(prev_anno))  unless prev_anno.empty?
  out('prev lightweight', prev_light, distance(prev_light)) unless prev_light.empty?
else
  next_light = `git describe --contains        #{ref} 2>/dev/null`.rstrip
  prev_anno  = `git describe --abbrev=0        #{ref} 2>/dev/null`.rstrip
  prev_light = `git describe --abbrev=0 --tags #{ref} 2>/dev/null`.rstrip
  out('next',             *next_light.split('~'))           unless next_light.empty?
  out('prev annotated',   prev_anno,  distance(prev_anno))  unless prev_anno.empty?
  out('prev lightweight', prev_light, distance(prev_light)) unless prev_light.empty?
end


================================================
FILE: bin/itb
================================================
#!/usr/bin/env ruby

class ITBooks
  def initialize(args)
    menu(lookup(args))
  end

  private

  def lookup(args)
    require 'net/http'
    require 'json'

    books = []
    page  = 1
    query = URI.encode(args.join(' '))

    loop do
      response = Net::HTTP.get(URI("http://it-ebooks-api.info/v1/search/#{query}/page/#{page}"))
      # Fix unescaped double quotes in JSON response.
      response.gsub!(/([^,:{])"([^,:}])/, '\1\"\2')
      response = JSON.parse(response, {symbolize_names: true})
      break if response[:Total].to_i == 0
      books += response[:Books]
      page += 1
    end

    if books.empty?
      puts 'No matches.'
      exit 1
    end

    books.sort! { |a,b| a[:Title] <=> b[:Title] }
  end

  def menu(books)
    loop do
      books.each_with_index do |book, i|
        puts "\e[32m %-4d \e[33m%s" % [ i, book[:Title] ]
      end

      print "\e[31m Select:\e[0m "
      begin
        choice = STDIN.gets.chomp.to_i
      rescue Interrupt
        break
      end

      show(books[choice][:ID])

      print "\e[31m Select another? [Yn]\e[0m "
      begin
        choice = STDIN.gets.chomp
      rescue Interrupt
        break
      end
      break if choice == 'n'
    end
  end

  def show(book_id)
    book = Net::HTTP.get(URI("http://it-ebooks-api.info/v1/book/#{book_id}"))
    book.gsub!(/([^,:{])"([^,:}])/, '\1\"\2')
    book = JSON.parse(book, {symbolize_names: true})

    begin
      require 'lisbn'
      isbn = Lisbn.new(book[:ISBN]).isbn10
    rescue LoadError
      isbn = nil
    end

    puts "\e[32m %-14s\e[0m%s" % ['Title',       book[:Title]      ]
    puts "\e[32m %-14s\e[0m%s" % ['Subtitle',    book[:SubTitle]   ]
    puts "\e[32m %-14s\e[0m%s" % ['Author',      book[:Author]     ]
    puts "\e[32m %-14s\e[0m%s" % ['Year',        book[:Year]       ]
    puts "\e[32m %-14s\e[0m%s" % ['Publisher',   book[:Publisher]  ]
    puts "\e[32m %-14s\e[0m%s" % ['ISBN',        book[:ISBN]       ]
    puts "\e[32m %-14s\e[0m%s" % ['Amazon',
                                  "http://www.amazon.de/gp/product/#{isbn}" ] if isbn
    puts "\e[32m %-14s\e[0m%s" % ['Download',    book[:Download]   ]
    puts "\e[32m %-14s\e[0m%s" % ['Description', book[:Description]]
  end
end

if ARGV.empty?
  $stderr.puts "usage: #{File.basename($0)} <query>"
  exit 1
end

ITBooks.new(ARGV)


================================================
FILE: bin/man
================================================
#!/usr/bin/env bash

# On :Man, Nvim uses `MANWIDTH=999 man` for the purpose of soft wrapping the
# resulting long lines afterwards. This works for all window sizes and supports
# resizing. But my eyes are too used to the manpager always giving me 80
# columns, so this wrapper forces $MANWIDTH to be set again.

MANWIDTH=80 exec /usr/bin/man "$@"


================================================
FILE: bin/markov
================================================
#!/usr/bin/env python

import sys
import fileinput
import random

class Markov:
    def __init__(self):
        self.suffixes = {}
        self.build_table()

    def read_input(self):
        lines = []
        for line in fileinput.input():
            lines.append(line)
        return ''.join(lines).split()

    def build_table(self):
        prefix1 = '\n'
        prefix2 = '\n'
        for suffix in self.read_input():
            self.suffixes.setdefault((prefix1, prefix2), []).append(suffix)
            prefix1, prefix2 = prefix2, suffix
        self.suffixes.setdefault((prefix1, prefix2), []).append('\n')

    def generate_output(self, maxwords=500):
        prefix1 = '\n'
        prefix2 = '\n'
        for i in xrange(maxwords):
            new = random.choice(self.suffixes[prefix1, prefix2])
            if new == '\n':
                sys.exit()
            sys.stdout.write(new + ' ')
            prefix1, prefix2 = prefix2, new

if __name__ == '__main__':
    m = Markov()
    m.generate_output()


================================================
FILE: bin/mhi
================================================
#!/usr/bin/env bash

# Configuration {{{1
mhi="$(readlink "$0")"
mhi=${mhi:=$0}
mhi="${mhi%/*}"

# Helpers {{{1
list_files() {
  local path="$1"
  for file in "$path"/*; do
    file="${file##*/}"  # basename
    echo "${file%.*}"   # strip ext
  done
}

case $1 in
  colors) # {{{1
    for i in {0..255}; do
      tput setab $i && echo -n " $i "
    done
    tput sgr0
    echo
    ;;

  conf|c) # {{{1
    arg=$2
    declare -A configs=(
      [g]=~/.config/git/config
      [l]=~/.vim/lua/mhi.lua
      [m]=~/.vim/magic.vim
      [t]=~/.tmux.conf
      [v]=~/.vim/vimrc
      [ze]=~/.zsh/.zshenv
      [zp]=~/.zsh/.zprofile
      [zr]=~/.zsh/.zshrc
    )
    if [[ -n $arg && -n ${configs[$arg]} ]]; then
      exec "$EDITOR" "${configs[$arg]}"
    else
      for conf in "${!configs[@]}"; do
        printf '%-6s %s\n' "$conf" "${configs[$conf]}"
      done | sort
    fi
    ;;

  fix) # {{{1
    shift
    exec "${mhi}/mhi-fix" "$@"
    ;;

  net|n) # {{{1
    shift
    exec "${mhi}/mhi-net" "$@"
    ;;

  path|p) # {{{1
    IFS=:
    if (( $# == 1 )); then
      # shellcheck disable=SC2086
      printf '%s\n' $PATH
    else
      shift
      # shellcheck disable=SC2086
      find $PATH -iname "$@" -exec ls -hl --time-style=long-iso {} + 2>/dev/null
    fi
    ;;

  *) # {{{1
    cat <<MSG
colors
conf|c
fix
net|n
path|p
MSG
    ;;
esac

# vim: sts=2 sw=2


================================================
FILE: bin/mhi-fix
================================================
#!/usr/bin/env bash

case $1 in
  spotlight) # {{{1
    hash brew 2>/dev/null || exit 1
    brew linkapps
    find /Applications -type l -maxdepth 1 | while read -r file; do
      [[ -f "${HOME}${file}" ]] || osascript -e 'on run {f}
        set dir to path to applications folder from user domain
        tell application "Finder" to make alias at dir to f as POSIX file
      end' "$file"
    done
    ;;

  *) # {{{1
    cat <<MSG
spotlight
MSG
    ;;
esac

# vim: sts=2 sw=2


================================================
FILE: bin/mhi-net
================================================
#!/usr/bin/env bash

case $1 in
  hosts) # {{{1
    awk '$1 == "Host" { print $2 }' ~/.ssh/config | sort
    ;;

  irc) # {{{1
    [[ -n $TMUX ]] && tmux rename-window irc
    exec ssh vimmer.net -t 'tmux attach -t irc'
    ;;

  *) # {{{1
    cat <<MSG
hosts
irc
MSG
    ;;
esac

# vim: sts=2 sw=2


================================================
FILE: bin/numsys
================================================
#!/usr/bin/env ruby

class NumSys
  # initalize {{{1
  def initialize(args)
    @Input = args.dup.freeze

    if args.empty?
      $stderr.puts "usage: #{__FILE__} <number>"
      exit 1
    end
  end

  # validate_input {{{1
  def validate_input(arg)
    case arg
    when /^([01]+)(?:b)?$/               then { sys: 'bin', val: $1 }
    when /^(\d+)(?:d)?$/                 then { sys: 'dec', val: $1 }
    when /^(?:0x)?([0-9a-fA-F]+)(?:h)?$/ then { sys: 'hex', val: $1 }
    else
      $stderr.puts "Wait, what? What is '#{arg}' supposed to mean?"
      nil
    end
  end

  # converting {{{1
  def c2to16(val)
    lookup = {
      '0000' => :'0', '0001' => :'1', '0010' => :'2', '0011' => :'3',
      '0100' => :'4', '0101' => :'5', '0110' => :'6', '0111' => :'7',
      '1000' => :'8', '1001' => :'9', '1010' => :'a', '1011' => :'b',
      '1100' => :'c', '1101' => :'d', '1110' => :'e', '1111' => :'f',
    }
    ret = []
    val = val.scan(/./)
    ret.unshift(lookup[val.pop(4).join.rjust(4, '0')]) while not val.empty?
    ret.join
  end

  def c16to2(val)
    lookup = {
      :'0' => 0,    :'1' => 1,    :'2' => 10,   :'3' => 11,
      :'4' => 100,  :'5' => 101,  :'6' => 110,  :'7' => 111,
      :'8' => 1000, :'9' => 1001, :'a' => 1010, :'b' => 1011,
      :'c' => 1100, :'d' => 1101, :'e' => 1110, :'f' => 1111,
    }
    ret = ''
    val.downcase.each_char do |char|
      ret << '%.4d' % lookup[char.to_sym]
    end
    ret
  end

  def c10to16(val)
    new   = val
    queue = []

    while val != 0
      new = (val / 16).floor
      rem = val % 16
      queue.unshift('%x' % rem)
      val = new
    end

    queue.join
  end

  def c2to10(val)
    i   = 0
    ret = 0
    val.reverse.each_char do |char|
      ret += (1 << i) if char.to_i == 1
      i += 1
    end
    ret.to_s
  end

  # pretty_print {{{1
  def pretty_print(results)
    results.each do |res|
      res.each_key do |sys|
        res[sys].gsub!(/^0+/, '')
        res[sys] = '0' if res[sys].empty?
      end

      printf "%-24s | 0x%-12s | %s\n", res[:bin], res[:hex], res[:dec]
    end
  end

  # handle_base {{{1
  def handle_base_02(bin)
    hex = c2to16(bin)
    dec = c2to10(bin)
    { bin: bin, dec: dec, hex: hex }
  end

  def handle_base_10(dec)
    hex = c10to16(dec.to_i)
    bin = c16to2(hex)
    { bin: bin, dec: dec, hex: hex }
  end

  def handle_base_16(hex)
    bin = c16to2(hex)
    dec = c2to10(bin)
    { bin: bin, dec: dec, hex: hex }
  end

  # run {{{1
  def run
    @Input.each do |arg|
      tmp     = validate_input(arg)
      results = []

      if tmp
        case tmp[:sys]
        when 'bin' then results << handle_base_02(tmp[:val])
        when 'dec' then results << handle_base_10(tmp[:val])
        when 'hex' then results << handle_base_16(tmp[:val])
        end
      end

      pretty_print results
    end
  end

end
# }}}

NumSys.new(ARGV).run


================================================
FILE: bin/s3cp
================================================
#!/usr/bin/env bash

if [[ $# -lt 1 ]]; then
    echo "usage: s3cp <local path> [s3 path] [options]"
    echo "See 'aws s3 cp help' for available options."
    exit 1
fi

target="${2:-"$(basename $1)"}"
aws s3 cp "$1" "s3://foobarquux/${target}" --acl public-read "${@:3}"
echo "https://s3.eu-west-2.amazonaws.com/foobarquux/${target}" | tee >(pbcopy)


================================================
FILE: bin/s3ls
================================================
#!/usr/bin/env bash

aws s3 ls foobarquux --recursive


================================================
FILE: bin/s3rm
================================================
#!/usr/bin/env bash

if [[ $# -lt 1 ]]; then
    echo "usage: s3rm <s3 path> [options]"
    echo "See 'aws s3 rm help' for available options."
    exit 1
fi

aws s3 rm "s3://foobarquux/$1" "${@:2}"


================================================
FILE: bin/s3screenshot
================================================
#!/usr/bin/env bash

if [[ $# -lt 1 ]]; then
    echo "usage: s3screenshot <filename>"
    echo "Use <space> to toggle between window selection and interactive selection."
    exit 1
fi

target="${1%.png}.png"

# -W  start in window selection mode
# -o  no shadow
if screencapture -Wo "/tmp/${target}"; then
    aws s3 cp "/tmp/${target}" "s3://foobarquux/screenshots/${target}" --acl public-read
    echo -n "Copied to pasteboard: "
    echo "https://s3.eu-west-2.a
Download .txt
gitextract_0vxcr2cu/

├── .Xdefaults
├── .Xmodmap
├── .bash_profile
├── .bashrc
├── .config/
│   ├── git/
│   │   ├── config
│   │   ├── config.colors.dark
│   │   ├── config.colors.light
│   │   └── template/
│   │       └── hooks/
│   │           ├── post-applypatch
│   │           ├── post-checkout
│   │           ├── post-commit
│   │           ├── post-merge
│   │           ├── post-rewrite
│   │           └── pre-commit
│   ├── karabiner/
│   │   └── assets/
│   │       └── complex_modifications/
│   │           ├── any.json
│   │           └── keychron-k6.json
│   └── rg/
│       └── rgrc
├── .ctags
├── .emacs.d/
│   ├── configs/
│   │   ├── erlang.el
│   │   └── haskell.el
│   └── init.el
├── .gemrc
├── .gitignore
├── .gnupg/
│   ├── gpg-agent.conf
│   └── gpg.conf
├── .hgrc
├── .iex.exs
├── .inputrc
├── .irbrc
├── .lldbinit
├── .macos
├── .misc/
│   ├── YellowLight.itermcolors
│   └── neovim-local.mk
├── .profile
├── .pryrc
├── .psqlrc
├── .pypirc
├── .rtorrent.rc
├── .shrc
├── .tmux.conf
├── .travis.yml
├── .vim/
│   ├── autoload/
│   │   └── mhi.vim
│   ├── colors/
│   │   └── fnord.vim
│   ├── lua/
│   │   └── config.lua
│   └── vimrc
├── .weechat/
│   └── weechat.conf
├── .xinitrc
├── .yarnrc
├── .zsh/
│   ├── .zlogout
│   ├── .zprofile
│   ├── .zshrc
│   ├── completion/
│   │   └── _mix
│   ├── dircolors.dark
│   └── dircolors.light
├── .zshenv
├── README.md
├── bin/
│   ├── battery
│   ├── book
│   ├── book.erl
│   ├── book.go
│   ├── bootstrap-homebrew
│   ├── bootstrap-host
│   ├── bootstrap-ruby
│   ├── bootstrap-vim
│   ├── build-angband
│   ├── build-elixir
│   ├── build-erlang
│   ├── build-git
│   ├── build-go
│   ├── build-htop
│   ├── build-tmux
│   ├── build-vim
│   ├── build-zsh
│   ├── busy
│   ├── c_rocks
│   ├── dotfiles
│   ├── ec
│   ├── english
│   ├── english-notification
│   ├── fix-term
│   ├── gem-info
│   ├── git-ctags
│   ├── git-neck
│   ├── git-standup
│   ├── git-to
│   ├── git-trail
│   ├── git-whereami
│   ├── itb
│   ├── man
│   ├── markov
│   ├── mhi
│   ├── mhi-fix
│   ├── mhi-net
│   ├── numsys
│   ├── s3cp
│   ├── s3ls
│   ├── s3rm
│   ├── s3screenshot
│   ├── shell_function_missing
│   ├── svn-clean
│   ├── svn-stats
│   ├── task
│   ├── tips
│   ├── twump
│   ├── unbook
│   ├── unixsniff
│   ├── vm
│   ├── weasel
│   ├── wlan
│   └── zproc
└── english.yaml
Download .txt
SYMBOL INDEX (9 symbols across 2 files)

FILE: .iex.exs
  class Mex (line 20) | defmodule Mex
    method expand_all (line 21) | defp expand_all(n, env) do

FILE: bin/book.go
  type byBase (line 15) | type byBase
    method Len (line 18) | func (b byBase) Len() int {
    method Less (line 22) | func (b byBase) Less(i, j int) bool {
    method Swap (line 26) | func (b byBase) Swap(i, j int) {
  function scanDir (line 31) | func scanDir(fnames *[]string, arg string) {
  function run (line 60) | func run(prog, bookpath string) {
  function main (line 69) | func main() {
Condensed preview — 110 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (250K chars).
[
  {
    "path": ".Xdefaults",
    "chars": 5118,
    "preview": "!!!  MISC  !!!\nXcursor.theme:            redglass\nXcursor.size:             28\n\nEclipse*fontList:         -*-terminus-*-"
  },
  {
    "path": ".Xmodmap",
    "chars": 163,
    "preview": "remove Lock = Caps_Lock\nkeysym Caps_Lock = Control_L\nadd Control = Control_L\n\nkeycode 94 = parenleft parenright bar brok"
  },
  {
    "path": ".bash_profile",
    "chars": 268,
    "preview": "if [[ -r ~/.profile ]]; then\n  . $HOME/.profile\nelse\n  echo 'No ~/.profile found.'\nfi\n\n# bashrc doesn't get sourced for "
  },
  {
    "path": ".bashrc",
    "chars": 271,
    "preview": "if [[ -r $HOME/.shrc ]]; then\n  . $HOME/.shrc\nelse\n  echo 'No .shrc found.'\nfi\n\nshopt -s globstar\n\nstty werase undef\nbin"
  },
  {
    "path": ".config/git/config",
    "chars": 3471,
    "preview": "; Config {{{1\n[user]\n  name       = Marco Hinz\n  email      = mh.codebro@gmail.com\n  signingKey = D56EA60F557FD8B6\n[core"
  },
  {
    "path": ".config/git/config.colors.dark",
    "chars": 349,
    "preview": "[alias]\n    l = log --graph --pretty='%C(242)%h %C(156)%s %C(248)%an%C(242), %C(248)%ar%C(222)%d' --decorate --date=rela"
  },
  {
    "path": ".config/git/config.colors.light",
    "chars": 384,
    "preview": "[alias]\n    l = log --graph --pretty='%C(245)%h %C(16)%s %C(reset)%C(ul 245)%an%C(reset), %C(248)%ar%C(124)%d' --decorat"
  },
  {
    "path": ".config/git/template/hooks/post-applypatch",
    "chars": 190,
    "preview": "#!/usr/bin/env bash\n\nif [[ \"$(uname -s)\" = Darwin ]]; then\n    osascript <<EOF\n    display notification \"git-ctags: `pwd"
  },
  {
    "path": ".config/git/template/hooks/post-checkout",
    "chars": 401,
    "preview": "#!/usr/bin/env bash\n\nif [[ \"$(uname -s)\" = Darwin ]]; then\n    osascript <<EOF\n    display notification \"git-ctags: `pwd"
  },
  {
    "path": ".config/git/template/hooks/post-commit",
    "chars": 186,
    "preview": "#!/usr/bin/env bash\n\nif [[ \"$(uname -s)\" = Darwin ]]; then\n    osascript <<EOF\n    display notification \"git-ctags: `pwd"
  },
  {
    "path": ".config/git/template/hooks/post-merge",
    "chars": 185,
    "preview": "#!/usr/bin/env bash\n\nif [[ \"$(uname -s)\" = Darwin ]]; then\n    osascript <<EOF\n    display notification \"git-ctags: `pwd"
  },
  {
    "path": ".config/git/template/hooks/post-rewrite",
    "chars": 267,
    "preview": "#!/usr/bin/env bash\n\ncase \"$1\" in\n    rebase)\n        if [[ \"$(uname -s)\" = Darwin ]]; then\n            osascript <<EOF\n"
  },
  {
    "path": ".config/git/template/hooks/pre-commit",
    "chars": 254,
    "preview": "#!/usr/bin/env bash\n\nif git rev-parse --verify HEAD &>/dev/null; then\n    against=HEAD\nelse\n    # Initial commit: diff a"
  },
  {
    "path": ".config/karabiner/assets/complex_modifications/any.json",
    "chars": 514,
    "preview": "{\n  \"title\": \"Any\",\n  \"rules\": [\n    {\n      \"manipulators\": [\n        {\n          \"description\": \"(Any) caps_lock > lef"
  },
  {
    "path": ".config/karabiner/assets/complex_modifications/keychron-k6.json",
    "chars": 1513,
    "preview": "{\n  \"title\": \"Keychron K6\",\n  \"rules\": [\n    {\n      \"description\": \"(Keychron K6) left_shift alone > `\",\n      \"manipul"
  },
  {
    "path": ".config/rg/rgrc",
    "chars": 34,
    "preview": "--hidden\n--no-ignore\n--smart-case\n"
  },
  {
    "path": ".ctags",
    "chars": 1399,
    "preview": "--regex-ruby=/(^|[:;])[ \\t]*([A-Z][[:alnum:]_]+) *=/\\2/c,class,constant/\n--regex-ruby=/^[ \\t]*attr_(reader|writer|access"
  },
  {
    "path": ".emacs.d/configs/erlang.el",
    "chars": 163,
    "preview": "(setq erlang-root-dir \"~/local/erlang/lib/erlang/erts-6.3.1\")\n(setq exec-path (cons \"~/local/erlang/lib/erlang/erts-6.3."
  },
  {
    "path": ".emacs.d/configs/haskell.el",
    "chars": 1600,
    "preview": "(require 'haskell-mode-autoloads)\n\n(custom-set-variables\n '(haskell-process-auto-import-loaded-modules t)\n '(haskell-pro"
  },
  {
    "path": ".emacs.d/init.el",
    "chars": 2064,
    "preview": "(when (< emacs-major-version 24)\n  (princ \"Install at least Emacs 24.\\n\" #'external-debugging-output)\n  (kill-emacs))\n\n("
  },
  {
    "path": ".gemrc",
    "chars": 114,
    "preview": ":update_sources: true\n:bulk_threshold: 1000\n:verbose: true\n:benchmark: false\n:backtrace: false\ngem: --no-document\n"
  },
  {
    "path": ".gitignore",
    "chars": 22,
    "preview": "/*/\n!/bin/\n!.*\n/.git/\n"
  },
  {
    "path": ".gnupg/gpg-agent.conf",
    "chars": 68,
    "preview": "pinentry-program /usr/local/bin/pinentry-mac\ndefault-cache-ttl 7200\n"
  },
  {
    "path": ".gnupg/gpg.conf",
    "chars": 269,
    "preview": "personal-digest-preferences SHA256\ncert-digest-algo SHA256\ndefault-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AE"
  },
  {
    "path": ".hgrc",
    "chars": 493,
    "preview": "[ui]\nusername = Marco Hinz <mh.codebro@gmail.com>\ncolor = always\n\n[pager]\npager = LESS='FRX' less\n\n[alias]\na    = add\nb "
  },
  {
    "path": ".iex.exs",
    "chars": 640,
    "preview": "IEx.configure [\n  colors: [\n    eval_info:       [:yellow, :bright],\n    eval_error:      [:red],\n    eval_interrupt:  ["
  },
  {
    "path": ".inputrc",
    "chars": 134,
    "preview": "set show-all-if-ambiguous on\n\nControl-p: history-search-backward\nControl-k: history-search-backward\nControl-n: history-s"
  },
  {
    "path": ".irbrc",
    "chars": 152,
    "preview": "begin\n  require 'pry'\n  Pry.start\n  exit\nrescue LoadError\n  require 'irb/completion'\n  IRB.conf[:PROMPT_MODE] = :SIMPLE\n"
  },
  {
    "path": ".lldbinit",
    "chars": 401,
    "preview": "command alias ptype target modules lookup -t %1\ncommand alias reload command source -s 1 ~/.lldbinit\n\nsettings set targe"
  },
  {
    "path": ".macos",
    "chars": 1276,
    "preview": "#!/usr/bin/env bash\n\nsudo -v\n\n# Cron {{{1\n# This needs full disk access enabled for the calling terminal emulator.\n# E.g"
  },
  {
    "path": ".misc/YellowLight.itermcolors",
    "chars": 8166,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
  },
  {
    "path": ".misc/neovim-local.mk",
    "chars": 1337,
    "preview": "CMAKE_BUILD_TYPE  := Debug\nCMAKE_EXTRA_FLAGS := -DCMAKE_INSTALL_PREFIX=${HOME}/local/nvim\nUSE_BUNDLED       := ON\n\n# DEP"
  },
  {
    "path": ".profile",
    "chars": 2055,
    "preview": "# This file gets sourced by every login shell.\n\n# PATH {{{1\nnewpath=(\n    # homebrew (keg-only)\n    /usr/local/sbin\n    "
  },
  {
    "path": ".pryrc",
    "chars": 502,
    "preview": "def line(obj, depth, indent=true)\n  print indent ? obj.rjust(depth.to_i + obj.length) : obj\nend\n\ndef ppp(obj, depth=0, i"
  },
  {
    "path": ".psqlrc",
    "chars": 106,
    "preview": "\\set PROMPT1 '%[%033[0;34m%]%/%R%x%#%[%033[0m%] '\n\\set PROMPT2 '%[%033[0;33m%]%R%x →%[%033[0m%] '\n\\x auto\n"
  },
  {
    "path": ".pypirc",
    "chars": 56,
    "preview": "[distutils]\nindex-servers = pypi\n\n[pypi]\nusername:mhinz\n"
  },
  {
    "path": ".rtorrent.rc",
    "chars": 309,
    "preview": "directory  = /data/torrent/download\nsession    = /data/torrent/session\n\nschedule   = low_diskspace,5,60,close_low_disksp"
  },
  {
    "path": ".shrc",
    "chars": 13074,
    "preview": "# This file gets sourced by .bashrc and .zshrc.\n\nos=\"$(uname -s)\"\n\nstty discard undef\n\nif [[ -z $THEME ]]; then\n    if ["
  },
  {
    "path": ".tmux.conf",
    "chars": 4207,
    "preview": "# tmux.conf\n\n#  bindings  {{{1\nbind-key a               send-prefix\nbind-key r               source-file ~/.tmux.conf \\;"
  },
  {
    "path": ".travis.yml",
    "chars": 121,
    "preview": "sudo: false\ndist: trusty\n\naddons:\n  apt:\n    packages: shellcheck\n\nscript: shellcheck bin/mhi* bin/build* bin/bootstrap*"
  },
  {
    "path": ".vim/autoload/mhi.vim",
    "chars": 10920,
    "preview": "\"\n\" Show the commit that touched the current line last.\n\"\nfunction! mhi#git_blame_current_line() abort\n  let gitdir = fi"
  },
  {
    "path": ".vim/colors/fnord.vim",
    "chars": 4249,
    "preview": "let g:colors_name = 'fnord'\n\nif !has('gui_running') || &termguicolors == 0\n  if exists('+termguicolors')\n    let &termgu"
  },
  {
    "path": ".vim/lua/config.lua",
    "chars": 5353,
    "preview": "local mapopts = { noremap = true, silent = true }\n\n-- lsp {{{1\nlocal function default_lsp_settings(_client, _bufnr)\n  vi"
  },
  {
    "path": ".vim/vimrc",
    "chars": 24140,
    "preview": "\"\n\"                         ███████████████████████████\n\"                         ███████▀▀▀░░░░░░░▀▀▀███████\n\"         "
  },
  {
    "path": ".weechat/weechat.conf",
    "chars": 19772,
    "preview": "#\n# weechat -- weechat.conf\n#\n# WARNING: It is NOT recommended to edit this file by hand,\n# especially if WeeChat is run"
  },
  {
    "path": ".xinitrc",
    "chars": 876,
    "preview": "#!/bin/sh\n\nfailsafe=\"xterm -ls -T failsafe -geometry 80x24-0-0\"\n\ntrap \"exec $failsafe\" EXIT SIGHUP SIGINT SIGPIPE SIGTER"
  },
  {
    "path": ".yarnrc",
    "chars": 221,
    "preview": "# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\n# yarn lockfile v1\n\n\ncache-folder \"/Users/mhi/.yarn/cac"
  },
  {
    "path": ".zsh/.zlogout",
    "chars": 122,
    "preview": "#!/usr/bin/zsh\n\nwhich sudo &>/dev/null && sudo -k\nclear\n\n[[ -n $SSH_CONNECTION ]] && echo -n \"Connection closed:  \"; dat"
  },
  {
    "path": ".zsh/.zprofile",
    "chars": 165,
    "preview": "# Opposed to Bash, Zsh doesn't source ~/.profile on its own.\n\nif [[ -r ~/.profile ]]; then\n  emulate sh -c 'source ~/.pr"
  },
  {
    "path": ".zsh/.zshrc",
    "chars": 6580,
    "preview": "#!/usr/bin/env zsh\n\nif [[ -r ~/.shrc ]]; then\n    source ~/.shrc\nelse\n    echo 'No .shrc found.'\nfi\n\n[[ -d $ZDOTDIR/comp"
  },
  {
    "path": ".zsh/completion/_mix",
    "chars": 1040,
    "preview": "#compdef mix\n\n_arguments \\\n  '1:task names:->tasks' \\\n  '*:task arguments:->arguments'\n\nlocal candidates\n\ncase $state in"
  },
  {
    "path": ".zsh/dircolors.dark",
    "chars": 22250,
    "preview": "# Thanks, https://github.com/trapd00r/LS_COLORS/blob/master/LS_COLORS\n\n# core {{{1\nBLK                   38;5;68\nCAPABIL"
  },
  {
    "path": ".zsh/dircolors.light",
    "chars": 4983,
    "preview": "# Configuration file for dircolors, a utility to help you set the\n# LS_COLORS environment variable used by GNU ls with t"
  },
  {
    "path": ".zshenv",
    "chars": 67,
    "preview": "#!/usr/bin/env zsh\n\n# Always sourced first.\n\nexport ZDOTDIR=~/.zsh\n"
  },
  {
    "path": "README.md",
    "chars": 744,
    "preview": "[![Build Status](https://travis-ci.org/mhinz/dotfiles.svg?branch=master)](https://travis-ci.org/mhinz/dotfiles)\n\nA few y"
  },
  {
    "path": "bin/battery",
    "chars": 139,
    "preview": "#!/bin/sh\n\nos=\"$(uname -o)\"\n\nif [ \"$os\" = Darwin ]; then\n    pmset -g batt | awk 'NR==2 { gsub(/;/, \"\"); print $3 }'\n   "
  },
  {
    "path": "bin/book",
    "chars": 984,
    "preview": "#!/usr/bin/env ruby\n\nrequire 'find'\n\nmodule Find\n  def populate(*paths)\n    matched = {}\n    find(*paths) do |path|\n    "
  },
  {
    "path": "bin/book.erl",
    "chars": 1068,
    "preview": "#!/usr/bin/env escript\n\n-define(BOOKPATH, '/data/books').\n\nlist_files(RegExp) ->\n    filelib:fold_files(?BOOKPATH, \"((?i"
  },
  {
    "path": "bin/book.go",
    "chars": 1820,
    "preview": "//usr/bin/env go run $0 $@; exit\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"sor"
  },
  {
    "path": "bin/bootstrap-homebrew",
    "chars": 1187,
    "preview": "#!/usr/bin/env bash\n\nxcode-select --install\n\nif ! command -v brew &>/dev/null; then\n    ruby -e \"$(curl -fsSL https://ra"
  },
  {
    "path": "bin/bootstrap-host",
    "chars": 779,
    "preview": "#!/bin/sh\n\nlist_ssh_hosts() {\n    awk '$1 == \"HostName\" { print $2 }' ~/.ssh/config | \\\n        cut -d. -f1 | \\\n        "
  },
  {
    "path": "bin/bootstrap-ruby",
    "chars": 267,
    "preview": "#!/usr/bin/env bash\n\ngem install rbenv gem-ctags\ngem ctags\n\nmkdir -p ~/.rbenv/plugins\ngit clone https://github.com/tpope"
  },
  {
    "path": "bin/bootstrap-vim",
    "chars": 345,
    "preview": "#!/usr/bin/env bash\n\nset -ex\n\nmkdir -p ~/.vim/files/{backup,info,swap,undo}\nmkdir -p ~/.vim/bundle\nmkdir -p ~/.config\n\ng"
  },
  {
    "path": "bin/build-angband",
    "chars": 799,
    "preview": "#!/usr/bin/env bash\n\nrepo='https://github.com/angband/angband'\ndir=\"${ME}/repo/angband\"\n\ncd \"$dir\" 2>/dev/null || {\n    "
  },
  {
    "path": "bin/build-elixir",
    "chars": 309,
    "preview": "#!/usr/bin/env bash\n\nset -e\n\ndir=\"${ME}/github/elixir-lang/elixir\"\n\nif [[ ! -d $dir ]]; then\n    mkdir -p \"${ME}/github/"
  },
  {
    "path": "bin/build-erlang",
    "chars": 404,
    "preview": "#!/usr/bin/env bash\n\nset -e\n\ndir=\"${ME}/github/erlang/otp\"\nprefix=\"${HOME}/local/erlang\"\n\nflags=(\n    \"--prefix=${prefix"
  },
  {
    "path": "bin/build-git",
    "chars": 564,
    "preview": "#!/usr/bin/env bash\n\nset -e\nset -x\n\ndir=\"${ME}/repo/git\"\nprefix=\"${HOME}/local/git\"\n\n# avoid \"Document /<path>/git/Docum"
  },
  {
    "path": "bin/build-go",
    "chars": 1049,
    "preview": "#!/usr/bin/env bash\n\nset -e\nset -x\n\n[[ -z ${GOROOT:+nope} ]] && { echo \"Export \\$GOROOT first.\"; exit 1; }\n[[ -z ${GOARC"
  },
  {
    "path": "bin/build-htop",
    "chars": 237,
    "preview": "#!/usr/bin/env bash\n\ndir=\"${ME}/repo/htop\"\nprefix=\"${HOME}/local/htop\"\n\ncd \"$dir\" || exit\n\nif [[ $1 != -f ]]; then\n    g"
  },
  {
    "path": "bin/build-tmux",
    "chars": 206,
    "preview": "#!/usr/bin/env bash\n\ncd \"${ME}/repo/tmux\" || exit\n\nif git pull | grep 'Already up[ -]to[ -]date.' && [ \"$1\" != -f ]; the"
  },
  {
    "path": "bin/build-vim",
    "chars": 1048,
    "preview": "#!/usr/bin/env bash\n\ndir=\"${ME}/github/vim/vim\"\nprefix=\"${HOME}/local/vim\"\n\n# python3-config --configdir\nflags=(\n    \"--"
  },
  {
    "path": "bin/build-zsh",
    "chars": 633,
    "preview": "#!/usr/bin/env bash\n\ndir=\"${ME}/repo/zsh\"\nprefix=\"${HOME}/local/zsh\"\n\ncd \"$dir\" || exit\necho '[*] Cleaning directory..'\n"
  },
  {
    "path": "bin/busy",
    "chars": 598,
    "preview": "#!/usr/bin/env bash\n\n# Just a hack to keep macOS from sleeping without having to fiddle with the\n# energy saver settings"
  },
  {
    "path": "bin/c_rocks",
    "chars": 2396,
    "preview": "#!/bin/bash\n\nheader[0]='      o__ __o                                            o                '\nheader[1]='     /v  "
  },
  {
    "path": "bin/dotfiles",
    "chars": 3773,
    "preview": "#!/bin/sh\n\nred=\"\\033[31m\"\ngreen=\"\\033[32m\"\nyellow=\"\\033[33m\"\nblue=\"\\033[34m\"\nreset=\"\\033[0m\"\n\ncheck_file() {\n    if ! wh"
  },
  {
    "path": "bin/ec",
    "chars": 331,
    "preview": "#!/usr/bin/env bash\n\nif emacsclient --eval t &>/dev/null; then\n    if [[ -z $@ ]]; then\n        emacsclient --eval \"(dir"
  },
  {
    "path": "bin/english",
    "chars": 274,
    "preview": "#!/usr/bin/env ruby\n\nrequire 'yaml'\n\nwords = YAML.load_file(File.expand_path('~/english.yaml'))\n\nwhile words.any?\n  word"
  },
  {
    "path": "bin/english-notification",
    "chars": 267,
    "preview": "#!/usr/bin/env ruby\n\nrequire 'YAML'\n\nwords = YAML.load_file(File.expand_path('~/english.yaml'))\n\nenglish = words.keys.sa"
  },
  {
    "path": "bin/fix-term",
    "chars": 918,
    "preview": "#!/bin/sh\n\n# kbs        backspace key\n# sitm/ritm  italic\n# smso/rmso  standout\n# smxx/rmxx  strikethrough\n# Smulx      "
  },
  {
    "path": "bin/gem-info",
    "chars": 69,
    "preview": "#!/bin/sh\n\ncurl -s https://rubygems.org/api/v1/gems/\"${1}\".json | jq\n"
  },
  {
    "path": "bin/git-ctags",
    "chars": 341,
    "preview": "#!/usr/bin/env bash\n\nset -e\n\nblacklist=(~ /usr/local/Homebrew)\n\nfor dir in \"${blacklist[@]}\"; do\n    if [[ $PWD = $dir ]"
  },
  {
    "path": "bin/git-neck",
    "chars": 517,
    "preview": "#!/bin/sh -e\n\n# git neck [-r] [COMMIT] - show commits until first branching point\n#\n# Stolen from http://chneukirchen.or"
  },
  {
    "path": "bin/git-standup",
    "chars": 484,
    "preview": "#!/usr/bin/env bash\n\nstandup() {\n    dir=$1\n    shift\n    if git -C \"$dir\" rev-parse --git-dir &>/dev/null; then\n       "
  },
  {
    "path": "bin/git-to",
    "chars": 549,
    "preview": "#!/usr/bin/env bash\n#\n# usage: git to [ref]\n#\n# The number of commits between a given ref and HEAD. If no ref is given, "
  },
  {
    "path": "bin/git-trail",
    "chars": 881,
    "preview": "#!/bin/sh -e\n\n# git trail [-r] [-t] [COMMIT] - show all branching points in Git history\n#\n# Stolen from http://chneukirc"
  },
  {
    "path": "bin/git-whereami",
    "chars": 1307,
    "preview": "#!/usr/bin/env ruby\n#\n# frozen_string_literal: true\n\n# usage: git whereami [HEAD]\n#\n# Show next and previous tags from r"
  },
  {
    "path": "bin/itb",
    "chars": 2335,
    "preview": "#!/usr/bin/env ruby\n\nclass ITBooks\n  def initialize(args)\n    menu(lookup(args))\n  end\n\n  private\n\n  def lookup(args)\n  "
  },
  {
    "path": "bin/man",
    "chars": 348,
    "preview": "#!/usr/bin/env bash\n\n# On :Man, Nvim uses `MANWIDTH=999 man` for the purpose of soft wrapping the\n# resulting long lines"
  },
  {
    "path": "bin/markov",
    "chars": 1020,
    "preview": "#!/usr/bin/env python\n\nimport sys\nimport fileinput\nimport random\n\nclass Markov:\n    def __init__(self):\n        self.suf"
  },
  {
    "path": "bin/mhi",
    "chars": 1368,
    "preview": "#!/usr/bin/env bash\n\n# Configuration {{{1\nmhi=\"$(readlink \"$0\")\"\nmhi=${mhi:=$0}\nmhi=\"${mhi%/*}\"\n\n# Helpers {{{1\nlist_fil"
  },
  {
    "path": "bin/mhi-fix",
    "chars": 479,
    "preview": "#!/usr/bin/env bash\n\ncase $1 in\n  spotlight) # {{{1\n    hash brew 2>/dev/null || exit 1\n    brew linkapps\n    find /Appl"
  },
  {
    "path": "bin/mhi-net",
    "chars": 299,
    "preview": "#!/usr/bin/env bash\n\ncase $1 in\n  hosts) # {{{1\n    awk '$1 == \"Host\" { print $2 }' ~/.ssh/config | sort\n    ;;\n\n  irc) "
  },
  {
    "path": "bin/numsys",
    "chars": 2872,
    "preview": "#!/usr/bin/env ruby\n\nclass NumSys\n  # initalize {{{1\n  def initialize(args)\n    @Input = args.dup.freeze\n\n    if args.em"
  },
  {
    "path": "bin/s3cp",
    "chars": 352,
    "preview": "#!/usr/bin/env bash\n\nif [[ $# -lt 1 ]]; then\n    echo \"usage: s3cp <local path> [s3 path] [options]\"\n    echo \"See 'aws "
  },
  {
    "path": "bin/s3ls",
    "chars": 54,
    "preview": "#!/usr/bin/env bash\n\naws s3 ls foobarquux --recursive\n"
  },
  {
    "path": "bin/s3rm",
    "chars": 198,
    "preview": "#!/usr/bin/env bash\n\nif [[ $# -lt 1 ]]; then\n    echo \"usage: s3rm <s3 path> [options]\"\n    echo \"See 'aws s3 rm help' f"
  },
  {
    "path": "bin/s3screenshot",
    "chars": 532,
    "preview": "#!/usr/bin/env bash\n\nif [[ $# -lt 1 ]]; then\n    echo \"usage: s3screenshot <filename>\"\n    echo \"Use <space> to toggle b"
  },
  {
    "path": "bin/shell_function_missing",
    "chars": 2012,
    "preview": "#!/usr/bin/env ruby\n\ncommand = ARGV\n\n# Prints and runs a command.\n#\n# @param [String, Array] cmd Command to run.\n#   Aut"
  },
  {
    "path": "bin/svn-clean",
    "chars": 132,
    "preview": "#!/bin/zsh\n\n# Before svn 1.9 there was no:\n# svn cleanup --remove-unversioned\n\nsvn status | awk '/^\\?/ {print $2}' | xar"
  },
  {
    "path": "bin/svn-stats",
    "chars": 609,
    "preview": "#!/usr/bin/perl\n\nuse warnings;\nuse strict;\n\nuse Term::ANSIColor qw( :constants );\nuse List::MoreUtils qw( uniq );\n\nmy %s"
  },
  {
    "path": "bin/task",
    "chars": 2215,
    "preview": "#!/usr/bin/env bash\n#\n# Simple todo list manager.\n#\n# Tasks will be written to ~/tasks.\n# Finished tasks, plus a timesta"
  },
  {
    "path": "bin/tips",
    "chars": 12805,
    "preview": "#!/usr/bin/env ruby\n\ntips = [\n  \"I would rather die of passion than of boredom.  — Vincent Van Gogh\",\n  \"If a system is "
  },
  {
    "path": "bin/twump",
    "chars": 453,
    "preview": "#!/usr/bin/env ruby\n\n# Quick'n'dirty way to dump a tweet and its replies. Great for dumping wisdom\n# dropped in a thread"
  },
  {
    "path": "bin/unbook",
    "chars": 943,
    "preview": "#!/usr/bin/env bash\n\nif [[ -d __unbook ]]; then\n    echo 'Directory \"__unbook\" exists. Remove it manually.' 1>&2\n    exi"
  },
  {
    "path": "bin/unixsniff",
    "chars": 402,
    "preview": "#!/usr/bin/env bash\n\n# This only works for stream sockets.\n# For datagram sockets use UNIX-RECVFROM/UNIX-RECV.\n\nif [[ $#"
  },
  {
    "path": "bin/vm",
    "chars": 2152,
    "preview": "#!/usr/bin/env bash\n\ncmds=(\n    dhcp\n    info\n    list\n    save\n    ssh\n    start\n    stop\n)\n\nusage() {\n    printf 'vm %"
  },
  {
    "path": "bin/weasel",
    "chars": 500,
    "preview": "#!/bin/bash\nset -eu\n\nweasels=(\n  clearly\n  completely\n  exceedingly\n  excellent\n  extremely\n  fairly\n  few\n  huge\n  inte"
  },
  {
    "path": "bin/wlan",
    "chars": 1041,
    "preview": "#!/bin/bash\n\nfunction connect()\n{\n    echo \"[*] Setting up wlan0..\"\n    sudo ifconfig wlan0 up\n    echo \"[*] Connect to "
  },
  {
    "path": "bin/zproc",
    "chars": 1602,
    "preview": "#!/bin/zsh\n\n#\n# Author: Marco Hinz <mh.codebro@gmail.com>\n# URL:    http://github.com/mhinz\n# Desc:   This script output"
  },
  {
    "path": "english.yaml",
    "chars": 18274,
    "preview": "abberation:                  Abweichung, Anomalie\naccomodation:                Unterkunft\naccretion:                   W"
  }
]

About this extraction

This page contains the full source code of the mhinz/dotfiles GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 110 files (225.9 KB), approximately 76.1k tokens, and a symbol index with 9 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!