mirror of
https://github.com/junegunn/fzf.git
synced 2025-08-03 05:32:08 -07:00
Compare commits
94 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
c4cf90a3d2 | ||
|
15c49a3e08 | ||
|
ae87f6548a | ||
|
7833fa7396 | ||
|
9278f3acd2 | ||
|
e83ae34a3b | ||
|
e13bafc1ab | ||
|
0ea66329b8 | ||
|
634670e3ea | ||
|
dea60b11bc | ||
|
5e90f0a57b | ||
|
0b4542fcdf | ||
|
02bd2d2adf | ||
|
dce6fe6f2d | ||
|
fcae99f09b | ||
|
fb1b026d3d | ||
|
9f953fc944 | ||
|
909ea1a698 | ||
|
7231acd442 | ||
|
7814371a9a | ||
|
6166e2dd80 | ||
|
ee0c8a2635 | ||
|
2bebddefc0 | ||
|
fdbf3d3fec | ||
|
f9136cffe6 | ||
|
51d84b1869 | ||
|
13e040baee | ||
|
cc0d5539ba | ||
|
b53f61fc59 | ||
|
4e0e03403e | ||
|
928fccc15b | ||
|
bbaa3ab8bd | ||
|
5e3cb3a4ea | ||
|
f71ea5f3ea | ||
|
f469c25730 | ||
|
18469b6954 | ||
|
d01db4862b | ||
|
8b2adba8d6 | ||
|
d459e9abce | ||
|
c9abe1b1ff | ||
|
a0e6147bb5 | ||
|
b0f491d3c3 | ||
|
392da53f53 | ||
|
ae72b0fb70 | ||
|
a79d080ea8 | ||
|
ec85fd552d | ||
|
11db046fc7 | ||
|
938151a834 | ||
|
14e3b84073 | ||
|
56100f0fa7 | ||
|
5254ee2e2a | ||
|
355d004895 | ||
|
a336494f5d | ||
|
8270f7f0ca | ||
|
638a956a9e | ||
|
d395ebd28f | ||
|
c0d3faa84f | ||
|
3492c8b780 | ||
|
a8b2c257cd | ||
|
5e8d8dab82 | ||
|
b504c6eb39 | ||
|
d261c36cde | ||
|
fe4e452d68 | ||
|
d54a4fa223 | ||
|
45bd323cab | ||
|
8677dbded1 | ||
|
794ad5785d | ||
|
fa5b58968e | ||
|
e720f56ea8 | ||
|
7db53e6459 | ||
|
e287bd7f04 | ||
|
022435a90a | ||
|
6c99cc1700 | ||
|
fe5b190a7d | ||
|
77bab51696 | ||
|
77048f3e3b | ||
|
8b618f7439 | ||
|
8973207bb4 | ||
|
6ad1736832 | ||
|
9fca611c4a | ||
|
8e7164553f | ||
|
3b52811796 | ||
|
2e84b1db64 | ||
|
9f33068ab3 | ||
|
eaa3c67a5e | ||
|
1b9b1d15bc | ||
|
97f433a274 | ||
|
45a3655eaf | ||
|
81ffde92fb | ||
|
0be4cead20 | ||
|
f6dd32046e | ||
|
443a80f254 | ||
|
8017635a71 | ||
|
98f62b191a |
81
CHANGELOG.md
81
CHANGELOG.md
@@ -1,6 +1,87 @@
|
|||||||
CHANGELOG
|
CHANGELOG
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
0.10.2
|
||||||
|
------
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- Improvement in perceived response time of queries
|
||||||
|
- Eager, efficient rune array conversion
|
||||||
|
- Graceful exit when failed to initialize ncurses (invalid $TERM)
|
||||||
|
- Improved ranking algorithm when `--nth` option is set
|
||||||
|
- Changed the default command not to fail when there are files whose names
|
||||||
|
start with dash
|
||||||
|
|
||||||
|
0.10.1
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--margin` option
|
||||||
|
- Added options for sticky header
|
||||||
|
- `--header-file`
|
||||||
|
- `--header-lines`
|
||||||
|
- Added `cancel` action which clears the input or closes the finder when the
|
||||||
|
input is already empty
|
||||||
|
- e.g. `export FZF_DEFAULT_OPTS="--bind esc:cancel"`
|
||||||
|
- Added `delete-char/eof` action to differentiate `CTRL-D` and `DEL`
|
||||||
|
|
||||||
|
### Minor improvements/fixes
|
||||||
|
|
||||||
|
- Fixed to allow binding colon and comma keys
|
||||||
|
- Fixed ANSI processor to handle color regions spanning multiple lines
|
||||||
|
|
||||||
|
0.10.0
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- More actions for `--bind`
|
||||||
|
- `select-all`
|
||||||
|
- `deselect-all`
|
||||||
|
- `toggle-all`
|
||||||
|
- `ignore`
|
||||||
|
- `execute(...)` action for running arbitrary command without leaving fzf
|
||||||
|
- `fzf --bind "ctrl-m:execute(less {})"`
|
||||||
|
- `fzf --bind "ctrl-t:execute(tmux new-window -d 'vim {}')"`
|
||||||
|
- If the command contains parentheses, use any of the follows alternative
|
||||||
|
notations to avoid parse errors
|
||||||
|
- `execute[...]`
|
||||||
|
- `execute~...~`
|
||||||
|
- `execute!...!`
|
||||||
|
- `execute@...@`
|
||||||
|
- `execute#...#`
|
||||||
|
- `execute$...$`
|
||||||
|
- `execute%...%`
|
||||||
|
- `execute^...^`
|
||||||
|
- `execute&...&`
|
||||||
|
- `execute*...*`
|
||||||
|
- `execute;...;`
|
||||||
|
- `execute/.../`
|
||||||
|
- `execute|...|`
|
||||||
|
- `execute:...`
|
||||||
|
- This is the special form that frees you from parse errors as it
|
||||||
|
does not expect the closing character
|
||||||
|
- The catch is that it should be the last one in the
|
||||||
|
comma-separated list
|
||||||
|
- Added support for optional search history
|
||||||
|
- `--history HISTORY_FILE`
|
||||||
|
- When used, `CTRL-N` and `CTRL-P` are automatically remapped to
|
||||||
|
`next-history` and `previous-history`
|
||||||
|
- `--history-size MAX_ENTRIES` (default: 1000)
|
||||||
|
- Cyclic scrolling can be enabled with `--cycle`
|
||||||
|
- Fixed the bug where the spinner was not spinning on idle input stream
|
||||||
|
- e.g. `sleep 100 | fzf`
|
||||||
|
|
||||||
|
### Minor improvements/fixes
|
||||||
|
|
||||||
|
- Added synonyms for key names that can be specified for `--bind`,
|
||||||
|
`--toggle-sort`, and `--expect`
|
||||||
|
- Fixed the color of multi-select marker on the current line
|
||||||
|
- Fixed to allow `^pattern$` in extended-search mode
|
||||||
|
|
||||||
|
|
||||||
0.9.13
|
0.9.13
|
||||||
------
|
------
|
||||||
|
|
||||||
|
15
README.md
15
README.md
@@ -127,6 +127,13 @@ such as: `^music .mp3$ sbtrkt !rmx`
|
|||||||
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
||||||
fzf with `-e` or `--extended-exact` option.
|
fzf with `-e` or `--extended-exact` option.
|
||||||
|
|
||||||
|
#### Environment variables
|
||||||
|
|
||||||
|
- `FZF_DEFAULT_COMMAND`
|
||||||
|
- Default command to use when input is tty
|
||||||
|
- `FZF_DEFAULT_OPTS`
|
||||||
|
- Default options. e.g. `export FZF_DEFAULT_OPTS="--extended --cycle"`
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
|
|
||||||
@@ -140,8 +147,9 @@ Key bindings for command line
|
|||||||
The install script will setup the following key bindings for bash, zsh, and
|
The install script will setup the following key bindings for bash, zsh, and
|
||||||
fish.
|
fish.
|
||||||
|
|
||||||
- `CTRL-T` - Paste the selected file path(s) into the command line
|
- `CTRL-T` - Paste the selected files and directories onto the command line
|
||||||
- `CTRL-R` - Paste the selected command from history into the command line
|
- Set `FZF_CTRL_T_COMMAND` to override the default command
|
||||||
|
- `CTRL-R` - Paste the selected command from history onto the command line
|
||||||
- Sort is disabled by default to respect chronological ordering
|
- Sort is disabled by default to respect chronological ordering
|
||||||
- Press `CTRL-R` again to toggle sort
|
- Press `CTRL-R` again to toggle sort
|
||||||
- `ALT-C` - cd into the selected directory
|
- `ALT-C` - cd into the selected directory
|
||||||
@@ -390,6 +398,9 @@ export FZF_DEFAULT_COMMAND='ag -l -g ""'
|
|||||||
|
|
||||||
# Now fzf (w/o pipe) will use ag instead of find
|
# Now fzf (w/o pipe) will use ag instead of find
|
||||||
fzf
|
fzf
|
||||||
|
|
||||||
|
# To apply the command to CTRL-T as well
|
||||||
|
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `git ls-tree` for fast traversal
|
#### `git ls-tree` for fast traversal
|
||||||
|
@@ -82,7 +82,7 @@ while [ $# -gt 0 ]; do
|
|||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
|
|
||||||
if [ -z "$TMUX_PANE" ]; then
|
if [ -z "$TMUX_PANE" ] || tmux list-panes -F '#F' | grep -q Z; then
|
||||||
fzf "${args[@]}"
|
fzf "${args[@]}"
|
||||||
exit $?
|
exit $?
|
||||||
fi
|
fi
|
||||||
@@ -107,7 +107,7 @@ fail() {
|
|||||||
fzf="$(which fzf 2> /dev/null)" || fzf="$(dirname "$0")/fzf"
|
fzf="$(which fzf 2> /dev/null)" || fzf="$(dirname "$0")/fzf"
|
||||||
[ -x "$fzf" ] || fail "fzf executable not found"
|
[ -x "$fzf" ] || fail "fzf executable not found"
|
||||||
|
|
||||||
envs="env "
|
envs="env TERM=$TERM "
|
||||||
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
||||||
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
||||||
|
|
||||||
|
6
fzf
6
fzf
@@ -206,11 +206,11 @@ class FZF
|
|||||||
@expect = true
|
@expect = true
|
||||||
when /^--expect=(.*)$/
|
when /^--expect=(.*)$/
|
||||||
@expect = true
|
@expect = true
|
||||||
when '--toggle-sort', '--tiebreak', '--color', '--bind'
|
when '--toggle-sort', '--tiebreak', '--color', '--bind', '--history', '--history-size'
|
||||||
argv.shift
|
argv.shift
|
||||||
when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',
|
when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',
|
||||||
'--inline-info', '--no-inline-info', /^--bind=(.*)$/,
|
'--inline-info', '--no-inline-info', '--read0', '--cycle', /^--bind=(.*)$/,
|
||||||
/^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/
|
/^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/, /^--history(-max)?=(.*)$/
|
||||||
# XXX
|
# XXX
|
||||||
else
|
else
|
||||||
usage 1, "illegal option: #{o}"
|
usage 1, "illegal option: #{o}"
|
||||||
|
15
install
15
install
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
version=0.9.13
|
[[ "$@" =~ --pre ]] && version=0.10.2 pre=1 ||
|
||||||
|
version=0.10.2 pre=0
|
||||||
|
|
||||||
cd $(dirname $BASH_SOURCE)
|
cd $(dirname $BASH_SOURCE)
|
||||||
fzf_base=$(pwd)
|
fzf_base=$(pwd)
|
||||||
@@ -45,11 +46,13 @@ symlink() {
|
|||||||
|
|
||||||
download() {
|
download() {
|
||||||
echo "Downloading bin/fzf ..."
|
echo "Downloading bin/fzf ..."
|
||||||
if [[ ! $1 =~ dev && -x "$fzf_base"/bin/fzf ]]; then
|
if [ $pre = 0 ]; then
|
||||||
echo " - Already exists"
|
if [ -x "$fzf_base"/bin/fzf ]; then
|
||||||
check_binary && return
|
echo " - Already exists"
|
||||||
elif [ -x "$fzf_base"/bin/$1 ]; then
|
check_binary && return
|
||||||
symlink $1 && check_binary && return
|
elif [ -x "$fzf_base"/bin/$1 ]; then
|
||||||
|
symlink $1 && check_binary && return
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
|
195
man/man1/fzf.1
195
man/man1/fzf.1
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
..
|
..
|
||||||
.TH fzf 1 "June 2015" "fzf 0.9.13" "fzf - a command-line fuzzy finder"
|
.TH fzf 1 "Aug 2015" "fzf 0.10.2" "fzf - a command-line fuzzy finder"
|
||||||
|
|
||||||
.SH NAME
|
.SH NAME
|
||||||
fzf - a command-line fuzzy finder
|
fzf - a command-line fuzzy finder
|
||||||
@@ -52,10 +52,10 @@ Comma-separated list of field index expressions for limiting search scope.
|
|||||||
See \fBFIELD INDEX EXPRESSION\fR for details.
|
See \fBFIELD INDEX EXPRESSION\fR for details.
|
||||||
.TP
|
.TP
|
||||||
.BI "--with-nth=" "N[,..]"
|
.BI "--with-nth=" "N[,..]"
|
||||||
Transform the item using the list of index expressions for search
|
Transform each item using index expressions within finder
|
||||||
.TP
|
.TP
|
||||||
.BI "-d, --delimiter=" "STR"
|
.BI "-d, --delimiter=" "STR"
|
||||||
Field delimiter regex for \fI--nth\fR and \fI--with-nth\fR (default: AWK-style)
|
Field delimiter regex for \fB--nth\fR and \fB--with-nth\fR (default: AWK-style)
|
||||||
.SS Search result
|
.SS Search result
|
||||||
.TP
|
.TP
|
||||||
.B "+s, --no-sort"
|
.B "+s, --no-sort"
|
||||||
@@ -122,6 +122,7 @@ e.g. \fBfzf --color=bg+:24\fR
|
|||||||
\fBpointer \fRPointer to the current line
|
\fBpointer \fRPointer to the current line
|
||||||
\fBmarker \fRMulti-select marker
|
\fBmarker \fRMulti-select marker
|
||||||
\fBspinner \fRStreaming input indicator
|
\fBspinner \fRStreaming input indicator
|
||||||
|
\fBheader \fRHeader
|
||||||
.RE
|
.RE
|
||||||
.TP
|
.TP
|
||||||
.B "--black"
|
.B "--black"
|
||||||
@@ -130,6 +131,34 @@ Use black background
|
|||||||
.B "--reverse"
|
.B "--reverse"
|
||||||
Reverse orientation
|
Reverse orientation
|
||||||
.TP
|
.TP
|
||||||
|
.BI "--margin=" MARGIN
|
||||||
|
Comma-separated expression for margins around the finder.
|
||||||
|
.br
|
||||||
|
.R ""
|
||||||
|
.br
|
||||||
|
.RS
|
||||||
|
.BR TRBL " Same margin for top, right, bottom, and left"
|
||||||
|
.br
|
||||||
|
.BR TB,RL " Vertical, horizontal margin"
|
||||||
|
.br
|
||||||
|
.BR T,RL,B " Top, horizontal, bottom margin"
|
||||||
|
.br
|
||||||
|
.BR T,R,B,L " Top, right, bottom, left margin"
|
||||||
|
.br
|
||||||
|
.R ""
|
||||||
|
.br
|
||||||
|
Each part can be given in absolute number or in percentage relative to the
|
||||||
|
terminal size with \fB%\fR suffix.
|
||||||
|
.br
|
||||||
|
.R ""
|
||||||
|
.br
|
||||||
|
e.g. \fBfzf --margin 10%\fR
|
||||||
|
\fBfzf --margin 1,5%\fR
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.B "--cycle"
|
||||||
|
Enable cyclic scroll
|
||||||
|
.TP
|
||||||
.B "--no-hscroll"
|
.B "--no-hscroll"
|
||||||
Disable horizontal scroll
|
Disable horizontal scroll
|
||||||
.TP
|
.TP
|
||||||
@@ -140,8 +169,7 @@ Display finder info inline with the query
|
|||||||
Input prompt (default: '> ')
|
Input prompt (default: '> ')
|
||||||
.TP
|
.TP
|
||||||
.BI "--toggle-sort=" "KEY"
|
.BI "--toggle-sort=" "KEY"
|
||||||
Key to toggle sort (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
Key to toggle sort. For the list of the allowed key names, see \fB--bind\fR.
|
||||||
or any single character)
|
|
||||||
.TP
|
.TP
|
||||||
.BI "--bind=" "KEYBINDS"
|
.BI "--bind=" "KEYBINDS"
|
||||||
Comma-separated list of custom key bindings. Each key binding expression
|
Comma-separated list of custom key bindings. Each key binding expression
|
||||||
@@ -151,38 +179,122 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
|||||||
.RE
|
.RE
|
||||||
|
|
||||||
.RS
|
.RS
|
||||||
.B KEY:
|
.B AVAILABLE KEYS:
|
||||||
\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR, or any single character
|
\fIctrl-[a-z]\fR
|
||||||
|
\fIalt-[a-z]\fR
|
||||||
|
\fIf[1-4]\fR
|
||||||
|
\fIenter\fR (\fIreturn\fR)
|
||||||
|
\fIspace\fR
|
||||||
|
\fIbspace\fR (\fIbs\fR)
|
||||||
|
\fIalt-bspace\fR (\fIalt-bs\fR)
|
||||||
|
\fItab\fR
|
||||||
|
\fIbtab\fR (\fIshift-tab\fR)
|
||||||
|
\fIesc\fR
|
||||||
|
\fIdel\fR
|
||||||
|
\fIup\fR
|
||||||
|
\fIdown\fR
|
||||||
|
\fIleft\fR
|
||||||
|
\fIright\fR
|
||||||
|
\fIhome\fR
|
||||||
|
\fIend\fR
|
||||||
|
\fIpgup\fR (\fIpage-up\fR)
|
||||||
|
\fIpgdn\fR (\fIpage-down\fR)
|
||||||
|
\fIshift-left\fR
|
||||||
|
\fIshift-right\fR
|
||||||
|
or any single character
|
||||||
.RE
|
.RE
|
||||||
|
|
||||||
.RS
|
.RS
|
||||||
.B ACTION:
|
\fBACTION: DEFAULT BINDINGS:
|
||||||
abort
|
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
||||||
accept
|
\fBaccept\fR \fIctrl-m (enter)\fR
|
||||||
backward-char
|
\fBbackward-char\fR \fIctrl-b left\fR
|
||||||
backward-delete-char
|
\fBbackward-delete-char\fR \fIctrl-h bspace\fR
|
||||||
backward-kill-word
|
\fBbackward-kill-word\fR \fIalt-bs\fR
|
||||||
backward-word
|
\fBbackward-word\fR \fIalt-b shift-left\fR
|
||||||
beginning-of-line
|
\fBbeginning-of-line\fR \fIctrl-a home\fR
|
||||||
clear-screen
|
\fBcancel\fR
|
||||||
delete-char
|
\fBclear-screen\fR \fIctrl-l\fR
|
||||||
down
|
\fBdelete-char\fR \fIdel\fR
|
||||||
end-of-line
|
\fBdelete-char/eof\fR \fIctrl-d\fR
|
||||||
forward-char
|
\fBdeselect-all\fR
|
||||||
forward-word
|
\fBdown\fR \fIctrl-j ctrl-n down\fR
|
||||||
kill-line (not bound)
|
\fBend-of-line\fR \fIctrl-e end\fR
|
||||||
kill-word
|
\fBexecute(...)\fR (see below for the details)
|
||||||
page-down
|
\fBforward-char\fR \fIctrl-f right\fR
|
||||||
page-up
|
\fBforward-word\fR \fIalt-f shift-right\fR
|
||||||
toggle (not bound)
|
\fBignore\fR
|
||||||
toggle-down
|
\fBkill-line\fR
|
||||||
toggle-sort (not bound; equivalent to \fB--toggle-sort\fR)
|
\fBkill-word\fR \fIalt-d\fR
|
||||||
toggle-up
|
\fBnext-history\fR (\fIctrl-n\fR on \fB--history\fR)
|
||||||
unix-line-discard
|
\fBpage-down\fR \fIpgdn\fR
|
||||||
unix-word-rubout
|
\fBpage-up\fR \fIpgup\fR
|
||||||
up
|
\fBprevious-history\fR (\fIctrl-p\fR on \fB--history\fR)
|
||||||
yank
|
\fBselect-all\fR
|
||||||
|
\fBtoggle\fR
|
||||||
|
\fBtoggle-all\fR
|
||||||
|
\fBtoggle-down\fR \fIctrl-i (tab)\fR
|
||||||
|
\fBtoggle-sort\fR (equivalent to \fB--toggle-sort\fR)
|
||||||
|
\fBtoggle-up\fR \fIbtab (shift-tab)\fR
|
||||||
|
\fBunix-line-discard\fR \fIctrl-u\fR
|
||||||
|
\fBunix-word-rubout\fR \fIctrl-w\fR
|
||||||
|
\fBup\fR \fIctrl-k ctrl-p up\fR
|
||||||
|
\fByank\fR \fIctrl-y\fR
|
||||||
.RE
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
With \fBexecute(...)\fR action, you can execute arbitrary commands without
|
||||||
|
leaving fzf. For example, you can turn fzf into a simple file browser by
|
||||||
|
binding \fBenter\fR key to \fBless\fR command like follows.
|
||||||
|
|
||||||
|
.RS
|
||||||
|
\fBfzf --bind "enter:execute(less {})"\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
\fB{}\fR is the placeholder for the double-quoted string of the current line.
|
||||||
|
If the command contains parentheses, you can use any of the following
|
||||||
|
alternative notations to avoid parse errors.
|
||||||
|
|
||||||
|
\fBexecute[...]\fR
|
||||||
|
\fBexecute~...~\fR
|
||||||
|
\fBexecute!...!\fR
|
||||||
|
\fBexecute@...@\fR
|
||||||
|
\fBexecute#...#\fR
|
||||||
|
\fBexecute$...$\fR
|
||||||
|
\fBexecute%...%\fR
|
||||||
|
\fBexecute^...^\fR
|
||||||
|
\fBexecute&...&\fR
|
||||||
|
\fBexecute*...*\fR
|
||||||
|
\fBexecute;...;\fR
|
||||||
|
\fBexecute/.../\fR
|
||||||
|
\fBexecute|...|\fR
|
||||||
|
\fBexecute:...\fR
|
||||||
|
.RS
|
||||||
|
This is the special form that frees you from parse errors as it does not expect
|
||||||
|
the closing character. The catch is that it should be the last one in the
|
||||||
|
comma-separated list.
|
||||||
|
.RE
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.BI "--history=" "HISTORY_FILE"
|
||||||
|
Load search history from the specified file and update the file on completion.
|
||||||
|
When enabled, \fBCTRL-N\fR and \fBCTRL-P\fR are automatically remapped to
|
||||||
|
\fBnext-history\fR and \fBprevious-history\fR.
|
||||||
|
.TP
|
||||||
|
.BI "--history-size=" "N"
|
||||||
|
Maximum number of entries in the history file (default: 1000). The file is
|
||||||
|
automatically truncated when the number of the lines exceeds the value.
|
||||||
|
.TP
|
||||||
|
.BI "--header-file=" "FILE"
|
||||||
|
The content of the file will be printed as the sticky header. The lines in the
|
||||||
|
file are displayed in order from top to bottom regardless of \fB--reverse\fR,
|
||||||
|
and are not affected by \fB--with-nth\fR. ANSI color codes are processed even
|
||||||
|
when \fB--ansi\fR is not set.
|
||||||
|
.TP
|
||||||
|
.BI "--header-lines=" "N"
|
||||||
|
The first N lines of the input are treated as the sticky header. When
|
||||||
|
\fB--with-nth\fR is set, the lines are transformed just like the other
|
||||||
|
lines that follow.
|
||||||
.SS Scripting
|
.SS Scripting
|
||||||
.TP
|
.TP
|
||||||
.BI "-q, --query=" "STR"
|
.BI "-q, --query=" "STR"
|
||||||
@@ -202,10 +314,9 @@ fzf becomes a fuzzy-version of grep.
|
|||||||
Print query as the first line
|
Print query as the first line
|
||||||
.TP
|
.TP
|
||||||
.BI "--expect=" "KEY[,..]"
|
.BI "--expect=" "KEY[,..]"
|
||||||
Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
Comma-separated list of keys that can be used to complete fzf in addition to
|
||||||
or any single character) that can be used to complete fzf in addition to the
|
the default enter key. When this option is set, fzf will print the name of the
|
||||||
default enter key. When this option is set, fzf will print the name of the key
|
key pressed as the first line of its output (or as the second line if
|
||||||
pressed as the first line of its output (or as the second line if
|
|
||||||
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
||||||
with the default enter key.
|
with the default enter key.
|
||||||
.RS
|
.RS
|
||||||
@@ -225,7 +336,7 @@ e.g. \fBfzf --multi | fzf --sync\fR
|
|||||||
Default command to use when input is tty
|
Default command to use when input is tty
|
||||||
.TP
|
.TP
|
||||||
.B FZF_DEFAULT_OPTS
|
.B FZF_DEFAULT_OPTS
|
||||||
Default options. e.g. \fB--extended --ansi\fR
|
Default options. e.g. \fBexport FZF_DEFAULT_OPTS="--extended --cycle"\fR
|
||||||
|
|
||||||
.SH EXIT STATUS
|
.SH EXIT STATUS
|
||||||
.BR 0 " Normal exit"
|
.BR 0 " Normal exit"
|
||||||
@@ -235,7 +346,7 @@ Default options. e.g. \fB--extended --ansi\fR
|
|||||||
.SH FIELD INDEX EXPRESSION
|
.SH FIELD INDEX EXPRESSION
|
||||||
|
|
||||||
A field index expression can be a non-zero integer or a range expression
|
A field index expression can be a non-zero integer or a range expression
|
||||||
([BEGIN]..[END]). \fI--nth\fR and \fI--with-nth\fR take a comma-separated list
|
([BEGIN]..[END]). \fB--nth\fR and \fB--with-nth\fR take a comma-separated list
|
||||||
of field index expressions.
|
of field index expressions.
|
||||||
|
|
||||||
.SS Examples
|
.SS Examples
|
||||||
@@ -258,7 +369,7 @@ of field index expressions.
|
|||||||
|
|
||||||
.SH EXTENDED SEARCH MODE
|
.SH EXTENDED SEARCH MODE
|
||||||
|
|
||||||
With \fI-x\fR or \fI--extended\fR option, fzf will start in "extended-search
|
With \fB-x\fR or \fB--extended\fR option, fzf will start in "extended-search
|
||||||
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
||||||
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
||||||
|
|
||||||
@@ -278,8 +389,8 @@ from the result.
|
|||||||
|
|
||||||
.SS Extended-exact mode
|
.SS Extended-exact mode
|
||||||
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
||||||
with ') every word, start fzf with \fI-e\fR or \fI--extended-exact\fR option
|
with ') every word, start fzf with \fB-e\fR or \fB--extended-exact\fR option
|
||||||
(instead of \fI-x\fR or \fI--extended\fR).
|
(instead of \fB-x\fR or \fB--extended\fR).
|
||||||
|
|
||||||
.SH AUTHOR
|
.SH AUTHOR
|
||||||
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||||
|
@@ -54,13 +54,17 @@ function! s:fzf_exec()
|
|||||||
return s:exec
|
return s:exec
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:tmux_not_zoomed()
|
||||||
|
return system('tmux list-panes -F "#F"') !~# 'Z'
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_enabled()
|
function! s:tmux_enabled()
|
||||||
if has('gui_running')
|
if has('gui_running')
|
||||||
return 0
|
return 0
|
||||||
endif
|
endif
|
||||||
|
|
||||||
if exists('s:tmux')
|
if exists('s:tmux')
|
||||||
return s:tmux
|
return s:tmux && s:tmux_not_zoomed()
|
||||||
endif
|
endif
|
||||||
|
|
||||||
let s:tmux = 0
|
let s:tmux = 0
|
||||||
@@ -68,7 +72,7 @@ function! s:tmux_enabled()
|
|||||||
let output = system('tmux -V')
|
let output = system('tmux -V')
|
||||||
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
||||||
endif
|
endif
|
||||||
return s:tmux
|
return s:tmux && s:tmux_not_zoomed()
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:shellesc(arg)
|
function! s:shellesc(arg)
|
||||||
@@ -98,7 +102,7 @@ function! fzf#run(...) abort
|
|||||||
try
|
try
|
||||||
let oshell = &shell
|
let oshell = &shell
|
||||||
set shell=sh
|
set shell=sh
|
||||||
if has('nvim') && bufexists('[FZF]')
|
if has('nvim') && bufexists('term://*:FZF')
|
||||||
echohl WarningMsg
|
echohl WarningMsg
|
||||||
echomsg 'FZF is already running!'
|
echomsg 'FZF is already running!'
|
||||||
echohl None
|
echohl None
|
||||||
@@ -248,13 +252,17 @@ function! s:calc_size(max, val)
|
|||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:getpos()
|
||||||
|
return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$')}
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! s:split(dict)
|
function! s:split(dict)
|
||||||
let directions = {
|
let directions = {
|
||||||
\ 'up': ['topleft', 'resize', &lines],
|
\ 'up': ['topleft', 'resize', &lines],
|
||||||
\ 'down': ['botright', 'resize', &lines],
|
\ 'down': ['botright', 'resize', &lines],
|
||||||
\ 'left': ['vertical topleft', 'vertical resize', &columns],
|
\ 'left': ['vertical topleft', 'vertical resize', &columns],
|
||||||
\ 'right': ['vertical botright', 'vertical resize', &columns] }
|
\ 'right': ['vertical botright', 'vertical resize', &columns] }
|
||||||
let s:ptab = tabpagenr()
|
let s:ppos = s:getpos()
|
||||||
try
|
try
|
||||||
for [dir, triple] in items(directions)
|
for [dir, triple] in items(directions)
|
||||||
let val = get(a:dict, dir, '')
|
let val = get(a:dict, dir, '')
|
||||||
@@ -280,32 +288,38 @@ function! s:execute_term(dict, command, temps)
|
|||||||
call s:split(a:dict)
|
call s:split(a:dict)
|
||||||
call s:pushd(a:dict)
|
call s:pushd(a:dict)
|
||||||
|
|
||||||
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps }
|
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps, 'name': 'FZF' }
|
||||||
function! fzf.on_exit(id, code)
|
function! fzf.on_exit(id, code)
|
||||||
let tab = tabpagenr()
|
let pos = s:getpos()
|
||||||
if bufnr('') == self.buf
|
let inplace = pos == s:ppos " {'window': 'enew'}
|
||||||
" We use close instead of bd! since Vim does not close the split when
|
if !inplace
|
||||||
" there's no other listed buffer
|
if bufnr('') == self.buf
|
||||||
close
|
" We use close instead of bd! since Vim does not close the split when
|
||||||
" FIXME This should be unnecessary due to `bufhidden=wipe` but in some
|
" there's no other listed buffer (nvim +'set nobuflisted')
|
||||||
" cases Neovim fails to clean up the buffer and `bufexists('[FZF]')
|
close
|
||||||
" returns 1 even when it cannot be seen anywhere else. e.g. `FZF!`
|
endif
|
||||||
silent! execute 'bd!' self.buf
|
if pos.tab == s:ppos.tab
|
||||||
endif
|
wincmd p
|
||||||
if s:ptab == tab
|
endif
|
||||||
wincmd p
|
|
||||||
endif
|
endif
|
||||||
call s:pushd(self.dict)
|
call s:pushd(self.dict)
|
||||||
try
|
try
|
||||||
redraw!
|
redraw!
|
||||||
call s:callback(self.dict, self.temps)
|
call s:callback(self.dict, self.temps)
|
||||||
|
|
||||||
|
if inplace && bufnr('') == self.buf
|
||||||
|
execute "normal! \<c-^>"
|
||||||
|
" No other listed buffer
|
||||||
|
if bufnr('') == self.buf
|
||||||
|
bd!
|
||||||
|
endif
|
||||||
|
endif
|
||||||
finally
|
finally
|
||||||
call s:popd(self.dict)
|
call s:popd(self.dict)
|
||||||
endtry
|
endtry
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
call termopen(a:command, fzf)
|
call termopen(a:command, fzf)
|
||||||
silent file [FZF]
|
|
||||||
startinsert
|
startinsert
|
||||||
return []
|
return []
|
||||||
endfunction
|
endfunction
|
||||||
@@ -354,9 +368,15 @@ function! s:cmd_callback(lines) abort
|
|||||||
endif
|
endif
|
||||||
let key = remove(a:lines, 0)
|
let key = remove(a:lines, 0)
|
||||||
let cmd = get(s:action, key, 'e')
|
let cmd = get(s:action, key, 'e')
|
||||||
for item in a:lines
|
try
|
||||||
execute cmd s:escape(item)
|
let autochdir = &autochdir
|
||||||
endfor
|
set noautochdir
|
||||||
|
for item in a:lines
|
||||||
|
execute cmd s:escape(item)
|
||||||
|
endfor
|
||||||
|
finally
|
||||||
|
let &autochdir = autochdir
|
||||||
|
endtry
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:cmd(bang, ...) abort
|
function! s:cmd(bang, ...) abort
|
||||||
|
@@ -45,7 +45,13 @@ _fzf_opts_completion() {
|
|||||||
--print-query
|
--print-query
|
||||||
--expect
|
--expect
|
||||||
--toggle-sort
|
--toggle-sort
|
||||||
--sync"
|
--sync
|
||||||
|
--cycle
|
||||||
|
--history
|
||||||
|
--history-size
|
||||||
|
--header-file
|
||||||
|
--header-lines
|
||||||
|
--margin"
|
||||||
|
|
||||||
case "${prev}" in
|
case "${prev}" in
|
||||||
--tiebreak)
|
--tiebreak)
|
||||||
@@ -56,6 +62,10 @@ _fzf_opts_completion() {
|
|||||||
COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )
|
COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )
|
||||||
return 0
|
return 0
|
||||||
;;
|
;;
|
||||||
|
--history|--header-file)
|
||||||
|
COMPREPLY=()
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
if [[ ${cur} =~ ^-|\+ ]]; then
|
||||||
@@ -67,9 +77,10 @@ _fzf_opts_completion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_handle_dynamic_completion() {
|
_fzf_handle_dynamic_completion() {
|
||||||
local cmd orig ret
|
local cmd orig ret orig_cmd
|
||||||
cmd="$1"
|
cmd="$1"
|
||||||
shift
|
shift
|
||||||
|
orig_cmd="$1"
|
||||||
|
|
||||||
orig=$(eval "echo \$_fzf_orig_completion_$cmd")
|
orig=$(eval "echo \$_fzf_orig_completion_$cmd")
|
||||||
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
||||||
@@ -77,7 +88,7 @@ _fzf_handle_dynamic_completion() {
|
|||||||
elif [ -n "$_fzf_completion_loader" ]; then
|
elif [ -n "$_fzf_completion_loader" ]; then
|
||||||
_completion_loader "$@"
|
_completion_loader "$@"
|
||||||
ret=$?
|
ret=$?
|
||||||
eval $(complete | \grep "\-F.* $cmd$" | _fzf_orig_completion_filter)
|
eval $(complete | \grep "\-F.* $orig_cmd$" | _fzf_orig_completion_filter)
|
||||||
source $BASH_SOURCE
|
source $BASH_SOURCE
|
||||||
return $ret
|
return $ret
|
||||||
fi
|
fi
|
||||||
@@ -207,7 +218,7 @@ EOF
|
|||||||
}
|
}
|
||||||
|
|
||||||
# fzf options
|
# fzf options
|
||||||
complete -F _fzf_opts_completion fzf
|
complete -o default -F _fzf_opts_completion fzf
|
||||||
|
|
||||||
d_cmds="cd pushd rmdir"
|
d_cmds="cd pushd rmdir"
|
||||||
f_cmds="
|
f_cmds="
|
||||||
|
@@ -1,10 +1,11 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
__fzf_select__() {
|
__fzf_select__() {
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command \\find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | fzf -m | while read item; do
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
|
eval "$cmd" | fzf -m | while read item; do
|
||||||
printf '%q ' "$item"
|
printf '%q ' "$item"
|
||||||
done
|
done
|
||||||
echo
|
echo
|
||||||
@@ -24,22 +25,28 @@ __fzf_select_tmux__() {
|
|||||||
else
|
else
|
||||||
height="-l $height"
|
height="-l $height"
|
||||||
fi
|
fi
|
||||||
tmux split-window $height "cd $(printf %q "$PWD");bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
tmux split-window $height "cd $(printf %q "$PWD"); FZF_CTRL_T_COMMAND=$(printf %q "$FZF_CTRL_T_COMMAND") bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||||
}
|
}
|
||||||
|
|
||||||
__fzf_cd__() {
|
__fzf_cd__() {
|
||||||
local dir
|
local dir
|
||||||
dir=$(command find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
dir=$(command \find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||||
}
|
}
|
||||||
|
|
||||||
__fzf_history__() {
|
__fzf_history__() (
|
||||||
local line
|
local line
|
||||||
|
shopt -u nocaseglob nocasematch
|
||||||
line=$(
|
line=$(
|
||||||
HISTTIMEFORMAT= history |
|
HISTTIMEFORMAT= history |
|
||||||
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r |
|
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r |
|
||||||
\grep '^ *[0-9]') && sed 's/ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
\grep '^ *[0-9]') &&
|
||||||
}
|
if [[ $- =~ H ]]; then
|
||||||
|
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||||
|
else
|
||||||
|
sed 's/^ *\([0-9]*\)\** *//' <<< "$line"
|
||||||
|
fi
|
||||||
|
)
|
||||||
|
|
||||||
__use_tmux=0
|
__use_tmux=0
|
||||||
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
||||||
|
@@ -14,10 +14,12 @@ function fzf_key_bindings
|
|||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_ctrl_t
|
function __fzf_ctrl_t
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
set -q FZF_CTRL_T_COMMAND; or set -l FZF_CTRL_T_COMMAND "
|
||||||
|
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) -m > $TMPDIR/fzf.result
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"
|
||||||
|
eval $FZF_CTRL_T_COMMAND | eval (__fzfcmd) -m > $TMPDIR/fzf.result
|
||||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
rm -f $TMPDIR/fzf.result
|
rm -f $TMPDIR/fzf.result
|
||||||
|
@@ -1,11 +1,14 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
# CTRL-T - Paste the selected file path(s) into the command line
|
# CTRL-T - Paste the selected file path(s) into the command line
|
||||||
__fsel() {
|
__fsel() {
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command \\find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) -m | while read item; do
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
|
eval "$cmd" | $(__fzfcmd) -m | while read item; do
|
||||||
printf '%q ' "$item"
|
printf '%q ' "$item"
|
||||||
done
|
done
|
||||||
echo
|
echo
|
||||||
@@ -15,8 +18,6 @@ __fzfcmd() {
|
|||||||
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||||
}
|
}
|
||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
|
||||||
|
|
||||||
fzf-file-widget() {
|
fzf-file-widget() {
|
||||||
LBUFFER="${LBUFFER}$(__fsel)"
|
LBUFFER="${LBUFFER}$(__fsel)"
|
||||||
zle redisplay
|
zle redisplay
|
||||||
@@ -26,7 +27,7 @@ bindkey '^T' fzf-file-widget
|
|||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
# ALT-C - cd into the selected directory
|
||||||
fzf-cd-widget() {
|
fzf-cd-widget() {
|
||||||
cd "${$(command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
cd "${$(command \find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m):-.}"
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m):-.}"
|
||||||
zle reset-prompt
|
zle reset-prompt
|
||||||
}
|
}
|
||||||
@@ -36,16 +37,10 @@ bindkey '\ec' fzf-cd-widget
|
|||||||
# CTRL-R - Paste the selected command from history into the command line
|
# CTRL-R - Paste the selected command from history into the command line
|
||||||
fzf-history-widget() {
|
fzf-history-widget() {
|
||||||
local selected restore_no_bang_hist
|
local selected restore_no_bang_hist
|
||||||
if selected=$(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r -q "$LBUFFER"); then
|
if selected=( $(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r -q "$LBUFFER") ); then
|
||||||
num=$(echo "$selected" | head -n1 | awk '{print $1}' | sed 's/[^0-9]//g')
|
num=$selected[1]
|
||||||
if [ -n "$num" ]; then
|
if [ -n "$num" ]; then
|
||||||
LBUFFER=!$num
|
zle vi-fetch-history -n $num
|
||||||
if setopt | grep nobanghist > /dev/null; then
|
|
||||||
restore_no_bang_hist=1
|
|
||||||
unsetopt no_bang_hist
|
|
||||||
fi
|
|
||||||
zle expand-history
|
|
||||||
[ -n "$restore_no_bang_hist" ] && setopt no_bang_hist
|
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
zle redisplay
|
zle redisplay
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package algo
|
package algo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
@@ -15,7 +16,7 @@ import (
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// FuzzyMatch performs fuzzy-match
|
// FuzzyMatch performs fuzzy-match
|
||||||
func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
@@ -33,7 +34,7 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
|||||||
sidx := -1
|
sidx := -1
|
||||||
eidx := -1
|
eidx := -1
|
||||||
|
|
||||||
for index, char := range *runes {
|
for index, char := range runes {
|
||||||
// This is considerably faster than blindly applying strings.ToLower to the
|
// This is considerably faster than blindly applying strings.ToLower to the
|
||||||
// whole string
|
// whole string
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
@@ -60,7 +61,7 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
|||||||
if sidx >= 0 && eidx >= 0 {
|
if sidx >= 0 && eidx >= 0 {
|
||||||
pidx--
|
pidx--
|
||||||
for index := eidx - 1; index >= sidx; index-- {
|
for index := eidx - 1; index >= sidx; index-- {
|
||||||
char := (*runes)[index]
|
char := runes[index]
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
if char >= 'A' && char <= 'Z' {
|
if char >= 'A' && char <= 'Z' {
|
||||||
char += 32
|
char += 32
|
||||||
@@ -87,12 +88,12 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
|||||||
//
|
//
|
||||||
// We might try to implement better algorithms in the future:
|
// We might try to implement better algorithms in the future:
|
||||||
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
||||||
func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
func ExactMatchNaive(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
numRunes := len(*runes)
|
numRunes := len(runes)
|
||||||
plen := len(pattern)
|
plen := len(pattern)
|
||||||
if numRunes < plen {
|
if numRunes < plen {
|
||||||
return -1, -1
|
return -1, -1
|
||||||
@@ -100,7 +101,7 @@ func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, in
|
|||||||
|
|
||||||
pidx := 0
|
pidx := 0
|
||||||
for index := 0; index < numRunes; index++ {
|
for index := 0; index < numRunes; index++ {
|
||||||
char := (*runes)[index]
|
char := runes[index]
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
if char >= 'A' && char <= 'Z' {
|
if char >= 'A' && char <= 'Z' {
|
||||||
char += 32
|
char += 32
|
||||||
@@ -122,13 +123,13 @@ func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, in
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PrefixMatch performs prefix-match
|
// PrefixMatch performs prefix-match
|
||||||
func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
func PrefixMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||||
if len(*runes) < len(pattern) {
|
if len(runes) < len(pattern) {
|
||||||
return -1, -1
|
return -1, -1
|
||||||
}
|
}
|
||||||
|
|
||||||
for index, r := range pattern {
|
for index, r := range pattern {
|
||||||
char := (*runes)[index]
|
char := runes[index]
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
char = unicode.ToLower(char)
|
char = unicode.ToLower(char)
|
||||||
}
|
}
|
||||||
@@ -140,7 +141,7 @@ func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SuffixMatch performs suffix-match
|
// SuffixMatch performs suffix-match
|
||||||
func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {
|
func SuffixMatch(caseSensitive bool, input []rune, pattern []rune) (int, int) {
|
||||||
runes := util.TrimRight(input)
|
runes := util.TrimRight(input)
|
||||||
trimmedLen := len(runes)
|
trimmedLen := len(runes)
|
||||||
diff := trimmedLen - len(pattern)
|
diff := trimmedLen - len(pattern)
|
||||||
@@ -159,3 +160,18 @@ func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {
|
|||||||
}
|
}
|
||||||
return trimmedLen - len(pattern), trimmedLen
|
return trimmedLen - len(pattern), trimmedLen
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EqualMatch performs equal-match
|
||||||
|
func EqualMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||||
|
if len(runes) != len(pattern) {
|
||||||
|
return -1, -1
|
||||||
|
}
|
||||||
|
runesStr := string(runes)
|
||||||
|
if !caseSensitive {
|
||||||
|
runesStr = strings.ToLower(runesStr)
|
||||||
|
}
|
||||||
|
if runesStr == string(pattern) {
|
||||||
|
return 0, len(pattern)
|
||||||
|
}
|
||||||
|
return -1, -1
|
||||||
|
}
|
||||||
|
@@ -5,12 +5,11 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {
|
func assertMatch(t *testing.T, fun func(bool, []rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
pattern = strings.ToLower(pattern)
|
pattern = strings.ToLower(pattern)
|
||||||
}
|
}
|
||||||
runes := []rune(input)
|
s, e := fun(caseSensitive, []rune(input), []rune(pattern))
|
||||||
s, e := fun(caseSensitive, &runes, []rune(pattern))
|
|
||||||
if s != sidx {
|
if s != sidx {
|
||||||
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
||||||
}
|
}
|
||||||
|
19
src/ansi.go
19
src/ansi.go
@@ -36,16 +36,18 @@ func init() {
|
|||||||
ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")
|
ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractColor(str *string) (*string, []ansiOffset) {
|
func extractColor(str string, state *ansiState) (string, []ansiOffset, *ansiState) {
|
||||||
var offsets []ansiOffset
|
var offsets []ansiOffset
|
||||||
|
|
||||||
var output bytes.Buffer
|
var output bytes.Buffer
|
||||||
var state *ansiState
|
|
||||||
|
if state != nil {
|
||||||
|
offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})
|
||||||
|
}
|
||||||
|
|
||||||
idx := 0
|
idx := 0
|
||||||
for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {
|
for _, offset := range ansiRegex.FindAllStringIndex(str, -1) {
|
||||||
output.WriteString((*str)[idx:offset[0]])
|
output.WriteString(str[idx:offset[0]])
|
||||||
newState := interpretCode((*str)[offset[0]:offset[1]], state)
|
newState := interpretCode(str[offset[0]:offset[1]], state)
|
||||||
|
|
||||||
if !newState.equals(state) {
|
if !newState.equals(state) {
|
||||||
if state != nil {
|
if state != nil {
|
||||||
@@ -67,7 +69,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
|||||||
idx = offset[1]
|
idx = offset[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
rest := (*str)[idx:]
|
rest := str[idx:]
|
||||||
if len(rest) > 0 {
|
if len(rest) > 0 {
|
||||||
output.WriteString(rest)
|
output.WriteString(rest)
|
||||||
if state != nil {
|
if state != nil {
|
||||||
@@ -75,8 +77,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
|||||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outputStr := output.String()
|
return output.String(), offsets, state
|
||||||
return &outputStr, offsets
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
||||||
|
@@ -14,79 +14,89 @@ func TestExtractColor(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
src := "hello world"
|
src := "hello world"
|
||||||
|
var state *ansiState
|
||||||
clean := "\x1b[0m"
|
clean := "\x1b[0m"
|
||||||
check := func(assertion func(ansiOffsets []ansiOffset)) {
|
check := func(assertion func(ansiOffsets []ansiOffset, state *ansiState)) {
|
||||||
output, ansiOffsets := extractColor(&src)
|
output, ansiOffsets, newState := extractColor(src, state)
|
||||||
if *output != "hello world" {
|
state = newState
|
||||||
|
if output != "hello world" {
|
||||||
t.Errorf("Invalid output: {}", output)
|
t.Errorf("Invalid output: {}", output)
|
||||||
}
|
}
|
||||||
fmt.Println(src, ansiOffsets, clean)
|
fmt.Println(src, ansiOffsets, clean)
|
||||||
assertion(ansiOffsets)
|
assertion(ansiOffsets, state)
|
||||||
}
|
}
|
||||||
|
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) > 0 {
|
if len(offsets) > 0 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[0mhello world"
|
src = "\x1b[0mhello world"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) > 0 {
|
if len(offsets) > 0 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello world"
|
src = "\x1b[1mhello world"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 11, -1, -1, true)
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello \x1b[mworld"
|
src = "\x1b[1mhello \x1b[mworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 6, -1, -1, true)
|
assert(offsets[0], 0, 6, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello \x1b[Kworld"
|
src = "\x1b[1mhello \x1b[Kworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 11, -1, -1, true)
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mworld"
|
src = "hello \x1b[34;45;1mworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 11, 4, 5, true)
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 11, 4, 5, true)
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 9, 4, 5, true)
|
assert(offsets[0], 6, 9, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
|
src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 3 {
|
if len(offsets) != 3 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
@@ -96,12 +106,47 @@ func TestExtractColor(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// {38,48};5;{38,48}
|
// {38,48};5;{38,48}
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
|
src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 2 {
|
if len(offsets) != 2 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 9, 38, 48, true)
|
assert(offsets[0], 6, 9, 38, 48, true)
|
||||||
assert(offsets[1], 9, 10, 48, 38, true)
|
assert(offsets[1], 9, 10, 48, 38, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[32;1mworld"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 11, 2, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello world"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 11, 2, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[0;38;5;200;48;5;100mworld"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 2 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 200 || state.bg != 100 || state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 6, 2, -1, true)
|
||||||
|
assert(offsets[1], 6, 11, 200, 100, false)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
@@ -7,7 +7,7 @@ type Chunk []*Item // >>> []Item
|
|||||||
|
|
||||||
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
||||||
// string and an integer
|
// string and an integer
|
||||||
type ItemBuilder func(*string, int) *Item
|
type ItemBuilder func([]byte, int) *Item
|
||||||
|
|
||||||
// ChunkList is a list of Chunks
|
// ChunkList is a list of Chunks
|
||||||
type ChunkList struct {
|
type ChunkList struct {
|
||||||
@@ -26,8 +26,13 @@ func NewChunkList(trans ItemBuilder) *ChunkList {
|
|||||||
trans: trans}
|
trans: trans}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Chunk) push(trans ItemBuilder, data *string, index int) {
|
func (c *Chunk) push(trans ItemBuilder, data []byte, index int) bool {
|
||||||
*c = append(*c, trans(data, index))
|
item := trans(data, index)
|
||||||
|
if item != nil {
|
||||||
|
*c = append(*c, item)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsFull returns true if the Chunk is full
|
// IsFull returns true if the Chunk is full
|
||||||
@@ -48,7 +53,7 @@ func CountItems(cs []*Chunk) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Push adds the item to the list
|
// Push adds the item to the list
|
||||||
func (cl *ChunkList) Push(data string) {
|
func (cl *ChunkList) Push(data []byte) bool {
|
||||||
cl.mutex.Lock()
|
cl.mutex.Lock()
|
||||||
defer cl.mutex.Unlock()
|
defer cl.mutex.Unlock()
|
||||||
|
|
||||||
@@ -57,8 +62,11 @@ func (cl *ChunkList) Push(data string) {
|
|||||||
cl.chunks = append(cl.chunks, &newChunk)
|
cl.chunks = append(cl.chunks, &newChunk)
|
||||||
}
|
}
|
||||||
|
|
||||||
cl.lastChunk().push(cl.trans, &data, cl.count)
|
if cl.lastChunk().push(cl.trans, data, cl.count) {
|
||||||
cl.count++
|
cl.count++
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot returns immutable snapshot of the ChunkList
|
// Snapshot returns immutable snapshot of the ChunkList
|
||||||
|
@@ -6,8 +6,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestChunkList(t *testing.T) {
|
func TestChunkList(t *testing.T) {
|
||||||
cl := NewChunkList(func(s *string, i int) *Item {
|
cl := NewChunkList(func(s []byte, i int) *Item {
|
||||||
return &Item{text: s, rank: Rank{0, 0, uint32(i * 2)}}
|
return &Item{text: []rune(string(s)), rank: Rank{0, 0, uint32(i * 2)}}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Snapshot
|
// Snapshot
|
||||||
@@ -17,8 +17,8 @@ func TestChunkList(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add some data
|
// Add some data
|
||||||
cl.Push("hello")
|
cl.Push([]byte("hello"))
|
||||||
cl.Push("world")
|
cl.Push([]byte("world"))
|
||||||
|
|
||||||
// Previously created snapshot should remain the same
|
// Previously created snapshot should remain the same
|
||||||
if len(snapshot) > 0 {
|
if len(snapshot) > 0 {
|
||||||
@@ -36,8 +36,8 @@ func TestChunkList(t *testing.T) {
|
|||||||
if len(*chunk1) != 2 {
|
if len(*chunk1) != 2 {
|
||||||
t.Error("Snapshot should contain only two items")
|
t.Error("Snapshot should contain only two items")
|
||||||
}
|
}
|
||||||
if *(*chunk1)[0].text != "hello" || (*chunk1)[0].rank.index != 0 ||
|
if string((*chunk1)[0].text) != "hello" || (*chunk1)[0].rank.index != 0 ||
|
||||||
*(*chunk1)[1].text != "world" || (*chunk1)[1].rank.index != 2 {
|
string((*chunk1)[1].text) != "world" || (*chunk1)[1].rank.index != 2 {
|
||||||
t.Error("Invalid data")
|
t.Error("Invalid data")
|
||||||
}
|
}
|
||||||
if chunk1.IsFull() {
|
if chunk1.IsFull() {
|
||||||
@@ -46,7 +46,7 @@ func TestChunkList(t *testing.T) {
|
|||||||
|
|
||||||
// Add more data
|
// Add more data
|
||||||
for i := 0; i < chunkSize*2; i++ {
|
for i := 0; i < chunkSize*2; i++ {
|
||||||
cl.Push(fmt.Sprintf("item %d", i))
|
cl.Push([]byte(fmt.Sprintf("item %d", i)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Previous snapshot should remain the same
|
// Previous snapshot should remain the same
|
||||||
@@ -64,8 +64,8 @@ func TestChunkList(t *testing.T) {
|
|||||||
t.Error("Unexpected number of items")
|
t.Error("Unexpected number of items")
|
||||||
}
|
}
|
||||||
|
|
||||||
cl.Push("hello")
|
cl.Push([]byte("hello"))
|
||||||
cl.Push("world")
|
cl.Push([]byte("world"))
|
||||||
|
|
||||||
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
||||||
if lastChunkCount != 2 {
|
if lastChunkCount != 2 {
|
||||||
|
@@ -8,14 +8,14 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
// Current version
|
// Current version
|
||||||
Version = "0.9.13"
|
version = "0.10.2"
|
||||||
|
|
||||||
// Core
|
// Core
|
||||||
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
||||||
coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
||||||
|
|
||||||
// Reader
|
// Reader
|
||||||
defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`
|
defaultCommand = `find . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
|
||||||
|
|
||||||
// Terminal
|
// Terminal
|
||||||
initialDelay = 100 * time.Millisecond
|
initialDelay = 100 * time.Millisecond
|
||||||
@@ -32,6 +32,9 @@ const (
|
|||||||
|
|
||||||
// Not to cache mergers with large lists
|
// Not to cache mergers with large lists
|
||||||
mergerCacheMax int = 100000
|
mergerCacheMax int = 100000
|
||||||
|
|
||||||
|
// History
|
||||||
|
defaultHistoryMax int = 1000
|
||||||
)
|
)
|
||||||
|
|
||||||
// fzf events
|
// fzf events
|
||||||
@@ -41,5 +44,6 @@ const (
|
|||||||
EvtSearchNew
|
EvtSearchNew
|
||||||
EvtSearchProgress
|
EvtSearchProgress
|
||||||
EvtSearchFin
|
EvtSearchFin
|
||||||
|
EvtHeader
|
||||||
EvtClose
|
EvtClose
|
||||||
)
|
)
|
||||||
|
69
src/core.go
69
src/core.go
@@ -44,6 +44,7 @@ Reader -> EvtReadNew -> Matcher (restart)
|
|||||||
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
||||||
Matcher -> EvtSearchProgress -> Terminal (update info)
|
Matcher -> EvtSearchProgress -> Terminal (update info)
|
||||||
Matcher -> EvtSearchFin -> Terminal (update list)
|
Matcher -> EvtSearchFin -> Terminal (update list)
|
||||||
|
Matcher -> EvtHeader -> Terminal (update header)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Run starts fzf
|
// Run starts fzf
|
||||||
@@ -54,7 +55,7 @@ func Run(opts *Options) {
|
|||||||
rankTiebreak = opts.Tiebreak
|
rankTiebreak = opts.Tiebreak
|
||||||
|
|
||||||
if opts.Version {
|
if opts.Version {
|
||||||
fmt.Println(Version)
|
fmt.Println(version)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,48 +63,68 @@ func Run(opts *Options) {
|
|||||||
eventBox := util.NewEventBox()
|
eventBox := util.NewEventBox()
|
||||||
|
|
||||||
// ANSI code processor
|
// ANSI code processor
|
||||||
ansiProcessor := func(data *string) (*string, []ansiOffset) {
|
ansiProcessor := func(data []byte) ([]rune, []ansiOffset) {
|
||||||
// By default, we do nothing
|
return util.BytesToRunes(data), nil
|
||||||
|
}
|
||||||
|
ansiProcessorRunes := func(data []rune) ([]rune, []ansiOffset) {
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
if opts.Ansi {
|
if opts.Ansi {
|
||||||
if opts.Theme != nil {
|
if opts.Theme != nil {
|
||||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
var state *ansiState
|
||||||
return extractColor(data)
|
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||||
|
trimmed, offsets, newState := extractColor(string(data), state)
|
||||||
|
state = newState
|
||||||
|
return []rune(trimmed), offsets
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// When color is disabled but ansi option is given,
|
// When color is disabled but ansi option is given,
|
||||||
// we simply strip out ANSI codes from the input
|
// we simply strip out ANSI codes from the input
|
||||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||||
trimmed, _ := extractColor(data)
|
trimmed, _, _ := extractColor(string(data), nil)
|
||||||
return trimmed, nil
|
return []rune(trimmed), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ansiProcessorRunes = func(data []rune) ([]rune, []ansiOffset) {
|
||||||
|
return ansiProcessor([]byte(string(data)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chunk list
|
// Chunk list
|
||||||
var chunkList *ChunkList
|
var chunkList *ChunkList
|
||||||
|
header := make([]string, 0, opts.HeaderLines)
|
||||||
if len(opts.WithNth) == 0 {
|
if len(opts.WithNth) == 0 {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||||
data, colors := ansiProcessor(data)
|
if len(header) < opts.HeaderLines {
|
||||||
|
header = append(header, string(data))
|
||||||
|
eventBox.Set(EvtHeader, header)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
runes, colors := ansiProcessor(data)
|
||||||
return &Item{
|
return &Item{
|
||||||
text: data,
|
text: runes,
|
||||||
index: uint32(index),
|
index: uint32(index),
|
||||||
colors: colors,
|
colors: colors,
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
rank: Rank{0, 0, uint32(index)}}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||||
tokens := Tokenize(data, opts.Delimiter)
|
runes := util.BytesToRunes(data)
|
||||||
|
tokens := Tokenize(runes, opts.Delimiter)
|
||||||
trans := Transform(tokens, opts.WithNth)
|
trans := Transform(tokens, opts.WithNth)
|
||||||
|
if len(header) < opts.HeaderLines {
|
||||||
|
header = append(header, string(joinTokens(trans)))
|
||||||
|
eventBox.Set(EvtHeader, header)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
item := Item{
|
item := Item{
|
||||||
text: joinTokens(trans),
|
text: joinTokens(trans),
|
||||||
origText: data,
|
origText: &runes,
|
||||||
index: uint32(index),
|
index: uint32(index),
|
||||||
colors: nil,
|
colors: nil,
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
rank: Rank{0, 0, uint32(index)}}
|
||||||
|
|
||||||
trimmed, colors := ansiProcessor(item.text)
|
trimmed, colors := ansiProcessorRunes(item.text)
|
||||||
item.text = trimmed
|
item.text = trimmed
|
||||||
item.colors = colors
|
item.colors = colors
|
||||||
return &item
|
return &item
|
||||||
@@ -113,7 +134,9 @@ func Run(opts *Options) {
|
|||||||
// Reader
|
// Reader
|
||||||
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
||||||
if !streamingFilter {
|
if !streamingFilter {
|
||||||
reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}
|
reader := Reader{func(data []byte) bool {
|
||||||
|
return chunkList.Push(data)
|
||||||
|
}, eventBox, opts.ReadZero}
|
||||||
go reader.ReadSource()
|
go reader.ReadSource()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,12 +157,13 @@ func Run(opts *Options) {
|
|||||||
|
|
||||||
if streamingFilter {
|
if streamingFilter {
|
||||||
reader := Reader{
|
reader := Reader{
|
||||||
func(str string) {
|
func(runes []byte) bool {
|
||||||
item := chunkList.trans(&str, 0)
|
item := chunkList.trans(runes, 0)
|
||||||
if pattern.MatchItem(item) {
|
if item != nil && pattern.MatchItem(item) {
|
||||||
fmt.Println(*item.text)
|
fmt.Println(string(item.text))
|
||||||
}
|
}
|
||||||
}, eventBox}
|
return false
|
||||||
|
}, eventBox, opts.ReadZero}
|
||||||
reader.ReadSource()
|
reader.ReadSource()
|
||||||
} else {
|
} else {
|
||||||
eventBox.Unwatch(EvtReadNew)
|
eventBox.Unwatch(EvtReadNew)
|
||||||
@@ -206,6 +230,9 @@ func Run(opts *Options) {
|
|||||||
terminal.UpdateProgress(val)
|
terminal.UpdateProgress(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case EvtHeader:
|
||||||
|
terminal.UpdateHeader(value.([]string), opts.HeaderLines)
|
||||||
|
|
||||||
case EvtSearchFin:
|
case EvtSearchFin:
|
||||||
switch val := value.(type) {
|
switch val := value.(type) {
|
||||||
case *Merger:
|
case *Merger:
|
||||||
|
@@ -4,15 +4,11 @@ package curses
|
|||||||
#include <ncurses.h>
|
#include <ncurses.h>
|
||||||
#include <locale.h>
|
#include <locale.h>
|
||||||
#cgo LDFLAGS: -lncurses
|
#cgo LDFLAGS: -lncurses
|
||||||
void swapOutput() {
|
|
||||||
FILE* temp = stdout;
|
|
||||||
stdout = stderr;
|
|
||||||
stderr = temp;
|
|
||||||
}
|
|
||||||
*/
|
*/
|
||||||
import "C"
|
import "C"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"syscall"
|
"syscall"
|
||||||
@@ -56,6 +52,7 @@ const (
|
|||||||
Mouse
|
Mouse
|
||||||
|
|
||||||
BTab
|
BTab
|
||||||
|
BSpace
|
||||||
|
|
||||||
Del
|
Del
|
||||||
PgUp
|
PgUp
|
||||||
@@ -98,6 +95,7 @@ const (
|
|||||||
ColInfo
|
ColInfo
|
||||||
ColCursor
|
ColCursor
|
||||||
ColSelected
|
ColSelected
|
||||||
|
ColHeader
|
||||||
ColUser
|
ColUser
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -118,6 +116,7 @@ type ColorTheme struct {
|
|||||||
Info int16
|
Info int16
|
||||||
Cursor int16
|
Cursor int16
|
||||||
Selected int16
|
Selected int16
|
||||||
|
Header int16
|
||||||
}
|
}
|
||||||
|
|
||||||
type Event struct {
|
type Event struct {
|
||||||
@@ -142,6 +141,7 @@ var (
|
|||||||
_colorMap map[int]int
|
_colorMap map[int]int
|
||||||
_prevDownTime time.Time
|
_prevDownTime time.Time
|
||||||
_clickY []int
|
_clickY []int
|
||||||
|
_screen *C.SCREEN
|
||||||
Default16 *ColorTheme
|
Default16 *ColorTheme
|
||||||
Dark256 *ColorTheme
|
Dark256 *ColorTheme
|
||||||
Light256 *ColorTheme
|
Light256 *ColorTheme
|
||||||
@@ -167,7 +167,8 @@ func init() {
|
|||||||
Spinner: C.COLOR_GREEN,
|
Spinner: C.COLOR_GREEN,
|
||||||
Info: C.COLOR_WHITE,
|
Info: C.COLOR_WHITE,
|
||||||
Cursor: C.COLOR_RED,
|
Cursor: C.COLOR_RED,
|
||||||
Selected: C.COLOR_MAGENTA}
|
Selected: C.COLOR_MAGENTA,
|
||||||
|
Header: C.COLOR_CYAN}
|
||||||
Dark256 = &ColorTheme{
|
Dark256 = &ColorTheme{
|
||||||
UseDefault: true,
|
UseDefault: true,
|
||||||
Fg: 15,
|
Fg: 15,
|
||||||
@@ -180,7 +181,8 @@ func init() {
|
|||||||
Spinner: 148,
|
Spinner: 148,
|
||||||
Info: 144,
|
Info: 144,
|
||||||
Cursor: 161,
|
Cursor: 161,
|
||||||
Selected: 168}
|
Selected: 168,
|
||||||
|
Header: 109}
|
||||||
Light256 = &ColorTheme{
|
Light256 = &ColorTheme{
|
||||||
UseDefault: true,
|
UseDefault: true,
|
||||||
Fg: 15,
|
Fg: 15,
|
||||||
@@ -193,7 +195,8 @@ func init() {
|
|||||||
Spinner: 65,
|
Spinner: 65,
|
||||||
Info: 101,
|
Info: 101,
|
||||||
Cursor: 161,
|
Cursor: 161,
|
||||||
Selected: 168}
|
Selected: 168,
|
||||||
|
Header: 31}
|
||||||
}
|
}
|
||||||
|
|
||||||
func attrColored(pair int, bold bool) C.int {
|
func attrColored(pair int, bold bool) C.int {
|
||||||
@@ -254,14 +257,16 @@ func Init(theme *ColorTheme, black bool, mouse bool) {
|
|||||||
// syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))
|
// syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))
|
||||||
}
|
}
|
||||||
|
|
||||||
C.swapOutput()
|
|
||||||
|
|
||||||
C.setlocale(C.LC_ALL, C.CString(""))
|
C.setlocale(C.LC_ALL, C.CString(""))
|
||||||
C.initscr()
|
_screen = C.newterm(nil, C.stderr, C.stdin)
|
||||||
|
if _screen == nil {
|
||||||
|
fmt.Println("Invalid $TERM: " + os.Getenv("TERM"))
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
C.set_term(_screen)
|
||||||
if mouse {
|
if mouse {
|
||||||
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
||||||
}
|
}
|
||||||
C.cbreak()
|
|
||||||
C.noecho()
|
C.noecho()
|
||||||
C.raw() // stty dsusp undef
|
C.raw() // stty dsusp undef
|
||||||
|
|
||||||
@@ -312,11 +317,12 @@ func initPairs(theme *ColorTheme, black bool) {
|
|||||||
C.init_pair(ColInfo, C.short(theme.Info), bg)
|
C.init_pair(ColInfo, C.short(theme.Info), bg)
|
||||||
C.init_pair(ColCursor, C.short(theme.Cursor), darkBG)
|
C.init_pair(ColCursor, C.short(theme.Cursor), darkBG)
|
||||||
C.init_pair(ColSelected, C.short(theme.Selected), darkBG)
|
C.init_pair(ColSelected, C.short(theme.Selected), darkBG)
|
||||||
|
C.init_pair(ColHeader, C.short(theme.Header), bg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Close() {
|
func Close() {
|
||||||
C.endwin()
|
C.endwin()
|
||||||
C.swapOutput()
|
C.delscreen(_screen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetBytes() []byte {
|
func GetBytes() []byte {
|
||||||
@@ -481,10 +487,14 @@ func GetChar() Event {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
switch _buf[0] {
|
switch _buf[0] {
|
||||||
case CtrlC, CtrlG, CtrlQ:
|
case CtrlC:
|
||||||
return Event{CtrlC, 0, nil}
|
return Event{CtrlC, 0, nil}
|
||||||
|
case CtrlG:
|
||||||
|
return Event{CtrlG, 0, nil}
|
||||||
|
case CtrlQ:
|
||||||
|
return Event{CtrlQ, 0, nil}
|
||||||
case 127:
|
case 127:
|
||||||
return Event{CtrlH, 0, nil}
|
return Event{BSpace, 0, nil}
|
||||||
case ESC:
|
case ESC:
|
||||||
return escSequence(&sz)
|
return escSequence(&sz)
|
||||||
}
|
}
|
||||||
|
96
src/history.go
Normal file
96
src/history.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// History struct represents input history
|
||||||
|
type History struct {
|
||||||
|
path string
|
||||||
|
lines []string
|
||||||
|
modified map[int]string
|
||||||
|
maxSize int
|
||||||
|
cursor int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHistory returns the pointer to a new History struct
|
||||||
|
func NewHistory(path string, maxSize int) (*History, error) {
|
||||||
|
fmtError := func(e error) error {
|
||||||
|
if os.IsPermission(e) {
|
||||||
|
return errors.New("permission denied: " + path)
|
||||||
|
}
|
||||||
|
return errors.New("invalid history file: " + e.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read history file
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
// If it doesn't exist, check if we can create a file with the name
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
data = []byte{}
|
||||||
|
if err := ioutil.WriteFile(path, data, 0600); err != nil {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Split lines and limit the maximum number of lines
|
||||||
|
lines := strings.Split(strings.Trim(string(data), "\n"), "\n")
|
||||||
|
if len(lines[len(lines)-1]) > 0 {
|
||||||
|
lines = append(lines, "")
|
||||||
|
}
|
||||||
|
return &History{
|
||||||
|
path: path,
|
||||||
|
maxSize: maxSize,
|
||||||
|
lines: lines,
|
||||||
|
modified: make(map[int]string),
|
||||||
|
cursor: len(lines) - 1}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) append(line string) error {
|
||||||
|
// We don't append empty lines
|
||||||
|
if len(line) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := append(h.lines[:len(h.lines)-1], line)
|
||||||
|
if len(lines) > h.maxSize {
|
||||||
|
lines = lines[len(lines)-h.maxSize : len(lines)]
|
||||||
|
}
|
||||||
|
h.lines = append(lines, "")
|
||||||
|
return ioutil.WriteFile(h.path, []byte(strings.Join(h.lines, "\n")), 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) override(str string) {
|
||||||
|
// You can update the history but they're not written to the file
|
||||||
|
if h.cursor == len(h.lines)-1 {
|
||||||
|
h.lines[h.cursor] = str
|
||||||
|
} else if h.cursor < len(h.lines)-1 {
|
||||||
|
h.modified[h.cursor] = str
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) current() string {
|
||||||
|
if str, prs := h.modified[h.cursor]; prs {
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
return h.lines[h.cursor]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) previous() string {
|
||||||
|
if h.cursor > 0 {
|
||||||
|
h.cursor--
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) next() string {
|
||||||
|
if h.cursor < len(h.lines)-1 {
|
||||||
|
h.cursor++
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
59
src/history_test.go
Normal file
59
src/history_test.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/user"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHistory(t *testing.T) {
|
||||||
|
maxHistory := 50
|
||||||
|
|
||||||
|
// Invalid arguments
|
||||||
|
user, _ := user.Current()
|
||||||
|
paths := []string{"/etc", "/proc"}
|
||||||
|
if user.Name != "root" {
|
||||||
|
paths = append(paths, "/etc/sudoers")
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
if _, e := NewHistory(path, maxHistory); e == nil {
|
||||||
|
t.Error("Error expected for: " + path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
for i := 0; i < maxHistory+10; i++ {
|
||||||
|
h.append("foobar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Read lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
for i := 0; i < maxHistory; i++ {
|
||||||
|
if h.lines[i] != "foobar" {
|
||||||
|
t.Error("Expected: foobar, actual: " + h.lines[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
h.append("barfoo")
|
||||||
|
h.append("")
|
||||||
|
h.append("foobarbaz")
|
||||||
|
}
|
||||||
|
{ // Read lines again
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
compare := func(idx int, exp string) {
|
||||||
|
if h.lines[idx] != exp {
|
||||||
|
t.Errorf("Expected: %s, actual: %s\n", exp, h.lines[idx])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compare(maxHistory-3, "foobar")
|
||||||
|
compare(maxHistory-2, "barfoo")
|
||||||
|
compare(maxHistory-1, "foobarbaz")
|
||||||
|
}
|
||||||
|
}
|
48
src/item.go
48
src/item.go
@@ -17,9 +17,9 @@ type colorOffset struct {
|
|||||||
|
|
||||||
// Item represents each input line
|
// Item represents each input line
|
||||||
type Item struct {
|
type Item struct {
|
||||||
text *string
|
text []rune
|
||||||
origText *string
|
origText *[]rune
|
||||||
transformed *[]Token
|
transformed []Token
|
||||||
index uint32
|
index uint32
|
||||||
offsets []Offset
|
offsets []Offset
|
||||||
colors []ansiOffset
|
colors []ansiOffset
|
||||||
@@ -37,14 +37,14 @@ type Rank struct {
|
|||||||
var rankTiebreak tiebreak
|
var rankTiebreak tiebreak
|
||||||
|
|
||||||
// Rank calculates rank of the Item
|
// Rank calculates rank of the Item
|
||||||
func (i *Item) Rank(cache bool) Rank {
|
func (item *Item) Rank(cache bool) Rank {
|
||||||
if cache && (i.rank.matchlen > 0 || i.rank.tiebreak > 0) {
|
if cache && (item.rank.matchlen > 0 || item.rank.tiebreak > 0) {
|
||||||
return i.rank
|
return item.rank
|
||||||
}
|
}
|
||||||
matchlen := 0
|
matchlen := 0
|
||||||
prevEnd := 0
|
prevEnd := 0
|
||||||
minBegin := math.MaxUint16
|
minBegin := math.MaxUint16
|
||||||
for _, offset := range i.offsets {
|
for _, offset := range item.offsets {
|
||||||
begin := int(offset[0])
|
begin := int(offset[0])
|
||||||
end := int(offset[1])
|
end := int(offset[1])
|
||||||
if prevEnd > begin {
|
if prevEnd > begin {
|
||||||
@@ -63,13 +63,22 @@ func (i *Item) Rank(cache bool) Rank {
|
|||||||
var tiebreak uint16
|
var tiebreak uint16
|
||||||
switch rankTiebreak {
|
switch rankTiebreak {
|
||||||
case byLength:
|
case byLength:
|
||||||
tiebreak = uint16(len(*i.text))
|
// It is guaranteed that .transformed in not null in normal execution
|
||||||
|
if item.transformed != nil {
|
||||||
|
lenSum := 0
|
||||||
|
for _, token := range item.transformed {
|
||||||
|
lenSum += len(token.text)
|
||||||
|
}
|
||||||
|
tiebreak = uint16(lenSum)
|
||||||
|
} else {
|
||||||
|
tiebreak = uint16(len(item.text))
|
||||||
|
}
|
||||||
case byBegin:
|
case byBegin:
|
||||||
// We can't just look at i.offsets[0][0] because it can be an inverse term
|
// We can't just look at item.offsets[0][0] because it can be an inverse term
|
||||||
tiebreak = uint16(minBegin)
|
tiebreak = uint16(minBegin)
|
||||||
case byEnd:
|
case byEnd:
|
||||||
if prevEnd > 0 {
|
if prevEnd > 0 {
|
||||||
tiebreak = uint16(1 + len(*i.text) - prevEnd)
|
tiebreak = uint16(1 + len(item.text) - prevEnd)
|
||||||
} else {
|
} else {
|
||||||
// Empty offsets due to inverse terms.
|
// Empty offsets due to inverse terms.
|
||||||
tiebreak = 1
|
tiebreak = 1
|
||||||
@@ -77,19 +86,26 @@ func (i *Item) Rank(cache bool) Rank {
|
|||||||
case byIndex:
|
case byIndex:
|
||||||
tiebreak = 1
|
tiebreak = 1
|
||||||
}
|
}
|
||||||
rank := Rank{uint16(matchlen), tiebreak, i.index}
|
rank := Rank{uint16(matchlen), tiebreak, item.index}
|
||||||
if cache {
|
if cache {
|
||||||
i.rank = rank
|
item.rank = rank
|
||||||
}
|
}
|
||||||
return rank
|
return rank
|
||||||
}
|
}
|
||||||
|
|
||||||
// AsString returns the original string
|
// AsString returns the original string
|
||||||
func (i *Item) AsString() string {
|
func (item *Item) AsString() string {
|
||||||
if i.origText != nil {
|
return *item.StringPtr()
|
||||||
return *i.origText
|
}
|
||||||
|
|
||||||
|
// StringPtr returns the pointer to the original string
|
||||||
|
func (item *Item) StringPtr() *string {
|
||||||
|
runes := item.text
|
||||||
|
if item.origText != nil {
|
||||||
|
runes = *item.origText
|
||||||
}
|
}
|
||||||
return *i.text
|
str := string(runes)
|
||||||
|
return &str
|
||||||
}
|
}
|
||||||
|
|
||||||
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
||||||
|
@@ -39,14 +39,14 @@ func TestRankComparison(t *testing.T) {
|
|||||||
|
|
||||||
// Match length, string length, index
|
// Match length, string length, index
|
||||||
func TestItemRank(t *testing.T) {
|
func TestItemRank(t *testing.T) {
|
||||||
strs := []string{"foo", "foobar", "bar", "baz"}
|
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
||||||
item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}
|
item1 := Item{text: strs[0], index: 1, offsets: []Offset{}}
|
||||||
rank1 := item1.Rank(true)
|
rank1 := item1.Rank(true)
|
||||||
if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {
|
if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {
|
||||||
t.Error(item1.Rank(true))
|
t.Error(item1.Rank(true))
|
||||||
}
|
}
|
||||||
// Only differ in index
|
// Only differ in index
|
||||||
item2 := Item{text: &strs[0], index: 0, offsets: []Offset{}}
|
item2 := Item{text: strs[0], index: 0, offsets: []Offset{}}
|
||||||
|
|
||||||
items := []*Item{&item1, &item2}
|
items := []*Item{&item1, &item2}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
@@ -62,10 +62,10 @@ func TestItemRank(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sort by relevance
|
// Sort by relevance
|
||||||
item3 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
item3 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||||
item4 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
item4 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||||
item5 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
item5 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||||
item6 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
item6 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||||
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
if items[0] != &item2 || items[1] != &item1 ||
|
if items[0] != &item2 || items[1] != &item1 ||
|
||||||
|
@@ -96,7 +96,7 @@ func (m *Matcher) Loop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !cancelled {
|
if !cancelled {
|
||||||
if merger.Cacheable() {
|
if merger.cacheable() {
|
||||||
m.mergerCache[patternString] = merger
|
m.mergerCache[patternString] = merger
|
||||||
}
|
}
|
||||||
merger.final = request.final
|
merger.final = request.final
|
||||||
|
@@ -82,7 +82,7 @@ func (mg *Merger) Get(idx int) *Item {
|
|||||||
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Merger) Cacheable() bool {
|
func (mg *Merger) cacheable() bool {
|
||||||
return mg.count < mergerCacheMax
|
return mg.count < mergerCacheMax
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -22,7 +22,7 @@ func randItem() *Item {
|
|||||||
offsets[idx] = Offset{sidx, eidx}
|
offsets[idx] = Offset{sidx, eidx}
|
||||||
}
|
}
|
||||||
return &Item{
|
return &Item{
|
||||||
text: &str,
|
text: []rune(str),
|
||||||
index: rand.Uint32(),
|
index: rand.Uint32(),
|
||||||
offsets: offsets}
|
offsets: offsets}
|
||||||
}
|
}
|
||||||
|
534
src/options.go
534
src/options.go
@@ -2,6 +2,7 @@ package fzf
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -15,7 +16,7 @@ import (
|
|||||||
|
|
||||||
const usage = `usage: fzf [options]
|
const usage = `usage: fzf [options]
|
||||||
|
|
||||||
Search mode
|
Search
|
||||||
-x, --extended Extended-search mode
|
-x, --extended Extended-search mode
|
||||||
-e, --extended-exact Extended-search mode (exact match)
|
-e, --extended-exact Extended-search mode (exact match)
|
||||||
-i Case-insensitive match (default: smart-case match)
|
-i Case-insensitive match (default: smart-case match)
|
||||||
@@ -23,36 +24,39 @@ const usage = `usage: fzf [options]
|
|||||||
-n, --nth=N[,..] Comma-separated list of field index expressions
|
-n, --nth=N[,..] Comma-separated list of field index expressions
|
||||||
for limiting search scope. Each can be a non-zero
|
for limiting search scope. Each can be a non-zero
|
||||||
integer or a range expression ([BEGIN]..[END])
|
integer or a range expression ([BEGIN]..[END])
|
||||||
--with-nth=N[,..] Transform the item using index expressions for search
|
--with-nth=N[,..] Transform item using index expressions within finder
|
||||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||||
|
|
||||||
Search result
|
|
||||||
+s, --no-sort Do not sort the result
|
+s, --no-sort Do not sort the result
|
||||||
--tac Reverse the order of the input
|
--tac Reverse the order of the input
|
||||||
--tiebreak=CRI Sort criterion when the scores are tied;
|
--tiebreak=CRITERION Sort criterion when the scores are tied;
|
||||||
[length|begin|end|index] (default: length)
|
[length|begin|end|index] (default: length)
|
||||||
|
|
||||||
Interface
|
Interface
|
||||||
-m, --multi Enable multi-select with tab/shift-tab
|
-m, --multi Enable multi-select with tab/shift-tab
|
||||||
--ansi Enable processing of ANSI color codes
|
--ansi Enable processing of ANSI color codes
|
||||||
--no-mouse Disable mouse
|
--no-mouse Disable mouse
|
||||||
--color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors
|
--color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors
|
||||||
--black Use black background
|
--black Use black background
|
||||||
--reverse Reverse orientation
|
--reverse Reverse orientation
|
||||||
--no-hscroll Disable horizontal scroll
|
--margin=MARGIN Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)
|
||||||
--inline-info Display finder info inline with the query
|
--cycle Enable cyclic scroll
|
||||||
--prompt=STR Input prompt (default: '> ')
|
--no-hscroll Disable horizontal scroll
|
||||||
--toggle-sort=KEY Key to toggle sort
|
--inline-info Display finder info inline with the query
|
||||||
--bind=KEYBINDS Custom key bindings. Refer to the man page.
|
--prompt=STR Input prompt (default: '> ')
|
||||||
|
--bind=KEYBINDS Custom key bindings. Refer to the man page.
|
||||||
|
--history=FILE History file
|
||||||
|
--history-size=N Maximum number of history entries (default: 1000)
|
||||||
|
--header-file=FILE The file whose content to be printed as header
|
||||||
|
--header-lines=N The first N lines of the input are treated as header
|
||||||
|
|
||||||
Scripting
|
Scripting
|
||||||
-q, --query=STR Start the finder with the given query
|
-q, --query=STR Start the finder with the given query
|
||||||
-1, --select-1 Automatically select the only match
|
-1, --select-1 Automatically select the only match
|
||||||
-0, --exit-0 Exit immediately when there's no match
|
-0, --exit-0 Exit immediately when there's no match
|
||||||
-f, --filter=STR Filter mode. Do not start interactive finder.
|
-f, --filter=STR Filter mode. Do not start interactive finder.
|
||||||
--print-query Print query as the first line
|
--print-query Print query as the first line
|
||||||
--expect=KEYS Comma-separated list of keys to complete fzf
|
--expect=KEYS Comma-separated list of keys to complete fzf
|
||||||
--sync Synchronous search for multi-staged filtering
|
--sync Synchronous search for multi-staged filtering
|
||||||
|
|
||||||
Environment variables
|
Environment variables
|
||||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||||
@@ -90,35 +94,46 @@ const (
|
|||||||
byIndex
|
byIndex
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func defaultMargin() [4]string {
|
||||||
|
return [4]string{"0", "0", "0", "0"}
|
||||||
|
}
|
||||||
|
|
||||||
// Options stores the values of command-line options
|
// Options stores the values of command-line options
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Mode Mode
|
Mode Mode
|
||||||
Case Case
|
Case Case
|
||||||
Nth []Range
|
Nth []Range
|
||||||
WithNth []Range
|
WithNth []Range
|
||||||
Delimiter *regexp.Regexp
|
Delimiter *regexp.Regexp
|
||||||
Sort int
|
Sort int
|
||||||
Tac bool
|
Tac bool
|
||||||
Tiebreak tiebreak
|
Tiebreak tiebreak
|
||||||
Multi bool
|
Multi bool
|
||||||
Ansi bool
|
Ansi bool
|
||||||
Mouse bool
|
Mouse bool
|
||||||
Theme *curses.ColorTheme
|
Theme *curses.ColorTheme
|
||||||
Black bool
|
Black bool
|
||||||
Reverse bool
|
Reverse bool
|
||||||
Hscroll bool
|
Cycle bool
|
||||||
InlineInfo bool
|
Hscroll bool
|
||||||
Prompt string
|
InlineInfo bool
|
||||||
Query string
|
Prompt string
|
||||||
Select1 bool
|
Query string
|
||||||
Exit0 bool
|
Select1 bool
|
||||||
Filter *string
|
Exit0 bool
|
||||||
ToggleSort bool
|
Filter *string
|
||||||
Expect []int
|
ToggleSort bool
|
||||||
Keymap map[int]actionType
|
Expect map[int]string
|
||||||
PrintQuery bool
|
Keymap map[int]actionType
|
||||||
Sync bool
|
Execmap map[int]string
|
||||||
Version bool
|
PrintQuery bool
|
||||||
|
ReadZero bool
|
||||||
|
Sync bool
|
||||||
|
History *History
|
||||||
|
Header []string
|
||||||
|
HeaderLines int
|
||||||
|
Margin [4]string
|
||||||
|
Version bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultTheme() *curses.ColorTheme {
|
func defaultTheme() *curses.ColorTheme {
|
||||||
@@ -130,33 +145,40 @@ func defaultTheme() *curses.ColorTheme {
|
|||||||
|
|
||||||
func defaultOptions() *Options {
|
func defaultOptions() *Options {
|
||||||
return &Options{
|
return &Options{
|
||||||
Mode: ModeFuzzy,
|
Mode: ModeFuzzy,
|
||||||
Case: CaseSmart,
|
Case: CaseSmart,
|
||||||
Nth: make([]Range, 0),
|
Nth: make([]Range, 0),
|
||||||
WithNth: make([]Range, 0),
|
WithNth: make([]Range, 0),
|
||||||
Delimiter: nil,
|
Delimiter: nil,
|
||||||
Sort: 1000,
|
Sort: 1000,
|
||||||
Tac: false,
|
Tac: false,
|
||||||
Tiebreak: byLength,
|
Tiebreak: byLength,
|
||||||
Multi: false,
|
Multi: false,
|
||||||
Ansi: false,
|
Ansi: false,
|
||||||
Mouse: true,
|
Mouse: true,
|
||||||
Theme: defaultTheme(),
|
Theme: defaultTheme(),
|
||||||
Black: false,
|
Black: false,
|
||||||
Reverse: false,
|
Reverse: false,
|
||||||
Hscroll: true,
|
Cycle: false,
|
||||||
InlineInfo: false,
|
Hscroll: true,
|
||||||
Prompt: "> ",
|
InlineInfo: false,
|
||||||
Query: "",
|
Prompt: "> ",
|
||||||
Select1: false,
|
Query: "",
|
||||||
Exit0: false,
|
Select1: false,
|
||||||
Filter: nil,
|
Exit0: false,
|
||||||
ToggleSort: false,
|
Filter: nil,
|
||||||
Expect: []int{},
|
ToggleSort: false,
|
||||||
Keymap: defaultKeymap(),
|
Expect: make(map[int]string),
|
||||||
PrintQuery: false,
|
Keymap: defaultKeymap(),
|
||||||
Sync: false,
|
Execmap: make(map[int]string),
|
||||||
Version: false}
|
PrintQuery: false,
|
||||||
|
ReadZero: false,
|
||||||
|
Sync: false,
|
||||||
|
History: nil,
|
||||||
|
Header: make([]string, 0),
|
||||||
|
HeaderLines: 0,
|
||||||
|
Margin: defaultMargin(),
|
||||||
|
Version: false}
|
||||||
}
|
}
|
||||||
|
|
||||||
func help(ok int) {
|
func help(ok int) {
|
||||||
@@ -166,14 +188,14 @@ func help(ok int) {
|
|||||||
|
|
||||||
func errorExit(msg string) {
|
func errorExit(msg string) {
|
||||||
os.Stderr.WriteString(msg + "\n")
|
os.Stderr.WriteString(msg + "\n")
|
||||||
help(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func optString(arg string, prefix string) (bool, string) {
|
func optString(arg string, prefixes ...string) (bool, string) {
|
||||||
rx, _ := regexp.Compile(fmt.Sprintf("^(?:%s)(.*)$", prefix))
|
for _, prefix := range prefixes {
|
||||||
matches := rx.FindStringSubmatch(arg)
|
if strings.HasPrefix(arg, prefix) {
|
||||||
if len(matches) > 1 {
|
return true, arg[len(prefix):]
|
||||||
return true, matches[1]
|
}
|
||||||
}
|
}
|
||||||
return false, ""
|
return false, ""
|
||||||
}
|
}
|
||||||
@@ -195,6 +217,31 @@ func optionalNextString(args []string, i *int) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func atoi(str string) int {
|
||||||
|
num, err := strconv.Atoi(str)
|
||||||
|
if err != nil {
|
||||||
|
errorExit("not a valid integer: " + str)
|
||||||
|
}
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
|
||||||
|
func atof(str string) float64 {
|
||||||
|
num, err := strconv.ParseFloat(str, 64)
|
||||||
|
if err != nil {
|
||||||
|
errorExit("not a valid number: " + str)
|
||||||
|
}
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextInt(args []string, i *int, message string) int {
|
||||||
|
if len(args) > *i+1 {
|
||||||
|
*i++
|
||||||
|
} else {
|
||||||
|
errorExit(message)
|
||||||
|
}
|
||||||
|
return atoi(args[*i])
|
||||||
|
}
|
||||||
|
|
||||||
func optionalNumeric(args []string, i *int) int {
|
func optionalNumeric(args []string, i *int) int {
|
||||||
if len(args) > *i+1 {
|
if len(args) > *i+1 {
|
||||||
if strings.IndexAny(args[*i+1], "0123456789") == 0 {
|
if strings.IndexAny(args[*i+1], "0123456789") == 0 {
|
||||||
@@ -238,7 +285,7 @@ func isAlphabet(char uint8) bool {
|
|||||||
return char >= 'a' && char <= 'z'
|
return char >= 'a' && char <= 'z'
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseKeyChords(str string, message string) []int {
|
func parseKeyChords(str string, message string) map[int]string {
|
||||||
if len(str) == 0 {
|
if len(str) == 0 {
|
||||||
errorExit(message)
|
errorExit(message)
|
||||||
}
|
}
|
||||||
@@ -248,22 +295,65 @@ func parseKeyChords(str string, message string) []int {
|
|||||||
tokens = append(tokens, ",")
|
tokens = append(tokens, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
var chords []int
|
chords := make(map[int]string)
|
||||||
for _, key := range tokens {
|
for _, key := range tokens {
|
||||||
if len(key) == 0 {
|
if len(key) == 0 {
|
||||||
continue // ignore
|
continue // ignore
|
||||||
}
|
}
|
||||||
lkey := strings.ToLower(key)
|
lkey := strings.ToLower(key)
|
||||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
chord := 0
|
||||||
chords = append(chords, curses.CtrlA+int(lkey[5])-'a')
|
switch lkey {
|
||||||
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
case "up":
|
||||||
chords = append(chords, curses.AltA+int(lkey[4])-'a')
|
chord = curses.Up
|
||||||
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
case "down":
|
||||||
chords = append(chords, curses.F1+int(key[1])-'1')
|
chord = curses.Down
|
||||||
} else if utf8.RuneCountInString(key) == 1 {
|
case "left":
|
||||||
chords = append(chords, curses.AltZ+int([]rune(key)[0]))
|
chord = curses.Left
|
||||||
} else {
|
case "right":
|
||||||
errorExit("unsupported key: " + key)
|
chord = curses.Right
|
||||||
|
case "enter", "return":
|
||||||
|
chord = curses.CtrlM
|
||||||
|
case "space":
|
||||||
|
chord = curses.AltZ + int(' ')
|
||||||
|
case "bspace", "bs":
|
||||||
|
chord = curses.BSpace
|
||||||
|
case "alt-bs", "alt-bspace":
|
||||||
|
chord = curses.AltBS
|
||||||
|
case "tab":
|
||||||
|
chord = curses.Tab
|
||||||
|
case "btab", "shift-tab":
|
||||||
|
chord = curses.BTab
|
||||||
|
case "esc":
|
||||||
|
chord = curses.ESC
|
||||||
|
case "del":
|
||||||
|
chord = curses.Del
|
||||||
|
case "home":
|
||||||
|
chord = curses.Home
|
||||||
|
case "end":
|
||||||
|
chord = curses.End
|
||||||
|
case "pgup", "page-up":
|
||||||
|
chord = curses.PgUp
|
||||||
|
case "pgdn", "page-down":
|
||||||
|
chord = curses.PgDn
|
||||||
|
case "shift-left":
|
||||||
|
chord = curses.SLeft
|
||||||
|
case "shift-right":
|
||||||
|
chord = curses.SRight
|
||||||
|
default:
|
||||||
|
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||||
|
chord = curses.CtrlA + int(lkey[5]) - 'a'
|
||||||
|
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||||
|
chord = curses.AltA + int(lkey[4]) - 'a'
|
||||||
|
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
||||||
|
chord = curses.F1 + int(key[1]) - '1'
|
||||||
|
} else if utf8.RuneCountInString(key) == 1 {
|
||||||
|
chord = curses.AltZ + int([]rune(key)[0])
|
||||||
|
} else {
|
||||||
|
errorExit("unsupported key: " + key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if chord > 0 {
|
||||||
|
chords[chord] = key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return chords
|
return chords
|
||||||
@@ -345,6 +435,8 @@ func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme
|
|||||||
theme.Cursor = ansi
|
theme.Cursor = ansi
|
||||||
case "marker":
|
case "marker":
|
||||||
theme.Selected = ansi
|
theme.Selected = ansi
|
||||||
|
case "header":
|
||||||
|
theme.Header = ansi
|
||||||
default:
|
default:
|
||||||
fail()
|
fail()
|
||||||
}
|
}
|
||||||
@@ -353,22 +445,57 @@ func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme
|
|||||||
return theme
|
return theme
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[int]actionType, bool) {
|
var executeRegexp *regexp.Regexp
|
||||||
for _, pairStr := range strings.Split(str, ",") {
|
|
||||||
fail := func() {
|
func firstKey(keymap map[int]string) int {
|
||||||
errorExit("invalid key binding: " + pairStr)
|
for k := range keymap {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
escapedColon = 0
|
||||||
|
escapedComma = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {
|
||||||
|
if executeRegexp == nil {
|
||||||
|
// Backreferences are not supported.
|
||||||
|
// "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')
|
||||||
|
executeRegexp = regexp.MustCompile(
|
||||||
|
"(?s):execute:.*|:execute(\\([^)]*\\)|\\[[^\\]]*\\]|~[^~]*~|![^!]*!|@[^@]*@|\\#[^\\#]*\\#|\\$[^\\$]*\\$|%[^%]*%|\\^[^\\^]*\\^|&[^&]*&|\\*[^\\*]*\\*|;[^;]*;|/[^/]*/|\\|[^\\|]*\\|)")
|
||||||
|
}
|
||||||
|
masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {
|
||||||
|
return ":execute(" + strings.Repeat(" ", len(src)-10) + ")"
|
||||||
|
})
|
||||||
|
masked = strings.Replace(masked, "::", string([]rune{escapedColon, ':'}), -1)
|
||||||
|
masked = strings.Replace(masked, ",:", string([]rune{escapedComma, ':'}), -1)
|
||||||
|
|
||||||
|
idx := 0
|
||||||
|
for _, pairStr := range strings.Split(masked, ",") {
|
||||||
|
origPairStr := str[idx : idx+len(pairStr)]
|
||||||
|
idx += len(pairStr) + 1
|
||||||
|
|
||||||
|
pair := strings.SplitN(pairStr, ":", 2)
|
||||||
|
if len(pair) < 2 {
|
||||||
|
errorExit("bind action not specified: " + origPairStr)
|
||||||
}
|
}
|
||||||
pair := strings.Split(pairStr, ":")
|
var key int
|
||||||
if len(pair) != 2 {
|
if len(pair[0]) == 1 && pair[0][0] == escapedColon {
|
||||||
fail()
|
key = ':' + curses.AltZ
|
||||||
|
} else if len(pair[0]) == 1 && pair[0][0] == escapedComma {
|
||||||
|
key = ',' + curses.AltZ
|
||||||
|
} else {
|
||||||
|
keys := parseKeyChords(pair[0], "key name required")
|
||||||
|
key = firstKey(keys)
|
||||||
}
|
}
|
||||||
keys := parseKeyChords(pair[0], "key name required")
|
|
||||||
if len(keys) != 1 {
|
act := origPairStr[len(pair[0])+1 : len(origPairStr)]
|
||||||
fail()
|
actLower := strings.ToLower(act)
|
||||||
}
|
switch actLower {
|
||||||
key := keys[0]
|
case "ignore":
|
||||||
act := strings.ToLower(pair[1])
|
keymap[key] = actIgnore
|
||||||
switch act {
|
|
||||||
case "beginning-of-line":
|
case "beginning-of-line":
|
||||||
keymap[key] = actBeginningOfLine
|
keymap[key] = actBeginningOfLine
|
||||||
case "abort":
|
case "abort":
|
||||||
@@ -385,8 +512,12 @@ func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[in
|
|||||||
keymap[key] = actClearScreen
|
keymap[key] = actClearScreen
|
||||||
case "delete-char":
|
case "delete-char":
|
||||||
keymap[key] = actDeleteChar
|
keymap[key] = actDeleteChar
|
||||||
|
case "delete-char/eof":
|
||||||
|
keymap[key] = actDeleteCharEOF
|
||||||
case "end-of-line":
|
case "end-of-line":
|
||||||
keymap[key] = actEndOfLine
|
keymap[key] = actEndOfLine
|
||||||
|
case "cancel":
|
||||||
|
keymap[key] = actCancel
|
||||||
case "forward-char":
|
case "forward-char":
|
||||||
keymap[key] = actForwardChar
|
keymap[key] = actForwardChar
|
||||||
case "forward-word":
|
case "forward-word":
|
||||||
@@ -407,6 +538,12 @@ func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[in
|
|||||||
keymap[key] = actToggleDown
|
keymap[key] = actToggleDown
|
||||||
case "toggle-up":
|
case "toggle-up":
|
||||||
keymap[key] = actToggleUp
|
keymap[key] = actToggleUp
|
||||||
|
case "toggle-all":
|
||||||
|
keymap[key] = actToggleAll
|
||||||
|
case "select-all":
|
||||||
|
keymap[key] = actSelectAll
|
||||||
|
case "deselect-all":
|
||||||
|
keymap[key] = actDeselectAll
|
||||||
case "toggle":
|
case "toggle":
|
||||||
keymap[key] = actToggle
|
keymap[key] = actToggle
|
||||||
case "down":
|
case "down":
|
||||||
@@ -417,14 +554,40 @@ func parseKeymap(keymap map[int]actionType, toggleSort bool, str string) (map[in
|
|||||||
keymap[key] = actPageUp
|
keymap[key] = actPageUp
|
||||||
case "page-down":
|
case "page-down":
|
||||||
keymap[key] = actPageDown
|
keymap[key] = actPageDown
|
||||||
|
case "previous-history":
|
||||||
|
keymap[key] = actPreviousHistory
|
||||||
|
case "next-history":
|
||||||
|
keymap[key] = actNextHistory
|
||||||
case "toggle-sort":
|
case "toggle-sort":
|
||||||
keymap[key] = actToggleSort
|
keymap[key] = actToggleSort
|
||||||
toggleSort = true
|
toggleSort = true
|
||||||
default:
|
default:
|
||||||
errorExit("unknown action: " + act)
|
if isExecuteAction(actLower) {
|
||||||
|
keymap[key] = actExecute
|
||||||
|
if act[7] == ':' {
|
||||||
|
execmap[key] = act[8:]
|
||||||
|
} else {
|
||||||
|
execmap[key] = act[8 : len(act)-1]
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
errorExit("unknown action: " + act)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return keymap, toggleSort
|
return keymap, execmap, toggleSort
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExecuteAction(str string) bool {
|
||||||
|
if !strings.HasPrefix(str, "execute") || len(str) < 9 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b := str[7]
|
||||||
|
e := str[len(str)-1]
|
||||||
|
if b == ':' || b == '(' && e == ')' || b == '[' && e == ']' ||
|
||||||
|
b == e && strings.ContainsAny(string(b), "~!@#$%^&*;/|") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
||||||
@@ -432,11 +595,84 @@ func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
|||||||
if len(keys) != 1 {
|
if len(keys) != 1 {
|
||||||
errorExit("multiple keys specified")
|
errorExit("multiple keys specified")
|
||||||
}
|
}
|
||||||
keymap[keys[0]] = actToggleSort
|
keymap[firstKey(keys)] = actToggleSort
|
||||||
return keymap
|
return keymap
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func readHeaderFile(filename string) []string {
|
||||||
|
content, err := ioutil.ReadFile(filename)
|
||||||
|
if err != nil {
|
||||||
|
errorExit("failed to read header file: " + filename)
|
||||||
|
}
|
||||||
|
return strings.Split(strings.TrimSuffix(string(content), "\n"), "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseMargin(margin string) [4]string {
|
||||||
|
margins := strings.Split(margin, ",")
|
||||||
|
checked := func(str string) string {
|
||||||
|
if strings.HasSuffix(str, "%") {
|
||||||
|
val := atof(str[:len(str)-1])
|
||||||
|
if val < 0 {
|
||||||
|
errorExit("margin must be non-negative")
|
||||||
|
}
|
||||||
|
if val > 100 {
|
||||||
|
errorExit("margin too large")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val := atoi(str)
|
||||||
|
if val < 0 {
|
||||||
|
errorExit("margin must be non-negative")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
switch len(margins) {
|
||||||
|
case 1:
|
||||||
|
m := checked(margins[0])
|
||||||
|
return [4]string{m, m, m, m}
|
||||||
|
case 2:
|
||||||
|
tb := checked(margins[0])
|
||||||
|
rl := checked(margins[1])
|
||||||
|
return [4]string{tb, rl, tb, rl}
|
||||||
|
case 3:
|
||||||
|
t := checked(margins[0])
|
||||||
|
rl := checked(margins[1])
|
||||||
|
b := checked(margins[2])
|
||||||
|
return [4]string{t, rl, b, rl}
|
||||||
|
case 4:
|
||||||
|
return [4]string{
|
||||||
|
checked(margins[0]), checked(margins[1]),
|
||||||
|
checked(margins[2]), checked(margins[3])}
|
||||||
|
default:
|
||||||
|
errorExit("invalid margin: " + margin)
|
||||||
|
}
|
||||||
|
return defaultMargin()
|
||||||
|
}
|
||||||
|
|
||||||
func parseOptions(opts *Options, allArgs []string) {
|
func parseOptions(opts *Options, allArgs []string) {
|
||||||
|
keymap := make(map[int]actionType)
|
||||||
|
var historyMax int
|
||||||
|
if opts.History == nil {
|
||||||
|
historyMax = defaultHistoryMax
|
||||||
|
} else {
|
||||||
|
historyMax = opts.History.maxSize
|
||||||
|
}
|
||||||
|
setHistory := func(path string) {
|
||||||
|
h, e := NewHistory(path, historyMax)
|
||||||
|
if e != nil {
|
||||||
|
errorExit(e.Error())
|
||||||
|
}
|
||||||
|
opts.History = h
|
||||||
|
}
|
||||||
|
setHistoryMax := func(max int) {
|
||||||
|
historyMax = max
|
||||||
|
if historyMax < 1 {
|
||||||
|
errorExit("history max must be a positive integer")
|
||||||
|
}
|
||||||
|
if opts.History != nil {
|
||||||
|
opts.History.maxSize = historyMax
|
||||||
|
}
|
||||||
|
}
|
||||||
for i := 0; i < len(allArgs); i++ {
|
for i := 0; i < len(allArgs); i++ {
|
||||||
arg := allArgs[i]
|
arg := allArgs[i]
|
||||||
switch arg {
|
switch arg {
|
||||||
@@ -458,7 +694,8 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
case "--tiebreak":
|
case "--tiebreak":
|
||||||
opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||||
case "--bind":
|
case "--bind":
|
||||||
opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))
|
keymap, opts.Execmap, opts.ToggleSort =
|
||||||
|
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))
|
||||||
case "--color":
|
case "--color":
|
||||||
spec := optionalNextString(allArgs, &i)
|
spec := optionalNextString(allArgs, &i)
|
||||||
if len(spec) == 0 {
|
if len(spec) == 0 {
|
||||||
@@ -467,7 +704,7 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Theme = parseTheme(opts.Theme, spec)
|
opts.Theme = parseTheme(opts.Theme, spec)
|
||||||
}
|
}
|
||||||
case "--toggle-sort":
|
case "--toggle-sort":
|
||||||
opts.Keymap = checkToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))
|
keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))
|
||||||
opts.ToggleSort = true
|
opts.ToggleSort = true
|
||||||
case "-d", "--delimiter":
|
case "-d", "--delimiter":
|
||||||
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
||||||
@@ -509,6 +746,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Reverse = true
|
opts.Reverse = true
|
||||||
case "--no-reverse":
|
case "--no-reverse":
|
||||||
opts.Reverse = false
|
opts.Reverse = false
|
||||||
|
case "--cycle":
|
||||||
|
opts.Cycle = true
|
||||||
|
case "--no-cycle":
|
||||||
|
opts.Cycle = false
|
||||||
case "--hscroll":
|
case "--hscroll":
|
||||||
opts.Hscroll = true
|
opts.Hscroll = true
|
||||||
case "--no-hscroll":
|
case "--no-hscroll":
|
||||||
@@ -525,6 +766,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Exit0 = true
|
opts.Exit0 = true
|
||||||
case "+0", "--no-exit-0":
|
case "+0", "--no-exit-0":
|
||||||
opts.Exit0 = false
|
opts.Exit0 = false
|
||||||
|
case "--read0":
|
||||||
|
opts.ReadZero = true
|
||||||
|
case "--no-read0":
|
||||||
|
opts.ReadZero = false
|
||||||
case "--print-query":
|
case "--print-query":
|
||||||
opts.PrintQuery = true
|
opts.PrintQuery = true
|
||||||
case "--no-print-query":
|
case "--no-print-query":
|
||||||
@@ -537,25 +782,48 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Sync = false
|
opts.Sync = false
|
||||||
case "--async":
|
case "--async":
|
||||||
opts.Sync = false
|
opts.Sync = false
|
||||||
|
case "--no-history":
|
||||||
|
opts.History = nil
|
||||||
|
case "--history":
|
||||||
|
setHistory(nextString(allArgs, &i, "history file path required"))
|
||||||
|
case "--history-size":
|
||||||
|
setHistoryMax(nextInt(allArgs, &i, "history max size required"))
|
||||||
|
case "--no-header-file":
|
||||||
|
opts.Header = []string{}
|
||||||
|
case "--no-header-lines":
|
||||||
|
opts.HeaderLines = 0
|
||||||
|
case "--header-file":
|
||||||
|
opts.Header = readHeaderFile(
|
||||||
|
nextString(allArgs, &i, "header file name required"))
|
||||||
|
opts.HeaderLines = 0
|
||||||
|
case "--header-lines":
|
||||||
|
opts.Header = []string{}
|
||||||
|
opts.HeaderLines = atoi(
|
||||||
|
nextString(allArgs, &i, "number of header lines required"))
|
||||||
|
case "--no-margin":
|
||||||
|
opts.Margin = defaultMargin()
|
||||||
|
case "--margin":
|
||||||
|
opts.Margin = parseMargin(
|
||||||
|
nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))
|
||||||
case "--version":
|
case "--version":
|
||||||
opts.Version = true
|
opts.Version = true
|
||||||
default:
|
default:
|
||||||
if match, value := optString(arg, "-q|--query="); match {
|
if match, value := optString(arg, "-q", "--query="); match {
|
||||||
opts.Query = value
|
opts.Query = value
|
||||||
} else if match, value := optString(arg, "-f|--filter="); match {
|
} else if match, value := optString(arg, "-f", "--filter="); match {
|
||||||
opts.Filter = &value
|
opts.Filter = &value
|
||||||
} else if match, value := optString(arg, "-d|--delimiter="); match {
|
} else if match, value := optString(arg, "-d", "--delimiter="); match {
|
||||||
opts.Delimiter = delimiterRegexp(value)
|
opts.Delimiter = delimiterRegexp(value)
|
||||||
} else if match, value := optString(arg, "--prompt="); match {
|
} else if match, value := optString(arg, "--prompt="); match {
|
||||||
opts.Prompt = value
|
opts.Prompt = value
|
||||||
} else if match, value := optString(arg, "-n|--nth="); match {
|
} else if match, value := optString(arg, "-n", "--nth="); match {
|
||||||
opts.Nth = splitNth(value)
|
opts.Nth = splitNth(value)
|
||||||
} else if match, value := optString(arg, "--with-nth="); match {
|
} else if match, value := optString(arg, "--with-nth="); match {
|
||||||
opts.WithNth = splitNth(value)
|
opts.WithNth = splitNth(value)
|
||||||
} else if match, _ := optString(arg, "-s|--sort="); match {
|
} else if match, _ := optString(arg, "-s", "--sort="); match {
|
||||||
opts.Sort = 1 // Don't care
|
opts.Sort = 1 // Don't care
|
||||||
} else if match, value := optString(arg, "--toggle-sort="); match {
|
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||||
opts.Keymap = checkToggleSort(opts.Keymap, value)
|
keymap = checkToggleSort(keymap, value)
|
||||||
opts.ToggleSort = true
|
opts.ToggleSort = true
|
||||||
} else if match, value := optString(arg, "--expect="); match {
|
} else if match, value := optString(arg, "--expect="); match {
|
||||||
opts.Expect = parseKeyChords(value, "key names required")
|
opts.Expect = parseKeyChords(value, "key names required")
|
||||||
@@ -564,13 +832,45 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
} else if match, value := optString(arg, "--color="); match {
|
} else if match, value := optString(arg, "--color="); match {
|
||||||
opts.Theme = parseTheme(opts.Theme, value)
|
opts.Theme = parseTheme(opts.Theme, value)
|
||||||
} else if match, value := optString(arg, "--bind="); match {
|
} else if match, value := optString(arg, "--bind="); match {
|
||||||
opts.Keymap, opts.ToggleSort = parseKeymap(opts.Keymap, opts.ToggleSort, value)
|
keymap, opts.Execmap, opts.ToggleSort =
|
||||||
|
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)
|
||||||
|
} else if match, value := optString(arg, "--history="); match {
|
||||||
|
setHistory(value)
|
||||||
|
} else if match, value := optString(arg, "--history-size="); match {
|
||||||
|
setHistoryMax(atoi(value))
|
||||||
|
} else if match, value := optString(arg, "--header-file="); match {
|
||||||
|
opts.Header = readHeaderFile(value)
|
||||||
|
opts.HeaderLines = 0
|
||||||
|
} else if match, value := optString(arg, "--header-lines="); match {
|
||||||
|
opts.Header = []string{}
|
||||||
|
opts.HeaderLines = atoi(value)
|
||||||
|
} else if match, value := optString(arg, "--margin="); match {
|
||||||
|
opts.Margin = parseMargin(value)
|
||||||
} else {
|
} else {
|
||||||
errorExit("unknown option: " + arg)
|
errorExit("unknown option: " + arg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opts.HeaderLines < 0 {
|
||||||
|
errorExit("header lines must be a non-negative integer")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change default actions for CTRL-N / CTRL-P when --history is used
|
||||||
|
if opts.History != nil {
|
||||||
|
if _, prs := keymap[curses.CtrlP]; !prs {
|
||||||
|
keymap[curses.CtrlP] = actPreviousHistory
|
||||||
|
}
|
||||||
|
if _, prs := keymap[curses.CtrlN]; !prs {
|
||||||
|
keymap[curses.CtrlN] = actNextHistory
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override default key bindings
|
||||||
|
for key, act := range keymap {
|
||||||
|
opts.Keymap[key] = act
|
||||||
|
}
|
||||||
|
|
||||||
// If we're not using extended search mode, --nth option becomes irrelevant
|
// If we're not using extended search mode, --nth option becomes irrelevant
|
||||||
// if it contains the whole range
|
// if it contains the whole range
|
||||||
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/curses"
|
"github.com/junegunn/fzf/src/curses"
|
||||||
@@ -71,63 +72,101 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseKeys(t *testing.T) {
|
func TestParseKeys(t *testing.T) {
|
||||||
keys := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
||||||
check := func(key int, expected int) {
|
check := func(i int, s string) {
|
||||||
if key != expected {
|
if pairs[i] != s {
|
||||||
t.Errorf("%d != %d", key, expected)
|
t.Errorf("%s != %s", pairs[i], s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
check(len(keys), 9)
|
if len(pairs) != 9 {
|
||||||
check(keys[0], curses.CtrlZ)
|
t.Error(9)
|
||||||
check(keys[1], curses.AltZ)
|
}
|
||||||
check(keys[2], curses.F2)
|
check(curses.CtrlZ, "ctrl-z")
|
||||||
check(keys[3], curses.AltZ+'@')
|
check(curses.AltZ, "alt-z")
|
||||||
check(keys[4], curses.AltA)
|
check(curses.F2, "f2")
|
||||||
check(keys[5], curses.AltZ+'!')
|
check(curses.AltZ+'@', "@")
|
||||||
check(keys[6], curses.CtrlA+'g'-'a')
|
check(curses.AltA, "Alt-a")
|
||||||
check(keys[7], curses.AltZ+'J')
|
check(curses.AltZ+'!', "!")
|
||||||
check(keys[8], curses.AltZ+'g')
|
check(curses.CtrlA+'g'-'a', "ctrl-G")
|
||||||
|
check(curses.AltZ+'J', "J")
|
||||||
|
check(curses.AltZ+'g', "g")
|
||||||
|
|
||||||
|
// Synonyms
|
||||||
|
pairs = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")
|
||||||
|
if len(pairs) != 9 {
|
||||||
|
t.Error(9)
|
||||||
|
}
|
||||||
|
check(curses.CtrlM, "Return")
|
||||||
|
check(curses.AltZ+' ', "space")
|
||||||
|
check(curses.Tab, "tab")
|
||||||
|
check(curses.BTab, "btab")
|
||||||
|
check(curses.ESC, "esc")
|
||||||
|
check(curses.Up, "up")
|
||||||
|
check(curses.Down, "down")
|
||||||
|
check(curses.Left, "left")
|
||||||
|
check(curses.Right, "right")
|
||||||
|
|
||||||
|
pairs = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")
|
||||||
|
if len(pairs) != 11 {
|
||||||
|
t.Error(11)
|
||||||
|
}
|
||||||
|
check(curses.Tab, "Ctrl-I")
|
||||||
|
check(curses.PgUp, "page-up")
|
||||||
|
check(curses.PgDn, "Page-Down")
|
||||||
|
check(curses.Home, "Home")
|
||||||
|
check(curses.End, "End")
|
||||||
|
check(curses.AltBS, "Alt-BSpace")
|
||||||
|
check(curses.SLeft, "shift-left")
|
||||||
|
check(curses.SRight, "shift-right")
|
||||||
|
check(curses.BTab, "shift-tab")
|
||||||
|
check(curses.CtrlM, "Enter")
|
||||||
|
check(curses.BSpace, "bspace")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseKeysWithComma(t *testing.T) {
|
func TestParseKeysWithComma(t *testing.T) {
|
||||||
check := func(key int, expected int) {
|
checkN := func(a int, b int) {
|
||||||
if key != expected {
|
if a != b {
|
||||||
t.Errorf("%d != %d", key, expected)
|
t.Errorf("%d != %d", a, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check := func(pairs map[int]string, i int, s string) {
|
||||||
|
if pairs[i] != s {
|
||||||
|
t.Errorf("%s != %s", pairs[i], s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
keys := parseKeyChords(",", "")
|
pairs := parseKeyChords(",", "")
|
||||||
check(len(keys), 1)
|
checkN(len(pairs), 1)
|
||||||
check(keys[0], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords(",,a,b", "")
|
pairs = parseKeyChords(",,a,b", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,b,,", "")
|
pairs = parseKeyChords("a,b,,", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,,,b", "")
|
pairs = parseKeyChords("a,,,b", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,,,b,c", "")
|
pairs = parseKeyChords("a,,,b,c", "")
|
||||||
check(len(keys), 4)
|
checkN(len(pairs), 4)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+'c')
|
check(pairs, curses.AltZ+'c', "c")
|
||||||
check(keys[3], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords(",,,", "")
|
pairs = parseKeyChords(",,,", "")
|
||||||
check(len(keys), 1)
|
checkN(len(pairs), 1)
|
||||||
check(keys[0], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBind(t *testing.T) {
|
func TestBind(t *testing.T) {
|
||||||
@@ -136,20 +175,48 @@ func TestBind(t *testing.T) {
|
|||||||
t.Errorf("%d != %d", action, expected)
|
t.Errorf("%d != %d", action, expected)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
checkString := func(action string, expected string) {
|
||||||
|
if action != expected {
|
||||||
|
t.Errorf("%d != %d", action, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
keymap := defaultKeymap()
|
keymap := defaultKeymap()
|
||||||
|
execmap := make(map[int]string)
|
||||||
check(actBeginningOfLine, keymap[curses.CtrlA])
|
check(actBeginningOfLine, keymap[curses.CtrlA])
|
||||||
keymap, toggleSort :=
|
keymap, execmap, toggleSort :=
|
||||||
parseKeymap(keymap, false,
|
parseKeymap(keymap, execmap, false,
|
||||||
"ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down")
|
"ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+
|
||||||
|
"f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+
|
||||||
|
"alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+
|
||||||
|
",,:abort,::accept,X:execute:\nfoobar,Y:execute(baz)")
|
||||||
if !toggleSort {
|
if !toggleSort {
|
||||||
t.Errorf("toggleSort not set")
|
t.Errorf("toggleSort not set")
|
||||||
}
|
}
|
||||||
check(actKillLine, keymap[curses.CtrlA])
|
check(actKillLine, keymap[curses.CtrlA])
|
||||||
check(actToggleSort, keymap[curses.CtrlB])
|
check(actToggleSort, keymap[curses.CtrlB])
|
||||||
check(actPageUp, keymap[curses.AltZ+'c'])
|
check(actPageUp, keymap[curses.AltZ+'c'])
|
||||||
|
check(actAbort, keymap[curses.AltZ+','])
|
||||||
|
check(actAccept, keymap[curses.AltZ+':'])
|
||||||
check(actPageDown, keymap[curses.AltZ])
|
check(actPageDown, keymap[curses.AltZ])
|
||||||
|
check(actExecute, keymap[curses.F1])
|
||||||
|
check(actExecute, keymap[curses.F2])
|
||||||
|
check(actExecute, keymap[curses.F3])
|
||||||
|
check(actExecute, keymap[curses.F4])
|
||||||
|
checkString("ls {}", execmap[curses.F1])
|
||||||
|
checkString("echo {}, {}, {}", execmap[curses.F2])
|
||||||
|
checkString("echo '({})'", execmap[curses.F3])
|
||||||
|
checkString("less {}", execmap[curses.F4])
|
||||||
|
checkString("echo (,),[,],/,:,;,%,{}", execmap[curses.AltA])
|
||||||
|
checkString("echo (,),[,],/,:,@,%,{}", execmap[curses.AltB])
|
||||||
|
checkString("\nfoobar,Y:execute(baz)", execmap[curses.AltZ+'X'])
|
||||||
|
|
||||||
keymap, toggleSort = parseKeymap(keymap, false, "f1:abort")
|
for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {
|
||||||
|
keymap, execmap, toggleSort =
|
||||||
|
parseKeymap(keymap, execmap, false, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))
|
||||||
|
checkString("foobar", execmap[curses.AltZ+int([]rune(fmt.Sprintf("%d", idx%10))[0])])
|
||||||
|
}
|
||||||
|
|
||||||
|
keymap, execmap, toggleSort = parseKeymap(keymap, execmap, false, "f1:abort")
|
||||||
if toggleSort {
|
if toggleSort {
|
||||||
t.Errorf("toggleSort set")
|
t.Errorf("toggleSort set")
|
||||||
}
|
}
|
||||||
|
@@ -24,6 +24,7 @@ const (
|
|||||||
termExact
|
termExact
|
||||||
termPrefix
|
termPrefix
|
||||||
termSuffix
|
termSuffix
|
||||||
|
termEqual
|
||||||
)
|
)
|
||||||
|
|
||||||
type term struct {
|
type term struct {
|
||||||
@@ -43,7 +44,7 @@ type Pattern struct {
|
|||||||
hasInvTerm bool
|
hasInvTerm bool
|
||||||
delimiter *regexp.Regexp
|
delimiter *regexp.Regexp
|
||||||
nth []Range
|
nth []Range
|
||||||
procFun map[termType]func(bool, *[]rune, []rune) (int, int)
|
procFun map[termType]func(bool, []rune, []rune) (int, int)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -113,9 +114,10 @@ func BuildPattern(mode Mode, caseMode Case,
|
|||||||
hasInvTerm: hasInvTerm,
|
hasInvTerm: hasInvTerm,
|
||||||
nth: nth,
|
nth: nth,
|
||||||
delimiter: delimiter,
|
delimiter: delimiter,
|
||||||
procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}
|
procFun: make(map[termType]func(bool, []rune, []rune) (int, int))}
|
||||||
|
|
||||||
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
||||||
|
ptr.procFun[termEqual] = algo.EqualMatch
|
||||||
ptr.procFun[termExact] = algo.ExactMatchNaive
|
ptr.procFun[termExact] = algo.ExactMatchNaive
|
||||||
ptr.procFun[termPrefix] = algo.PrefixMatch
|
ptr.procFun[termPrefix] = algo.PrefixMatch
|
||||||
ptr.procFun[termSuffix] = algo.SuffixMatch
|
ptr.procFun[termSuffix] = algo.SuffixMatch
|
||||||
@@ -151,8 +153,13 @@ func parseTerms(mode Mode, caseMode Case, str string) []term {
|
|||||||
text = text[1:]
|
text = text[1:]
|
||||||
}
|
}
|
||||||
} else if strings.HasPrefix(text, "^") {
|
} else if strings.HasPrefix(text, "^") {
|
||||||
typ = termPrefix
|
if strings.HasSuffix(text, "$") {
|
||||||
text = text[1:]
|
typ = termEqual
|
||||||
|
text = text[1 : len(text)-1]
|
||||||
|
} else {
|
||||||
|
typ = termPrefix
|
||||||
|
text = text[1:]
|
||||||
|
}
|
||||||
} else if strings.HasSuffix(text, "$") {
|
} else if strings.HasSuffix(text, "$") {
|
||||||
typ = termSuffix
|
typ = termSuffix
|
||||||
text = text[:len(text)-1]
|
text = text[:len(text)-1]
|
||||||
@@ -298,27 +305,25 @@ func (p *Pattern) extendedMatch(item *Item) []Offset {
|
|||||||
return offsets
|
return offsets
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) prepareInput(item *Item) *[]Token {
|
func (p *Pattern) prepareInput(item *Item) []Token {
|
||||||
if item.transformed != nil {
|
if item.transformed != nil {
|
||||||
return item.transformed
|
return item.transformed
|
||||||
}
|
}
|
||||||
|
|
||||||
var ret *[]Token
|
var ret []Token
|
||||||
if len(p.nth) > 0 {
|
if len(p.nth) > 0 {
|
||||||
tokens := Tokenize(item.text, p.delimiter)
|
tokens := Tokenize(item.text, p.delimiter)
|
||||||
ret = Transform(tokens, p.nth)
|
ret = Transform(tokens, p.nth)
|
||||||
} else {
|
} else {
|
||||||
runes := []rune(*item.text)
|
ret = []Token{Token{text: item.text, prefixLength: 0}}
|
||||||
trans := []Token{Token{text: &runes, prefixLength: 0}}
|
|
||||||
ret = &trans
|
|
||||||
}
|
}
|
||||||
item.transformed = ret
|
item.transformed = ret
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),
|
func (p *Pattern) iter(pfun func(bool, []rune, []rune) (int, int),
|
||||||
tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {
|
tokens []Token, caseSensitive bool, pattern []rune) (int, int) {
|
||||||
for _, part := range *tokens {
|
for _, part := range tokens {
|
||||||
prefixLength := part.prefixLength
|
prefixLength := part.prefixLength
|
||||||
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
|
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
|
||||||
return sidx + prefixLength, eidx + prefixLength
|
return sidx + prefixLength, eidx + prefixLength
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/algo"
|
"github.com/junegunn/fzf/src/algo"
|
||||||
@@ -8,8 +9,8 @@ import (
|
|||||||
|
|
||||||
func TestParseTermsExtended(t *testing.T) {
|
func TestParseTermsExtended(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtended, CaseSmart,
|
terms := parseTerms(ModeExtended, CaseSmart,
|
||||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ ^iii$")
|
||||||
if len(terms) != 8 ||
|
if len(terms) != 9 ||
|
||||||
terms[0].typ != termFuzzy || terms[0].inv ||
|
terms[0].typ != termFuzzy || terms[0].inv ||
|
||||||
terms[1].typ != termExact || terms[1].inv ||
|
terms[1].typ != termExact || terms[1].inv ||
|
||||||
terms[2].typ != termPrefix || terms[2].inv ||
|
terms[2].typ != termPrefix || terms[2].inv ||
|
||||||
@@ -17,7 +18,8 @@ func TestParseTermsExtended(t *testing.T) {
|
|||||||
terms[4].typ != termFuzzy || !terms[4].inv ||
|
terms[4].typ != termFuzzy || !terms[4].inv ||
|
||||||
terms[5].typ != termExact || !terms[5].inv ||
|
terms[5].typ != termExact || !terms[5].inv ||
|
||||||
terms[6].typ != termPrefix || !terms[6].inv ||
|
terms[6].typ != termPrefix || !terms[6].inv ||
|
||||||
terms[7].typ != termSuffix || !terms[7].inv {
|
terms[7].typ != termSuffix || !terms[7].inv ||
|
||||||
|
terms[8].typ != termEqual || terms[8].inv {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
for idx, term := range terms {
|
for idx, term := range terms {
|
||||||
@@ -58,13 +60,29 @@ func TestExact(t *testing.T) {
|
|||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pattern := BuildPattern(ModeExtended, CaseSmart,
|
pattern := BuildPattern(ModeExtended, CaseSmart,
|
||||||
[]Range{}, nil, []rune("'abc"))
|
[]Range{}, nil, []rune("'abc"))
|
||||||
runes := []rune("aabbcc abc")
|
sidx, eidx := algo.ExactMatchNaive(
|
||||||
sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)
|
pattern.caseSensitive, []rune("aabbcc abc"), pattern.terms[0].text)
|
||||||
if sidx != 7 || eidx != 10 {
|
if sidx != 7 || eidx != 10 {
|
||||||
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEqual(t *testing.T) {
|
||||||
|
defer clearPatternCache()
|
||||||
|
clearPatternCache()
|
||||||
|
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("^AbC$"))
|
||||||
|
|
||||||
|
match := func(str string, sidxExpected int, eidxExpected int) {
|
||||||
|
sidx, eidx := algo.EqualMatch(
|
||||||
|
pattern.caseSensitive, []rune(str), pattern.terms[0].text)
|
||||||
|
if sidx != sidxExpected || eidx != eidxExpected {
|
||||||
|
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match("ABC", -1, -1)
|
||||||
|
match("AbC", 0, 3)
|
||||||
|
}
|
||||||
|
|
||||||
func TestCaseSensitivity(t *testing.T) {
|
func TestCaseSensitivity(t *testing.T) {
|
||||||
defer clearPatternCache()
|
defer clearPatternCache()
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
@@ -91,25 +109,23 @@ func TestCaseSensitivity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestOrigTextAndTransformed(t *testing.T) {
|
func TestOrigTextAndTransformed(t *testing.T) {
|
||||||
strptr := func(str string) *string {
|
|
||||||
return &str
|
|
||||||
}
|
|
||||||
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))
|
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))
|
||||||
tokens := Tokenize(strptr("junegunn"), nil)
|
tokens := Tokenize([]rune("junegunn"), nil)
|
||||||
trans := Transform(tokens, []Range{Range{1, 1}})
|
trans := Transform(tokens, []Range{Range{1, 1}})
|
||||||
|
|
||||||
|
origRunes := []rune("junegunn.choi")
|
||||||
for _, mode := range []Mode{ModeFuzzy, ModeExtended} {
|
for _, mode := range []Mode{ModeFuzzy, ModeExtended} {
|
||||||
chunk := Chunk{
|
chunk := Chunk{
|
||||||
&Item{
|
&Item{
|
||||||
text: strptr("junegunn"),
|
text: []rune("junegunn"),
|
||||||
origText: strptr("junegunn.choi"),
|
origText: &origRunes,
|
||||||
transformed: trans},
|
transformed: trans},
|
||||||
}
|
}
|
||||||
pattern.mode = mode
|
pattern.mode = mode
|
||||||
matches := pattern.matchChunk(&chunk)
|
matches := pattern.matchChunk(&chunk)
|
||||||
if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||
|
if string(matches[0].text) != "junegunn" || string(*matches[0].origText) != "junegunn.choi" ||
|
||||||
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
||||||
matches[0].transformed != trans {
|
!reflect.DeepEqual(matches[0].transformed, trans) {
|
||||||
t.Error("Invalid match result", matches)
|
t.Error("Invalid match result", matches)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -11,8 +11,9 @@ import (
|
|||||||
|
|
||||||
// Reader reads from command or standard input
|
// Reader reads from command or standard input
|
||||||
type Reader struct {
|
type Reader struct {
|
||||||
pusher func(string)
|
pusher func([]byte) bool
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
|
delimNil bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadSource reads data from the default command or from standard input
|
// ReadSource reads data from the default command or from standard input
|
||||||
@@ -30,30 +31,25 @@ func (r *Reader) ReadSource() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) feed(src io.Reader) {
|
func (r *Reader) feed(src io.Reader) {
|
||||||
|
delim := byte('\n')
|
||||||
|
if r.delimNil {
|
||||||
|
delim = '\000'
|
||||||
|
}
|
||||||
reader := bufio.NewReader(src)
|
reader := bufio.NewReader(src)
|
||||||
eof := false
|
for {
|
||||||
Loop:
|
// ReadBytes returns err != nil if and only if the returned data does not
|
||||||
for !eof {
|
// end in delim.
|
||||||
buf := []byte{}
|
bytea, err := reader.ReadBytes(delim)
|
||||||
iter := 0 // TODO: max size?
|
if len(bytea) > 0 {
|
||||||
for {
|
if err == nil {
|
||||||
// "ReadLine either returns a non-nil line or it returns an error, never both"
|
bytea = bytea[:len(bytea)-1]
|
||||||
line, isPrefix, err := reader.ReadLine()
|
|
||||||
eof = err == io.EOF
|
|
||||||
if eof {
|
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
break Loop
|
|
||||||
}
|
}
|
||||||
iter++
|
if r.pusher(bytea) {
|
||||||
buf = append(buf, line...)
|
r.eventBox.Set(EvtReadNew, nil)
|
||||||
if !isPrefix {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if iter > 0 {
|
if err != nil {
|
||||||
r.pusher(string(buf))
|
break
|
||||||
r.eventBox.Set(EvtReadNew, nil)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -10,7 +10,7 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
strs := []string{}
|
strs := []string{}
|
||||||
eb := util.NewEventBox()
|
eb := util.NewEventBox()
|
||||||
reader := Reader{
|
reader := Reader{
|
||||||
pusher: func(s string) { strs = append(strs, s) },
|
pusher: func(s []byte) bool { strs = append(strs, string(s)); return true },
|
||||||
eventBox: eb}
|
eventBox: eb}
|
||||||
|
|
||||||
// Check EventBox
|
// Check EventBox
|
||||||
|
357
src/terminal.go
357
src/terminal.go
@@ -4,9 +4,11 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
@@ -32,10 +34,16 @@ type Terminal struct {
|
|||||||
multi bool
|
multi bool
|
||||||
sort bool
|
sort bool
|
||||||
toggleSort bool
|
toggleSort bool
|
||||||
expect []int
|
expect map[int]string
|
||||||
keymap map[int]actionType
|
keymap map[int]actionType
|
||||||
pressed int
|
execmap map[int]string
|
||||||
|
pressed string
|
||||||
printQuery bool
|
printQuery bool
|
||||||
|
history *History
|
||||||
|
cycle bool
|
||||||
|
header []string
|
||||||
|
margin [4]string
|
||||||
|
marginInt [4]int
|
||||||
count int
|
count int
|
||||||
progress int
|
progress int
|
||||||
reading bool
|
reading bool
|
||||||
@@ -74,6 +82,7 @@ var _runeWidths = make(map[rune]int)
|
|||||||
const (
|
const (
|
||||||
reqPrompt util.EventType = iota
|
reqPrompt util.EventType = iota
|
||||||
reqInfo
|
reqInfo
|
||||||
|
reqHeader
|
||||||
reqList
|
reqList
|
||||||
reqRefresh
|
reqRefresh
|
||||||
reqRedraw
|
reqRedraw
|
||||||
@@ -94,8 +103,10 @@ const (
|
|||||||
actBackwardChar
|
actBackwardChar
|
||||||
actBackwardDeleteChar
|
actBackwardDeleteChar
|
||||||
actBackwardWord
|
actBackwardWord
|
||||||
|
actCancel
|
||||||
actClearScreen
|
actClearScreen
|
||||||
actDeleteChar
|
actDeleteChar
|
||||||
|
actDeleteCharEOF
|
||||||
actEndOfLine
|
actEndOfLine
|
||||||
actForwardChar
|
actForwardChar
|
||||||
actForwardWord
|
actForwardWord
|
||||||
@@ -105,7 +116,10 @@ const (
|
|||||||
actUnixWordRubout
|
actUnixWordRubout
|
||||||
actYank
|
actYank
|
||||||
actBackwardKillWord
|
actBackwardKillWord
|
||||||
|
actSelectAll
|
||||||
|
actDeselectAll
|
||||||
actToggle
|
actToggle
|
||||||
|
actToggleAll
|
||||||
actToggleDown
|
actToggleDown
|
||||||
actToggleUp
|
actToggleUp
|
||||||
actDown
|
actDown
|
||||||
@@ -113,6 +127,9 @@ const (
|
|||||||
actPageUp
|
actPageUp
|
||||||
actPageDown
|
actPageDown
|
||||||
actToggleSort
|
actToggleSort
|
||||||
|
actPreviousHistory
|
||||||
|
actNextHistory
|
||||||
|
actExecute
|
||||||
)
|
)
|
||||||
|
|
||||||
func defaultKeymap() map[int]actionType {
|
func defaultKeymap() map[int]actionType {
|
||||||
@@ -124,10 +141,11 @@ func defaultKeymap() map[int]actionType {
|
|||||||
keymap[C.CtrlG] = actAbort
|
keymap[C.CtrlG] = actAbort
|
||||||
keymap[C.CtrlQ] = actAbort
|
keymap[C.CtrlQ] = actAbort
|
||||||
keymap[C.ESC] = actAbort
|
keymap[C.ESC] = actAbort
|
||||||
keymap[C.CtrlD] = actDeleteChar
|
keymap[C.CtrlD] = actDeleteCharEOF
|
||||||
keymap[C.CtrlE] = actEndOfLine
|
keymap[C.CtrlE] = actEndOfLine
|
||||||
keymap[C.CtrlF] = actForwardChar
|
keymap[C.CtrlF] = actForwardChar
|
||||||
keymap[C.CtrlH] = actBackwardDeleteChar
|
keymap[C.CtrlH] = actBackwardDeleteChar
|
||||||
|
keymap[C.BSpace] = actBackwardDeleteChar
|
||||||
keymap[C.Tab] = actToggleDown
|
keymap[C.Tab] = actToggleDown
|
||||||
keymap[C.BTab] = actToggleUp
|
keymap[C.BTab] = actToggleUp
|
||||||
keymap[C.CtrlJ] = actDown
|
keymap[C.CtrlJ] = actDown
|
||||||
@@ -154,7 +172,7 @@ func defaultKeymap() map[int]actionType {
|
|||||||
|
|
||||||
keymap[C.Home] = actBeginningOfLine
|
keymap[C.Home] = actBeginningOfLine
|
||||||
keymap[C.End] = actEndOfLine
|
keymap[C.End] = actEndOfLine
|
||||||
keymap[C.Del] = actDeleteChar // FIXME Del vs. CTRL-D
|
keymap[C.Del] = actDeleteChar
|
||||||
keymap[C.PgUp] = actPageUp
|
keymap[C.PgUp] = actPageUp
|
||||||
keymap[C.PgDn] = actPageDown
|
keymap[C.PgDn] = actPageDown
|
||||||
|
|
||||||
@@ -181,8 +199,15 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
toggleSort: opts.ToggleSort,
|
toggleSort: opts.ToggleSort,
|
||||||
expect: opts.Expect,
|
expect: opts.Expect,
|
||||||
keymap: opts.Keymap,
|
keymap: opts.Keymap,
|
||||||
pressed: 0,
|
execmap: opts.Execmap,
|
||||||
|
pressed: "",
|
||||||
printQuery: opts.PrintQuery,
|
printQuery: opts.PrintQuery,
|
||||||
|
history: opts.History,
|
||||||
|
margin: opts.Margin,
|
||||||
|
marginInt: [4]int{0, 0, 0, 0},
|
||||||
|
cycle: opts.Cycle,
|
||||||
|
header: opts.Header,
|
||||||
|
reading: true,
|
||||||
merger: EmptyMerger,
|
merger: EmptyMerger,
|
||||||
selected: make(map[uint32]selectedItem),
|
selected: make(map[uint32]selectedItem),
|
||||||
reqBox: util.NewEventBox(),
|
reqBox: util.NewEventBox(),
|
||||||
@@ -214,6 +239,22 @@ func (t *Terminal) UpdateCount(cnt int, final bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateHeader updates the header
|
||||||
|
func (t *Terminal) UpdateHeader(header []string, lines int) {
|
||||||
|
t.mutex.Lock()
|
||||||
|
t.header = make([]string, lines)
|
||||||
|
copy(t.header, header)
|
||||||
|
if !t.reverse {
|
||||||
|
reversed := make([]string, lines)
|
||||||
|
for idx, str := range t.header {
|
||||||
|
reversed[lines-idx-1] = str
|
||||||
|
}
|
||||||
|
t.header = reversed
|
||||||
|
}
|
||||||
|
t.mutex.Unlock()
|
||||||
|
t.reqBox.Set(reqHeader, nil)
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateProgress updates the search progress
|
// UpdateProgress updates the search progress
|
||||||
func (t *Terminal) UpdateProgress(progress float32) {
|
func (t *Terminal) UpdateProgress(progress float32) {
|
||||||
t.mutex.Lock()
|
t.mutex.Lock()
|
||||||
@@ -242,17 +283,7 @@ func (t *Terminal) output() {
|
|||||||
fmt.Println(string(t.input))
|
fmt.Println(string(t.input))
|
||||||
}
|
}
|
||||||
if len(t.expect) > 0 {
|
if len(t.expect) > 0 {
|
||||||
if t.pressed == 0 {
|
fmt.Println(t.pressed)
|
||||||
fmt.Println()
|
|
||||||
} else if util.Between(t.pressed, C.AltA, C.AltZ) {
|
|
||||||
fmt.Printf("alt-%c\n", t.pressed+'a'-C.AltA)
|
|
||||||
} else if util.Between(t.pressed, C.F1, C.F4) {
|
|
||||||
fmt.Printf("f%c\n", t.pressed+'1'-C.F1)
|
|
||||||
} else if util.Between(t.pressed, C.CtrlA, C.CtrlZ) {
|
|
||||||
fmt.Printf("ctrl-%c\n", t.pressed+'a'-C.CtrlA)
|
|
||||||
} else {
|
|
||||||
fmt.Printf("%c\n", t.pressed-C.AltZ)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(t.selected) == 0 {
|
if len(t.selected) == 0 {
|
||||||
cnt := t.merger.Length()
|
cnt := t.merger.Length()
|
||||||
@@ -291,10 +322,50 @@ func displayWidth(runes []rune) int {
|
|||||||
return l
|
return l
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const minWidth = 16
|
||||||
|
const minHeight = 4
|
||||||
|
|
||||||
|
func (t *Terminal) calculateMargins() {
|
||||||
|
screenWidth := C.MaxX()
|
||||||
|
screenHeight := C.MaxY()
|
||||||
|
for idx, str := range t.margin {
|
||||||
|
if str == "0" {
|
||||||
|
t.marginInt[idx] = 0
|
||||||
|
} else if strings.HasSuffix(str, "%") {
|
||||||
|
num, _ := strconv.ParseFloat(str[:len(str)-1], 64)
|
||||||
|
var val float64
|
||||||
|
if idx%2 == 0 {
|
||||||
|
val = float64(screenHeight)
|
||||||
|
} else {
|
||||||
|
val = float64(screenWidth)
|
||||||
|
}
|
||||||
|
t.marginInt[idx] = int(val * num * 0.01)
|
||||||
|
} else {
|
||||||
|
num, _ := strconv.Atoi(str)
|
||||||
|
t.marginInt[idx] = num
|
||||||
|
}
|
||||||
|
}
|
||||||
|
adjust := func(idx1 int, idx2 int, max int, min int) {
|
||||||
|
if max >= min {
|
||||||
|
margin := t.marginInt[idx1] + t.marginInt[idx2]
|
||||||
|
if max-margin < min {
|
||||||
|
desired := max - min
|
||||||
|
t.marginInt[idx1] = desired * t.marginInt[idx1] / margin
|
||||||
|
t.marginInt[idx2] = desired * t.marginInt[idx2] / margin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
adjust(1, 3, screenWidth, minWidth)
|
||||||
|
adjust(0, 2, screenHeight, minHeight)
|
||||||
|
}
|
||||||
|
|
||||||
func (t *Terminal) move(y int, x int, clear bool) {
|
func (t *Terminal) move(y int, x int, clear bool) {
|
||||||
|
x += t.marginInt[3]
|
||||||
maxy := C.MaxY()
|
maxy := C.MaxY()
|
||||||
if !t.reverse {
|
if !t.reverse {
|
||||||
y = maxy - y - 1
|
y = maxy - y - 1 - t.marginInt[2]
|
||||||
|
} else {
|
||||||
|
y += t.marginInt[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
if clear {
|
if clear {
|
||||||
@@ -349,17 +420,49 @@ func (t *Terminal) printInfo() {
|
|||||||
C.CPrint(C.ColInfo, false, output)
|
C.CPrint(C.ColInfo, false, output)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) maxHeight() int {
|
||||||
|
return C.MaxY() - t.marginInt[0] - t.marginInt[2]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) printHeader() {
|
||||||
|
if len(t.header) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
max := t.maxHeight()
|
||||||
|
var state *ansiState
|
||||||
|
for idx, lineStr := range t.header {
|
||||||
|
if !t.reverse {
|
||||||
|
idx = len(t.header) - idx - 1
|
||||||
|
}
|
||||||
|
line := idx + 2
|
||||||
|
if t.inlineInfo {
|
||||||
|
line--
|
||||||
|
}
|
||||||
|
if line >= max {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
trimmed, colors, newState := extractColor(lineStr, state)
|
||||||
|
state = newState
|
||||||
|
item := &Item{
|
||||||
|
text: []rune(trimmed),
|
||||||
|
index: 0,
|
||||||
|
colors: colors,
|
||||||
|
rank: Rank{0, 0, 0}}
|
||||||
|
|
||||||
|
t.move(line, 2, true)
|
||||||
|
t.printHighlighted(item, false, C.ColHeader, 0, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (t *Terminal) printList() {
|
func (t *Terminal) printList() {
|
||||||
t.constrain()
|
t.constrain()
|
||||||
|
|
||||||
maxy := t.maxItems()
|
maxy := t.maxItems()
|
||||||
count := t.merger.Length() - t.offset
|
count := t.merger.Length() - t.offset
|
||||||
for i := 0; i < maxy; i++ {
|
for i := 0; i < maxy; i++ {
|
||||||
var line int
|
line := i + 2 + len(t.header)
|
||||||
if t.inlineInfo {
|
if t.inlineInfo {
|
||||||
line = i + 1
|
line--
|
||||||
} else {
|
|
||||||
line = i + 2
|
|
||||||
}
|
}
|
||||||
t.move(line, 0, true)
|
t.move(line, 0, true)
|
||||||
if i < count {
|
if i < count {
|
||||||
@@ -373,7 +476,7 @@ func (t *Terminal) printItem(item *Item, current bool) {
|
|||||||
if current {
|
if current {
|
||||||
C.CPrint(C.ColCursor, true, ">")
|
C.CPrint(C.ColCursor, true, ">")
|
||||||
if selected {
|
if selected {
|
||||||
C.CPrint(C.ColCurrent, true, ">")
|
C.CPrint(C.ColSelected, true, ">")
|
||||||
} else {
|
} else {
|
||||||
C.CPrint(C.ColCurrent, true, " ")
|
C.CPrint(C.ColCurrent, true, " ")
|
||||||
}
|
}
|
||||||
@@ -434,9 +537,10 @@ func (t *Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, c
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Overflow
|
// Overflow
|
||||||
text := []rune(*item.text)
|
text := make([]rune, len(item.text))
|
||||||
|
copy(text, item.text)
|
||||||
offsets := item.colorOffsets(col2, bold, current)
|
offsets := item.colorOffsets(col2, bold, current)
|
||||||
maxWidth := C.MaxX() - 3
|
maxWidth := C.MaxX() - 3 - t.marginInt[1] - t.marginInt[3]
|
||||||
fullWidth := displayWidth(text)
|
fullWidth := displayWidth(text)
|
||||||
if fullWidth > maxWidth {
|
if fullWidth > maxWidth {
|
||||||
if t.hscroll {
|
if t.hscroll {
|
||||||
@@ -519,9 +623,11 @@ func processTabs(runes []rune, prefixWidth int) (string, int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printAll() {
|
func (t *Terminal) printAll() {
|
||||||
|
t.calculateMargins()
|
||||||
t.printList()
|
t.printList()
|
||||||
t.printPrompt()
|
t.printPrompt()
|
||||||
t.printInfo()
|
t.printInfo()
|
||||||
|
t.printHeader()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) refresh() {
|
func (t *Terminal) refresh() {
|
||||||
@@ -580,16 +686,29 @@ func keyMatch(key int, event C.Event) bool {
|
|||||||
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func executeCommand(template string, current string) {
|
||||||
|
command := strings.Replace(template, "{}", fmt.Sprintf("%q", current), -1)
|
||||||
|
cmd := exec.Command("sh", "-c", command)
|
||||||
|
cmd.Stdin = os.Stdin
|
||||||
|
cmd.Stdout = os.Stdout
|
||||||
|
cmd.Stderr = os.Stderr
|
||||||
|
C.Endwin()
|
||||||
|
cmd.Run()
|
||||||
|
C.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
// Loop is called to start Terminal I/O
|
// Loop is called to start Terminal I/O
|
||||||
func (t *Terminal) Loop() {
|
func (t *Terminal) Loop() {
|
||||||
<-t.startChan
|
<-t.startChan
|
||||||
{ // Late initialization
|
{ // Late initialization
|
||||||
t.mutex.Lock()
|
t.mutex.Lock()
|
||||||
t.initFunc()
|
t.initFunc()
|
||||||
|
t.calculateMargins()
|
||||||
t.printPrompt()
|
t.printPrompt()
|
||||||
t.placeCursor()
|
t.placeCursor()
|
||||||
C.Refresh()
|
C.Refresh()
|
||||||
t.printInfo()
|
t.printInfo()
|
||||||
|
t.printHeader()
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
go func() {
|
go func() {
|
||||||
timer := time.NewTimer(initialDelay)
|
timer := time.NewTimer(initialDelay)
|
||||||
@@ -605,6 +724,27 @@ func (t *Terminal) Loop() {
|
|||||||
t.reqBox.Set(reqRedraw, nil)
|
t.reqBox.Set(reqRedraw, nil)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// Keep the spinner spinning
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
t.mutex.Lock()
|
||||||
|
reading := t.reading
|
||||||
|
t.mutex.Unlock()
|
||||||
|
if !reading {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(spinnerDuration)
|
||||||
|
t.reqBox.Set(reqInfo, nil)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
exit := func(code int) {
|
||||||
|
if code == 0 && t.history != nil {
|
||||||
|
t.history.append(string(t.input))
|
||||||
|
}
|
||||||
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -623,6 +763,8 @@ func (t *Terminal) Loop() {
|
|||||||
t.printInfo()
|
t.printInfo()
|
||||||
case reqList:
|
case reqList:
|
||||||
t.printList()
|
t.printList()
|
||||||
|
case reqHeader:
|
||||||
|
t.printHeader()
|
||||||
case reqRefresh:
|
case reqRefresh:
|
||||||
t.suppress = false
|
t.suppress = false
|
||||||
case reqRedraw:
|
case reqRedraw:
|
||||||
@@ -633,10 +775,10 @@ func (t *Terminal) Loop() {
|
|||||||
case reqClose:
|
case reqClose:
|
||||||
C.Close()
|
C.Close()
|
||||||
t.output()
|
t.output()
|
||||||
os.Exit(0)
|
exit(0)
|
||||||
case reqQuit:
|
case reqQuit:
|
||||||
C.Close()
|
C.Close()
|
||||||
os.Exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.placeCursor()
|
t.placeCursor()
|
||||||
@@ -661,39 +803,48 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
selectItem := func(item *Item) bool {
|
||||||
|
if _, found := t.selected[item.index]; !found {
|
||||||
|
t.selected[item.index] = selectedItem{time.Now(), item.StringPtr()}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
toggleY := func(y int) {
|
||||||
|
item := t.merger.Get(y)
|
||||||
|
if !selectItem(item) {
|
||||||
|
delete(t.selected, item.index)
|
||||||
|
}
|
||||||
|
}
|
||||||
toggle := func() {
|
toggle := func() {
|
||||||
if t.cy < t.merger.Length() {
|
if t.cy < t.merger.Length() {
|
||||||
item := t.merger.Get(t.cy)
|
toggleY(t.cy)
|
||||||
if _, found := t.selected[item.index]; !found {
|
|
||||||
var strptr *string
|
|
||||||
if item.origText != nil {
|
|
||||||
strptr = item.origText
|
|
||||||
} else {
|
|
||||||
strptr = item.text
|
|
||||||
}
|
|
||||||
t.selected[item.index] = selectedItem{time.Now(), strptr}
|
|
||||||
} else {
|
|
||||||
delete(t.selected, item.index)
|
|
||||||
}
|
|
||||||
req(reqInfo)
|
req(reqInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, key := range t.expect {
|
for key, ret := range t.expect {
|
||||||
if keyMatch(key, event) {
|
if keyMatch(key, event) {
|
||||||
t.pressed = key
|
t.pressed = ret
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
action := t.keymap[event.Type]
|
action := t.keymap[event.Type]
|
||||||
|
mapkey := event.Type
|
||||||
if event.Type == C.Rune {
|
if event.Type == C.Rune {
|
||||||
code := int(event.Char) + int(C.AltZ)
|
mapkey = int(event.Char) + int(C.AltZ)
|
||||||
if act, prs := t.keymap[code]; prs {
|
if act, prs := t.keymap[mapkey]; prs {
|
||||||
action = act
|
action = act
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
switch action {
|
switch action {
|
||||||
|
case actIgnore:
|
||||||
|
case actExecute:
|
||||||
|
if t.cy >= 0 && t.cy < t.merger.Length() {
|
||||||
|
item := t.merger.Get(t.cy)
|
||||||
|
executeCommand(t.execmap[mapkey], item.AsString())
|
||||||
|
}
|
||||||
case actInvalid:
|
case actInvalid:
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
continue
|
continue
|
||||||
@@ -711,11 +862,21 @@ func (t *Terminal) Loop() {
|
|||||||
case actAbort:
|
case actAbort:
|
||||||
req(reqQuit)
|
req(reqQuit)
|
||||||
case actDeleteChar:
|
case actDeleteChar:
|
||||||
|
t.delChar()
|
||||||
|
case actDeleteCharEOF:
|
||||||
if !t.delChar() && t.cx == 0 {
|
if !t.delChar() && t.cx == 0 {
|
||||||
req(reqQuit)
|
req(reqQuit)
|
||||||
}
|
}
|
||||||
case actEndOfLine:
|
case actEndOfLine:
|
||||||
t.cx = len(t.input)
|
t.cx = len(t.input)
|
||||||
|
case actCancel:
|
||||||
|
if len(t.input) == 0 {
|
||||||
|
req(reqQuit)
|
||||||
|
} else {
|
||||||
|
t.yanked = t.input
|
||||||
|
t.input = []rune{}
|
||||||
|
t.cx = 0
|
||||||
|
}
|
||||||
case actForwardChar:
|
case actForwardChar:
|
||||||
if t.cx < len(t.input) {
|
if t.cx < len(t.input) {
|
||||||
t.cx++
|
t.cx++
|
||||||
@@ -725,11 +886,34 @@ func (t *Terminal) Loop() {
|
|||||||
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
||||||
t.cx--
|
t.cx--
|
||||||
}
|
}
|
||||||
|
case actSelectAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
item := t.merger.Get(i)
|
||||||
|
selectItem(item)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
|
case actDeselectAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
item := t.merger.Get(i)
|
||||||
|
delete(t.selected, item.index)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
case actToggle:
|
case actToggle:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
|
case actToggleAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
toggleY(i)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
case actToggleDown:
|
case actToggleDown:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
@@ -796,16 +980,21 @@ func (t *Terminal) Loop() {
|
|||||||
prefix := copySlice(t.input[:t.cx])
|
prefix := copySlice(t.input[:t.cx])
|
||||||
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
||||||
t.cx++
|
t.cx++
|
||||||
|
case actPreviousHistory:
|
||||||
|
if t.history != nil {
|
||||||
|
t.history.override(string(t.input))
|
||||||
|
t.input = []rune(t.history.previous())
|
||||||
|
t.cx = len(t.input)
|
||||||
|
}
|
||||||
|
case actNextHistory:
|
||||||
|
if t.history != nil {
|
||||||
|
t.history.override(string(t.input))
|
||||||
|
t.input = []rune(t.history.next())
|
||||||
|
t.cx = len(t.input)
|
||||||
|
}
|
||||||
case actMouse:
|
case actMouse:
|
||||||
me := event.MouseEvent
|
me := event.MouseEvent
|
||||||
mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y
|
mx, my := me.X, me.Y
|
||||||
if !t.reverse {
|
|
||||||
my = C.MaxY() - my - 1
|
|
||||||
}
|
|
||||||
min := 2
|
|
||||||
if t.inlineInfo {
|
|
||||||
min = 1
|
|
||||||
}
|
|
||||||
if me.S != 0 {
|
if me.S != 0 {
|
||||||
// Scroll
|
// Scroll
|
||||||
if t.merger.Length() > 0 {
|
if t.merger.Length() > 0 {
|
||||||
@@ -815,23 +1004,36 @@ func (t *Terminal) Loop() {
|
|||||||
t.vmove(me.S)
|
t.vmove(me.S)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
} else if me.Double {
|
} else if mx >= t.marginInt[3] && mx < C.MaxX()-t.marginInt[1] &&
|
||||||
// Double-click
|
my >= t.marginInt[0] && my < C.MaxY()-t.marginInt[2] {
|
||||||
if my >= min {
|
mx -= t.marginInt[3]
|
||||||
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
my -= t.marginInt[0]
|
||||||
req(reqClose)
|
mx = util.Constrain(mx-len(t.prompt), 0, len(t.input))
|
||||||
}
|
if !t.reverse {
|
||||||
|
my = t.maxHeight() - my - 1
|
||||||
}
|
}
|
||||||
} else if me.Down {
|
min := 2 + len(t.header)
|
||||||
if my == 0 && mx >= 0 {
|
if t.inlineInfo {
|
||||||
// Prompt
|
min--
|
||||||
t.cx = mx
|
}
|
||||||
} else if my >= min {
|
if me.Double {
|
||||||
// List
|
// Double-click
|
||||||
if t.vset(t.offset+my-min) && t.multi && me.Mod {
|
if my >= min {
|
||||||
toggle()
|
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
||||||
|
req(reqClose)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if me.Down {
|
||||||
|
if my == 0 && mx >= 0 {
|
||||||
|
// Prompt
|
||||||
|
t.cx = mx
|
||||||
|
} else if my >= min {
|
||||||
|
// List
|
||||||
|
if t.vset(t.offset+my-min) && t.multi && me.Mod {
|
||||||
|
toggle()
|
||||||
|
}
|
||||||
|
req(reqList)
|
||||||
}
|
}
|
||||||
req(reqList)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -867,14 +1069,27 @@ func (t *Terminal) constrain() {
|
|||||||
t.offset = util.Max(0, count-height)
|
t.offset = util.Max(0, count-height)
|
||||||
t.cy = util.Constrain(t.offset+diffpos, 0, count-1)
|
t.cy = util.Constrain(t.offset+diffpos, 0, count-1)
|
||||||
}
|
}
|
||||||
|
t.offset = util.Max(0, t.offset)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) vmove(o int) {
|
func (t *Terminal) vmove(o int) {
|
||||||
if t.reverse {
|
if t.reverse {
|
||||||
t.vset(t.cy - o)
|
o *= -1
|
||||||
} else {
|
|
||||||
t.vset(t.cy + o)
|
|
||||||
}
|
}
|
||||||
|
dest := t.cy + o
|
||||||
|
if t.cycle {
|
||||||
|
max := t.merger.Length() - 1
|
||||||
|
if dest > max {
|
||||||
|
if t.cy == max {
|
||||||
|
dest = 0
|
||||||
|
}
|
||||||
|
} else if dest < 0 {
|
||||||
|
if t.cy == 0 {
|
||||||
|
dest = max
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.vset(dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) vset(o int) bool {
|
func (t *Terminal) vset(o int) bool {
|
||||||
@@ -883,9 +1098,9 @@ func (t *Terminal) vset(o int) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) maxItems() int {
|
func (t *Terminal) maxItems() int {
|
||||||
|
max := t.maxHeight() - 2 - len(t.header)
|
||||||
if t.inlineInfo {
|
if t.inlineInfo {
|
||||||
return C.MaxY() - 1
|
max++
|
||||||
} else {
|
|
||||||
return C.MaxY() - 2
|
|
||||||
}
|
}
|
||||||
|
return util.Max(max, 0)
|
||||||
}
|
}
|
||||||
|
@@ -18,7 +18,7 @@ type Range struct {
|
|||||||
|
|
||||||
// Token contains the tokenized part of the strings and its prefix length
|
// Token contains the tokenized part of the strings and its prefix length
|
||||||
type Token struct {
|
type Token struct {
|
||||||
text *[]rune
|
text []rune
|
||||||
prefixLength int
|
prefixLength int
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,8 +75,7 @@ func withPrefixLengths(tokens []string, begin int) []Token {
|
|||||||
for idx, token := range tokens {
|
for idx, token := range tokens {
|
||||||
// Need to define a new local variable instead of the reused token to take
|
// Need to define a new local variable instead of the reused token to take
|
||||||
// the pointer to it
|
// the pointer to it
|
||||||
runes := []rune(token)
|
ret[idx] = Token{text: []rune(token), prefixLength: prefixLength}
|
||||||
ret[idx] = Token{text: &runes, prefixLength: prefixLength}
|
|
||||||
prefixLength += len([]rune(token))
|
prefixLength += len([]rune(token))
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
@@ -88,13 +87,13 @@ const (
|
|||||||
awkWhite
|
awkWhite
|
||||||
)
|
)
|
||||||
|
|
||||||
func awkTokenizer(input *string) ([]string, int) {
|
func awkTokenizer(input []rune) ([]string, int) {
|
||||||
// 9, 32
|
// 9, 32
|
||||||
ret := []string{}
|
ret := []string{}
|
||||||
str := []rune{}
|
str := []rune{}
|
||||||
prefixLength := 0
|
prefixLength := 0
|
||||||
state := awkNil
|
state := awkNil
|
||||||
for _, r := range []rune(*input) {
|
for _, r := range input {
|
||||||
white := r == 9 || r == 32
|
white := r == 9 || r == 32
|
||||||
switch state {
|
switch state {
|
||||||
case awkNil:
|
case awkNil:
|
||||||
@@ -126,34 +125,34 @@ func awkTokenizer(input *string) ([]string, int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Tokenize tokenizes the given string with the delimiter
|
// Tokenize tokenizes the given string with the delimiter
|
||||||
func Tokenize(str *string, delimiter *regexp.Regexp) []Token {
|
func Tokenize(runes []rune, delimiter *regexp.Regexp) []Token {
|
||||||
if delimiter == nil {
|
if delimiter == nil {
|
||||||
// AWK-style (\S+\s*)
|
// AWK-style (\S+\s*)
|
||||||
tokens, prefixLength := awkTokenizer(str)
|
tokens, prefixLength := awkTokenizer(runes)
|
||||||
return withPrefixLengths(tokens, prefixLength)
|
return withPrefixLengths(tokens, prefixLength)
|
||||||
}
|
}
|
||||||
tokens := delimiter.FindAllString(*str, -1)
|
tokens := delimiter.FindAllString(string(runes), -1)
|
||||||
return withPrefixLengths(tokens, 0)
|
return withPrefixLengths(tokens, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinTokens(tokens *[]Token) *string {
|
func joinTokens(tokens []Token) []rune {
|
||||||
ret := ""
|
ret := []rune{}
|
||||||
for _, token := range *tokens {
|
for _, token := range tokens {
|
||||||
ret += string(*token.text)
|
ret = append(ret, token.text...)
|
||||||
}
|
}
|
||||||
return &ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinTokensAsRunes(tokens *[]Token) *[]rune {
|
func joinTokensAsRunes(tokens []Token) []rune {
|
||||||
ret := []rune{}
|
ret := []rune{}
|
||||||
for _, token := range *tokens {
|
for _, token := range tokens {
|
||||||
ret = append(ret, *token.text...)
|
ret = append(ret, token.text...)
|
||||||
}
|
}
|
||||||
return &ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform is used to transform the input when --with-nth option is given
|
// Transform is used to transform the input when --with-nth option is given
|
||||||
func Transform(tokens []Token, withNth []Range) *[]Token {
|
func Transform(tokens []Token, withNth []Range) []Token {
|
||||||
transTokens := make([]Token, len(withNth))
|
transTokens := make([]Token, len(withNth))
|
||||||
numTokens := len(tokens)
|
numTokens := len(tokens)
|
||||||
for idx, r := range withNth {
|
for idx, r := range withNth {
|
||||||
@@ -162,14 +161,14 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
|||||||
if r.begin == r.end {
|
if r.begin == r.end {
|
||||||
idx := r.begin
|
idx := r.begin
|
||||||
if idx == rangeEllipsis {
|
if idx == rangeEllipsis {
|
||||||
part = append(part, *joinTokensAsRunes(&tokens)...)
|
part = append(part, joinTokensAsRunes(tokens)...)
|
||||||
} else {
|
} else {
|
||||||
if idx < 0 {
|
if idx < 0 {
|
||||||
idx += numTokens + 1
|
idx += numTokens + 1
|
||||||
}
|
}
|
||||||
if idx >= 1 && idx <= numTokens {
|
if idx >= 1 && idx <= numTokens {
|
||||||
minIdx = idx - 1
|
minIdx = idx - 1
|
||||||
part = append(part, *tokens[idx-1].text...)
|
part = append(part, tokens[idx-1].text...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -196,7 +195,7 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
|||||||
minIdx = util.Max(0, begin-1)
|
minIdx = util.Max(0, begin-1)
|
||||||
for idx := begin; idx <= end; idx++ {
|
for idx := begin; idx <= end; idx++ {
|
||||||
if idx >= 1 && idx <= numTokens {
|
if idx >= 1 && idx <= numTokens {
|
||||||
part = append(part, *tokens[idx-1].text...)
|
part = append(part, tokens[idx-1].text...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,7 +205,7 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
|||||||
} else {
|
} else {
|
||||||
prefixLength = 0
|
prefixLength = 0
|
||||||
}
|
}
|
||||||
transTokens[idx] = Token{&part, prefixLength}
|
transTokens[idx] = Token{part, prefixLength}
|
||||||
}
|
}
|
||||||
return &transTokens
|
return transTokens
|
||||||
}
|
}
|
||||||
|
@@ -43,14 +43,14 @@ func TestParseRange(t *testing.T) {
|
|||||||
func TestTokenize(t *testing.T) {
|
func TestTokenize(t *testing.T) {
|
||||||
// AWK-style
|
// AWK-style
|
||||||
input := " abc: def: ghi "
|
input := " abc: def: ghi "
|
||||||
tokens := Tokenize(&input, nil)
|
tokens := Tokenize([]rune(input), nil)
|
||||||
if string(*tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {
|
if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With delimiter
|
// With delimiter
|
||||||
tokens = Tokenize(&input, delimiterRegexp(":"))
|
tokens = Tokenize([]rune(input), delimiterRegexp(":"))
|
||||||
if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {
|
if string(tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,39 +58,39 @@ func TestTokenize(t *testing.T) {
|
|||||||
func TestTransform(t *testing.T) {
|
func TestTransform(t *testing.T) {
|
||||||
input := " abc: def: ghi: jkl"
|
input := " abc: def: ghi: jkl"
|
||||||
{
|
{
|
||||||
tokens := Tokenize(&input, nil)
|
tokens := Tokenize([]rune(input), nil)
|
||||||
{
|
{
|
||||||
ranges := splitNth("1,2,3")
|
ranges := splitNth("1,2,3")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *joinTokens(tx) != "abc: def: ghi: " {
|
if string(joinTokens(tx)) != "abc: def: ghi: " {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *joinTokens(tx) != "abc: def: ghi: def: ghi: jklabc: " ||
|
if string(joinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||
|
||||||
len(*tx) != 4 ||
|
len(tx) != 4 ||
|
||||||
string(*(*tx)[0].text) != "abc: def: " || (*tx)[0].prefixLength != 2 ||
|
string(tx[0].text) != "abc: def: " || tx[0].prefixLength != 2 ||
|
||||||
string(*(*tx)[1].text) != "ghi: " || (*tx)[1].prefixLength != 14 ||
|
string(tx[1].text) != "ghi: " || tx[1].prefixLength != 14 ||
|
||||||
string(*(*tx)[2].text) != "def: ghi: jkl" || (*tx)[2].prefixLength != 8 ||
|
string(tx[2].text) != "def: ghi: jkl" || tx[2].prefixLength != 8 ||
|
||||||
string(*(*tx)[3].text) != "abc: " || (*tx)[3].prefixLength != 2 {
|
string(tx[3].text) != "abc: " || tx[3].prefixLength != 2 {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
tokens := Tokenize(&input, delimiterRegexp(":"))
|
tokens := Tokenize([]rune(input), delimiterRegexp(":"))
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||
|
if string(joinTokens(tx)) != " abc: def: ghi: def: ghi: jkl abc:" ||
|
||||||
len(*tx) != 4 ||
|
len(tx) != 4 ||
|
||||||
string(*(*tx)[0].text) != " abc: def:" || (*tx)[0].prefixLength != 0 ||
|
string(tx[0].text) != " abc: def:" || tx[0].prefixLength != 0 ||
|
||||||
string(*(*tx)[1].text) != " ghi:" || (*tx)[1].prefixLength != 12 ||
|
string(tx[1].text) != " ghi:" || tx[1].prefixLength != 12 ||
|
||||||
string(*(*tx)[2].text) != " def: ghi: jkl" || (*tx)[2].prefixLength != 6 ||
|
string(tx[2].text) != " def: ghi: jkl" || tx[2].prefixLength != 6 ||
|
||||||
string(*(*tx)[3].text) != " abc:" || (*tx)[3].prefixLength != 0 {
|
string(tx[3].text) != " abc:" || tx[3].prefixLength != 0 {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -6,6 +6,7 @@ import "C"
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Max returns the largest integer
|
// Max returns the largest integer
|
||||||
@@ -19,7 +20,7 @@ func Max(first int, items ...int) int {
|
|||||||
return max
|
return max
|
||||||
}
|
}
|
||||||
|
|
||||||
// Max32 returns the smallest 32-bit integer
|
// Min32 returns the smallest 32-bit integer
|
||||||
func Min32(first int32, second int32) int32 {
|
func Min32(first int32, second int32) int32 {
|
||||||
if first <= second {
|
if first <= second {
|
||||||
return first
|
return first
|
||||||
@@ -69,22 +70,33 @@ func DurWithin(
|
|||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
func Between(val int, min int, max int) bool {
|
|
||||||
return val >= min && val <= max
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsTty returns true is stdin is a terminal
|
// IsTty returns true is stdin is a terminal
|
||||||
func IsTty() bool {
|
func IsTty() bool {
|
||||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func TrimRight(runes *[]rune) []rune {
|
func TrimRight(runes []rune) []rune {
|
||||||
var i int
|
var i int
|
||||||
for i = len(*runes) - 1; i >= 0; i-- {
|
for i = len(runes) - 1; i >= 0; i-- {
|
||||||
char := (*runes)[i]
|
char := runes[i]
|
||||||
if char != ' ' && char != '\t' {
|
if char != ' ' && char != '\t' {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return (*runes)[0 : i+1]
|
return runes[0 : i+1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func BytesToRunes(bytea []byte) []rune {
|
||||||
|
runes := make([]rune, 0, len(bytea))
|
||||||
|
for i := 0; i < len(bytea); {
|
||||||
|
if bytea[i] < utf8.RuneSelf {
|
||||||
|
runes = append(runes, rune(bytea[i]))
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
r, sz := utf8.DecodeRune(bytea[i:])
|
||||||
|
i += sz
|
||||||
|
runes = append(runes, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return runes
|
||||||
}
|
}
|
||||||
|
345
test/test_go.rb
345
test/test_go.rb
@@ -72,17 +72,6 @@ class Tmux
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def closed?
|
|
||||||
!go("list-window -F '#I'").include?(win)
|
|
||||||
end
|
|
||||||
|
|
||||||
def close
|
|
||||||
wait do
|
|
||||||
send_keys 'C-c', 'C-u', 'exit', :Enter
|
|
||||||
closed?
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def kill
|
def kill
|
||||||
go("kill-window -t #{win} 2> /dev/null")
|
go("kill-window -t #{win} 2> /dev/null")
|
||||||
end
|
end
|
||||||
@@ -152,21 +141,27 @@ class TestBase < Minitest::Test
|
|||||||
|
|
||||||
attr_reader :tmux
|
attr_reader :tmux
|
||||||
|
|
||||||
|
def tempname
|
||||||
|
[TEMPNAME,
|
||||||
|
caller_locations.map(&:label).find { |l| l =~ /^test_/ }].join '-'
|
||||||
|
end
|
||||||
|
|
||||||
def setup
|
def setup
|
||||||
ENV.delete 'FZF_DEFAULT_OPTS'
|
ENV.delete 'FZF_DEFAULT_OPTS'
|
||||||
|
ENV.delete 'FZF_CTRL_T_COMMAND'
|
||||||
ENV.delete 'FZF_DEFAULT_COMMAND'
|
ENV.delete 'FZF_DEFAULT_COMMAND'
|
||||||
File.unlink TEMPNAME while File.exists?(TEMPNAME)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def readonce
|
def readonce
|
||||||
wait { File.exists?(TEMPNAME) }
|
wait { File.exists?(tempname) }
|
||||||
File.read(TEMPNAME)
|
File.read(tempname)
|
||||||
ensure
|
ensure
|
||||||
File.unlink TEMPNAME while File.exists?(TEMPNAME)
|
File.unlink tempname while File.exists?(tempname)
|
||||||
|
tmux.prepare
|
||||||
end
|
end
|
||||||
|
|
||||||
def fzf(*opts)
|
def fzf(*opts)
|
||||||
fzf!(*opts) + " > #{TEMPNAME}.tmp; mv #{TEMPNAME}.tmp #{TEMPNAME}"
|
fzf!(*opts) + " > #{tempname}.tmp; mv #{tempname}.tmp #{tempname}"
|
||||||
end
|
end
|
||||||
|
|
||||||
def fzf!(*opts)
|
def fzf!(*opts)
|
||||||
@@ -214,7 +209,6 @@ class TestGoFZF < TestBase
|
|||||||
assert_equal '> 391', lines[-1]
|
assert_equal '> 391', lines[-1]
|
||||||
|
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.close
|
|
||||||
assert_equal '1391', readonce.chomp
|
assert_equal '1391', readonce.chomp
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -223,7 +217,6 @@ class TestGoFZF < TestBase
|
|||||||
tmux.until { |lines| lines.last =~ /^>/ }
|
tmux.until { |lines| lines.last =~ /^>/ }
|
||||||
|
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.close
|
|
||||||
assert_equal 'hello', readonce.chomp
|
assert_equal 'hello', readonce.chomp
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -290,7 +283,6 @@ class TestGoFZF < TestBase
|
|||||||
# CTRL-M
|
# CTRL-M
|
||||||
tmux.send_keys "C-M"
|
tmux.send_keys "C-M"
|
||||||
tmux.until { |lines| lines.last !~ /^>/ }
|
tmux.until { |lines| lines.last !~ /^>/ }
|
||||||
tmux.close
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_multi_order
|
def test_multi_order
|
||||||
@@ -303,7 +295,6 @@ class TestGoFZF < TestBase
|
|||||||
tmux.until { |lines| lines[-2].include? '(6)' }
|
tmux.until { |lines| lines[-2].include? '(6)' }
|
||||||
tmux.send_keys "C-M"
|
tmux.send_keys "C-M"
|
||||||
assert_equal %w[3 2 5 6 8 7], readonce.split($/)
|
assert_equal %w[3 2 5 6 8 7], readonce.split($/)
|
||||||
tmux.close
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_with_nth
|
def test_with_nth
|
||||||
@@ -321,7 +312,9 @@ class TestGoFZF < TestBase
|
|||||||
|
|
||||||
# However, the output must not be transformed
|
# However, the output must not be transformed
|
||||||
if multi
|
if multi
|
||||||
tmux.send_keys :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(2)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
assert_equal [' 1st 2nd 3rd/', ' first second third/'], readonce.split($/)
|
assert_equal [' 1st 2nd 3rd/', ' first second third/'], readonce.split($/)
|
||||||
else
|
else
|
||||||
tmux.send_keys '^', '3'
|
tmux.send_keys '^', '3'
|
||||||
@@ -357,7 +350,9 @@ class TestGoFZF < TestBase
|
|||||||
[:'0', :'1', [:'1', :'0']].each do |opt|
|
[:'0', :'1', [:'1', :'0']].each do |opt|
|
||||||
tmux.send_keys "seq 1 100 | #{fzf :print_query, :multi, :q, 5, *opt}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf :print_query, :multi, :q, 5, *opt}", :Enter
|
||||||
tmux.until { |lines| lines.last =~ /^> 5/ }
|
tmux.until { |lines| lines.last =~ /^> 5/ }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
assert_equal ['5', '5', '15', '25'], readonce.split($/)
|
assert_equal ['5', '5', '15', '25'], readonce.split($/)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -374,7 +369,9 @@ class TestGoFZF < TestBase
|
|||||||
tmux.until { |lines| lines[-1] == '>' }
|
tmux.until { |lines| lines[-1] == '>' }
|
||||||
tmux.send_keys 9
|
tmux.send_keys 9
|
||||||
tmux.until { |lines| lines[-2] == ' 19/100' }
|
tmux.until { |lines| lines[-2] == ' 19/100' }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1] == '>' }
|
tmux.until { |lines| lines[-1] == '>' }
|
||||||
tmux.send_keys 'C-K', :Enter
|
tmux.send_keys 'C-K', :Enter
|
||||||
assert_equal ['1919'], readonce.split($/)
|
assert_equal ['1919'], readonce.split($/)
|
||||||
@@ -383,7 +380,9 @@ class TestGoFZF < TestBase
|
|||||||
def test_tac
|
def test_tac
|
||||||
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
||||||
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
assert_equal %w[1000 999 998], readonce.split($/)
|
assert_equal %w[1000 999 998], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -391,7 +390,9 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
||||||
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
tmux.send_keys '99'
|
tmux.send_keys '99'
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
assert_equal %w[99 999 998], readonce.split($/)
|
assert_equal %w[99 999 998], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -400,7 +401,9 @@ class TestGoFZF < TestBase
|
|||||||
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
tmux.send_keys '00'
|
tmux.send_keys '00'
|
||||||
tmux.until { |lines| lines[-2].include? '10/1000' }
|
tmux.until { |lines| lines[-2].include? '10/1000' }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
assert_equal %w[1000 900 800], readonce.split($/)
|
assert_equal %w[1000 900 800], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -454,16 +457,12 @@ class TestGoFZF < TestBase
|
|||||||
end
|
end
|
||||||
|
|
||||||
def test_unicode_case
|
def test_unicode_case
|
||||||
tempname = TEMPNAME + Time.now.to_f.to_s
|
|
||||||
writelines tempname, %w[строКА1 СТРОКА2 строка3 Строка4]
|
writelines tempname, %w[строКА1 СТРОКА2 строка3 Строка4]
|
||||||
assert_equal %w[СТРОКА2 Строка4], `cat #{tempname} | #{FZF} -fС`.split($/)
|
assert_equal %w[СТРОКА2 Строка4], `cat #{tempname} | #{FZF} -fС`.split($/)
|
||||||
assert_equal %w[строКА1 СТРОКА2 строка3 Строка4], `cat #{tempname} | #{FZF} -fс`.split($/)
|
assert_equal %w[строКА1 СТРОКА2 строка3 Строка4], `cat #{tempname} | #{FZF} -fс`.split($/)
|
||||||
rescue
|
|
||||||
File.unlink tempname
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_tiebreak
|
def test_tiebreak
|
||||||
tempname = TEMPNAME + Time.now.to_f.to_s
|
|
||||||
input = %w[
|
input = %w[
|
||||||
--foobar--------
|
--foobar--------
|
||||||
-----foobar---
|
-----foobar---
|
||||||
@@ -500,8 +499,32 @@ class TestGoFZF < TestBase
|
|||||||
], `cat #{tempname} | #{FZF} -ffoobar --tiebreak end`.split($/)
|
], `cat #{tempname} | #{FZF} -ffoobar --tiebreak end`.split($/)
|
||||||
|
|
||||||
assert_equal input, `cat #{tempname} | #{FZF} -f"!z" -x --tiebreak end`.split($/)
|
assert_equal input, `cat #{tempname} | #{FZF} -f"!z" -x --tiebreak end`.split($/)
|
||||||
rescue
|
end
|
||||||
File.unlink tempname
|
|
||||||
|
def test_tiebreak_length_with_nth
|
||||||
|
input = %w[
|
||||||
|
1:hell
|
||||||
|
123:hello
|
||||||
|
12345:he
|
||||||
|
1234567:h
|
||||||
|
]
|
||||||
|
writelines tempname, input
|
||||||
|
|
||||||
|
output = %w[
|
||||||
|
1:hell
|
||||||
|
12345:he
|
||||||
|
123:hello
|
||||||
|
1234567:h
|
||||||
|
]
|
||||||
|
assert_equal output, `cat #{tempname} | #{FZF} -fh`.split($/)
|
||||||
|
|
||||||
|
output = %w[
|
||||||
|
1234567:h
|
||||||
|
12345:he
|
||||||
|
1:hell
|
||||||
|
123:hello
|
||||||
|
]
|
||||||
|
assert_equal output, `cat #{tempname} | #{FZF} -fh -n2 -d:`.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_invalid_cache
|
def test_invalid_cache
|
||||||
@@ -527,15 +550,230 @@ class TestGoFZF < TestBase
|
|||||||
end
|
end
|
||||||
|
|
||||||
def test_long_line
|
def test_long_line
|
||||||
tempname = TEMPNAME + Time.now.to_f.to_s
|
|
||||||
data = '.' * 256 * 1024
|
data = '.' * 256 * 1024
|
||||||
File.open(tempname, 'w') do |f|
|
File.open(tempname, 'w') do |f|
|
||||||
f << data
|
f << data
|
||||||
end
|
end
|
||||||
assert_equal data, `cat #{tempname} | #{FZF} -f .`.chomp
|
assert_equal data, `cat #{tempname} | #{FZF} -f .`.chomp
|
||||||
ensure
|
|
||||||
File.unlink tempname
|
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_read0
|
||||||
|
lines = `find .`.split($/)
|
||||||
|
assert_equal lines.last, `find . | #{FZF} -e -f "^#{lines.last}$"`.chomp
|
||||||
|
assert_equal lines.last, `find . -print0 | #{FZF} --read0 -e -f "^#{lines.last}$"`.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_select_all_deselect_all_toggle_all
|
||||||
|
tmux.send_keys "seq 100 | #{fzf '--bind ctrl-a:select-all,ctrl-d:deselect-all,ctrl-t:toggle-all --multi'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(3)' }
|
||||||
|
tmux.send_keys 'C-t'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(97)' }
|
||||||
|
tmux.send_keys 'C-a'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(100)' }
|
||||||
|
tmux.send_keys :Tab, :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(98)' }
|
||||||
|
tmux.send_keys 'C-d'
|
||||||
|
tmux.until { |lines| !lines[-2].include? '(' }
|
||||||
|
tmux.send_keys :Tab, :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(2)' }
|
||||||
|
tmux.send_keys 0
|
||||||
|
tmux.until { |lines| lines[-2].include? '10/100' }
|
||||||
|
tmux.send_keys 'C-a'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(12)' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal %w[2 1 10 20 30 40 50 60 70 80 90 100], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_history
|
||||||
|
history_file = '/tmp/fzf-test-history'
|
||||||
|
|
||||||
|
# History with limited number of entries
|
||||||
|
File.unlink history_file rescue nil
|
||||||
|
opts = "--history=#{history_file} --history-size=4"
|
||||||
|
input = %w[00 11 22 33 44].map { |e| e + $/ }
|
||||||
|
input.each do |keys|
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys keys
|
||||||
|
tmux.until { |lines| lines[-2].include? '1/100' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
end
|
||||||
|
assert_equal input[1..-1], File.readlines(history_file)
|
||||||
|
|
||||||
|
# Update history entries (not changed on disk)
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 44' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 33' }
|
||||||
|
tmux.send_keys :BSpace
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 3' }
|
||||||
|
tmux.send_keys 1
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 31' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 22' }
|
||||||
|
tmux.send_keys 'C-n'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 31' }
|
||||||
|
tmux.send_keys 0
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 310' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
assert_equal %w[22 33 44 310].map { |e| e + $/ }, File.readlines(history_file)
|
||||||
|
|
||||||
|
# Respect --bind option
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts + ' --bind ctrl-p:next-history,ctrl-n:previous-history'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys 'C-n', 'C-n', 'C-n', 'C-n', 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with?('33') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
ensure
|
||||||
|
File.unlink history_file
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_execute
|
||||||
|
output = '/tmp/fzf-test-execute'
|
||||||
|
opts = %[--bind \\"alt-a:execute(echo '[{}]' >> #{output}),alt-b:execute[echo '({}), ({})' >> #{output}],C:execute:echo '({}), [{}], @{}@' >> #{output}\\"]
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys :Escape, :a, :Escape, :a
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.send_keys :Escape, :b, :Escape, :b
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.send_keys :C
|
||||||
|
tmux.send_keys 'foobar'
|
||||||
|
tmux.until { |lines| lines[-2].include? '0/100' }
|
||||||
|
tmux.send_keys :Escape, :a, :Escape, :b, :Escape, :c
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
assert_equal ['["1"]', '["1"]', '("2"), ("2")', '("2"), ("2")', '("3"), ["3"], @"3"@'],
|
||||||
|
File.readlines(output).map(&:chomp)
|
||||||
|
ensure
|
||||||
|
File.unlink output rescue nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_cycle
|
||||||
|
tmux.send_keys "seq 8 | #{fzf :cycle}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '8/8' }
|
||||||
|
tmux.send_keys :Down
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
tmux.send_keys :Down
|
||||||
|
tmux.until { |lines| lines[-9].start_with? '>' }
|
||||||
|
tmux.send_keys :PgUp
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
tmux.send_keys :PgUp
|
||||||
|
tmux.until { |lines| lines[-3].start_with? '>' }
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.until { |lines| lines[-4].start_with? '>' }
|
||||||
|
tmux.send_keys :PgDn
|
||||||
|
tmux.until { |lines| lines[-3].start_with? '>' }
|
||||||
|
tmux.send_keys :PgDn
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_lines
|
||||||
|
tmux.send_keys "seq 100 | #{fzf '--header-lines=10 -q 5'}", :Enter
|
||||||
|
2.times do
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[-2].include?('/90') &&
|
||||||
|
lines[-3] == ' 1' &&
|
||||||
|
lines[-4] == ' 2' &&
|
||||||
|
lines[-13] == '> 15'
|
||||||
|
end
|
||||||
|
tmux.send_keys :Down
|
||||||
|
end
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal '15', readonce.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_lines_reverse
|
||||||
|
tmux.send_keys "seq 100 | #{fzf '--header-lines=10 -q 5 --reverse'}", :Enter
|
||||||
|
2.times do
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[1].include?('/90') &&
|
||||||
|
lines[2] == ' 1' &&
|
||||||
|
lines[3] == ' 2' &&
|
||||||
|
lines[12] == '> 15'
|
||||||
|
end
|
||||||
|
tmux.send_keys :Up
|
||||||
|
end
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal '15', readonce.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_lines_overflow
|
||||||
|
tmux.send_keys "seq 100 | #{fzf '--header-lines=200'}", :Enter
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[-2].include?('0/0') &&
|
||||||
|
lines[-3].include?(' 1')
|
||||||
|
end
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal '', readonce.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_lines_with_nth
|
||||||
|
tmux.send_keys "seq 100 | #{fzf "--header-lines 5 --with-nth 1,1,1,1,1"}", :Enter
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[-2].include?('95/95') &&
|
||||||
|
lines[-3] == ' 11111' &&
|
||||||
|
lines[-7] == ' 55555' &&
|
||||||
|
lines[-8] == '> 66666'
|
||||||
|
end
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal '6', readonce.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_file
|
||||||
|
tmux.send_keys "seq 100 | #{fzf "--header-file <(head -5 #{__FILE__})"}", :Enter
|
||||||
|
header = File.readlines(__FILE__).take(5).map(&:strip)
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[-2].include?('100/100') &&
|
||||||
|
lines[-7..-3].map(&:strip) == header
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_header_file_reverse
|
||||||
|
tmux.send_keys "seq 100 | #{fzf "--header-file=<(head -5 #{__FILE__}) --reverse"}", :Enter
|
||||||
|
header = File.readlines(__FILE__).take(5).map(&:strip)
|
||||||
|
tmux.until do |lines|
|
||||||
|
lines[1].include?('100/100') &&
|
||||||
|
lines[2..6].map(&:strip) == header
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_canel
|
||||||
|
tmux.send_keys "seq 10 | #{fzf "--bind 2:cancel"}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include?('10/10') }
|
||||||
|
tmux.send_keys '123'
|
||||||
|
tmux.until { |lines| lines[-1] == '> 3' && lines[-2].include?('1/10') }
|
||||||
|
tmux.send_keys 'C-y', 'C-y'
|
||||||
|
tmux.until { |lines| lines[-1] == '> 311' }
|
||||||
|
tmux.send_keys 2
|
||||||
|
tmux.until { |lines| lines[-1] == '>' }
|
||||||
|
tmux.send_keys 2
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_margin
|
||||||
|
tmux.send_keys "yes | head -1000 | #{fzf "--margin 5,3"}", :Enter
|
||||||
|
tmux.until { |lines| lines[4] == '' && lines[5] == ' y' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_margin_reverse
|
||||||
|
tmux.send_keys "seq 1000 | #{fzf "--margin 7,5 --reverse"}", :Enter
|
||||||
|
tmux.until { |lines| lines[1 + 7] == ' 1000/1000' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_invalid_term
|
||||||
|
tmux.send_keys "TERM=xxx fzf", :Enter
|
||||||
|
tmux.until { |lines| lines.any? { |l| l.include? 'Invalid $TERM: xxx' } }
|
||||||
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
def writelines path, lines
|
def writelines path, lines
|
||||||
File.unlink path while File.exists? path
|
File.unlink path while File.exists? path
|
||||||
@@ -552,12 +790,20 @@ module TestShell
|
|||||||
@tmux.kill
|
@tmux.kill
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def set_var name, val
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys "export #{name}='#{val}'", :Enter
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
def test_ctrl_t
|
def test_ctrl_t
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'C-t', pane: 0
|
tmux.send_keys 'C-t', pane: 0
|
||||||
lines = tmux.until(1) { |lines| lines.item_count > 1 }
|
lines = tmux.until(1) { |lines| lines.item_count > 1 }
|
||||||
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
tmux.send_keys :BTab, :BTab, :Enter, pane: 1
|
tmux.send_keys :BTab, :BTab, pane: 1
|
||||||
|
tmux.until(1) { |lines| lines[-2].include?('(2)') }
|
||||||
|
tmux.send_keys :Enter, pane: 1
|
||||||
tmux.until(0) { |lines| lines[-1].include? expected }
|
tmux.until(0) { |lines| lines[-1].include? expected }
|
||||||
tmux.send_keys 'C-c'
|
tmux.send_keys 'C-c'
|
||||||
|
|
||||||
@@ -566,15 +812,27 @@ module TestShell
|
|||||||
tmux.send_keys 'C-t', pane: 0
|
tmux.send_keys 'C-t', pane: 0
|
||||||
lines = tmux.until(0) { |lines| lines.item_count > 1 }
|
lines = tmux.until(0) { |lines| lines.item_count > 1 }
|
||||||
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
tmux.send_keys :BTab, :BTab, :Enter, pane: 0
|
tmux.send_keys :BTab, :BTab, pane: 0
|
||||||
|
tmux.until(0) { |lines| lines[-2].include?('(2)') }
|
||||||
|
tmux.send_keys :Enter, pane: 0
|
||||||
tmux.until(0) { |lines| lines[-1].include? expected }
|
tmux.until(0) { |lines| lines[-1].include? expected }
|
||||||
tmux.send_keys 'C-c', 'C-d'
|
tmux.send_keys 'C-c', 'C-d'
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_ctrl_t_command
|
||||||
|
set_var "FZF_CTRL_T_COMMAND", "seq 100"
|
||||||
|
tmux.send_keys 'C-t', pane: 0
|
||||||
|
lines = tmux.until(1) { |lines| lines.item_count == 100 }
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab, pane: 1
|
||||||
|
tmux.until(1) { |lines| lines[-2].include?('(3)') }
|
||||||
|
tmux.send_keys :Enter, pane: 1
|
||||||
|
tmux.until(0) { |lines| lines[-1].include? '1 2 3' }
|
||||||
|
end
|
||||||
|
|
||||||
def test_alt_c
|
def test_alt_c
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys :Escape, :c, pane: 0
|
tmux.send_keys :Escape, :c, pane: 0
|
||||||
lines = tmux.until(1) { |lines| lines.item_count > 0 }
|
lines = tmux.until(1) { |lines| lines.item_count > 0 && lines[-3][2..-1] }
|
||||||
expected = lines[-3][2..-1]
|
expected = lines[-3][2..-1]
|
||||||
tmux.send_keys :Enter, pane: 1
|
tmux.send_keys :Enter, pane: 1
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
@@ -611,7 +869,9 @@ module CompletionTest
|
|||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab, pane: 0
|
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab, pane: 0
|
||||||
tmux.until(1) { |lines| lines.item_count > 0 }
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
tmux.send_keys :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab
|
||||||
|
tmux.until(1) { |lines| lines[-2].include?('(2)') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
tmux.until do |lines|
|
tmux.until do |lines|
|
||||||
tmux.send_keys 'C-L'
|
tmux.send_keys 'C-L'
|
||||||
lines[-1].include?('/tmp/fzf-test/10') &&
|
lines[-1].include?('/tmp/fzf-test/10') &&
|
||||||
@@ -708,6 +968,7 @@ class TestBash < TestBase
|
|||||||
include CompletionTest
|
include CompletionTest
|
||||||
|
|
||||||
def new_shell
|
def new_shell
|
||||||
|
tmux.prepare
|
||||||
tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter
|
tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
end
|
end
|
||||||
@@ -742,6 +1003,12 @@ class TestFish < TestBase
|
|||||||
tmux.until { |lines| lines.empty? }
|
tmux.until { |lines| lines.empty? }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def set_var name, val
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys "set -g #{name} '#{val}'", :Enter
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
def setup
|
def setup
|
||||||
super
|
super
|
||||||
@tmux = Tmux.new :fish
|
@tmux = Tmux.new :fish
|
||||||
|
Reference in New Issue
Block a user