This commit is contained in:
John Doty 2013-07-08 15:51:25 -07:00
commit f825c6a061
49 changed files with 4153 additions and 43 deletions

114
.bashrc Normal file
View file

@ -0,0 +1,114 @@
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi

3
.config/fish/config.fish Normal file
View file

@ -0,0 +1,3 @@
if status --is-login
set PATH $PATH ~/bin
end

View file

@ -0,0 +1,180 @@
(1
(ack .
[(1 2)
nil "Interface to ack-like source code search tools" tar])
(adaptive-wrap .
[(0 2)
nil "Smart line-wrapping with wrap-prefix" single])
(all .
[(1 0)
nil "Edit all lines matching a given regexp" single])
(auctex .
[(11 86 1)
nil "Integrated environment for *TeX*" tar])
(cl-lib .
[(0 3)
nil "Properly prefixed CL functions and macros" single])
(coffee-mode .
[(0 4 1)
nil "Major mode for CoffeeScript files" tar])
(company .
[(0 6 10)
nil "Modular in-buffer completion framework" tar])
(csv-mode .
[(1 2)
nil "Major mode for editing comma/char separated values" single])
(debbugs .
[(0 4)
nil "SOAP library to access debbugs servers" tar])
(dict-tree .
[(0 12 8)
((trie
(0 2 5))
(tNFA
(0 1 1))
(heap
(0 3)))
"Dictionary data structure" single])
(djvu .
[(0 5)
nil "Edit and view Djvu files via djvused" single])
(docbook .
[(0 1)
nil "Info-like viewer for DocBook" single])
(ediprolog .
[(1 0)
nil "Emacs Does Interactive Prolog" single])
(eldoc-eval .
[(0 1)
nil "Enable eldoc support when minibuffer is in use." single])
(enwc .
[(1 0)
nil "The Emacs Network Client" tar])
(epoch-view .
[(0 0 1)
nil "Minor mode to visualize epoch timestamps" single])
(f90-interface-browser .
[(1 1)
nil "Parse and browse f90 interfaces" single])
(ggtags .
[(0 6 6)
nil "GNU Global source code tagging system" single])
(heap .
[(0 3)
nil "Heap (a.k.a. priority queue) data structure" single])
(ioccur .
[(2 4)
nil "Incremental occur" single])
(jgraph-mode .
[(1 0)
nil "Major mode for Jgraph files" single])
(js2-mode .
[(20130619)
((emacs
(24 1)))
"Improved JavaScript editing mode" single])
(jumpc .
[(3 0)
nil "jump to previous insertion points" single])
(lex .
[(1 1)
nil "Lexical analyser construction" tar])
(lmc .
[(1 2)
nil "Little Man Computer in Elisp" single])
(load-dir .
[(0 0 3)
nil "Load all Emacs Lisp files in a given directory" single])
(markchars .
[(0 2 0)
nil "Mark chars fitting certain characteristics" single])
(memory-usage .
[(0 2)
nil "Analyze the memory usage of Emacs in various ways" single])
(minimap .
[(1 0)
nil "Sidebar showing a \"mini-map\" of a buffer" single])
(muse .
[(3 20)
nil "Authoring and publishing tool" tar])
(nhexl-mode .
[(0 1)
nil "Minor mode to edit files via hex-dump format" single])
(nlinum .
[(1 1)
nil "Show line numbers in the margin" single])
(notes-mode .
[(1 30)
nil "Organizing on-line note-taking" tar])
(num3-mode .
[(1 1)
nil "highlight groups of digits in long numbers" single])
(oauth2 .
[(0 9)
nil "OAuth 2.0 Authorization Protocol" single])
(omn-mode .
[(1 0)
nil "Support for OWL Manchester Notation" single])
(org .
[(20130704)
nil "Outline-based notes management and organizer" tar])
(quarter-plane .
[(0 1)
nil "Minor mode for quarter-plane style editing" single])
(queue .
[(0 1)
nil "Queue data structure" single])
(rainbow-mode .
[(0 8)
nil "Colorize color names in buffers" single])
(register-list .
[(0 1)
nil "Interactively list/edit registers" single])
(shen-mode .
[(0 1)
nil "Utilities for working with Shen code." tar])
(sisu-mode .
[(3 0 3)
nil "Major mode for SiSU markup text" single])
(smart-operator .
[(4 0)
nil "Insert operators with surrounding spaces smartly" single])
(sml-mode .
[(6 4)
nil "Major mode for editing (Standard) ML" single])
(sokoban .
[(1 0 4)
nil "Sokoban game for emacs" tar])
(svg-clock .
[(0 4)
nil "Analog clock using Scalable Vector Graphics" single])
(tNFA .
[(0 1 1)
((queue
(0 1)))
"Tagged non-deterministic finite-state automata" single])
(trie .
[(0 2 6)
((tNFA
(0 1 1))
(heap
(0 3)))
"Trie data structure" single])
(undo-tree .
[(0 6 3)
nil "Treat undo history as a tree" single])
(uni-confusables .
[(0 1)
nil "Unicode confusables table" tar])
(vlf .
[(0 2)
nil "View Large Files" single])
(windresize .
[(0 1)
nil "Resize windows interactively" single])
(xclip .
[(1 0)
nil "Emacs Interface to XClip" single])
(yasnippet .
[(0 8 0)
nil "A template system for Emacs" tar]))

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,52 @@
;;; go-mode-autoloads.el --- automatically extracted autoloads
;;
;;; Code:
;;;### (autoloads (godoc gofmt-before-save gofmt go-mode) "go-mode"
;;;;;; "go-mode.el" (20953 5091))
;;; Generated autoloads from go-mode.el
(autoload 'go-mode "go-mode" "\
Major mode for editing Go source text.
This provides basic syntax highlighting for keywords, built-ins,
functions, and some types. It also provides indentation that is
\(almost) identical to gofmt.
\(fn)" t nil)
(add-to-list 'auto-mode-alist (cons "\\.go$" #'go-mode))
(autoload 'gofmt "go-mode" "\
Pipe the current buffer through the external tool `gofmt`.
Replace the current buffer on success; display errors on failure.
\(fn)" t nil)
(autoload 'gofmt-before-save "go-mode" "\
Add this to .emacs to run gofmt on the current buffer when saving:
(add-hook 'before-save-hook #'gofmt-before-save)
\(fn)" t nil)
(autoload 'godoc "go-mode" "\
Show go documentation for a query, much like M-x man.
\(fn QUERY)" t nil)
;;;***
;;;### (autoloads nil nil ("go-mode-load.el" "go-mode-pkg.el") (20953
;;;;;; 5091 375046))
;;;***
(provide 'go-mode-autoloads)
;; Local Variables:
;; version-control: never
;; no-byte-compile: t
;; no-update-autoloads: t
;; coding: utf-8
;; End:
;;; go-mode-autoloads.el ends here

View file

@ -0,0 +1,50 @@
;;; go-mode-load.el --- Major mode for the Go programming language
;;; Commentary:
;; To install go-mode, add the following lines to your .emacs file:
;; (add-to-list 'load-path "PATH CONTAINING go-mode-load.el" t)
;; (require 'go-mode-load)
;; After this, go-mode will be used for files ending in '.go'.
;; To compile go-mode from the command line, run the following
;; emacs -batch -f batch-byte-compile go-mode.el
;; See go-mode.el for documentation.
;;; Code:
;; To update this file, evaluate the following form
;; (let ((generated-autoload-file buffer-file-name)) (update-file-autoloads "go-mode.el"))
;;;### (autoloads (gofmt-before-save gofmt go-mode) "go-mode" "go-mode.el"
;;;;;; (19917 17808))
;;; Generated autoloads from go-mode.el
(autoload 'go-mode "go-mode" "\
Major mode for editing Go source text.
This provides basic syntax highlighting for keywords, built-ins,
functions, and some types. It also provides indentation that is
\(almost) identical to gofmt.
\(fn)" t nil)
(add-to-list 'auto-mode-alist (cons "\\.go$" #'go-mode))
(autoload 'gofmt "go-mode" "\
Pipe the current buffer through the external tool `gofmt`.
Replace the current buffer on success; display errors on failure.
\(fn)" t nil)
(autoload 'gofmt-before-save "go-mode" "\
Add this to .emacs to run gofmt on the current buffer when saving:
(add-hook 'before-save-hook #'gofmt-before-save)
\(fn)" t nil)
;;;***
(provide 'go-mode-load)

View file

@ -0,0 +1,2 @@
(define-package "go-mode" "12869"
"Major mode for the Go programming language.")

View file

@ -0,0 +1,823 @@
;;; go-mode.el --- Major mode for the Go programming language
;;; Commentary:
;; For installation instructions, see go-mode-load.el
;;; To do:
;; * Indentation is *almost* identical to gofmt
;; ** We think struct literal keys are labels and outdent them
;; ** We disagree on the indentation of function literals in arguments
;; ** There are bugs with the close brace of struct literals
;; * Highlight identifiers according to their syntactic context: type,
;; variable, function call, or tag
;; * Command for adding an import
;; ** Check if it's already there
;; ** Factor/unfactor the import line
;; ** Alphabetize
;; * Remove unused imports
;; ** This is hard, since I have to be aware of shadowing to do it
;; right
;; * Format region using gofmt
;;; Code:
(eval-when-compile (require 'cl))
(defvar go-mode-syntax-table
(let ((st (make-syntax-table)))
;; Add _ to :word: character class
(modify-syntax-entry ?_ "w" st)
;; Operators (punctuation)
(modify-syntax-entry ?+ "." st)
(modify-syntax-entry ?- "." st)
(modify-syntax-entry ?* "." st)
(modify-syntax-entry ?/ "." st)
(modify-syntax-entry ?% "." st)
(modify-syntax-entry ?& "." st)
(modify-syntax-entry ?| "." st)
(modify-syntax-entry ?^ "." st)
(modify-syntax-entry ?! "." st)
(modify-syntax-entry ?= "." st)
(modify-syntax-entry ?< "." st)
(modify-syntax-entry ?> "." st)
;; Strings and comments are font-locked separately.
(modify-syntax-entry ?\" "." st)
(modify-syntax-entry ?\' "." st)
(modify-syntax-entry ?` "." st)
(modify-syntax-entry ?\\ "." st)
st)
"Syntax table for Go mode.")
(defvar go-mode-keywords
'("break" "default" "func" "interface" "select"
"case" "defer" "go" "map" "struct"
"chan" "else" "goto" "package" "switch"
"const" "fallthrough" "if" "range" "type"
"continue" "for" "import" "return" "var")
"All keywords in the Go language. Used for font locking and
some syntax analysis.")
(defvar go-mode-font-lock-keywords
(let ((builtins '("append" "cap" "close" "complex" "copy" "delete" "imag" "len"
"make" "new" "panic" "print" "println" "real" "recover"))
(constants '("nil" "true" "false" "iota"))
(type-name "\\s *\\(?:[*(]\\s *\\)*\\(?:\\w+\\s *\\.\\s *\\)?\\(\\w+\\)")
)
`((go-mode-font-lock-cs-comment 0 font-lock-comment-face t)
(go-mode-font-lock-cs-string 0 font-lock-string-face t)
(,(regexp-opt go-mode-keywords 'words) . font-lock-keyword-face)
(,(regexp-opt builtins 'words) . font-lock-builtin-face)
(,(regexp-opt constants 'words) . font-lock-constant-face)
;; Function names in declarations
("\\<func\\>\\s *\\(\\w+\\)" 1 font-lock-function-name-face)
;; Function names in methods are handled by function call pattern
;; Function names in calls
;; XXX Doesn't match if function name is surrounded by parens
("\\(\\w+\\)\\s *(" 1 font-lock-function-name-face)
;; Type names
("\\<type\\>\\s *\\(\\w+\\)" 1 font-lock-type-face)
(,(concat "\\<type\\>\\s *\\w+\\s *" type-name) 1 font-lock-type-face)
;; Arrays/slices/map value type
;; XXX Wrong. Marks 0 in expression "foo[0] * x"
;; (,(concat "]" type-name) 1 font-lock-type-face)
;; Map key type
(,(concat "\\<map\\s *\\[" type-name) 1 font-lock-type-face)
;; Channel value type
(,(concat "\\<chan\\>\\s *\\(?:<-\\)?" type-name) 1 font-lock-type-face)
;; new/make type
(,(concat "\\<\\(?:new\\|make\\)\\>\\(?:\\s \\|)\\)*(" type-name) 1 font-lock-type-face)
;; Type conversion
(,(concat "\\.\\s *(" type-name) 1 font-lock-type-face)
;; Method receiver type
(,(concat "\\<func\\>\\s *(\\w+\\s +" type-name) 1 font-lock-type-face)
;; Labels
;; XXX Not quite right. Also marks compound literal fields.
("^\\s *\\(\\w+\\)\\s *:\\(\\S.\\|$\\)" 1 font-lock-constant-face)
("\\<\\(goto\\|break\\|continue\\)\\>\\s *\\(\\w+\\)" 2 font-lock-constant-face)))
"Basic font lock keywords for Go mode. Highlights keywords,
built-ins, functions, and some types.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key map
;;
(defvar go-mode-map
(let ((m (make-sparse-keymap)))
(define-key m "}" #'go-mode-insert-and-indent)
(define-key m ")" #'go-mode-insert-and-indent)
(define-key m "," #'go-mode-insert-and-indent)
(define-key m ":" #'go-mode-delayed-electric)
;; In case we get : indentation wrong, correct ourselves
(define-key m "=" #'go-mode-insert-and-indent)
m)
"Keymap used by Go mode to implement electric keys.")
(defun go-mode-insert-and-indent (key)
"Invoke the global binding of KEY, then reindent the line."
(interactive (list (this-command-keys)))
(call-interactively (lookup-key (current-global-map) key))
(indent-according-to-mode))
(defvar go-mode-delayed-point nil
"The point following the previous insertion if the insertion
was a delayed electric key. Used to communicate between
`go-mode-delayed-electric' and `go-mode-delayed-electric-hook'.")
(make-variable-buffer-local 'go-mode-delayed-point)
(defun go-mode-delayed-electric (p)
"Perform electric insertion, but delayed by one event.
This inserts P into the buffer, as usual, then waits for another key.
If that second key causes a buffer modification starting at the
point after the insertion of P, reindents the line containing P."
(interactive "p")
(self-insert-command p)
(setq go-mode-delayed-point (point)))
(defun go-mode-delayed-electric-hook (b e l)
"An after-change-function that implements `go-mode-delayed-electric'."
(when (and go-mode-delayed-point
(= go-mode-delayed-point b))
(save-excursion
(save-match-data
(goto-char go-mode-delayed-point)
(indent-according-to-mode))))
(setq go-mode-delayed-point nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Parser
;;
(defvar go-mode-mark-cs-end 1
"The point at which the comment/string cache ends. The buffer
will be marked from the beginning up to this point (that is, up
to and including character (1- go-mode-mark-cs-end)).")
(make-variable-buffer-local 'go-mode-mark-cs-end)
(defvar go-mode-mark-string-end 1
"The point at which the string cache ends. The buffer
will be marked from the beginning up to this point (that is, up
to and including character (1- go-mode-mark-string-end)).")
(make-variable-buffer-local 'go-mode-mark-string-end)
(defvar go-mode-mark-comment-end 1
"The point at which the comment cache ends. The buffer
will be marked from the beginning up to this point (that is, up
to and including character (1- go-mode-mark-comment-end)).")
(make-variable-buffer-local 'go-mode-mark-comment-end)
(defvar go-mode-mark-nesting-end 1
"The point at which the nesting cache ends. The buffer will be
marked from the beginning up to this point.")
(make-variable-buffer-local 'go-mode-mark-nesting-end)
(defun go-mode-mark-clear-cache (b e)
"A before-change-function that clears the comment/string and
nesting caches from the modified point on."
(save-restriction
(widen)
(when (<= b go-mode-mark-cs-end)
;; Remove the property adjacent to the change position.
;; It may contain positions pointing beyond the new end mark.
(let ((b (let ((cs (get-text-property (max 1 (1- b)) 'go-mode-cs)))
(if cs (car cs) b))))
(remove-text-properties
b (min go-mode-mark-cs-end (point-max)) '(go-mode-cs nil))
(setq go-mode-mark-cs-end b)))
(when (<= b go-mode-mark-string-end)
;; Remove the property adjacent to the change position.
;; It may contain positions pointing beyond the new end mark.
(let ((b (let ((cs (get-text-property (max 1 (1- b)) 'go-mode-string)))
(if cs (car cs) b))))
(remove-text-properties
b (min go-mode-mark-string-end (point-max)) '(go-mode-string nil))
(setq go-mode-mark-string-end b)))
(when (<= b go-mode-mark-comment-end)
;; Remove the property adjacent to the change position.
;; It may contain positions pointing beyond the new end mark.
(let ((b (let ((cs (get-text-property (max 1 (1- b)) 'go-mode-comment)))
(if cs (car cs) b))))
(remove-text-properties
b (min go-mode-mark-string-end (point-max)) '(go-mode-comment nil))
(setq go-mode-mark-comment-end b)))
(when (< b go-mode-mark-nesting-end)
(remove-text-properties b (min go-mode-mark-nesting-end (point-max)) '(go-mode-nesting nil))
(setq go-mode-mark-nesting-end b))))
(defmacro go-mode-parser (&rest body)
"Evaluate BODY in an environment set up for parsers that use
text properties to mark text. This inhibits changes to the undo
list or the buffer's modification status and inhibits calls to
the modification hooks. It also saves the excursion and
restriction and widens the buffer, since most parsers are
context-sensitive."
(let ((modified-var (make-symbol "modified")))
`(let ((buffer-undo-list t)
(,modified-var (buffer-modified-p))
(inhibit-modification-hooks t)
(inhibit-read-only t))
(save-excursion
(save-restriction
(widen)
(unwind-protect
(progn ,@body)
(set-buffer-modified-p ,modified-var)))))))
(defun go-mode-cs (&optional pos)
"Return the comment/string state at point POS. If point is
inside a comment or string (including the delimiters), this
returns a pair (START . END) indicating the extents of the
comment or string."
(unless pos
(setq pos (point)))
(when (> pos go-mode-mark-cs-end)
(go-mode-mark-cs pos))
(get-text-property pos 'go-mode-cs))
(defun go-mode-mark-cs (end)
"Mark comments and strings up to point END. Don't call this
directly; use `go-mode-cs'."
(setq end (min end (point-max)))
(go-mode-parser
(save-match-data
(let ((pos
;; Back up to the last known state.
(let ((last-cs
(and (> go-mode-mark-cs-end 1)
(get-text-property (1- go-mode-mark-cs-end)
'go-mode-cs))))
(if last-cs
(car last-cs)
(max 1 (1- go-mode-mark-cs-end))))))
(while (< pos end)
(goto-char pos)
(let ((cs-end ; end of the text property
(cond
((looking-at "//")
(end-of-line)
(1+ (point)))
((looking-at "/\\*")
(goto-char (+ pos 2))
(if (search-forward "*/" (1+ end) t)
(point)
end))
((looking-at "\"")
(goto-char (1+ pos))
(if (looking-at "[^\"\n\\\\]*\\(\\\\.[^\"\n\\\\]*\\)*\"")
(match-end 0)
(end-of-line)
(point)))
((looking-at "'")
(goto-char (1+ pos))
(if (looking-at "[^'\n\\\\]*\\(\\\\.[^'\n\\\\]*\\)*'")
(match-end 0)
(end-of-line)
(point)))
((looking-at "`")
(goto-char (1+ pos))
(while (if (search-forward "`" end t)
(if (eq (char-after) ?`)
(goto-char (1+ (point))))
(goto-char end)
nil))
(point)))))
(cond
(cs-end
(put-text-property pos cs-end 'go-mode-cs (cons pos cs-end))
(setq pos cs-end))
((re-search-forward "[\"'`]\\|/[/*]" end t)
(setq pos (match-beginning 0)))
(t
(setq pos end)))))
(setq go-mode-mark-cs-end pos)))))
(defun go-mode-in-comment (&optional pos)
"Return the comment/string state at point POS. If point is
inside a comment (including the delimiters), this
returns a pair (START . END) indicating the extents of the
comment or string."
(unless pos
(setq pos (point)))
(when (> pos go-mode-mark-comment-end)
(go-mode-mark-comment pos))
(get-text-property pos 'go-mode-comment))
(defun go-mode-mark-comment (end)
"Mark comments up to point END. Don't call this directly; use `go-mode-in-comment'."
(setq end (min end (point-max)))
(go-mode-parser
(save-match-data
(let ((pos
;; Back up to the last known state.
(let ((last-comment
(and (> go-mode-mark-comment-end 1)
(get-text-property (1- go-mode-mark-comment-end)
'go-mode-comment))))
(if last-comment
(car last-comment)
(max 1 (1- go-mode-mark-comment-end))))))
(while (< pos end)
(goto-char pos)
(let ((comment-end ; end of the text property
(cond
((looking-at "//")
(end-of-line)
(1+ (point)))
((looking-at "/\\*")
(goto-char (+ pos 2))
(if (search-forward "*/" (1+ end) t)
(point)
end)))))
(cond
(comment-end
(put-text-property pos comment-end 'go-mode-comment (cons pos comment-end))
(setq pos comment-end))
((re-search-forward "/[/*]" end t)
(setq pos (match-beginning 0)))
(t
(setq pos end)))))
(setq go-mode-mark-comment-end pos)))))
(defun go-mode-in-string (&optional pos)
"Return the string state at point POS. If point is
inside a string (including the delimiters), this
returns a pair (START . END) indicating the extents of the
comment or string."
(unless pos
(setq pos (point)))
(when (> pos go-mode-mark-string-end)
(go-mode-mark-string pos))
(get-text-property pos 'go-mode-string))
(defun go-mode-mark-string (end)
"Mark strings up to point END. Don't call this
directly; use `go-mode-in-string'."
(setq end (min end (point-max)))
(go-mode-parser
(save-match-data
(let ((pos
;; Back up to the last known state.
(let ((last-cs
(and (> go-mode-mark-string-end 1)
(get-text-property (1- go-mode-mark-string-end)
'go-mode-string))))
(if last-cs
(car last-cs)
(max 1 (1- go-mode-mark-string-end))))))
(while (< pos end)
(goto-char pos)
(let ((cs-end ; end of the text property
(cond
((looking-at "\"")
(goto-char (1+ pos))
(if (looking-at "[^\"\n\\\\]*\\(\\\\.[^\"\n\\\\]*\\)*\"")
(match-end 0)
(end-of-line)
(point)))
((looking-at "'")
(goto-char (1+ pos))
(if (looking-at "[^'\n\\\\]*\\(\\\\.[^'\n\\\\]*\\)*'")
(match-end 0)
(end-of-line)
(point)))
((looking-at "`")
(goto-char (1+ pos))
(while (if (search-forward "`" end t)
(if (eq (char-after) ?`)
(goto-char (1+ (point))))
(goto-char end)
nil))
(point)))))
(cond
(cs-end
(put-text-property pos cs-end 'go-mode-string (cons pos cs-end))
(setq pos cs-end))
((re-search-forward "[\"'`]" end t)
(setq pos (match-beginning 0)))
(t
(setq pos end)))))
(setq go-mode-mark-string-end pos)))))
(defun go-mode-font-lock-cs (limit comment)
"Helper function for highlighting comment/strings. If COMMENT is t,
set match data to the next comment after point, and advance point
after it. If COMMENT is nil, use the next string. Returns nil
if no further tokens of the type exist."
;; Ensures that `next-single-property-change' below will work properly.
(go-mode-cs limit)
(let (cs next (result 'scan))
(while (eq result 'scan)
(if (or (>= (point) limit) (eobp))
(setq result nil)
(setq cs (go-mode-cs))
(if cs
(if (eq (= (char-after (car cs)) ?/) comment)
;; If inside the expected comment/string, highlight it.
(progn
;; If the match includes a "\n", we have a
;; multi-line construct. Mark it as such.
(goto-char (car cs))
(when (search-forward "\n" (cdr cs) t)
(put-text-property
(car cs) (cdr cs) 'font-lock-multline t))
(set-match-data (list (car cs) (cdr cs) (current-buffer)))
(goto-char (cdr cs))
(setq result t))
;; Wrong type. Look for next comment/string after this one.
(goto-char (cdr cs)))
;; Not inside comment/string. Search for next comment/string.
(setq next (next-single-property-change
(point) 'go-mode-cs nil limit))
(if (and next (< next limit))
(goto-char next)
(setq result nil)))))
result))
(defun go-mode-font-lock-cs-string (limit)
"Font-lock iterator for strings."
(go-mode-font-lock-cs limit nil))
(defun go-mode-font-lock-cs-comment (limit)
"Font-lock iterator for comments."
(go-mode-font-lock-cs limit t))
(defsubst go-mode-nesting (&optional pos)
"Return the nesting at point POS. The nesting is a list
of (START . END) pairs for all braces, parens, and brackets
surrounding POS, starting at the inner-most nesting. START is
the location of the open character. END is the location of the
close character or nil if the nesting scanner has not yet
encountered the close character."
(unless pos
(setq pos (point)))
(if (= pos 1)
'()
(when (> pos go-mode-mark-nesting-end)
(go-mode-mark-nesting pos))
(get-text-property (- pos 1) 'go-mode-nesting)))
(defun go-mode-mark-nesting (pos)
"Mark nesting up to point END. Don't call this directly; use
`go-mode-nesting'."
(go-mode-cs pos)
(go-mode-parser
;; Mark depth
(goto-char go-mode-mark-nesting-end)
(let ((nesting (go-mode-nesting))
(last (point)))
(while (< last pos)
;; Find the next depth-changing character
(skip-chars-forward "^(){}[]" pos)
;; Mark everything up to this character with the current
;; nesting
(put-text-property last (point) 'go-mode-nesting nesting)
(when nil
(let ((depth (length nesting)))
(put-text-property last (point) 'face
`((:background
,(format "gray%d" (* depth 10)))))))
(setq last (point))
;; Update nesting
(unless (eobp)
(let ((ch (unless (go-mode-cs) (char-after))))
(forward-char 1)
(case ch
((?\( ?\{ ?\[)
(setq nesting (cons (cons (- (point) 1) nil)
nesting)))
((?\) ?\} ?\])
(when nesting
(setcdr (car nesting) (- (point) 1))
(setq nesting (cdr nesting))))))))
;; Update state
(setq go-mode-mark-nesting-end last))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Indentation
;;
(defvar go-mode-non-terminating-keywords-regexp
(let* ((kws go-mode-keywords)
(kws (remove "break" kws))
(kws (remove "continue" kws))
(kws (remove "fallthrough" kws))
(kws (remove "return" kws)))
(regexp-opt kws 'words))
"Regular expression matching all Go keywords that *do not*
implicitly terminate a statement.")
(defun go-mode-semicolon-p ()
"True iff point immediately follows either an explicit or
implicit semicolon. Point should immediately follow the last
token on the line."
;; #Semicolons
(case (char-before)
((?\;) t)
;; String literal
((?' ?\" ?`) t)
;; One of the operators and delimiters ++, --, ), ], or }
((?+) (eq (char-before (1- (point))) ?+))
((?-) (eq (char-before (1- (point))) ?-))
((?\) ?\] ?\}) t)
;; An identifier or one of the keywords break, continue,
;; fallthrough, or return or a numeric literal
(otherwise
(save-excursion
(when (/= (skip-chars-backward "[:word:]_") 0)
(not (looking-at go-mode-non-terminating-keywords-regexp)))))))
(defun go-mode-whitespace-p (char)
"Is char whitespace in the syntax table for go."
(eq 32 (char-syntax char)))
(defun go-mode-backward-skip-comments ()
"Skip backward over comments and whitespace."
;; only proceed if point is in a comment or white space
(if (or (go-mode-in-comment)
(go-mode-whitespace-p (char-after (point))))
(let ((loop-guard t))
(while (and
loop-guard
(not (bobp)))
(cond ((go-mode-whitespace-p (char-after (point)))
;; moves point back over any whitespace
(re-search-backward "[^[:space:]]"))
((go-mode-in-comment)
;; move point to char preceeding current comment
(goto-char (1- (car (go-mode-in-comment)))))
;; not in a comment or whitespace? we must be done.
(t (setq loop-guard nil)
(forward-char 1)))))))
(defun go-mode-indentation ()
"Compute the ideal indentation level of the current line.
To the first order, this is the brace depth of the current line,
plus parens that follow certain keywords. case, default, and
labels are outdented one level, and continuation lines are
indented one level."
(save-excursion
(back-to-indentation)
(let ((cs (go-mode-cs)))
;; Treat comments and strings differently only if the beginning
;; of the line is contained within them
(when (and cs (= (point) (car cs)))
(setq cs nil))
;; What type of context am I in?
(cond
((and cs (save-excursion
(goto-char (car cs))
(looking-at "\\s\"")))
;; Inside a multi-line string. Don't mess with indentation.
nil)
(cs
;; Inside a general comment
(goto-char (car cs))
(forward-char 1)
(current-column))
(t
;; Not in a multi-line string or comment
(let ((indent 0)
(inside-indenting-paren nil))
;; Count every enclosing brace, plus parens that follow
;; import, const, var, or type and indent according to
;; depth. This simple rule does quite well, but also has a
;; very large extent. It would be better if we could mimic
;; some nearby indentation.
(save-excursion
(skip-chars-forward "})")
(let ((first t))
(dolist (nest (go-mode-nesting))
(case (char-after (car nest))
((?\{)
(incf indent tab-width))
((?\()
(goto-char (car nest))
(go-mode-backward-skip-comments)
(backward-char)
;; Really just want the token before
(when (looking-back "\\<import\\|const\\|var\\|type\\|package"
(max (- (point) 7) (point-min)))
(incf indent tab-width)
(when first
(setq inside-indenting-paren t)))))
(setq first nil))))
;; case, default, and labels are outdented 1 level
(when (looking-at "\\<case\\>\\|\\<default\\>\\|\\w+\\s *:\\(\\S.\\|$\\)")
(decf indent tab-width))
(when (looking-at "\\w+\\s *:.+,\\s *$")
(incf indent tab-width))
;; Continuation lines are indented 1 level
(beginning-of-line) ; back up to end of previous line
(backward-char)
(go-mode-backward-skip-comments) ; back up past any comments
(when (case (char-before)
((nil ?\{ ?:)
;; At the beginning of a block or the statement
;; following a label.
nil)
((?\()
;; Usually a continuation line in an expression,
;; unless this paren is part of a factored
;; declaration.
(not inside-indenting-paren))
((?,)
;; Could be inside a literal. We're a little
;; conservative here and consider any comma within
;; curly braces (as opposed to parens) to be a
;; literal separator. This will fail to recognize
;; line-breaks in parallel assignments as
;; continuation lines.
(let ((depth (go-mode-nesting)))
(and depth
(not (eq (char-after (caar depth)) ?\{)))))
(t
;; We're in the middle of a block. Did the
;; previous line end with an implicit or explicit
;; semicolon?
(not (go-mode-semicolon-p))))
(incf indent tab-width))
(max indent 0)))))))
(defun go-mode-indent-line ()
"Indent the current line according to `go-mode-indentation'."
(interactive)
;; turn off case folding to distinguish keywords from identifiers
;; e.g. "default" is a keyword; "Default" can be a variable name.
(let ((case-fold-search nil))
(let ((col (go-mode-indentation)))
(when col
(let ((offset (- (current-column) (current-indentation))))
(indent-line-to col)
(when (> offset 0)
(forward-char offset)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Go mode
;;
;;;###autoload
(define-derived-mode go-mode nil "Go"
"Major mode for editing Go source text.
This provides basic syntax highlighting for keywords, built-ins,
functions, and some types. It also provides indentation that is
\(almost) identical to gofmt."
;; Font lock
(set (make-local-variable 'font-lock-defaults)
'(go-mode-font-lock-keywords nil nil nil nil))
;; Remove stale text properties
(save-restriction
(widen)
(remove-text-properties 1 (point-max)
'(go-mode-cs nil go-mode-nesting nil)))
;; Reset the syntax mark caches
(setq go-mode-mark-cs-end 1
go-mode-mark-nesting-end 1)
(add-hook 'before-change-functions #'go-mode-mark-clear-cache nil t)
;; Indentation
(set (make-local-variable 'indent-line-function)
#'go-mode-indent-line)
(add-hook 'after-change-functions #'go-mode-delayed-electric-hook nil t)
;; Comments
(set (make-local-variable 'comment-start) "// ")
(set (make-local-variable 'comment-end) "")
;; Go style
(setq indent-tabs-mode t))
;;;###autoload
(add-to-list 'auto-mode-alist (cons "\\.go$" #'go-mode))
(defun go-mode-reload ()
"Reload go-mode.el and put the current buffer into Go mode.
Useful for development work."
(interactive)
(unload-feature 'go-mode)
(require 'go-mode)
(go-mode))
;;;###autoload
(defun gofmt ()
"Pipe the current buffer through the external tool `gofmt`.
Replace the current buffer on success; display errors on failure."
(interactive)
(let ((currconf (current-window-configuration)))
(let ((srcbuf (current-buffer)))
(with-temp-buffer
(let ((outbuf (current-buffer))
(errbuf (get-buffer-create "*Gofmt Errors*"))
(coding-system-for-read 'utf-8) ;; use utf-8 with subprocesses
(coding-system-for-write 'utf-8))
(with-current-buffer errbuf (erase-buffer))
(with-current-buffer srcbuf
(save-restriction
(let (deactivate-mark)
(widen)
(if (= 0 (shell-command-on-region (point-min) (point-max) "gofmt"
outbuf nil errbuf))
;; restore window config
;; gofmt succeeded: replace the current buffer with outbuf,
;; restore the mark and point, and discard errbuf.
(let ((old-mark (mark t)) (old-point (point)))
(set-window-configuration currconf)
(erase-buffer)
(insert-buffer-substring outbuf)
(goto-char (min old-point (point-max)))
(if old-mark (push-mark (min old-mark (point-max)) t))
(kill-buffer errbuf))
;; gofmt failed: display the errors
(display-buffer errbuf)))))
;; Collapse any window opened on outbuf if shell-command-on-region
;; displayed it.
(delete-windows-on outbuf))))))
;;;###autoload
(defun gofmt-before-save ()
"Add this to .emacs to run gofmt on the current buffer when saving:
(add-hook 'before-save-hook #'gofmt-before-save)"
(interactive)
(when (eq major-mode 'go-mode) (gofmt)))
(defun godoc-read-query ()
"Read a godoc query from the minibuffer."
;; Compute the default query as the symbol under the cursor.
;; TODO: This does the wrong thing for e.g. multipart.NewReader (it only grabs
;; half) but I see no way to disambiguate that from e.g. foobar.SomeMethod.
(let* ((bounds (bounds-of-thing-at-point 'symbol))
(symbol (if bounds
(buffer-substring-no-properties (car bounds)
(cdr bounds)))))
(read-string (if symbol
(format "godoc (default %s): " symbol)
"godoc: ")
nil nil symbol)))
(defun godoc-get-buffer (query)
"Get an empty buffer for a godoc query."
(let* ((buffer-name (concat "*godoc " query "*"))
(buffer (get-buffer buffer-name)))
;; Kill the existing buffer if it already exists.
(when buffer (kill-buffer buffer))
(get-buffer-create buffer-name)))
(defun godoc-buffer-sentinel (proc event)
"Sentinel function run when godoc command completes."
(with-current-buffer (process-buffer proc)
(cond ((string= event "finished\n") ;; Successful exit.
(goto-char (point-min))
(display-buffer (current-buffer) 'not-this-window))
((not (= (process-exit-status proc) 0)) ;; Error exit.
(let ((output (buffer-string)))
(kill-buffer (current-buffer))
(message (concat "godoc: " output)))))))
;;;###autoload
(defun godoc (query)
"Show go documentation for a query, much like M-x man."
(interactive (list (godoc-read-query)))
(unless (string= query "")
(set-process-sentinel
(start-process-shell-command "godoc" (godoc-get-buffer query)
(concat "godoc " query))
'godoc-buffer-sentinel)
nil))
(provide 'go-mode)

View file

@ -10,10 +10,10 @@
;; There are many like it, but this one is mine.
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(blink-matching-paren-dont-ignore-comments t)
'(c-echo-syntactic-information-p t)
'(c-indent-level 4)
@ -28,6 +28,7 @@
'(font-lock-support-mode (quote jit-lock-mode))
'(global-auto-revert-mode t)
'(global-font-lock-mode t nil (font-lock))
'(ido-enable-flex-matching t)
'(ido-mode (quote both) nil (ido))
'(indent-tabs-mode nil)
'(inhibit-startup-screen t)
@ -38,6 +39,7 @@
'(mouse-buffer-menu-mode-mult 0)
'(org-hide-leading-stars t)
'(org-odd-levels-only t)
'(package-archives (quote (("gnu" . "http://elpa.gnu.org/packages/") ("marmalade" . "http://marmalade-repo.org/packages/"))))
'(rmail-mail-new-frame t)
'(scroll-conservatively 1)
'(scroll-step 1)
@ -71,20 +73,6 @@
;; Also GO mode
(add-to-list 'load-path "c:/go/misc/emacs" t)
;; =================================================================
;; Package installer configuration
;; =================================================================
;;; This was installed by package-install.el.
;;; This provides support for the package system and
;;; interfacing with ELPA, the package archive.
;;; Move this code earlier if you want to reference
;;; packages in your .emacs.
(when
(load
(expand-file-name "~/.emacs.d/elpa/package.el"))
(package-initialize))
;; =================================================================
;; EMACS general look and feel
;; =================================================================
@ -493,7 +481,7 @@
;; Note that apparently go-mode is too special for the standard
;; autoload/add-to-list stuff. Good for it!
;; =================================================================
(require 'go-mode-load)
;;(require 'go-mode-load)
;; =================================================================
;; LUA Mode
@ -517,8 +505,8 @@
;; have been thinking of something.
;; =================================================================
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)

View file

@ -2,7 +2,7 @@
name = John Doty
email = jddoty@gmail.com
[core]
editor = c:/emacs/bin/emacs.exe
editor = emacs
[pretty]
doty = * %C(bold green)%h%Creset -%C(bold white)%d%Creset %s %C(bold)(%cr)%Creset <%aN>%Creset
[format]

113
.gitignore vendored
View file

@ -1,7 +1,108 @@
# Because this is in my home directory, it's best to just ignore all files for the moment.
*
.aptitude/
.bash_history
.bash_logout
.bitcoin/
Bitlocker/
Calibre Library/
CardMinder/
.cache/
.config/fish/fish_history
.config/fish/fishd*
.config/fish/generated_completions
Diablo III/
DnD - 3.5/
DnD - 4.0/
DnD - Mesh/
DnD/
Doty Family/
Downloads/
.DS_Store
.gem/
.gimp-2.6/
.histfile
.ido.last
.landscape/
.lesshst
.links2/
.mysql_history
.sabnzbd/
.sickbeard/
.ssh/
.subversion/
.thumbnails/
.VirtualBox/
.w3m/
.zcompdump
Backup/
bifrost
bin/
go-ext/
newznab/
sabnzbd/
src/
test/
# These are the things we're tracking.
!.emacs.d
!.gitignore
!WindowsPowershell
*~
*.acdb
*.elc
*.docx
*.htm
*.exe
*.txt
*.rdp
*.xbel
*.xls
*.xlsm
*.xlsx
*.zip
_viminfo
Database1.accdb
Dungeon Tiles.vss
Endless Space/
Expression/
Fax/
Fiddler2/
IISExpress/
Inform/
John's Quicken Data.QDF-backup
KentuckyRouteZero/
LINQPad Queries/
Memoir Class Manual.pdf
My Games/
My Kindle Content/
My Received Files/
My Shapes/
My Sharing Folders.lnk
New folder/
OneNote Notebooks/
Playing.vsd
Protege-1996-1.pdf
Purchased/
Quicken/
SampleExplorer.Settings.xml
Saved Games/
ScanSnap/
Seesmic/
Shared/
Shiner/
SimCity 4/
Tales of the City/
Taxes/
Telltale Games/
Thumbs.db
Tokens.vsd
VirtualBox VMs/
Visual Studio 11/
Visual Studio 2005/
Visual Studio 2008/
Visual Studio 2010/
Visual Studio 2012/
WorldWorks/
backupcert.pfx
ddi/
desktop.ini
lshort.pdf
notes
rallymaker/

22
.profile Normal file
View file

@ -0,0 +1,22 @@
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.
# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi

34
.tmux.conf Normal file
View file

@ -0,0 +1,34 @@
# C-b is not acceptable -- Vim uses it
set-option -g prefix C-b
bind-key C-b last-window
# Start numbering at 1
set -g base-index 1
# Allows for faster key repetition
set -s escape-time 0
# Set status bar
set -g status-bg black
set -g status-fg white
set -g status-left ""
set -g status-right "#[fg=green]#H"
# Rather than constraining window size to the maximum size of any client
# connected to the *session*, constrain window size to the maximum size of any
# client connected to *that window*. Much more reasonable.
setw -g aggressive-resize on
# Allows us to use C-a a <command> to send commands to a TMUX session inside
# another TMUX session
bind-key a send-prefix
# Activity monitoring
#setw -g monitor-activity on
#set -g visual-activity on
# Example of using a shell command in the status line
#set -g status-right "#[fg=yellow]#(uptime | cut -d ',' -f 2-)"
# Highlight active window
set-window-option -g window-status-current-bg red

93
.vimrc Normal file
View file

@ -0,0 +1,93 @@
" This is my .vimrc. Good times!
" It was shamelessly stolen from the sample .vimrc, because I have yet to have
" any good taste.
" When started as "evim", evim.vim will already have done these settings.
if v:progname =~? "evim"
finish
endif
" Use Vim settings, rather than Vi settings (much better!).
" This must be first, because it changes other options as a side effect.
set nocompatible
" allow backspacing over everything in insert mode
set backspace=indent,eol,start
if has("vms")
set nobackup " do not keep a backup file, use versions instead
else
set backup " keep a backup file
endif
set history=50 " keep 50 lines of command line history
set ruler " show the cursor position all the time
set showcmd " display incomplete commands
set incsearch " do incremental searching
" For Win32 GUI: remove 't' flag from 'guioptions': no tearoff menu entries
" let &guioptions = substitute(&guioptions, "t", "", "g")
" Don't use Ex mode, use Q for formatting
map Q gq
" CTRL-U in insert mode deletes a lot. Use CTRL-G u to first break undo,
" so that you can undo CTRL-U after inserting a line break.
inoremap <C-U> <C-G>u<C-U>
" In many terminal emulators the mouse works just fine, thus enable it.
if has('mouse')
set mouse=a
endif
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
" Only do this part when compiled with support for autocommands.
if has("autocmd")
" Support for go
set rtp+=$GOROOT/misc/vim
" Enable file type detection.
" Use the default filetype settings, so that mail gets 'tw' set to 72,
" 'cindent' is on in C files, etc.
" Also load indent files, to automatically do language-dependent indenting.
filetype plugin indent on
" Put these in an autocmd group, so that we can delete them easily.
augroup vimrcEx
au!
" For all text files set 'textwidth' to 78 characters.
autocmd FileType text setlocal textwidth=78
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
" Also don't do it when the mark is in the first line, that is the default
" position when opening a file.
autocmd BufReadPost *
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ exe "normal! g`\"" |
\ endif
augroup END
else
set autoindent " always set autoindenting on
endif " has("autocmd")
" Convenient command to see the difference between the current buffer and the
" file it was loaded from, thus the changes you made.
" Only define it when not defined already.
if !exists(":DiffOrig")
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
\ | wincmd p | diffthis
endif

37
.zshrc Normal file
View file

@ -0,0 +1,37 @@
# Lines configured by zsh-newuser-install
HISTFILE=~/.histfile
HISTSIZE=1000
SAVEHIST=2000
setopt autocd
setopt histappend
unsetopt beep
bindkey -e
# End of lines configured by zsh-newuser-install
# The following lines were added by compinstall
zstyle :compinstall filename '/home/doty/.zshrc'
autoload -Uz compinit
compinit
# End of lines added by compinstall
PS1='%n@%m:%~$ '
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
if [ -f ~/.zsh_aliases ]; then
. ~/.zsh_aliases
fi

View file

@ -49,20 +49,30 @@ function prompt
{
$ok = $?
if (!$global:SolarizedColors)
if ($Host.Name -eq "ConsoleHost")
{
Set-SolarizedColors -Dark
$global:SolarizedColors = $true
}
if (!$global:SolarizedColors)
{
Set-SolarizedColors -Dark
$global:SolarizedColors = $true
}
# Our "theme", as it were. Note that we assume the use of the
# solarized colors.
#
$cdelim = [ConsoleColor]::DarkCyan
$chost = [ConsoleColor]::DarkGreen
$cloc = $csym = [ConsoleColor]::DarkCyan
if (-not $ok) { $csym = [ConsoleColor]::DarkRed; }
# Our "theme", as it were. Note that we assume the use of the
# solarized colors.
#
$cdelim = [ConsoleColor]::DarkCyan
$chost = [ConsoleColor]::DarkGreen
$cloc = $csym = [ConsoleColor]::DarkCyan
if (-not $ok) { $csym = [ConsoleColor]::DarkRed; }
}
else
{
$cdelim = [ConsoleColor]::Gray
$chost = [ConsoleColor]::Green
$cloc = $csym = [ConsoleColor]::Gray
if (-not $ok) { $csym = [ConsoleColor]::Red; }
}
write-host "$([char]0x0A7) " -n -f $csym
write-host ([net.dns]::GetHostName()) -n -f $chost
write-host ' {' -n -f $cdelim
@ -195,3 +205,6 @@ function Wrap-Text ($txt)
$t
}
function ConvertFrom-Base64UTF8($base64) {
return [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($base64))
}

View file

@ -2657,7 +2657,7 @@ This fn does these things:
csharp-advise-revert-buffer
activate compile)
(let ((is-flymake-enabled
(and (fboundp 'flymake-mode)
(and (boundp 'flymake-mode)
flymake-mode)))
;; disable
(if is-flymake-enabled

1
vimfiles/.VimballRecord Normal file
View file

@ -0,0 +1 @@
command-t-1.4.vba: call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/controller.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/extconf.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/finder/buffer_finder.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/finder/file_finder.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/finder/jump_finder.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/finder/tag_finder.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/finder.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/match_window.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/prompt.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/scanner/buffer_scanner.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/scanner/file_scanner.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/scanner/jump_scanner.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/scanner/tag_scanner.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/scanner.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/settings.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/stub.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/vim/path_utilities.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/vim/screen.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/vim/window.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/vim.rb')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/ext.c')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/match.c')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/matcher.c')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/ext.h')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/match.h')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/matcher.h')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/ruby_compat.h')|call delete('C:\Users\John\Documents\vimfiles/ruby/command-t/depend')|call delete('C:\Users\John\Documents\vimfiles/doc/command-t.txt')|call delete('C:\Users\John\Documents\vimfiles/plugin/command-t.vim')

3
vimfiles/.netrwhist Normal file
View file

@ -0,0 +1,3 @@
let g:netrw_dirhistmax =10
let g:netrw_dirhist_cnt =1
let g:netrw_dirhist_1='C:\src\Rama\RamaGo'

51
vimfiles/doc/tags Normal file
View file

@ -0,0 +1,51 @@
:CommandT command-t.txt /*:CommandT*
:CommandTBuffer command-t.txt /*:CommandTBuffer*
:CommandTFlush command-t.txt /*:CommandTFlush*
:CommandTJumps command-t.txt /*:CommandTJumps*
:CommandTTag command-t.txt /*:CommandTTag*
command-t command-t.txt /*command-t*
command-t-authors command-t.txt /*command-t-authors*
command-t-commands command-t.txt /*command-t-commands*
command-t-contents command-t.txt /*command-t-contents*
command-t-development command-t.txt /*command-t-development*
command-t-donations command-t.txt /*command-t-donations*
command-t-history command-t.txt /*command-t-history*
command-t-installation command-t.txt /*command-t-installation*
command-t-intro command-t.txt /*command-t-intro*
command-t-license command-t.txt /*command-t-license*
command-t-mappings command-t.txt /*command-t-mappings*
command-t-options command-t.txt /*command-t-options*
command-t-pathogen command-t.txt /*command-t-pathogen*
command-t-requirements command-t.txt /*command-t-requirements*
command-t-trouble-shooting command-t.txt /*command-t-trouble-shooting*
command-t-usage command-t.txt /*command-t-usage*
command-t-website command-t.txt /*command-t-website*
command-t-wildignore command-t.txt /*command-t-wildignore*
command-t.txt command-t.txt /*command-t.txt*
g:CommandTAcceptSelectionMap command-t.txt /*g:CommandTAcceptSelectionMap*
g:CommandTAcceptSelectionSplitMap command-t.txt /*g:CommandTAcceptSelectionSplitMap*
g:CommandTAcceptSelectionTabMap command-t.txt /*g:CommandTAcceptSelectionTabMap*
g:CommandTAcceptSelectionVSplitMap command-t.txt /*g:CommandTAcceptSelectionVSplitMap*
g:CommandTAlwaysShowDotFiles command-t.txt /*g:CommandTAlwaysShowDotFiles*
g:CommandTBackspaceMap command-t.txt /*g:CommandTBackspaceMap*
g:CommandTCancelMap command-t.txt /*g:CommandTCancelMap*
g:CommandTClearMap command-t.txt /*g:CommandTClearMap*
g:CommandTCursorEndMap command-t.txt /*g:CommandTCursorEndMap*
g:CommandTCursorLeftMap command-t.txt /*g:CommandTCursorLeftMap*
g:CommandTCursorRightMap command-t.txt /*g:CommandTCursorRightMap*
g:CommandTCursorStartMap command-t.txt /*g:CommandTCursorStartMap*
g:CommandTDeleteMap command-t.txt /*g:CommandTDeleteMap*
g:CommandTMatchWindowAtTop command-t.txt /*g:CommandTMatchWindowAtTop*
g:CommandTMatchWindowReverse command-t.txt /*g:CommandTMatchWindowReverse*
g:CommandTMaxCachedDirectories command-t.txt /*g:CommandTMaxCachedDirectories*
g:CommandTMaxDepth command-t.txt /*g:CommandTMaxDepth*
g:CommandTMaxFiles command-t.txt /*g:CommandTMaxFiles*
g:CommandTMaxHeight command-t.txt /*g:CommandTMaxHeight*
g:CommandTMinHeight command-t.txt /*g:CommandTMinHeight*
g:CommandTNeverShowDotFiles command-t.txt /*g:CommandTNeverShowDotFiles*
g:CommandTRefreshMap command-t.txt /*g:CommandTRefreshMap*
g:CommandTScanDotDirectories command-t.txt /*g:CommandTScanDotDirectories*
g:CommandTSelectNextMap command-t.txt /*g:CommandTSelectNextMap*
g:CommandTSelectPrevMap command-t.txt /*g:CommandTSelectPrevMap*
g:CommandTTagIncludeFilenames command-t.txt /*g:CommandTTagIncludeFilenames*
g:CommandTToggleFocusMap command-t.txt /*g:CommandTToggleFocusMap*

View file

@ -0,0 +1,186 @@
" command-t.vim
" Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
"
" Redistribution and use in source and binary forms, with or without
" modification, are permitted provided that the following conditions are met:
"
" 1. Redistributions of source code must retain the above copyright notice,
" this list of conditions and the following disclaimer.
" 2. Redistributions in binary form must reproduce the above copyright notice,
" this list of conditions and the following disclaimer in the documentation
" and/or other materials provided with the distribution.
"
" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
" POSSIBILITY OF SUCH DAMAGE.
if exists("g:command_t_loaded") || &cp
finish
endif
let g:command_t_loaded = 1
command CommandTBuffer call <SID>CommandTShowBufferFinder()
command CommandTJump call <SID>CommandTShowJumpFinder()
command CommandTTag call <SID>CommandTShowTagFinder()
command -nargs=? -complete=dir CommandT call <SID>CommandTShowFileFinder(<q-args>)
command CommandTFlush call <SID>CommandTFlush()
if !hasmapto(':CommandT<CR>')
silent! nnoremap <unique> <silent> <Leader>t :CommandT<CR>
endif
if !hasmapto(':CommandTBuffer<CR>')
silent! nnoremap <unique> <silent> <Leader>b :CommandTBuffer<CR>
endif
function s:CommandTRubyWarning()
echohl WarningMsg
echo "command-t.vim requires Vim to be compiled with Ruby support"
echo "For more information type: :help command-t"
echohl none
endfunction
function s:CommandTShowBufferFinder()
if has('ruby')
ruby $command_t.show_buffer_finder
else
call s:CommandTRubyWarning()
endif
endfunction
function s:CommandTShowFileFinder(arg)
if has('ruby')
ruby $command_t.show_file_finder
else
call s:CommandTRubyWarning()
endif
endfunction
function s:CommandTShowJumpFinder()
if has('ruby')
ruby $command_t.show_jump_finder
else
call s:CommandTRubyWarning()
endif
endfunction
function s:CommandTShowTagFinder()
if has('ruby')
ruby $command_t.show_tag_finder
else
call s:CommandTRubyWarning()
endif
endfunction
function s:CommandTFlush()
if has('ruby')
ruby $command_t.flush
else
call s:CommandTRubyWarning()
endif
endfunction
if !has('ruby')
finish
endif
function CommandTHandleKey(arg)
ruby $command_t.handle_key
endfunction
function CommandTBackspace()
ruby $command_t.backspace
endfunction
function CommandTDelete()
ruby $command_t.delete
endfunction
function CommandTAcceptSelection()
ruby $command_t.accept_selection
endfunction
function CommandTAcceptSelectionTab()
ruby $command_t.accept_selection :command => 'tabe'
endfunction
function CommandTAcceptSelectionSplit()
ruby $command_t.accept_selection :command => 'sp'
endfunction
function CommandTAcceptSelectionVSplit()
ruby $command_t.accept_selection :command => 'vs'
endfunction
function CommandTRefresh()
ruby $command_t.refresh
endfunction
function CommandTToggleFocus()
ruby $command_t.toggle_focus
endfunction
function CommandTCancel()
ruby $command_t.cancel
endfunction
function CommandTSelectNext()
ruby $command_t.select_next
endfunction
function CommandTSelectPrev()
ruby $command_t.select_prev
endfunction
function CommandTClear()
ruby $command_t.clear
endfunction
function CommandTCursorLeft()
ruby $command_t.cursor_left
endfunction
function CommandTCursorRight()
ruby $command_t.cursor_right
endfunction
function CommandTCursorEnd()
ruby $command_t.cursor_end
endfunction
function CommandTCursorStart()
ruby $command_t.cursor_start
endfunction
ruby << EOF
# require Ruby files
begin
# prepare controller
require 'command-t/vim'
require 'command-t/controller'
$command_t = CommandT::Controller.new
rescue LoadError
load_path_modified = false
::VIM::evaluate('&runtimepath').to_s.split(',').each do |path|
lib = "#{path}/ruby"
if !$LOAD_PATH.include?(lib) and File.exist?(lib)
$LOAD_PATH << lib
load_path_modified = true
end
end
retry if load_path_modified
# could get here if C extension was not compiled, or was compiled
# for the wrong architecture or Ruby version
require 'command-t/stub'
$command_t = CommandT::Stub.new
end
EOF

View file

@ -0,0 +1,357 @@
# Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/finder/buffer_finder'
require 'command-t/finder/jump_finder'
require 'command-t/finder/file_finder'
require 'command-t/finder/tag_finder'
require 'command-t/match_window'
require 'command-t/prompt'
require 'command-t/vim/path_utilities'
module CommandT
class Controller
include VIM::PathUtilities
def initialize
@prompt = Prompt.new
end
def show_buffer_finder
@path = VIM::pwd
@active_finder = buffer_finder
show
end
def show_jump_finder
@path = VIM::pwd
@active_finder = jump_finder
show
end
def show_tag_finder
@path = VIM::pwd
@active_finder = tag_finder
show
end
def show_file_finder
# optional parameter will be desired starting directory, or ""
@path = File.expand_path(::VIM::evaluate('a:arg'), VIM::pwd)
@active_finder = file_finder
file_finder.path = @path
show
rescue Errno::ENOENT
# probably a problem with the optional parameter
@match_window.print_no_such_file_or_directory
end
def hide
@match_window.close
if VIM::Window.select @initial_window
if @initial_buffer.number == 0
# upstream bug: buffer number misreported as 0
# see: https://wincent.com/issues/1617
::VIM::command "silent b #{@initial_buffer.name}"
else
::VIM::command "silent b #{@initial_buffer.number}"
end
end
end
def refresh
return unless @active_finder && @active_finder.respond_to?(:flush)
@active_finder.flush
list_matches
end
def flush
@max_height = nil
@min_height = nil
@file_finder = nil
@tag_finder = nil
end
def handle_key
key = ::VIM::evaluate('a:arg').to_i.chr
if @focus == @prompt
@prompt.add! key
list_matches
else
@match_window.find key
end
end
def backspace
if @focus == @prompt
@prompt.backspace!
list_matches
end
end
def delete
if @focus == @prompt
@prompt.delete!
list_matches
end
end
def accept_selection options = {}
selection = @match_window.selection
hide
open_selection(selection, options) unless selection.nil?
end
def toggle_focus
@focus.unfocus # old focus
@focus = @focus == @prompt ? @match_window : @prompt
@focus.focus # new focus
end
def cancel
hide
end
def select_next
@match_window.select_next
end
def select_prev
@match_window.select_prev
end
def clear
@prompt.clear!
list_matches
end
def cursor_left
@prompt.cursor_left if @focus == @prompt
end
def cursor_right
@prompt.cursor_right if @focus == @prompt
end
def cursor_end
@prompt.cursor_end if @focus == @prompt
end
def cursor_start
@prompt.cursor_start if @focus == @prompt
end
def leave
@match_window.leave
end
def unload
@match_window.unload
end
private
def show
@initial_window = $curwin
@initial_buffer = $curbuf
@match_window = MatchWindow.new \
:prompt => @prompt,
:match_window_at_top => get_bool('g:CommandTMatchWindowAtTop'),
:match_window_reverse => get_bool('g:CommandTMatchWindowReverse'),
:min_height => min_height
@focus = @prompt
@prompt.focus
register_for_key_presses
clear # clears prompt and lists matches
end
def max_height
@max_height ||= get_number('g:CommandTMaxHeight') || 0
end
def min_height
@min_height ||= begin
min_height = get_number('g:CommandTMinHeight') || 0
min_height = max_height if max_height != 0 && min_height > max_height
min_height
end
end
def get_number name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_i : nil
end
def get_bool name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_i != 0 : nil
end
def get_string name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_s : nil
end
# expect a string or a list of strings
def get_list_or_string name
return nil unless VIM::exists?(name)
list_or_string = ::VIM::evaluate("#{name}")
if list_or_string.kind_of?(Array)
list_or_string.map { |item| item.to_s }
else
list_or_string.to_s
end
end
# Backslash-escape space, \, |, %, #, "
def sanitize_path_string str
# for details on escaping command-line mode arguments see: :h :
# (that is, help on ":") in the Vim documentation.
str.gsub(/[ \\|%#"]/, '\\\\\0')
end
def default_open_command
if !get_bool('&hidden') && get_bool('&modified')
'sp'
else
'e'
end
end
def ensure_appropriate_window_selection
# normally we try to open the selection in the current window, but there
# is one exception:
#
# - we don't touch any "unlisted" buffer with buftype "nofile" (such as
# NERDTree or MiniBufExplorer); this is to avoid things like the "Not
# enough room" error which occurs when trying to open in a split in a
# shallow (potentially 1-line) buffer like MiniBufExplorer is current
#
# Other "unlisted" buffers, such as those with buftype "help" are treated
# normally.
initial = $curwin
while true do
break unless ::VIM::evaluate('&buflisted').to_i == 0 &&
::VIM::evaluate('&buftype').to_s == 'nofile'
::VIM::command 'wincmd w' # try next window
break if $curwin == initial # have already tried all
end
end
def open_selection selection, options = {}
command = options[:command] || default_open_command
selection = File.expand_path selection, @path
selection = relative_path_under_working_directory selection
selection = sanitize_path_string selection
ensure_appropriate_window_selection
@active_finder.open_selection command, selection, options
end
def map key, function, param = nil
::VIM::command "noremap <silent> <buffer> #{key} " \
":call CommandT#{function}(#{param})<CR>"
end
def term
@term ||= ::VIM::evaluate('&term')
end
def register_for_key_presses
# "normal" keys (interpreted literally)
numbers = ('0'..'9').to_a.join
lowercase = ('a'..'z').to_a.join
uppercase = lowercase.upcase
punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space
(numbers + lowercase + uppercase + punctuation).each_byte do |b|
map "<Char-#{b}>", 'HandleKey', b
end
# "special" keys (overridable by settings)
{
'AcceptSelection' => '<CR>',
'AcceptSelectionSplit' => ['<C-CR>', '<C-s>'],
'AcceptSelectionTab' => '<C-t>',
'AcceptSelectionVSplit' => '<C-v>',
'Backspace' => '<BS>',
'Cancel' => ['<C-c>', '<Esc>'],
'Clear' => '<C-u>',
'CursorEnd' => '<C-e>',
'CursorLeft' => ['<Left>', '<C-h>'],
'CursorRight' => ['<Right>', '<C-l>'],
'CursorStart' => '<C-a>',
'Delete' => '<Del>',
'Refresh' => '<C-f>',
'SelectNext' => ['<C-n>', '<C-j>', '<Down>'],
'SelectPrev' => ['<C-p>', '<C-k>', '<Up>'],
'ToggleFocus' => '<Tab>',
}.each do |key, value|
if override = get_list_or_string("g:CommandT#{key}Map")
Array(override).each do |mapping|
map mapping, key
end
else
Array(value).each do |mapping|
unless mapping == '<Esc>' && term =~ /\A(screen|xterm|vt100)/
map mapping, key
end
end
end
end
end
# Returns the desired maximum number of matches, based on available
# vertical space and the g:CommandTMaxHeight option.
def match_limit
limit = VIM::Screen.lines - 5
limit = 1 if limit < 0
limit = [limit, max_height].min if max_height > 0
limit
end
def list_matches
matches = @active_finder.sorted_matches_for @prompt.abbrev, :limit => match_limit
@match_window.matches = matches
end
def buffer_finder
@buffer_finder ||= CommandT::BufferFinder.new
end
def file_finder
@file_finder ||= CommandT::FileFinder.new nil,
:max_depth => get_number('g:CommandTMaxDepth'),
:max_files => get_number('g:CommandTMaxFiles'),
:max_caches => get_number('g:CommandTMaxCachedDirectories'),
:always_show_dot_files => get_bool('g:CommandTAlwaysShowDotFiles'),
:never_show_dot_files => get_bool('g:CommandTNeverShowDotFiles'),
:scan_dot_directories => get_bool('g:CommandTScanDotDirectories')
end
def jump_finder
@jump_finder ||= CommandT::JumpFinder.new
end
def tag_finder
@tag_finder ||= CommandT::TagFinder.new \
:include_filenames => get_bool('g:CommandTTagIncludeFilenames')
end
end # class Controller
end # module commandT

View file

@ -0,0 +1,24 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
CFLAGS += -std=c99 -Wall -Wextra -Wno-unused-parameter

View file

@ -0,0 +1,65 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "match.h"
#include "matcher.h"
VALUE mCommandT = 0; // module CommandT
VALUE cCommandTMatch = 0; // class CommandT::Match
VALUE cCommandTMatcher = 0; // class CommandT::Matcher
VALUE CommandT_option_from_hash(const char *option, VALUE hash)
{
if (NIL_P(hash))
return Qnil;
VALUE key = ID2SYM(rb_intern(option));
if (rb_funcall(hash, rb_intern("has_key?"), 1, key) == Qtrue)
return rb_hash_aref(hash, key);
else
return Qnil;
}
void Init_ext()
{
// module CommandT
mCommandT = rb_define_module("CommandT");
// class CommandT::Match
cCommandTMatch = rb_define_class_under(mCommandT, "Match", rb_cObject);
// methods
rb_define_method(cCommandTMatch, "initialize", CommandTMatch_initialize, -1);
rb_define_method(cCommandTMatch, "matches?", CommandTMatch_matches, 0);
rb_define_method(cCommandTMatch, "to_s", CommandTMatch_to_s, 0);
// attributes
rb_define_attr(cCommandTMatch, "score", Qtrue, Qfalse); // reader: true, writer: false
// class CommandT::Matcher
cCommandTMatcher = rb_define_class_under(mCommandT, "Matcher", rb_cObject);
// methods
rb_define_method(cCommandTMatcher, "initialize", CommandTMatcher_initialize, -1);
rb_define_method(cCommandTMatcher, "sorted_matches_for", CommandTMatcher_sorted_matches_for, 2);
rb_define_method(cCommandTMatcher, "matches_for", CommandTMatcher_matches_for, 1);
}

View file

@ -0,0 +1,36 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <ruby.h>
extern VALUE mCommandT; // module CommandT
extern VALUE cCommandTMatch; // class CommandT::Match
extern VALUE cCommandTMatcher; // class CommandT::Matcher
// Encapsulates common pattern of checking for an option in an optional
// options hash. The hash itself may be nil, but an exception will be
// raised if it is not nil and not a hash.
VALUE CommandT_option_from_hash(const char *option, VALUE hash);
// Debugging macro.
#define ruby_inspect(obj) rb_funcall(rb_mKernel, rb_intern("p"), 1, obj)

View file

@ -0,0 +1,34 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'mkmf'
def missing item
puts "couldn't find #{item} (required)"
exit 1
end
RbConfig::MAKEFILE_CONFIG['CC'] = ENV['CC'] if ENV['CC']
have_header('ruby.h') or missing('ruby.h')
create_makefile('ext')

View file

@ -0,0 +1,54 @@
# Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/ext' # CommandT::Matcher
module CommandT
# Encapsulates a Scanner instance (which builds up a list of available files
# in a directory) and a Matcher instance (which selects from that list based
# on a search string).
#
# Specialized subclasses use different kinds of scanners adapted for
# different kinds of search (files, buffers).
class Finder
include VIM::PathUtilities
def initialize path = Dir.pwd, options = {}
raise RuntimeError, 'Subclass responsibility'
end
# Options:
# :limit (integer): limit the number of returned matches
def sorted_matches_for str, options = {}
@matcher.sorted_matches_for str, options
end
def open_selection command, selection, options = {}
::VIM::command "silent #{command} #{selection}"
end
def path= path
@scanner.path = path
end
end # class Finder
end # CommandT

View file

@ -0,0 +1,35 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/ext' # CommandT::Matcher
require 'command-t/scanner/buffer_scanner'
require 'command-t/finder'
module CommandT
class BufferFinder < Finder
def initialize
@scanner = BufferScanner.new
@matcher = Matcher.new @scanner, :always_show_dot_files => true
end
end # class BufferFinder
end # CommandT

View file

@ -0,0 +1,39 @@
# Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/ext' # CommandT::Matcher
require 'command-t/finder'
require 'command-t/scanner/file_scanner'
module CommandT
class FileFinder < Finder
def initialize path = Dir.pwd, options = {}
@scanner = FileScanner.new path, options
@matcher = Matcher.new @scanner, options
end
def flush
@scanner.flush
end
end # class FileFinder
end # CommandT

View file

@ -0,0 +1,35 @@
# Copyright 2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/ext' # CommandT::Matcher
require 'command-t/scanner/jump_scanner'
require 'command-t/finder'
module CommandT
class JumpFinder < Finder
def initialize
@scanner = JumpScanner.new
@matcher = Matcher.new @scanner, :always_show_dot_files => true
end
end # class JumpFinder
end # module CommandT

View file

@ -0,0 +1,44 @@
# Copyright 2011-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/ext' # CommandT::Matcher
require 'command-t/scanner/tag_scanner'
require 'command-t/finder'
module CommandT
class TagFinder < Finder
def initialize options = {}
@scanner = TagScanner.new options
@matcher = Matcher.new @scanner, :always_show_dot_files => true
end
def open_selection command, selection, options = {}
if @scanner.include_filenames
selection = selection[0, selection.index(':')]
end
# open the tag and center the screen on it
::VIM::command "silent! tag #{selection} | :normal zz"
end
end # class TagFinder
end # module CommandT

View file

@ -0,0 +1,189 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "match.h"
#include "ext.h"
#include "ruby_compat.h"
// use a struct to make passing params during recursion easier
typedef struct
{
char *str_p; // pointer to string to be searched
long str_len; // length of same
char *abbrev_p; // pointer to search string (abbreviation)
long abbrev_len; // length of same
double max_score_per_char;
int dot_file; // boolean: true if str is a dot-file
int always_show_dot_files; // boolean
int never_show_dot_files; // boolean
} matchinfo_t;
double recursive_match(matchinfo_t *m, // sharable meta-data
long str_idx, // where in the path string to start
long abbrev_idx, // where in the search string to start
long last_idx, // location of last matched character
double score) // cumulative score so far
{
double seen_score = 0; // remember best score seen via recursion
int dot_file_match = 0; // true if abbrev matches a dot-file
int dot_search = 0; // true if searching for a dot
for (long i = abbrev_idx; i < m->abbrev_len; i++)
{
char c = m->abbrev_p[i];
if (c == '.')
dot_search = 1;
int found = 0;
for (long j = str_idx; j < m->str_len; j++, str_idx++)
{
char d = m->str_p[j];
if (d == '.')
{
if (j == 0 || m->str_p[j - 1] == '/')
{
m->dot_file = 1; // this is a dot-file
if (dot_search) // and we are searching for a dot
dot_file_match = 1; // so this must be a match
}
}
else if (d >= 'A' && d <= 'Z')
d += 'a' - 'A'; // add 32 to downcase
if (c == d)
{
found = 1;
dot_search = 0;
// calculate score
double score_for_char = m->max_score_per_char;
long distance = j - last_idx;
if (distance > 1)
{
double factor = 1.0;
char last = m->str_p[j - 1];
char curr = m->str_p[j]; // case matters, so get again
if (last == '/')
factor = 0.9;
else if (last == '-' ||
last == '_' ||
last == ' ' ||
(last >= '0' && last <= '9'))
factor = 0.8;
else if (last >= 'a' && last <= 'z' &&
curr >= 'A' && curr <= 'Z')
factor = 0.8;
else if (last == '.')
factor = 0.7;
else
// if no "special" chars behind char, factor diminishes
// as distance from last matched char increases
factor = (1.0 / distance) * 0.75;
score_for_char *= factor;
}
if (++j < m->str_len)
{
// bump cursor one char to the right and
// use recursion to try and find a better match
double sub_score = recursive_match(m, j, i, last_idx, score);
if (sub_score > seen_score)
seen_score = sub_score;
}
score += score_for_char;
last_idx = str_idx++;
break;
}
}
if (!found)
return 0.0;
}
if (m->dot_file)
{
if (m->never_show_dot_files ||
(!dot_file_match && !m->always_show_dot_files))
return 0.0;
}
return (score > seen_score) ? score : seen_score;
}
// Match.new abbrev, string, options = {}
VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self)
{
// process arguments: 2 mandatory, 1 optional
VALUE str, abbrev, options;
if (rb_scan_args(argc, argv, "21", &str, &abbrev, &options) == 2)
options = Qnil;
str = StringValue(str);
abbrev = StringValue(abbrev); // already downcased by caller
// check optional options hash for overrides
VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options);
VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options);
matchinfo_t m;
m.str_p = RSTRING_PTR(str);
m.str_len = RSTRING_LEN(str);
m.abbrev_p = RSTRING_PTR(abbrev);
m.abbrev_len = RSTRING_LEN(abbrev);
m.max_score_per_char = (1.0 / m.str_len + 1.0 / m.abbrev_len) / 2;
m.dot_file = 0;
m.always_show_dot_files = always_show_dot_files == Qtrue;
m.never_show_dot_files = never_show_dot_files == Qtrue;
// calculate score
double score = 1.0;
if (m.abbrev_len == 0) // special case for zero-length search string
{
// filter out dot files
if (!m.always_show_dot_files)
{
for (long i = 0; i < m.str_len; i++)
{
char c = m.str_p[i];
if (c == '.' && (i == 0 || m.str_p[i - 1] == '/'))
{
score = 0.0;
break;
}
}
}
}
else // normal case
score = recursive_match(&m, 0, 0, 0, 0.0);
// clean-up and final book-keeping
rb_iv_set(self, "@score", rb_float_new(score));
rb_iv_set(self, "@str", str);
return Qnil;
}
VALUE CommandTMatch_matches(VALUE self)
{
double score = NUM2DBL(rb_iv_get(self, "@score"));
return score > 0 ? Qtrue : Qfalse;
}
VALUE CommandTMatch_to_s(VALUE self)
{
return rb_iv_get(self, "@str");
}

View file

@ -0,0 +1,29 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <ruby.h>
extern VALUE CommandTMatch_initialize(int argc, VALUE *argv, VALUE self);
extern VALUE CommandTMatch_matches(VALUE self);
extern VALUE CommandTMatch_score(VALUE self);
extern VALUE CommandTMatch_to_s(VALUE self);

View file

@ -0,0 +1,445 @@
# Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'ostruct'
require 'command-t/settings'
module CommandT
class MatchWindow
SELECTION_MARKER = '> '
MARKER_LENGTH = SELECTION_MARKER.length
UNSELECTED_MARKER = ' ' * MARKER_LENGTH
MH_START = '<commandt>'
MH_END = '</commandt>'
@@buffer = nil
def initialize options = {}
@prompt = options[:prompt]
@reverse_list = options[:match_window_reverse]
@min_height = options[:min_height]
# save existing window dimensions so we can restore them later
@windows = []
(0..(::VIM::Window.count - 1)).each do |i|
@windows << OpenStruct.new(:index => i,
:height => ::VIM::Window[i].height,
:width => ::VIM::Window[i].width)
end
# global settings (must manually save and restore)
@settings = Settings.new
::VIM::set_option 'timeout' # ensure mappings timeout
::VIM::set_option 'timeoutlen=0' # respond immediately to mappings
::VIM::set_option 'nohlsearch' # don't highlight search strings
::VIM::set_option 'noinsertmode' # don't make Insert mode the default
::VIM::set_option 'noshowcmd' # don't show command info on last line
::VIM::set_option 'report=9999' # don't show "X lines changed" reports
::VIM::set_option 'sidescroll=0' # don't sidescroll in jumps
::VIM::set_option 'sidescrolloff=0' # don't sidescroll automatically
::VIM::set_option 'noequalalways' # don't auto-balance window sizes
# show match window
split_location = options[:match_window_at_top] ? 'topleft' : 'botright'
if @@buffer # still have buffer from last time
::VIM::command "silent! #{split_location} #{@@buffer.number}sbuffer"
raise "Can't re-open GoToFile buffer" unless $curbuf.number == @@buffer.number
$curwin.height = 1
else # creating match window for first time and set it up
split_command = "silent! #{split_location} 1split GoToFile"
[
split_command,
'setlocal bufhidden=unload', # unload buf when no longer displayed
'setlocal buftype=nofile', # buffer is not related to any file
'setlocal nomodifiable', # prevent manual edits
'setlocal noswapfile', # don't create a swapfile
'setlocal nowrap', # don't soft-wrap
'setlocal nonumber', # don't show line numbers
'setlocal nolist', # don't use List mode (visible tabs etc)
'setlocal foldcolumn=0', # don't show a fold column at side
'setlocal foldlevel=99', # don't fold anything
'setlocal nocursorline', # don't highlight line cursor is on
'setlocal nospell', # spell-checking off
'setlocal nobuflisted', # don't show up in the buffer list
'setlocal textwidth=0' # don't hard-wrap (break long lines)
].each { |command| ::VIM::command command }
# don't show the color column
::VIM::command 'setlocal colorcolumn=0' if VIM::exists?('+colorcolumn')
# don't show relative line numbers
::VIM::command 'setlocal norelativenumber' if VIM::exists?('+relativenumber')
# sanity check: make sure the buffer really was created
raise "Can't find GoToFile buffer" unless $curbuf.name.match /GoToFile\z/
@@buffer = $curbuf
end
# syntax coloring
if VIM::has_syntax?
::VIM::command "syntax match CommandTSelection \"^#{SELECTION_MARKER}.\\+$\""
::VIM::command 'syntax match CommandTNoEntries "^-- NO MATCHES --$"'
::VIM::command 'syntax match CommandTNoEntries "^-- NO SUCH FILE OR DIRECTORY --$"'
::VIM::command 'setlocal synmaxcol=9999'
if VIM::has_conceal?
::VIM::command 'setlocal conceallevel=2'
::VIM::command 'setlocal concealcursor=nvic'
::VIM::command 'syntax region CommandTCharMatched ' \
"matchgroup=CommandTCharMatched start=+#{MH_START}+ " \
"matchgroup=CommandTCharMatchedEnd end=+#{MH_END}+ concealends"
::VIM::command 'highlight def CommandTCharMatched ' \
'term=bold,underline cterm=bold,underline ' \
'gui=bold,underline'
end
::VIM::command 'highlight link CommandTSelection Visual'
::VIM::command 'highlight link CommandTNoEntries Error'
::VIM::evaluate 'clearmatches()'
# hide cursor
@cursor_highlight = get_cursor_highlight
hide_cursor
end
# perform cleanup using an autocmd to ensure we don't get caught out
# by some unexpected means of dismissing or leaving the Command-T window
# (eg. <C-W q>, <C-W k> etc)
::VIM::command 'autocmd! * <buffer>'
::VIM::command 'autocmd BufLeave <buffer> silent! ruby $command_t.leave'
::VIM::command 'autocmd BufUnload <buffer> silent! ruby $command_t.unload'
@has_focus = false
@selection = nil
@abbrev = ''
@window = $curwin
end
def close
# Unlisted buffers like those provided by Netrw, NERDTree and Vim's help
# don't actually appear in the buffer list; if they are the only such
# buffers present when Command-T is invoked (for example, when invoked
# immediately after starting Vim with a directory argument, like `vim .`)
# then performing the normal clean-up will yield an "E90: Cannot unload
# last buffer" error. We can work around that by doing a :quit first.
if ::VIM::Buffer.count == 0
::VIM::command 'silent quit'
end
# Workaround for upstream bug in Vim 7.3 on some platforms
#
# On some platforms, $curbuf.number always returns 0. One workaround is
# to build Vim with --disable-largefile, but as this is producing lots of
# support requests, implement the following fallback to the buffer name
# instead, at least until upstream gets fixed.
#
# For more details, see: https://wincent.com/issues/1617
if $curbuf.number == 0
# use bwipeout as bunload fails if passed the name of a hidden buffer
::VIM::command 'silent! bwipeout! GoToFile'
@@buffer = nil
else
::VIM::command "silent! bunload! #{@@buffer.number}"
end
end
def leave
close
unload
end
def unload
restore_window_dimensions
@settings.restore
@prompt.dispose
show_cursor
end
def add! char
@abbrev += char
end
def backspace!
@abbrev.chop!
end
def select_next
if @selection < @matches.length - 1
@selection += 1
print_match(@selection - 1) # redraw old selection (removes marker)
print_match(@selection) # redraw new selection (adds marker)
move_cursor_to_selected_line
else
# (possibly) loop or scroll
end
end
def select_prev
if @selection > 0
@selection -= 1
print_match(@selection + 1) # redraw old selection (removes marker)
print_match(@selection) # redraw new selection (adds marker)
move_cursor_to_selected_line
else
# (possibly) loop or scroll
end
end
def matches= matches
matches = matches.reverse if @reverse_list
if matches != @matches
@matches = matches
@selection = @reverse_list ? @matches.length - 1 : 0
print_matches
move_cursor_to_selected_line
end
end
def focus
unless @has_focus
@has_focus = true
if VIM::has_syntax?
::VIM::command 'highlight link CommandTSelection Search'
end
end
end
def unfocus
if @has_focus
@has_focus = false
if VIM::has_syntax?
::VIM::command 'highlight link CommandTSelection Visual'
end
end
end
def find char
# is this a new search or the continuation of a previous one?
now = Time.now
if @last_key_time.nil? or @last_key_time < (now - 0.5)
@find_string = char
else
@find_string += char
end
@last_key_time = now
# see if there's anything up ahead that matches
@matches.each_with_index do |match, idx|
if match[0, @find_string.length].casecmp(@find_string) == 0
old_selection = @selection
@selection = idx
print_match(old_selection) # redraw old selection (removes marker)
print_match(@selection) # redraw new selection (adds marker)
break
end
end
end
# Returns the currently selected item as a String.
def selection
@matches[@selection]
end
def print_no_such_file_or_directory
print_error 'NO SUCH FILE OR DIRECTORY'
end
private
def move_cursor_to_selected_line
# on some non-GUI terminals, the cursor doesn't hide properly
# so we move the cursor to prevent it from blinking away in the
# upper-left corner in a distracting fashion
@window.cursor = [@selection + 1, 0]
end
def print_error msg
return unless VIM::Window.select(@window)
unlock
clear
@window.height = @min_height > 0 ? @min_height : 1
@@buffer[1] = "-- #{msg} --"
lock
end
def restore_window_dimensions
# sort from tallest to shortest, tie-breaking on window width
@windows.sort! do |a, b|
order = b.height <=> a.height
if order.zero?
b.width <=> a.width
else
order
end
end
# starting with the tallest ensures that there are no constraints
# preventing windows on the side of vertical splits from regaining
# their original full size
@windows.each do |w|
# beware: window may be nil
if window = ::VIM::Window[w.index]
window.height = w.height
window.width = w.width
end
end
end
def match_text_for_idx idx
match = truncated_match @matches[idx].to_s
if idx == @selection
prefix = SELECTION_MARKER
suffix = padding_for_selected_match match
else
if VIM::has_syntax? && VIM::has_conceal?
match = match_with_syntax_highlight match
end
prefix = UNSELECTED_MARKER
suffix = ''
end
prefix + match + suffix
end
# Highlight matching characters within the matched string.
#
# Note that this is only approximate; it will highlight the first matching
# instances within the string, which may not actually be the instances that
# were used by the matching/scoring algorithm to determine the best score
# for the match.
#
def match_with_syntax_highlight match
highlight_chars = @prompt.abbrev.downcase.chars.to_a
match.chars.inject([]) do |output, char|
if char.downcase == highlight_chars.first
highlight_chars.shift
output.concat [MH_START, char, MH_END]
else
output << char
end
end.join
end
# Print just the specified match.
def print_match idx
return unless VIM::Window.select(@window)
unlock
@@buffer[idx + 1] = match_text_for_idx idx
lock
end
# Print all matches.
def print_matches
match_count = @matches.length
if match_count == 0
print_error 'NO MATCHES'
else
return unless VIM::Window.select(@window)
unlock
clear
actual_lines = 1
@window_width = @window.width # update cached value
max_lines = VIM::Screen.lines - 5
max_lines = 1 if max_lines < 0
actual_lines = match_count < @min_height ? @min_height : match_count
actual_lines = max_lines if actual_lines > max_lines
@window.height = actual_lines
(1..actual_lines).each do |line|
idx = line - 1
if @@buffer.count >= line
@@buffer[line] = match_text_for_idx idx
else
@@buffer.append line - 1, match_text_for_idx(idx)
end
end
lock
end
end
# Prepare padding for match text (trailing spaces) so that selection
# highlighting extends all the way to the right edge of the window.
def padding_for_selected_match str
len = str.length
if len >= @window_width - MARKER_LENGTH
''
else
' ' * (@window_width - MARKER_LENGTH - len)
end
end
# Convert "really/long/path" into "really...path" based on available
# window width.
def truncated_match str
len = str.length
available_width = @window_width - MARKER_LENGTH
return str if len <= available_width
left = (available_width / 2) - 1
right = (available_width / 2) - 2 + (available_width % 2)
str[0, left] + '...' + str[-right, right]
end
def clear
# range = % (whole buffer)
# action = d (delete)
# register = _ (black hole register, don't record deleted text)
::VIM::command 'silent %d _'
end
def get_cursor_highlight
# there are 3 possible formats to check for, each needing to be
# transformed in a certain way in order to reapply the highlight:
# Cursor xxx guifg=bg guibg=fg -> :hi! Cursor guifg=bg guibg=fg
# Cursor xxx links to SomethingElse -> :hi! link Cursor SomethingElse
# Cursor xxx cleared -> :hi! clear Cursor
highlight = VIM::capture 'silent! 0verbose highlight Cursor'
if highlight =~ /^Cursor\s+xxx\s+links to (\w+)/
"link Cursor #{$~[1]}"
elsif highlight =~ /^Cursor\s+xxx\s+cleared/
'clear Cursor'
elsif highlight =~ /Cursor\s+xxx\s+(.+)/
"Cursor #{$~[1]}"
else # likely cause E411 Cursor highlight group not found
nil
end
end
def hide_cursor
if @cursor_highlight
::VIM::command 'highlight Cursor NONE'
end
end
def show_cursor
if @cursor_highlight
::VIM::command "highlight #{@cursor_highlight}"
end
end
def lock
::VIM::command 'setlocal nomodifiable'
end
def unlock
::VIM::command 'setlocal modifiable'
end
end
end

View file

@ -0,0 +1,164 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h> /* for qsort() */
#include <string.h> /* for strcmp() */
#include "matcher.h"
#include "ext.h"
#include "ruby_compat.h"
// comparison function for use with qsort
int comp_alpha(const void *a, const void *b)
{
VALUE a_val = *(VALUE *)a;
VALUE b_val = *(VALUE *)b;
ID to_s = rb_intern("to_s");
VALUE a_str = rb_funcall(a_val, to_s, 0);
VALUE b_str = rb_funcall(b_val, to_s, 0);
char *a_p = RSTRING_PTR(a_str);
long a_len = RSTRING_LEN(a_str);
char *b_p = RSTRING_PTR(b_str);
long b_len = RSTRING_LEN(b_str);
int order = 0;
if (a_len > b_len)
{
order = strncmp(a_p, b_p, b_len);
if (order == 0)
order = 1; // shorter string (b) wins
}
else if (a_len < b_len)
{
order = strncmp(a_p, b_p, a_len);
if (order == 0)
order = -1; // shorter string (a) wins
}
else
order = strncmp(a_p, b_p, a_len);
return order;
}
// comparison function for use with qsort
int comp_score(const void *a, const void *b)
{
VALUE a_val = *(VALUE *)a;
VALUE b_val = *(VALUE *)b;
ID score = rb_intern("score");
double a_score = RFLOAT_VALUE(rb_funcall(a_val, score, 0));
double b_score = RFLOAT_VALUE(rb_funcall(b_val, score, 0));
if (a_score > b_score)
return -1; // a scores higher, a should appear sooner
else if (a_score < b_score)
return 1; // b scores higher, a should appear later
else
return comp_alpha(a, b);
}
VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self)
{
// process arguments: 1 mandatory, 1 optional
VALUE scanner, options;
if (rb_scan_args(argc, argv, "11", &scanner, &options) == 1)
options = Qnil;
if (NIL_P(scanner))
rb_raise(rb_eArgError, "nil scanner");
rb_iv_set(self, "@scanner", scanner);
// check optional options hash for overrides
VALUE always_show_dot_files = CommandT_option_from_hash("always_show_dot_files", options);
if (always_show_dot_files != Qtrue)
always_show_dot_files = Qfalse;
VALUE never_show_dot_files = CommandT_option_from_hash("never_show_dot_files", options);
if (never_show_dot_files != Qtrue)
never_show_dot_files = Qfalse;
rb_iv_set(self, "@always_show_dot_files", always_show_dot_files);
rb_iv_set(self, "@never_show_dot_files", never_show_dot_files);
return Qnil;
}
VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options)
{
// process optional options hash
VALUE limit_option = CommandT_option_from_hash("limit", options);
// get unsorted matches
VALUE matches = CommandTMatcher_matches_for(self, abbrev);
abbrev = StringValue(abbrev);
if (RSTRING_LEN(abbrev) == 0 ||
(RSTRING_LEN(abbrev) == 1 && RSTRING_PTR(abbrev)[0] == '.'))
// alphabetic order if search string is only "" or "."
qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_alpha);
else
// for all other non-empty search strings, sort by score
qsort(RARRAY_PTR(matches), RARRAY_LEN(matches), sizeof(VALUE), comp_score);
// apply optional limit option
long limit = NIL_P(limit_option) ? 0 : NUM2LONG(limit_option);
if (limit == 0 || RARRAY_LEN(matches) < limit)
limit = RARRAY_LEN(matches);
// will return an array of strings, not an array of Match objects
for (long i = 0; i < limit; i++)
{
VALUE str = rb_funcall(RARRAY_PTR(matches)[i], rb_intern("to_s"), 0);
RARRAY_PTR(matches)[i] = str;
}
// trim off any items beyond the limit
if (limit < RARRAY_LEN(matches))
(void)rb_funcall(matches, rb_intern("slice!"), 2, LONG2NUM(limit),
LONG2NUM(RARRAY_LEN(matches) - limit));
return matches;
}
VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev)
{
if (NIL_P(abbrev))
rb_raise(rb_eArgError, "nil abbrev");
VALUE matches = rb_ary_new();
VALUE scanner = rb_iv_get(self, "@scanner");
VALUE always_show_dot_files = rb_iv_get(self, "@always_show_dot_files");
VALUE never_show_dot_files = rb_iv_get(self, "@never_show_dot_files");
VALUE options = Qnil;
if (always_show_dot_files == Qtrue)
{
options = rb_hash_new();
rb_hash_aset(options, ID2SYM(rb_intern("always_show_dot_files")), always_show_dot_files);
}
else if (never_show_dot_files == Qtrue)
{
options = rb_hash_new();
rb_hash_aset(options, ID2SYM(rb_intern("never_show_dot_files")), never_show_dot_files);
}
abbrev = rb_funcall(abbrev, rb_intern("downcase"), 0);
VALUE paths = rb_funcall(scanner, rb_intern("paths"), 0);
for (long i = 0, max = RARRAY_LEN(paths); i < max; i++)
{
VALUE path = RARRAY_PTR(paths)[i];
VALUE match = rb_funcall(cCommandTMatch, rb_intern("new"), 3, path, abbrev, options);
if (rb_funcall(match, rb_intern("matches?"), 0) == Qtrue)
rb_funcall(matches, rb_intern("push"), 1, match);
}
return matches;
}

View file

@ -0,0 +1,30 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <ruby.h>
extern VALUE CommandTMatcher_initialize(int argc, VALUE *argv, VALUE self);
extern VALUE CommandTMatcher_sorted_matches_for(VALUE self, VALUE abbrev, VALUE options);
// most likely the function will be subsumed by the sorted_matcher_for function
extern VALUE CommandTMatcher_matches_for(VALUE self, VALUE abbrev);

View file

@ -0,0 +1,165 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
# Abuse the status line as a prompt.
class Prompt
attr_accessor :abbrev
def initialize
@abbrev = '' # abbreviation entered so far
@col = 0 # cursor position
@has_focus = false
end
# Erase whatever is displayed in the prompt line,
# effectively disposing of the prompt
def dispose
::VIM::command 'echo'
::VIM::command 'redraw'
end
# Clear any entered text.
def clear!
@abbrev = ''
@col = 0
redraw
end
# Insert a character at (before) the current cursor position.
def add! char
left, cursor, right = abbrev_segments
@abbrev = left + char + cursor + right
@col += 1
redraw
end
# Delete a character to the left of the current cursor position.
def backspace!
if @col > 0
left, cursor, right = abbrev_segments
@abbrev = left.chop! + cursor + right
@col -= 1
redraw
end
end
# Delete a character at the current cursor position.
def delete!
if @col < @abbrev.length
left, cursor, right = abbrev_segments
@abbrev = left + right
redraw
end
end
def cursor_left
if @col > 0
@col -= 1
redraw
end
end
def cursor_right
if @col < @abbrev.length
@col += 1
redraw
end
end
def cursor_end
if @col < @abbrev.length
@col = @abbrev.length
redraw
end
end
def cursor_start
if @col != 0
@col = 0
redraw
end
end
def redraw
if @has_focus
prompt_highlight = 'Comment'
normal_highlight = 'None'
cursor_highlight = 'Underlined'
else
prompt_highlight = 'NonText'
normal_highlight = 'NonText'
cursor_highlight = 'NonText'
end
left, cursor, right = abbrev_segments
components = [prompt_highlight, '>>', 'None', ' ']
components += [normal_highlight, left] unless left.empty?
components += [cursor_highlight, cursor] unless cursor.empty?
components += [normal_highlight, right] unless right.empty?
components += [cursor_highlight, ' '] if cursor.empty?
set_status *components
end
def focus
unless @has_focus
@has_focus = true
redraw
end
end
def unfocus
if @has_focus
@has_focus = false
redraw
end
end
private
# Returns the @abbrev string divided up into three sections, any of
# which may actually be zero width, depending on the location of the
# cursor:
# - left segment (to left of cursor)
# - cursor segment (character at cursor)
# - right segment (to right of cursor)
def abbrev_segments
left = @abbrev[0, @col]
cursor = @abbrev[@col, 1]
right = @abbrev[(@col + 1)..-1] || ''
[left, cursor, right]
end
def set_status *args
# see ':help :echo' for why forcing a redraw here helps
# prevent the status line from getting inadvertantly cleared
# after our echo commands
::VIM::command 'redraw'
while (highlight = args.shift) and (text = args.shift) do
text = VIM::escape_for_single_quotes text
::VIM::command "echohl #{highlight}"
::VIM::command "echon '#{text}'"
end
::VIM::command 'echohl None'
end
end # class Prompt
end # module CommandT

View file

@ -0,0 +1,49 @@
// Copyright 2010 Wincent Colaiuta. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <ruby.h>
// for compatibility with older versions of Ruby which don't declare RSTRING_PTR
#ifndef RSTRING_PTR
#define RSTRING_PTR(s) (RSTRING(s)->ptr)
#endif
// for compatibility with older versions of Ruby which don't declare RSTRING_LEN
#ifndef RSTRING_LEN
#define RSTRING_LEN(s) (RSTRING(s)->len)
#endif
// for compatibility with older versions of Ruby which don't declare RARRAY_PTR
#ifndef RARRAY_PTR
#define RARRAY_PTR(a) (RARRAY(a)->ptr)
#endif
// for compatibility with older versions of Ruby which don't declare RARRAY_LEN
#ifndef RARRAY_LEN
#define RARRAY_LEN(a) (RARRAY(a)->len)
#endif
// for compatibility with older versions of Ruby which don't declare RFLOAT_VALUE
#ifndef RFLOAT_VALUE
#define RFLOAT_VALUE(f) (RFLOAT(f)->value)
#endif

View file

@ -0,0 +1,28 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
module CommandT
class Scanner; end
end # module CommandT

View file

@ -0,0 +1,42 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
require 'command-t/vim/path_utilities'
require 'command-t/scanner'
module CommandT
# Returns a list of all open buffers.
class BufferScanner < Scanner
include VIM::PathUtilities
def paths
(0..(::VIM::Buffer.count - 1)).map do |n|
buffer = ::VIM::Buffer[n]
if buffer.name # beware, may be nil
relative_path_under_working_directory buffer.name
end
end.compact
end
end # class BufferScanner
end # module CommandT

View file

@ -0,0 +1,101 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
require 'command-t/scanner'
module CommandT
# Reads the current directory recursively for the paths to all regular files.
class FileScanner < Scanner
class FileLimitExceeded < ::RuntimeError; end
attr_accessor :path
def initialize path = Dir.pwd, options = {}
@paths = {}
@paths_keys = []
@path = path
@max_depth = options[:max_depth] || 15
@max_files = options[:max_files] || 10_000
@max_caches = options[:max_caches] || 1
@scan_dot_directories = options[:scan_dot_directories] || false
end
def paths
return @paths[@path] if @paths.has_key?(@path)
begin
ensure_cache_under_limit
@paths[@path] = []
@depth = 0
@files = 0
@prefix_len = @path.chomp('/').length
add_paths_for_directory @path, @paths[@path]
rescue FileLimitExceeded
end
@paths[@path]
end
def flush
@paths = {}
end
private
def ensure_cache_under_limit
# Ruby 1.8 doesn't have an ordered hash, so use a separate stack to
# track and expire the oldest entry in the cache
if @max_caches > 0 && @paths_keys.length >= @max_caches
@paths.delete @paths_keys.shift
end
@paths_keys << @path
end
def path_excluded? path
# first strip common prefix (@path) from path to match VIM's behavior
path = path[(@prefix_len + 1)..-1]
path = VIM::escape_for_single_quotes path
::VIM::evaluate("empty(expand(fnameescape('#{path}')))").to_i == 1
end
def add_paths_for_directory dir, accumulator
Dir.foreach(dir) do |entry|
next if ['.', '..'].include?(entry)
path = File.join(dir, entry)
unless path_excluded?(path)
if File.file?(path)
@files += 1
raise FileLimitExceeded if @files > @max_files
accumulator << path[@prefix_len + 1..-1]
elsif File.directory?(path)
next if @depth >= @max_depth
next if (entry.match(/\A\./) && !@scan_dot_directories)
@depth += 1
add_paths_for_directory path, accumulator
@depth -= 1
end
end
end
rescue Errno::EACCES
# skip over directories for which we don't have access
end
end # class FileScanner
end # module CommandT

View file

@ -0,0 +1,54 @@
# Copyright 2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
require 'command-t/vim/path_utilities'
require 'command-t/scanner'
module CommandT
# Returns a list of files in the jumplist.
class JumpScanner < Scanner
include VIM::PathUtilities
def paths
jumps_with_filename = jumps.lines.select do |line|
line_contains_filename?(line)
end
filenames = jumps_with_filename[1..-2].map do |line|
relative_path_under_working_directory line.split[3]
end
filenames.sort.uniq
end
private
def line_contains_filename? line
line.split.count > 3
end
def jumps
VIM::capture 'silent jumps'
end
end # class JumpScanner
end # module CommandT

View file

@ -0,0 +1,49 @@
# Copyright 2011-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
require 'command-t/scanner'
module CommandT
class TagScanner < Scanner
attr_reader :include_filenames
def initialize options = {}
@include_filenames = options[:include_filenames] || false
end
def paths
taglist.map do |tag|
path = tag['name']
path << ":#{tag['filename']}" if @include_filenames
path
end.uniq.sort
end
private
def taglist
::VIM::evaluate 'taglist(".")'
end
end # class TagScanner
end # module CommandT

View file

@ -0,0 +1,77 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
# Convenience class for saving and restoring global settings.
class Settings
def initialize
save
end
def save
@timeoutlen = get_number 'timeoutlen'
@report = get_number 'report'
@sidescroll = get_number 'sidescroll'
@sidescrolloff = get_number 'sidescrolloff'
@timeout = get_bool 'timeout'
@equalalways = get_bool 'equalalways'
@hlsearch = get_bool 'hlsearch'
@insertmode = get_bool 'insertmode'
@showcmd = get_bool 'showcmd'
end
def restore
set_number 'timeoutlen', @timeoutlen
set_number 'report', @report
set_number 'sidescroll', @sidescroll
set_number 'sidescrolloff', @sidescrolloff
set_bool 'timeout', @timeout
set_bool 'equalalways', @equalalways
set_bool 'hlsearch', @hlsearch
set_bool 'insertmode', @insertmode
set_bool 'showcmd', @showcmd
end
private
def get_number setting
::VIM::evaluate("&#{setting}").to_i
end
def get_bool setting
::VIM::evaluate("&#{setting}").to_i == 1
end
def set_number setting, value
::VIM::set_option "#{setting}=#{value}"
end
def set_bool setting, value
if value
::VIM::set_option setting
else
::VIM::set_option "no#{setting}"
end
end
end # class Settings
end # module CommandT

View file

@ -0,0 +1,42 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
class Stub
@@load_error = ['command-t.vim could not load the C extension',
'Please see INSTALLATION and TROUBLE-SHOOTING in the help',
'For more information type: :help command-t']
[:flush, :show_buffer_finder, :show_file_finder, :show_tag_finder].each do |method|
define_method(method.to_sym) { warn *@@load_error }
end
private
def warn *msg
::VIM::command 'echohl WarningMsg'
msg.each { |m| ::VIM::command "echo '#{m}'" }
::VIM::command 'echohl none'
end
end # class Stub
end # module CommandT

View file

@ -0,0 +1,59 @@
# Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim/screen'
require 'command-t/vim/window'
module CommandT
module VIM
def self.has_syntax?
::VIM::evaluate('has("syntax")').to_i != 0
end
def self.exists? str
::VIM::evaluate(%{exists("#{str}")}).to_i != 0
end
def self.has_conceal?
::VIM::evaluate('has("conceal")').to_i != 0
end
def self.pwd
::VIM::evaluate 'getcwd()'
end
# Execute cmd, capturing the output into a variable and returning it.
def self.capture cmd
::VIM::command 'silent redir => g:command_t_captured_output'
::VIM::command cmd
::VIM::command 'silent redir END'
::VIM::evaluate 'g:command_t_captured_output'
end
# Escape a string for safe inclusion in a Vim single-quoted string
# (single quotes escaped by doubling, everything else is literal)
def self.escape_for_single_quotes str
str.gsub "'", "''"
end
end # module VIM
end # module CommandT

View file

@ -0,0 +1,40 @@
# Copyright 2010-2011 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/vim'
module CommandT
module VIM
module PathUtilities
private
def relative_path_under_working_directory path
# any path under the working directory will be specified as a relative
# path to improve the readability of the buffer list etc
pwd = File.expand_path(VIM::pwd) + '/'
path.index(pwd) == 0 ? path[pwd.length..-1] : path
end
end # module PathUtilities
end # module VIM
end # module CommandT

View file

@ -0,0 +1,32 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
module VIM
module Screen
def self.lines
::VIM::evaluate('&lines').to_i
end
end # module Screen
end # module VIM
end # module CommandT

View file

@ -0,0 +1,38 @@
# Copyright 2010 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
module CommandT
module VIM
class Window
def self.select window
return true if $curwin == window
initial = $curwin
while true do
::VIM::command 'wincmd w' # cycle through windows
return true if $curwin == window # have selected desired window
return false if $curwin == initial # have already looped through all
end
end
end # class Window
end # module VIM
end # module CommandT