mirror of
https://github.com/junegunn/fzf.git
synced 2025-07-28 10:42:00 -07:00
Compare commits
189 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
b28c14b93a | ||
|
879ead210f | ||
|
2f6d23b91e | ||
|
5f63a7b587 | ||
|
d9ce797d88 | ||
|
12230f8043 | ||
|
0c8de1ca44 | ||
|
89687105f4 | ||
|
74d1694be9 | ||
|
935e986be5 | ||
|
e5ac2ebd7c | ||
|
8d6e13bf94 | ||
|
2ca704405a | ||
|
802c1c2937 | ||
|
3cb5fef6b6 | ||
|
6da2e0aa1e | ||
|
24f3ec7f33 | ||
|
a57b375b41 | ||
|
6cc9d53978 | ||
|
df32c05833 | ||
|
c0652adf4c | ||
|
6ea760a336 | ||
|
f704b94603 | ||
|
444a67cafa | ||
|
f91cbd5688 | ||
|
3073ca3e5a | ||
|
b47ab633e2 | ||
|
09a2ab39fe | ||
|
6cf54833f7 | ||
|
2ccdf21a1f | ||
|
cf8afc527e | ||
|
1d6f05f974 | ||
|
85751966e9 | ||
|
a7bc9d5351 | ||
|
42c006d07c | ||
|
1b9ca314b8 | ||
|
e72a360337 | ||
|
45108ddd53 | ||
|
e3401a0645 | ||
|
26b9100709 | ||
|
a568120e42 | ||
|
e57182c658 | ||
|
6354dbbbdf | ||
|
2b3e740569 | ||
|
40d934e378 | ||
|
e95d82748f | ||
|
30bd0b53db | ||
|
1893eca41a | ||
|
82067463b8 | ||
|
ce9c51d399 | ||
|
96176476f3 | ||
|
68c84264af | ||
|
69438a55ca | ||
|
8695b5e319 | ||
|
95970164ad | ||
|
f6c6e59a50 | ||
|
45143f9541 | ||
|
23244bb410 | ||
|
edb647667e | ||
|
8d3a302a17 | ||
|
1d2d32c847 | ||
|
d635b3fd3c | ||
|
0f281ef894 | ||
|
b18db4733c | ||
|
6e08fe337c | ||
|
2a2c0a0957 | ||
|
4230b6f3c9 | ||
|
aa171b45cb | ||
|
661d06c90a | ||
|
a9aa263d3a | ||
|
6208fc9cfd | ||
|
e1dd798482 | ||
|
c8a3f6f06a | ||
|
3b9984379c | ||
|
a1b60b1d42 | ||
|
b5850ebd4c | ||
|
ac0a62e494 | ||
|
54b4b0c56f | ||
|
033afde3b5 | ||
|
a07944a5bb | ||
|
32010055e1 | ||
|
971ea2217c | ||
|
d513a210c6 | ||
|
a1db64e7b1 | ||
|
0b9c4e1e74 | ||
|
248320fa55 | ||
|
d4e26707c7 | ||
|
99ea1056ac | ||
|
7bcf4effa5 | ||
|
e1df876b61 | ||
|
28ffb9638d | ||
|
1c20255504 | ||
|
1fd884b34f | ||
|
701687faab | ||
|
bbc3055feb | ||
|
95c69083c7 | ||
|
57a37b5832 | ||
|
d29ae1c462 | ||
|
df468fc482 | ||
|
31278bcc68 | ||
|
e7e86b68f4 | ||
|
a89d8995c3 | ||
|
dbc854d5f4 | ||
|
f1cd0e2daf | ||
|
90d32bd756 | ||
|
e99731ea85 | ||
|
15659ac6e6 | ||
|
3ef41845a9 | ||
|
c84e681581 | ||
|
c3cf3427b1 | ||
|
2c4f71d85b | ||
|
c6328affae | ||
|
aaef18295d | ||
|
14f0d2035e | ||
|
64afff6b9a | ||
|
6bddffbca4 | ||
|
81a88693c1 | ||
|
68541e66b7 | ||
|
672b593634 | ||
|
5769d3867d | ||
|
724ffa3756 | ||
|
5694b5ed30 | ||
|
a1184ceb4e | ||
|
02203c7739 | ||
|
4d709e0dd2 | ||
|
ae04f56dbd | ||
|
f80ff8c917 | ||
|
b4ce89bbf5 | ||
|
486b87d821 | ||
|
b3010a4624 | ||
|
7d53051ec8 | ||
|
ed893c5f47 | ||
|
a4eb3323da | ||
|
1da065e50e | ||
|
86bc9d506f | ||
|
eee45a9578 | ||
|
659f49a09a | ||
|
8fa9e85980 | ||
|
92a75c9563 | ||
|
7c7a30c472 | ||
|
ea271cd4e2 | ||
|
6a38d07a4c | ||
|
c4e5ee63bb | ||
|
862da2c0b1 | ||
|
545370d2b3 | ||
|
59220c63a6 | ||
|
86306dd45a | ||
|
98d2bfa0db | ||
|
aec48f159b | ||
|
ad7e433a7d | ||
|
5a60aa5050 | ||
|
ebea470875 | ||
|
d980e00961 | ||
|
987799f8fb | ||
|
d2f3604c1d | ||
|
72cc558fdc | ||
|
6bc3fe6e67 | ||
|
9398878048 | ||
|
ca19762e58 | ||
|
8764be07e2 | ||
|
2022a3ad96 | ||
|
65d9d416b4 | ||
|
fa2f9f1f21 | ||
|
c656cfbdce | ||
|
de829c0938 | ||
|
64443221aa | ||
|
9017e29741 | ||
|
0a22142d88 | ||
|
ac160f98a8 | ||
|
62e01a2a62 | ||
|
5660cebaf6 | ||
|
a7e588ceac | ||
|
5baf1c5536 | ||
|
9a2d9ad947 | ||
|
90b0cd44ac | ||
|
698e8008df | ||
|
1de4cc3ba8 | ||
|
0d66ad23c6 | ||
|
7f7741099b | ||
|
5a72dc6922 | ||
|
80ed02e72e | ||
|
8fb31e1b4d | ||
|
148f21415a | ||
|
1c31e07d34 | ||
|
55d566b72f | ||
|
60336c7423 | ||
|
7ae877bd3a | ||
|
c601fc6437 | ||
|
e5fec408c4 |
29
.github/ISSUE_TEMPLATE.md
vendored
Normal file
29
.github/ISSUE_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
<!-- Check all that apply [x] -->
|
||||
- Category
|
||||
- [ ] fzf binary
|
||||
- [ ] fzf-tmux script
|
||||
- [ ] Key bindings
|
||||
- [ ] Completion
|
||||
- [ ] Vim
|
||||
- [ ] Neovim
|
||||
- [ ] Etc.
|
||||
- OS
|
||||
- [ ] Linux
|
||||
- [ ] Mac OS X
|
||||
- [ ] Windows
|
||||
- [ ] Etc.
|
||||
- Shell
|
||||
- [ ] bash
|
||||
- [ ] zsh
|
||||
- [ ] fish
|
||||
|
||||
<!--
|
||||
### Before submitting
|
||||
|
||||
- Make sure that you have the latest version of fzf
|
||||
- If you use tmux, make sure $TERM is set to screen or screen-256color
|
||||
- For more Vim stuff, check out https://github.com/junegunn/fzf.vim
|
||||
|
||||
Describe your problem or suggestion from here ...
|
||||
-->
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,6 @@
|
||||
bin
|
||||
src/fzf/fzf_*
|
||||
src/fzf/fzf-*
|
||||
gopath
|
||||
pkg
|
||||
Gemfile.lock
|
||||
.DS_Store
|
||||
|
@@ -4,7 +4,7 @@ rvm:
|
||||
|
||||
install:
|
||||
- sudo apt-get update
|
||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev
|
||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev libgpm-dev
|
||||
- sudo add-apt-repository -y ppa:pi-rho/dev
|
||||
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
||||
- sudo apt-get update
|
||||
|
103
CHANGELOG.md
103
CHANGELOG.md
@@ -1,6 +1,109 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
0.12.0
|
||||
------
|
||||
|
||||
- Enhanced ranking algorithm
|
||||
- Minor bug fixes
|
||||
|
||||
0.11.4
|
||||
------
|
||||
|
||||
- Added `--hscroll-off=COL` option (default: 10) (#513)
|
||||
- Some fixes in Vim plugin and shell extensions
|
||||
|
||||
0.11.3
|
||||
------
|
||||
|
||||
- Graceful exit on SIGTERM (#482)
|
||||
- `$SHELL` instead of `sh` for `execute` action and `$FZF_DEFAULT_COMMAND` (#481)
|
||||
- Changes in fuzzy completion API
|
||||
- [`_fzf_compgen_{path,dir}`](https://github.com/junegunn/fzf/commit/9617647)
|
||||
- [`_fzf_complete_COMMAND_post`](https://github.com/junegunn/fzf/commit/8206746)
|
||||
for post-processing
|
||||
|
||||
0.11.2
|
||||
------
|
||||
|
||||
- `--tiebreak` now accepts comma-separated list of sort criteria
|
||||
- Each criterion should appear only once in the list
|
||||
- `index` is only allowed at the end of the list
|
||||
- `index` is implicitly appended to the list when not specified
|
||||
- Default is `length` (or equivalently `length,index`)
|
||||
- `begin` criterion will ignore leading whitespaces when calculating the index
|
||||
- Added `toggle-in` and `toggle-out` actions
|
||||
- Switch direction depending on `--reverse`-ness
|
||||
- `export FZF_DEFAULT_OPTS="--bind tab:toggle-out,shift-tab:toggle-in"`
|
||||
- Reduced the initial delay when `--tac` is not given
|
||||
- fzf defers the initial rendering of the screen up to 100ms if the input
|
||||
stream is ongoing to prevent unnecessary redraw during the initial
|
||||
phase. However, 100ms delay is quite noticeable and might give the
|
||||
impression that fzf is not snappy enough. This commit reduces the
|
||||
maximum delay down to 20ms when `--tac` is not specified, in which case
|
||||
the input list quickly fills the entire screen.
|
||||
|
||||
0.11.1
|
||||
------
|
||||
|
||||
- Added `--tabstop=SPACES` option
|
||||
|
||||
0.11.0
|
||||
------
|
||||
|
||||
- Added OR operator for extended-search mode
|
||||
- Added `--execute-multi` action
|
||||
- Fixed incorrect cursor position when unicode wide characters are used in
|
||||
`--prompt`
|
||||
- Fixes and improvements in shell extensions
|
||||
|
||||
0.10.9
|
||||
------
|
||||
|
||||
- Extended-search mode is now enabled by default
|
||||
- `--extended-exact` is deprecated and instead we have `--exact` for
|
||||
orthogonally controlling "exactness" of search
|
||||
- Fixed not to display non-printable characters
|
||||
- Added `double-click` for `--bind` option
|
||||
- More robust handling of SIGWINCH
|
||||
|
||||
0.10.8
|
||||
------
|
||||
|
||||
- Fixed panic when trying to set colors after colors are disabled (#370)
|
||||
|
||||
0.10.7
|
||||
------
|
||||
|
||||
- Fixed unserialized interrupt handling during execute action which often
|
||||
caused invalid memory access and crash
|
||||
- Changed `--tiebreak=length` (default) to use trimmed length when `--nth` is
|
||||
used
|
||||
|
||||
0.10.6
|
||||
------
|
||||
|
||||
- Replaced `--header-file` with `--header` option
|
||||
- `--header` and `--header-lines` can be used together
|
||||
- Changed exit status
|
||||
- 0: Okay
|
||||
- 1: No match
|
||||
- 2: Error
|
||||
- 130: Interrupted
|
||||
- 64-bit linux binary is statically-linked with ncurses to avoid
|
||||
compatibility issues.
|
||||
|
||||
0.10.5
|
||||
------
|
||||
|
||||
- `'`-prefix to unquote the term in `--extended-exact` mode
|
||||
- Backward scan when `--tiebreak=end` is set
|
||||
|
||||
0.10.4
|
||||
------
|
||||
|
||||
- Fixed to remove ANSI code from output when `--with-nth` is set
|
||||
|
||||
0.10.3
|
||||
------
|
||||
|
||||
|
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Junegunn Choi
|
||||
Copyright (c) 2016 Junegunn Choi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
157
README.md
157
README.md
@@ -1,4 +1,4 @@
|
||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf) <a href="http://flattr.com/thing/3115381/junegunnfzf-on-GitHub" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a>
|
||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf)
|
||||
===
|
||||
|
||||
fzf is a general-purpose command-line fuzzy finder.
|
||||
@@ -21,7 +21,7 @@ Pros
|
||||
Installation
|
||||
------------
|
||||
|
||||
fzf project consists of the followings:
|
||||
fzf project consists of the following:
|
||||
|
||||
- `fzf` executable
|
||||
- `fzf-tmux` script for launching fzf in a tmux pane
|
||||
@@ -50,10 +50,10 @@ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
|
||||
On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
||||
|
||||
```sh
|
||||
brew reinstall --HEAD fzf
|
||||
brew install fzf
|
||||
|
||||
# Install shell extensions
|
||||
/usr/local/Cellar/fzf/HEAD/install
|
||||
/usr/local/opt/fzf/install
|
||||
```
|
||||
|
||||
#### Install as Vim plugin
|
||||
@@ -68,7 +68,7 @@ Or you can have [vim-plug](https://github.com/junegunn/vim-plug) manage fzf
|
||||
(recommended):
|
||||
|
||||
```vim
|
||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
|
||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
|
||||
```
|
||||
|
||||
#### Upgrading fzf
|
||||
@@ -78,7 +78,7 @@ while. Please follow the instruction below depending on the installation
|
||||
method.
|
||||
|
||||
- git: `cd ~/.fzf && git pull && ./install`
|
||||
- brew: `brew reinstall --HEAD fzf`
|
||||
- brew: `brew update; brew reinstall fzf`
|
||||
- vim-plug: `:PlugUpdate fzf`
|
||||
|
||||
Usage
|
||||
@@ -108,31 +108,41 @@ vim $(fzf)
|
||||
- Mouse: scroll, click, double-click; shift-click and shift-scroll on
|
||||
multi-select mode
|
||||
|
||||
#### Extended-search mode
|
||||
#### Search syntax
|
||||
|
||||
With `-x` or `--extended` option, fzf will start in "extended-search mode".
|
||||
Unless otherwise specified, fzf starts in "extended-search mode" where you can
|
||||
type in multiple search terms delimited by spaces. e.g. `^music .mp3$ sbtrkt
|
||||
!rmx`
|
||||
|
||||
In this mode, you can specify multiple patterns delimited by spaces,
|
||||
such as: `^music .mp3$ sbtrkt !rmx`
|
||||
| Token | Match type | Description |
|
||||
| -------- | -------------------- | -------------------------------- |
|
||||
| `sbtrkt` | fuzzy-match | Items that match `sbtrkt` |
|
||||
| `^music` | prefix-exact-match | Items that start with `music` |
|
||||
| `.mp3$` | suffix-exact-match | Items that end with `.mp3` |
|
||||
| `'wild` | exact-match (quoted) | Items that include `wild` |
|
||||
| `!rmx` | inverse-fuzzy-match | Items that do not match `rmx` |
|
||||
| `!'fire` | inverse-exact-match | Items that do not include `fire` |
|
||||
|
||||
| Token | Description | Match type |
|
||||
| -------- | -------------------------------- | -------------------- |
|
||||
| `^music` | Items that start with `music` | prefix-exact-match |
|
||||
| `.mp3$` | Items that end with `.mp3` | suffix-exact-match |
|
||||
| `sbtrkt` | Items that match `sbtrkt` | fuzzy-match |
|
||||
| `!rmx` | Items that do not match `rmx` | inverse-fuzzy-match |
|
||||
| `'wild` | Items that include `wild` | exact-match (quoted) |
|
||||
| `!'fire` | Items that do not include `fire` | inverse-exact-match |
|
||||
If you don't prefer fuzzy matching and do not wish to "quote" every word,
|
||||
start fzf with `-e` or `--exact` option. Note that when `--exact` is set,
|
||||
`'`-prefix "unquotes" the term.
|
||||
|
||||
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
||||
fzf with `-e` or `--extended-exact` option.
|
||||
A single bar character term acts as an OR operator. For example, the following
|
||||
query matches entries that start with `core` and end with either `go`, `rb`,
|
||||
or `py`.
|
||||
|
||||
```
|
||||
^core go$ | rb$ | py$
|
||||
```
|
||||
|
||||
#### Environment variables
|
||||
|
||||
- `FZF_DEFAULT_COMMAND`
|
||||
- Default command to use when input is tty
|
||||
- e.g. `export FZF_DEFAULT_COMMAND='ag -g ""'`
|
||||
- `FZF_DEFAULT_OPTS`
|
||||
- Default options. e.g. `export FZF_DEFAULT_OPTS="--extended --cycle"`
|
||||
- Default options
|
||||
- e.g. `export FZF_DEFAULT_OPTS="--reverse --inline-info"`
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -249,11 +259,33 @@ export FZF_COMPLETION_TRIGGER='~~'
|
||||
|
||||
# Options to fzf command
|
||||
export FZF_COMPLETION_OPTS='+c -x'
|
||||
|
||||
# Use ag instead of the default find command for listing candidates.
|
||||
# - The first argument to the function is the base path to start traversal
|
||||
# - Note that ag only lists files not directories
|
||||
# - See the source code (completion.{bash,zsh}) for the details.
|
||||
_fzf_compgen_path() {
|
||||
ag -g "" "$1"
|
||||
}
|
||||
```
|
||||
|
||||
#### Supported commands
|
||||
|
||||
On bash, fuzzy completion is enabled only for a predefined set of commands
|
||||
(`complete | grep _fzf` to see the list). But you can enable it for other
|
||||
commands as well like follows.
|
||||
|
||||
```sh
|
||||
# There are also _fzf_path_completion and _fzf_dir_completion
|
||||
complete -F _fzf_file_completion -o default -o bashdefault doge
|
||||
```
|
||||
|
||||
Usage as Vim plugin
|
||||
-------------------
|
||||
|
||||
This repository only enables basic integration with Vim. If you're looking for
|
||||
more, check out [fzf.vim](https://github.com/junegunn/fzf.vim) project.
|
||||
|
||||
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
||||
|
||||
#### `:FZF[!]`
|
||||
@@ -286,10 +318,8 @@ customization.
|
||||
|
||||
#### `fzf#run([options])`
|
||||
|
||||
For more advanced uses, you can call `fzf#run()` function which returns the list
|
||||
of the selected items.
|
||||
|
||||
`fzf#run()` may take an options-dictionary:
|
||||
For more advanced uses, you can use `fzf#run()` function with the following
|
||||
options.
|
||||
|
||||
| Option name | Type | Description |
|
||||
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
||||
@@ -305,65 +335,7 @@ of the selected items.
|
||||
| `launcher` | string | External terminal emulator to start fzf with (GVim only) |
|
||||
| `launcher` | funcref | Function for generating `launcher` string (GVim only) |
|
||||
|
||||
_However on Neovim `fzf#run` is asynchronous and does not return values so you
|
||||
should use `sink` or `sink*` to process the output from fzf._
|
||||
|
||||
##### Examples
|
||||
|
||||
If `sink` option is not given, `fzf#run` will simply return the list.
|
||||
|
||||
```vim
|
||||
let items = fzf#run({ 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
||||
```
|
||||
|
||||
But if `sink` is given as a string, the command will be executed for each
|
||||
selected item.
|
||||
|
||||
```vim
|
||||
" Each selected item will be opened in a new tab
|
||||
let items = fzf#run({ 'sink': 'tabe', 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
||||
```
|
||||
|
||||
We can also use a Vim list as the source as follows:
|
||||
|
||||
```vim
|
||||
" Choose a color scheme with fzf
|
||||
nnoremap <silent> <Leader>C :call fzf#run({
|
||||
\ 'source':
|
||||
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
|
||||
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
|
||||
\ 'sink': 'colo',
|
||||
\ 'options': '+m',
|
||||
\ 'left': 20,
|
||||
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
|
||||
\ })<CR>
|
||||
```
|
||||
|
||||
`sink` option can be a function reference. The following example creates a
|
||||
handy mapping that selects an open buffer.
|
||||
|
||||
```vim
|
||||
" List of buffers
|
||||
function! s:buflist()
|
||||
redir => ls
|
||||
silent ls
|
||||
redir END
|
||||
return split(ls, '\n')
|
||||
endfunction
|
||||
|
||||
function! s:bufopen(e)
|
||||
execute 'buffer' matchstr(a:e, '^[ 0-9]*')
|
||||
endfunction
|
||||
|
||||
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
||||
\ 'source': reverse(<sid>buflist()),
|
||||
\ 'sink': function('<sid>bufopen'),
|
||||
\ 'options': '+m',
|
||||
\ 'down': len(<sid>buflist()) + 2
|
||||
\ })<CR>
|
||||
```
|
||||
|
||||
More examples can be found on [the wiki
|
||||
Examples can be found on [the wiki
|
||||
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
||||
|
||||
Tips
|
||||
@@ -371,7 +343,7 @@ Tips
|
||||
|
||||
#### Rendering issues
|
||||
|
||||
If you have any rendering issues, check the followings:
|
||||
If you have any rendering issues, check the following:
|
||||
|
||||
1. Make sure `$TERM` is correctly set. fzf will use 256-color only if it
|
||||
contains `256` (e.g. `xterm-256color`)
|
||||
@@ -391,10 +363,10 @@ filtering:
|
||||
|
||||
```sh
|
||||
# Feed the output of ag into fzf
|
||||
ag -l -g "" | fzf
|
||||
ag -g "" | fzf
|
||||
|
||||
# Setting ag as the default source for fzf
|
||||
export FZF_DEFAULT_COMMAND='ag -l -g ""'
|
||||
export FZF_DEFAULT_COMMAND='ag -g ""'
|
||||
|
||||
# Now fzf (w/o pipe) will use ag instead of find
|
||||
fzf
|
||||
@@ -411,7 +383,8 @@ speed of the traversal.
|
||||
```sh
|
||||
export FZF_DEFAULT_COMMAND='
|
||||
(git ls-tree -r --name-only HEAD ||
|
||||
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
||||
find . -path "*/\.*" -prune -o -type f -print -o -type l -print |
|
||||
sed s/^..//) 2> /dev/null'
|
||||
```
|
||||
|
||||
#### Fish shell
|
||||
@@ -425,14 +398,6 @@ of fzf to a temporary file.
|
||||
fzf > $TMPDIR/fzf.result; and vim (cat $TMPDIR/fzf.result)
|
||||
```
|
||||
|
||||
#### Handling UTF-8 NFD paths on OSX
|
||||
|
||||
Use iconv to convert NFD paths to NFC:
|
||||
|
||||
```sh
|
||||
find . | iconv -f utf-8-mac -t utf8//ignore | fzf
|
||||
```
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
|
50
bin/fzf-tmux
50
bin/fzf-tmux
@@ -82,27 +82,43 @@ while [ $# -gt 0 ]; do
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "$TMUX_PANE" ] || tmux list-panes -F '#F' | grep -q Z; then
|
||||
if [ -z "$TMUX" ]; then
|
||||
fzf "${args[@]}"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
# Handle zoomed tmux pane by moving it to a temp window
|
||||
if tmux list-panes -F '#F' | grep -q Z; then
|
||||
zoomed=1
|
||||
original_window=$(tmux display-message -p "#{window_id}")
|
||||
tmp_window=$(tmux new-window -d -P -F "#{window_id}" "bash -c 'while :; do for c in \\| / - \\\\; do sleep 0.2; printf \"\\r\$c fzf-tmux is running\\r\"; done; done'")
|
||||
tmux swap-pane -t $tmp_window \; select-window -t $tmp_window
|
||||
fi
|
||||
|
||||
set -e
|
||||
|
||||
# Clean up named pipes on exit
|
||||
id=$RANDOM
|
||||
argsf=/tmp/fzf-args-$id
|
||||
fifo1=/tmp/fzf-fifo1-$id
|
||||
fifo2=/tmp/fzf-fifo2-$id
|
||||
fifo3=/tmp/fzf-fifo3-$id
|
||||
argsf="${TMPDIR:-/tmp}/fzf-args-$id"
|
||||
fifo1="${TMPDIR:-/tmp}/fzf-fifo1-$id"
|
||||
fifo2="${TMPDIR:-/tmp}/fzf-fifo2-$id"
|
||||
fifo3="${TMPDIR:-/tmp}/fzf-fifo3-$id"
|
||||
cleanup() {
|
||||
rm -f $argsf $fifo1 $fifo2 $fifo3
|
||||
|
||||
# Remove temp window if we were zoomed
|
||||
if [ -n "$zoomed" ]; then
|
||||
tmux swap-pane -t $original_window \; \
|
||||
select-window -t $original_window \; \
|
||||
kill-window -t $tmp_window \; \
|
||||
resize-pane -Z
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT SIGINT SIGTERM
|
||||
|
||||
fail() {
|
||||
>&2 echo "$1"
|
||||
exit 1
|
||||
exit 2
|
||||
}
|
||||
fzf="$(which fzf 2> /dev/null)" || fzf="$(dirname "$0")/fzf"
|
||||
[ -x "$fzf" ] || fail "fzf executable not found"
|
||||
@@ -111,26 +127,32 @@ envs="env TERM=$TERM "
|
||||
[ -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")"
|
||||
|
||||
mkfifo $fifo2
|
||||
mkfifo $fifo3
|
||||
mkfifo -m o+w $fifo2
|
||||
mkfifo -m o+w $fifo3
|
||||
|
||||
# Build arguments to fzf
|
||||
opts=""
|
||||
for arg in "${args[@]}"; do
|
||||
opts="$opts \"${arg//\"/\\\"}\""
|
||||
arg="${arg//\"/\\\"}"
|
||||
arg="${arg//\`/\\\`}"
|
||||
opts="$opts \"$arg\""
|
||||
done
|
||||
|
||||
if [ -n "$term" -o -t 0 ]; then
|
||||
cat <<< "$fzf $opts > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||
tmux set-window-option -q synchronize-panes off \;\
|
||||
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap
|
||||
tmux set-window-option synchronize-panes off \;\
|
||||
set-window-option remain-on-exit off \;\
|
||||
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap \
|
||||
> /dev/null 2>&1
|
||||
else
|
||||
mkfifo $fifo1
|
||||
cat <<< "$fzf $opts < $fifo1 > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||
tmux set-window-option -q synchronize-panes off \;\
|
||||
split-window $opt "$envs bash $argsf" $swap
|
||||
tmux set-window-option synchronize-panes off \;\
|
||||
set-window-option remain-on-exit off \;\
|
||||
split-window $opt "$envs bash $argsf" $swap \
|
||||
> /dev/null 2>&1
|
||||
cat <&0 > $fifo1 &
|
||||
fi
|
||||
cat $fifo2
|
||||
[ "$(cat $fifo3)" = '0' ]
|
||||
exit "$(cat $fifo3)"
|
||||
|
||||
|
4
fzf
4
fzf
@@ -370,7 +370,7 @@ class FZF
|
||||
+i Case-sensitive match
|
||||
-n, --nth=N[,..] Comma-separated list of field index expressions
|
||||
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
|
||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||
|
||||
@@ -396,7 +396,7 @@ class FZF
|
||||
|
||||
Environment variables
|
||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||
FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")] + $/ + $/
|
||||
FZF_DEFAULT_OPTS Default options (e.g. "-x -m --sort 10000")] + $/ + $/
|
||||
exit x
|
||||
end
|
||||
|
||||
|
261
install
261
install
@@ -1,36 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
[[ "$@" =~ --pre ]] && version=0.10.3 pre=1 ||
|
||||
version=0.10.3 pre=0
|
||||
set -u
|
||||
|
||||
cd $(dirname $BASH_SOURCE)
|
||||
fzf_base=$(pwd)
|
||||
[[ "$@" =~ --pre ]] && version=0.12.0 pre=1 ||
|
||||
version=0.12.0 pre=0
|
||||
|
||||
# If stdin is a tty, we are "interactive".
|
||||
[ -t 0 ] && interactive=yes
|
||||
auto_completion=
|
||||
key_bindings=
|
||||
update_config=2
|
||||
binary_arch=
|
||||
|
||||
help() {
|
||||
cat << EOF
|
||||
usage: $0 [OPTIONS]
|
||||
|
||||
--help Show this message
|
||||
--bin Download fzf binary only; Do not generate ~/.fzf.{bash,zsh}
|
||||
--all Download fzf binary and update configuration files
|
||||
to enable key bindings and fuzzy completion
|
||||
--[no-]key-bindings Enable/disable key bindings (CTRL-T, CTRL-R, ALT-C)
|
||||
--[no-]completion Enable/disable fuzzy completion (bash & zsh)
|
||||
--[no-]update-rc Whether or not to update shell configuration files
|
||||
|
||||
--32 Download 32-bit binary
|
||||
--64 Download 64-bit binary
|
||||
EOF
|
||||
}
|
||||
|
||||
for opt in "$@"; do
|
||||
case $opt in
|
||||
--help)
|
||||
help
|
||||
exit 0
|
||||
;;
|
||||
--all)
|
||||
auto_completion=1
|
||||
key_bindings=1
|
||||
update_config=1
|
||||
;;
|
||||
--key-bindings) key_bindings=1 ;;
|
||||
--no-key-bindings) key_bindings=0 ;;
|
||||
--completion) auto_completion=1 ;;
|
||||
--no-completion) auto_completion=0 ;;
|
||||
--update-rc) update_config=1 ;;
|
||||
--no-update-rc) update_config=0 ;;
|
||||
--32) binary_arch=386 ;;
|
||||
--64) binary_arch=amd64 ;;
|
||||
--bin|--pre) ;;
|
||||
*)
|
||||
echo "unknown option: $opt"
|
||||
help
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
fzf_base="$(pwd)"
|
||||
|
||||
ask() {
|
||||
# If stdin is a tty, we are "interactive".
|
||||
# non-interactive shell: wait for a linefeed
|
||||
# interactive shell: continue after a single keypress
|
||||
[ -n "$interactive" ] && read_n='-n 1' || read_n=
|
||||
read_n=$([ -t 0 ] && echo "-n 1")
|
||||
|
||||
read -p "$1 ([y]/n) " $read_n -r
|
||||
echo
|
||||
[[ ! $REPLY =~ ^[Nn]$ ]]
|
||||
[[ $REPLY =~ ^[Nn]$ ]]
|
||||
}
|
||||
|
||||
check_binary() {
|
||||
echo -n " - Checking fzf executable ... "
|
||||
local output=$("$fzf_base"/bin/fzf --version 2>&1)
|
||||
if [ "$version" = "$output" ]; then
|
||||
local output
|
||||
output=$("$fzf_base"/bin/fzf --version 2>&1)
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Error: $output"
|
||||
binary_error="Invalid binary"
|
||||
elif [ "$version" != "$output" ]; then
|
||||
echo "$output != $version"
|
||||
binary_error="Invalid version"
|
||||
else
|
||||
echo "$output"
|
||||
binary_error=""
|
||||
else
|
||||
echo "$output != $version"
|
||||
rm -f "$fzf_base"/bin/fzf
|
||||
binary_error="Invalid binary"
|
||||
return 1
|
||||
return 0
|
||||
fi
|
||||
rm -f "$fzf_base"/bin/fzf
|
||||
return 1
|
||||
}
|
||||
|
||||
symlink() {
|
||||
@@ -44,15 +99,27 @@ symlink() {
|
||||
fi
|
||||
}
|
||||
|
||||
link_fzf_in_path() {
|
||||
if which_fzf="$(command -v fzf)"; then
|
||||
echo " - Found in \$PATH"
|
||||
echo " - Creating symlink: $which_fzf -> bin/fzf"
|
||||
(cd "$fzf_base"/bin && rm -f fzf && ln -sf "$which_fzf" fzf)
|
||||
check_binary && return
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
download() {
|
||||
echo "Downloading bin/fzf ..."
|
||||
if [ $pre = 0 ]; then
|
||||
if [ -x "$fzf_base"/bin/fzf ]; then
|
||||
echo " - Already exists"
|
||||
check_binary && return
|
||||
elif [ -x "$fzf_base"/bin/$1 ]; then
|
||||
fi
|
||||
if [ -x "$fzf_base"/bin/$1 ]; then
|
||||
symlink $1 && check_binary && return
|
||||
fi
|
||||
link_fzf_in_path && return
|
||||
fi
|
||||
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
||||
if [ $? -ne 0 ]; then
|
||||
@@ -61,9 +128,9 @@ download() {
|
||||
fi
|
||||
|
||||
local url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}.tgz
|
||||
if which curl > /dev/null; then
|
||||
if command -v curl > /dev/null; then
|
||||
curl -fL $url | tar -xz
|
||||
elif which wget > /dev/null; then
|
||||
elif command -v wget > /dev/null; then
|
||||
wget -O - $url | tar -xz
|
||||
else
|
||||
binary_error="curl or wget not found"
|
||||
@@ -83,26 +150,19 @@ archi=$(uname -sm)
|
||||
binary_available=1
|
||||
binary_error=""
|
||||
case "$archi" in
|
||||
Darwin\ x86_64) download fzf-$version-darwin_amd64 ;;
|
||||
Darwin\ i*86) download fzf-$version-darwin_386 ;;
|
||||
Linux\ x86_64) download fzf-$version-linux_amd64 ;;
|
||||
Linux\ i*86) download fzf-$version-linux_386 ;;
|
||||
Darwin\ x86_64) download fzf-$version-darwin_${binary_arch:-amd64} ;;
|
||||
Darwin\ i*86) download fzf-$version-darwin_${binary_arch:-386} ;;
|
||||
Linux\ x86_64) download fzf-$version-linux_${binary_arch:-amd64} ;;
|
||||
Linux\ i*86) download fzf-$version-linux_${binary_arch:-386} ;;
|
||||
*) binary_available=0 binary_error=1 ;;
|
||||
esac
|
||||
|
||||
cd "$fzf_base"
|
||||
if [ -n "$binary_error" ]; then
|
||||
if [ $binary_available -eq 0 ]; then
|
||||
echo "No prebuilt binary for $archi ... "
|
||||
else
|
||||
echo " - $binary_error !!!"
|
||||
exit 1
|
||||
fi
|
||||
install_ruby_fzf() {
|
||||
echo "Installing legacy Ruby version ..."
|
||||
|
||||
# ruby executable
|
||||
echo -n "Checking Ruby executable ... "
|
||||
ruby=`which ruby`
|
||||
ruby=$(command -v ruby)
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "ruby executable not found !!!"
|
||||
exit 1
|
||||
@@ -110,7 +170,7 @@ if [ -n "$binary_error" ]; then
|
||||
|
||||
# System ruby is preferred
|
||||
system_ruby=/usr/bin/ruby
|
||||
if [ -x $system_ruby -a $system_ruby != "$ruby" ]; then
|
||||
if [ -x $system_ruby ] && [ $system_ruby != "$ruby" ]; then
|
||||
$system_ruby --disable-gems -rcurses -e0 2> /dev/null
|
||||
[ $? -eq 0 ] && ruby=$system_ruby
|
||||
fi
|
||||
@@ -163,43 +223,72 @@ if [ -n "$binary_error" ]; then
|
||||
echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf
|
||||
chmod +x "$fzf_base"/bin/fzf
|
||||
echo "OK"
|
||||
}
|
||||
|
||||
cd "$fzf_base"
|
||||
if [ -n "$binary_error" ]; then
|
||||
if [ $binary_available -eq 0 ]; then
|
||||
echo "No prebuilt binary for $archi ..."
|
||||
if command -v go > /dev/null; then
|
||||
echo -n "Building binary (go get github.com/junegunn/fzf/src/fzf) ... "
|
||||
if go get github.com/junegunn/fzf/src/fzf; then
|
||||
echo "OK"
|
||||
link_fzf_in_path
|
||||
else
|
||||
echo "Failed to build binary ..."
|
||||
install_ruby_fzf
|
||||
fi
|
||||
else
|
||||
echo "go executable not found. Cannot build binary ..."
|
||||
install_ruby_fzf
|
||||
fi
|
||||
else
|
||||
echo " - $binary_error !!!"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
[[ "$*" =~ "--bin" ]] && exit 0
|
||||
|
||||
# Auto-completion
|
||||
ask "Do you want to add auto-completion support?"
|
||||
auto_completion=$?
|
||||
if [ -z "$auto_completion" ]; then
|
||||
ask "Do you want to enable fuzzy auto-completion?"
|
||||
auto_completion=$?
|
||||
fi
|
||||
|
||||
# Key-bindings
|
||||
ask "Do you want to add key bindings?"
|
||||
key_bindings=$?
|
||||
if [ -z "$key_bindings" ]; then
|
||||
ask "Do you want to enable key bindings?"
|
||||
key_bindings=$?
|
||||
fi
|
||||
|
||||
echo
|
||||
for shell in bash zsh; do
|
||||
has_zsh=$(command -v zsh > /dev/null && echo 1 || echo 0)
|
||||
shells=$([ $has_zsh -eq 1 ] && echo "bash zsh" || echo "bash")
|
||||
for shell in $shells; do
|
||||
echo -n "Generate ~/.fzf.$shell ... "
|
||||
src=~/.fzf.${shell}
|
||||
|
||||
fzf_completion="[[ \$- =~ i ]] && source \"$fzf_base/shell/completion.${shell}\" 2> /dev/null"
|
||||
if [ $auto_completion -ne 0 ]; then
|
||||
fzf_completion="[[ \$- == *i* ]] && source \"$fzf_base/shell/completion.${shell}\" 2> /dev/null"
|
||||
if [ $auto_completion -eq 0 ]; then
|
||||
fzf_completion="# $fzf_completion"
|
||||
fi
|
||||
|
||||
fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""
|
||||
if [ $key_bindings -ne 0 ]; then
|
||||
if [ $key_bindings -eq 0 ]; then
|
||||
fzf_key_bindings="# $fzf_key_bindings"
|
||||
fi
|
||||
|
||||
cat > $src << EOF
|
||||
# Setup fzf
|
||||
# ---------
|
||||
if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then
|
||||
if [[ ! "\$PATH" == *$fzf_base/bin* ]]; then
|
||||
export PATH="\$PATH:$fzf_base/bin"
|
||||
fi
|
||||
|
||||
# Man path
|
||||
# --------
|
||||
if [[ ! "\$MANPATH" =~ "$fzf_base/man" && -d "$fzf_base/man" ]]; then
|
||||
if [[ ! "\$MANPATH" == *$fzf_base/man* && -d "$fzf_base/man" ]]; then
|
||||
export MANPATH="\$MANPATH:$fzf_base/man"
|
||||
fi
|
||||
|
||||
@@ -216,9 +305,8 @@ EOF
|
||||
done
|
||||
|
||||
# fish
|
||||
has_fish=0
|
||||
if [ -n "$(which fish 2> /dev/null)" ]; then
|
||||
has_fish=1
|
||||
has_fish=$(command -v fish > /dev/null && echo 1 || echo 0)
|
||||
if [ $has_fish -eq 1 ]; then
|
||||
echo -n "Update fish_user_paths ... "
|
||||
fish << EOF
|
||||
echo \$fish_user_paths | grep $fzf_base/bin > /dev/null
|
||||
@@ -232,51 +320,74 @@ EOF
|
||||
rm -f ~/.config/fish/functions/fzf.fish && echo "OK" || echo "Failed"
|
||||
fi
|
||||
|
||||
if [ $key_bindings -eq 0 ]; then
|
||||
echo -n "Symlink ~/.config/fish/functions/fzf_key_bindings.fish ... "
|
||||
ln -sf $fzf_base/shell/key-bindings.fish \
|
||||
~/.config/fish/functions/fzf_key_bindings.fish && echo "OK" || echo "Failed"
|
||||
fish_binding=~/.config/fish/functions/fzf_key_bindings.fish
|
||||
if [ $key_bindings -ne 0 ]; then
|
||||
echo -n "Symlink $fish_binding ... "
|
||||
ln -sf "$fzf_base/shell/key-bindings.fish" \
|
||||
"$fish_binding" && echo "OK" || echo "Failed"
|
||||
else
|
||||
echo -n "Removing $fish_binding ... "
|
||||
rm -f "$fish_binding"
|
||||
echo "OK"
|
||||
fi
|
||||
fi
|
||||
|
||||
append_line() {
|
||||
echo "Update $2:"
|
||||
echo " - $1"
|
||||
[ -f "$2" ] || touch "$2"
|
||||
if [ $# -lt 3 ]; then
|
||||
line=$(\grep -nF "$1" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
||||
set -e
|
||||
|
||||
local update line file pat lno
|
||||
update="$1"
|
||||
line="$2"
|
||||
file="$3"
|
||||
pat="${4:-}"
|
||||
|
||||
echo "Update $file:"
|
||||
echo " - $line"
|
||||
[ -f "$file" ] || touch "$file"
|
||||
if [ $# -lt 4 ]; then
|
||||
lno=$(\grep -nF "$line" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||
else
|
||||
line=$(\grep -nF "$3" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
||||
lno=$(\grep -nF "$pat" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||
fi
|
||||
if [ -n "$line" ]; then
|
||||
echo " - Already exists: line #$line"
|
||||
if [ -n "$lno" ]; then
|
||||
echo " - Already exists: line #$lno"
|
||||
else
|
||||
echo >> "$2"
|
||||
echo "$1" >> "$2"
|
||||
echo " + Added"
|
||||
if [ $update -eq 1 ]; then
|
||||
echo >> "$file"
|
||||
echo "$line" >> "$file"
|
||||
echo " + Added"
|
||||
else
|
||||
echo " ~ Skipped"
|
||||
fi
|
||||
fi
|
||||
echo
|
||||
set +e
|
||||
}
|
||||
|
||||
if [ $update_config -eq 2 ]; then
|
||||
echo
|
||||
ask "Do you want to update your shell configuration files?"
|
||||
update_config=$?
|
||||
fi
|
||||
echo
|
||||
for shell in bash zsh; do
|
||||
append_line "[ -f ~/.fzf.${shell} ] && source ~/.fzf.${shell}" ~/.${shell}rc "~/.fzf.${shell}"
|
||||
for shell in $shells; do
|
||||
[ $shell = zsh ] && dest=${ZDOTDIR:-~}/.zshrc || dest=~/.bashrc
|
||||
append_line $update_config "[ -f ~/.fzf.${shell} ] && source ~/.fzf.${shell}" "$dest" "~/.fzf.${shell}"
|
||||
done
|
||||
|
||||
if [ $key_bindings -eq 0 -a $has_fish -eq 1 ]; then
|
||||
if [ $key_bindings -eq 1 ] && [ $has_fish -eq 1 ]; then
|
||||
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
||||
append_line "fzf_key_bindings" "$bind_file"
|
||||
append_line $update_config "fzf_key_bindings" "$bind_file"
|
||||
fi
|
||||
|
||||
cat << EOF
|
||||
Finished. Restart your shell or reload config file.
|
||||
source ~/.bashrc # bash
|
||||
source ~/.zshrc # zsh
|
||||
EOF
|
||||
[ $has_fish -eq 1 ] && echo " fzf_key_bindings # fish"; cat << EOF
|
||||
|
||||
Use uninstall script to remove fzf.
|
||||
|
||||
For more information, see: https://github.com/junegunn/fzf
|
||||
EOF
|
||||
if [ $update_config -eq 1 ]; then
|
||||
echo 'Finished. Restart your shell or reload config file.'
|
||||
echo ' source ~/.bashrc # bash'
|
||||
[ $has_zsh -eq 1 ] && echo " source ${ZDOTDIR:-~}/.zshrc # zsh"
|
||||
[ $has_fish -eq 1 ] && [ $key_bindings -eq 1 ] && echo ' fzf_key_bindings # fish'
|
||||
echo
|
||||
echo 'Use uninstall script to remove fzf.'
|
||||
echo
|
||||
fi
|
||||
echo 'For more information, see: https://github.com/junegunn/fzf'
|
||||
|
||||
|
121
man/man1/fzf.1
121
man/man1/fzf.1
@@ -1,7 +1,7 @@
|
||||
.ig
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Junegunn Choi
|
||||
Copyright (c) 2016 Junegunn Choi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -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
|
||||
THE SOFTWARE.
|
||||
..
|
||||
.TH fzf 1 "Aug 2015" "fzf 0.10.3" "fzf - a command-line fuzzy finder"
|
||||
.TH fzf 1 "Apr 2016" "fzf 0.12.0" "fzf - a command-line fuzzy finder"
|
||||
|
||||
.SH NAME
|
||||
fzf - a command-line fuzzy finder
|
||||
@@ -36,10 +36,11 @@ fzf is a general-purpose command-line fuzzy finder.
|
||||
.SS Search mode
|
||||
.TP
|
||||
.B "-x, --extended"
|
||||
Extended-search mode
|
||||
Extended-search mode. Since 0.10.9, this is enabled by default. You can disable
|
||||
it with \fB+x\fR or \fB--no-extended\fR.
|
||||
.TP
|
||||
.B "-e, --extended-exact"
|
||||
Extended-search mode (exact match)
|
||||
.B "-e, --exact"
|
||||
Enable exact-match
|
||||
.TP
|
||||
.B "-i"
|
||||
Case-insensitive match (default: smart-case match)
|
||||
@@ -67,10 +68,10 @@ Reverse the order of the input
|
||||
e.g. \fBhistory | fzf --tac --no-sort\fR
|
||||
.RE
|
||||
.TP
|
||||
.BI "--tiebreak=" "CRI"
|
||||
Sort criterion to use when the scores are tied
|
||||
.BI "--tiebreak=" "CRI[,..]"
|
||||
Comma-separated list of sort criteria to apply when the scores are tied.
|
||||
.br
|
||||
.R ""
|
||||
|
||||
.br
|
||||
.BR length " Prefers item with shorter length"
|
||||
.br
|
||||
@@ -80,6 +81,15 @@ Sort criterion to use when the scores are tied
|
||||
.br
|
||||
.BR index " Prefers item that appeared earlier in the input stream"
|
||||
.br
|
||||
|
||||
.br
|
||||
- Each criterion should appear only once in the list
|
||||
.br
|
||||
- \fBindex\fR is only allowed at the end of the list
|
||||
.br
|
||||
- \fBindex\fR is implicitly appended to the list when not specified
|
||||
.br
|
||||
- Default is \fBlength\fR (or equivalently \fBlength\fR,index)
|
||||
.SS Interface
|
||||
.TP
|
||||
.B "-m, --multi"
|
||||
@@ -134,7 +144,7 @@ Reverse orientation
|
||||
.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"
|
||||
@@ -145,23 +155,31 @@ Comma-separated expression for margins around the finder.
|
||||
.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
|
||||
.BI "--tabstop=" SPACES
|
||||
Number of spaces for a tab character (default: 8)
|
||||
.TP
|
||||
.B "--cycle"
|
||||
Enable cyclic scroll
|
||||
.TP
|
||||
.B "--no-hscroll"
|
||||
Disable horizontal scroll
|
||||
.TP
|
||||
.BI "--hscroll-off=" "COL"
|
||||
Number of screen columns to keep to the right of the highlighted substring
|
||||
(default: 10). Setting it to a large value will cause the text to be positioned
|
||||
on the center of the screen.
|
||||
.TP
|
||||
.B "--inline-info"
|
||||
Display finder info inline with the query
|
||||
.TP
|
||||
@@ -179,11 +197,11 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||
.RE
|
||||
|
||||
.RS
|
||||
.B AVAILABLE KEYS:
|
||||
.B AVAILABLE KEYS: (SYNONYMS)
|
||||
\fIctrl-[a-z]\fR
|
||||
\fIalt-[a-z]\fR
|
||||
\fIf[1-4]\fR
|
||||
\fIenter\fR (\fIreturn\fR)
|
||||
\fIenter\fR (\fIreturn\fR \fIctrl-m\fR)
|
||||
\fIspace\fR
|
||||
\fIbspace\fR (\fIbs\fR)
|
||||
\fIalt-bspace\fR (\fIalt-bs\fR)
|
||||
@@ -201,13 +219,14 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||
\fIpgdn\fR (\fIpage-down\fR)
|
||||
\fIshift-left\fR
|
||||
\fIshift-right\fR
|
||||
\fIdouble-click\fR
|
||||
or any single character
|
||||
.RE
|
||||
|
||||
.RS
|
||||
\fBACTION: DEFAULT BINDINGS:
|
||||
\fBACTION: DEFAULT BINDINGS (NOTES):
|
||||
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
||||
\fBaccept\fR \fIctrl-m (enter)\fR
|
||||
\fBaccept\fR \fIenter double-click\fR
|
||||
\fBbackward-char\fR \fIctrl-b left\fR
|
||||
\fBbackward-delete-char\fR \fIctrl-h bspace\fR
|
||||
\fBbackward-kill-word\fR \fIalt-bs\fR
|
||||
@@ -221,6 +240,7 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||
\fBdown\fR \fIctrl-j ctrl-n down\fR
|
||||
\fBend-of-line\fR \fIctrl-e end\fR
|
||||
\fBexecute(...)\fR (see below for the details)
|
||||
\fBexecute-multi(...)\fR (see below for the details)
|
||||
\fBforward-char\fR \fIctrl-f right\fR
|
||||
\fBforward-word\fR \fIalt-f shift-right\fR
|
||||
\fBignore\fR
|
||||
@@ -234,6 +254,8 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||
\fBtoggle\fR
|
||||
\fBtoggle-all\fR
|
||||
\fBtoggle-down\fR \fIctrl-i (tab)\fR
|
||||
\fBtoggle-in\fR (\fB--reverse\fR ? \fBtoggle-up\fR : \fBtoggle-down\fR)
|
||||
\fBtoggle-out\fR (\fB--reverse\fR ? \fBtoggle-down\fR : \fBtoggle-up\fR)
|
||||
\fBtoggle-sort\fR (equivalent to \fB--toggle-sort\fR)
|
||||
\fBtoggle-up\fR \fIbtab (shift-tab)\fR
|
||||
\fBunix-line-discard\fR \fIctrl-u\fR
|
||||
@@ -274,6 +296,12 @@ 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
|
||||
|
||||
\fBexecute-multi(...)\fR is an alternative action that executes the command
|
||||
with the selected entries when multi-select is enabled (\fB--multi\fR). With
|
||||
this action, \fB{}\fR is replaced with the double-quoted strings of the
|
||||
selected entries separated by spaces.
|
||||
|
||||
.RE
|
||||
.TP
|
||||
.BI "--history=" "HISTORY_FILE"
|
||||
@@ -285,11 +313,11 @@ When enabled, \fBCTRL-N\fR and \fBCTRL-P\fR are automatically remapped to
|
||||
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.
|
||||
.BI "--header=" "STR"
|
||||
The given string will be printed as the sticky header. The lines are displayed
|
||||
in the given order from top to bottom regardless of \fB--reverse\fR option, 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
|
||||
@@ -341,7 +369,11 @@ Default options. e.g. \fBexport FZF_DEFAULT_OPTS="--extended --cycle"\fR
|
||||
.SH EXIT STATUS
|
||||
.BR 0 " Normal exit"
|
||||
.br
|
||||
.BR 1 " Interrupted with \fBCTRL-C\fR or \fBESC\fR"
|
||||
.BR 1 " No match"
|
||||
.br
|
||||
.BR 2 " Error"
|
||||
.br
|
||||
.BR 130 " Interrupted with \fBCTRL-C\fR or \fBESC\fR"
|
||||
|
||||
.SH FIELD INDEX EXPRESSION
|
||||
|
||||
@@ -369,34 +401,51 @@ of field index expressions.
|
||||
|
||||
.SH EXTENDED SEARCH MODE
|
||||
|
||||
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,
|
||||
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
||||
Unless specified otherwise, fzf will start in "extended-search mode". In this
|
||||
mode, you can specify multiple patterns delimited by spaces, such as: \fB'wild
|
||||
^music .mp3$ sbtrkt !rmx\fR
|
||||
|
||||
.SS Exact-match (quoted)
|
||||
A term that is prefixed by a single-quote character (') is interpreted as an
|
||||
"exact-match" (or "non-fuzzy") term. fzf will search for the exact occurrences
|
||||
of the string.
|
||||
A term that is prefixed by a single-quote character (\fB'\fR) is interpreted as
|
||||
an "exact-match" (or "non-fuzzy") term. fzf will search for the exact
|
||||
occurrences of the string.
|
||||
|
||||
.SS Anchored-match
|
||||
A term can be prefixed by ^, or suffixed by $ to become an anchored-match term.
|
||||
Then fzf will search for the items that start with or end with the given
|
||||
string. An anchored-match term is also an exact-match term.
|
||||
A term can be prefixed by \fB^\fR, or suffixed by \fB$\fR to become an
|
||||
anchored-match term. Then fzf will search for the items that start with or end
|
||||
with the given string. An anchored-match term is also an exact-match term.
|
||||
|
||||
.SS Negation
|
||||
If a term is prefixed by !, fzf will exclude the items that satisfy the term
|
||||
from the result.
|
||||
If a term is prefixed by \fB!\fR, fzf will exclude the items that satisfy the
|
||||
term from the result.
|
||||
|
||||
.SS Extended-exact mode
|
||||
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
||||
with ') every word, start fzf with \fB-e\fR or \fB--extended-exact\fR option
|
||||
(instead of \fB-x\fR or \fB--extended\fR).
|
||||
.SS Exact-match by default
|
||||
If you don't prefer fuzzy matching and do not wish to "quote" (prefixing with
|
||||
\fB'\fR) every word, start fzf with \fB-e\fR or \fB--exact\fR option. Note that
|
||||
when \fB--exact\fR is set, \fB'\fR-prefix "unquotes" the term.
|
||||
|
||||
.SS OR operator
|
||||
A single bar character term acts as an OR operator. For example, the following
|
||||
query matches entries that start with \fBcore\fR and end with either \fBgo\fR,
|
||||
\fBrb\fR, or \fBpy\fR.
|
||||
|
||||
e.g. \fB^core go$ | rb$ | py$\fR
|
||||
|
||||
.SH AUTHOR
|
||||
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||
|
||||
.SH SEE ALSO
|
||||
.B Project homepage:
|
||||
.RS
|
||||
.I https://github.com/junegunn/fzf
|
||||
.RE
|
||||
.br
|
||||
|
||||
.br
|
||||
.B Extra Vim plugin:
|
||||
.RS
|
||||
.I https://github.com/junegunn/fzf.vim
|
||||
.RE
|
||||
|
||||
.SH LICENSE
|
||||
MIT
|
||||
|
192
plugin/fzf.vim
192
plugin/fzf.vim
@@ -1,4 +1,4 @@
|
||||
" Copyright (c) 2015 Junegunn Choi
|
||||
" Copyright (c) 2016 Junegunn Choi
|
||||
"
|
||||
" MIT License
|
||||
"
|
||||
@@ -40,9 +40,7 @@ function! s:fzf_exec()
|
||||
\ input('fzf executable not found. Download binary? (y/n) ') =~? '^y'
|
||||
redraw
|
||||
echo
|
||||
echohl WarningMsg
|
||||
echo 'Downloading fzf binary. Please wait ...'
|
||||
echohl None
|
||||
call s:warn('Downloading fzf binary. Please wait ...')
|
||||
let s:installed = 1
|
||||
call system(s:install.' --bin')
|
||||
return s:fzf_exec()
|
||||
@@ -54,17 +52,13 @@ function! s:fzf_exec()
|
||||
return s:exec
|
||||
endfunction
|
||||
|
||||
function! s:tmux_not_zoomed()
|
||||
return system('tmux list-panes -F "#F"') !~# 'Z'
|
||||
endfunction
|
||||
|
||||
function! s:tmux_enabled()
|
||||
if has('gui_running')
|
||||
return 0
|
||||
endif
|
||||
|
||||
if exists('s:tmux')
|
||||
return s:tmux && s:tmux_not_zoomed()
|
||||
return s:tmux
|
||||
endif
|
||||
|
||||
let s:tmux = 0
|
||||
@@ -72,7 +66,7 @@ function! s:tmux_enabled()
|
||||
let output = system('tmux -V')
|
||||
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
||||
endif
|
||||
return s:tmux && s:tmux_not_zoomed()
|
||||
return s:tmux
|
||||
endfunction
|
||||
|
||||
function! s:shellesc(arg)
|
||||
@@ -80,7 +74,7 @@ function! s:shellesc(arg)
|
||||
endfunction
|
||||
|
||||
function! s:escape(path)
|
||||
return escape(a:path, ' %#\')
|
||||
return escape(a:path, ' $%#''"\')
|
||||
endfunction
|
||||
|
||||
" Upgrade legacy options
|
||||
@@ -98,14 +92,24 @@ function! s:upgrade(dict)
|
||||
return copy
|
||||
endfunction
|
||||
|
||||
function! s:error(msg)
|
||||
echohl ErrorMsg
|
||||
echom a:msg
|
||||
echohl None
|
||||
endfunction
|
||||
|
||||
function! s:warn(msg)
|
||||
echohl WarningMsg
|
||||
echom a:msg
|
||||
echohl None
|
||||
endfunction
|
||||
|
||||
function! fzf#run(...) abort
|
||||
try
|
||||
let oshell = &shell
|
||||
set shell=sh
|
||||
if has('nvim') && bufexists('term://*:FZF')
|
||||
echohl WarningMsg
|
||||
echomsg 'FZF is already running!'
|
||||
echohl None
|
||||
call s:warn('FZF is already running!')
|
||||
return []
|
||||
endif
|
||||
let dict = exists('a:1') ? s:upgrade(a:1) : {}
|
||||
@@ -135,17 +139,13 @@ try
|
||||
let tmux = !has('nvim') && s:tmux_enabled() && s:splittable(dict)
|
||||
let command = prefix.(tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result
|
||||
|
||||
try
|
||||
if tmux
|
||||
return s:execute_tmux(dict, command, temps)
|
||||
elseif has('nvim')
|
||||
return s:execute_term(dict, command, temps)
|
||||
else
|
||||
return s:execute(dict, command, temps)
|
||||
endif
|
||||
finally
|
||||
call s:popd(dict)
|
||||
endtry
|
||||
if has('nvim')
|
||||
return s:execute_term(dict, command, temps)
|
||||
endif
|
||||
|
||||
let ret = tmux ? s:execute_tmux(dict, command, temps) : s:execute(dict, command, temps)
|
||||
call s:popd(dict, ret)
|
||||
return ret
|
||||
finally
|
||||
let &shell = oshell
|
||||
endtry
|
||||
@@ -164,7 +164,13 @@ function! s:fzf_tmux(dict)
|
||||
let size = ''
|
||||
for o in ['up', 'down', 'left', 'right']
|
||||
if s:present(a:dict, o)
|
||||
let size = '-'.o[0].(a:dict[o] == 1 ? '' : a:dict[o])
|
||||
let spec = a:dict[o]
|
||||
if (o == 'up' || o == 'down') && spec[0] == '~'
|
||||
let size = '-'.o[0].s:calc_size(&lines, spec[1:], a:dict)
|
||||
else
|
||||
" Legacy boolean option
|
||||
let size = '-'.o[0].(spec == 1 ? '' : spec)
|
||||
endif
|
||||
break
|
||||
endif
|
||||
endfor
|
||||
@@ -183,23 +189,35 @@ function! s:pushd(dict)
|
||||
return 1
|
||||
endif
|
||||
let a:dict.prev_dir = cwd
|
||||
execute 'chdir '.s:escape(a:dict.dir)
|
||||
execute 'chdir' s:escape(a:dict.dir)
|
||||
let a:dict.dir = getcwd()
|
||||
return 1
|
||||
endif
|
||||
return 0
|
||||
endfunction
|
||||
|
||||
function! s:popd(dict)
|
||||
if has_key(a:dict, 'prev_dir')
|
||||
execute 'chdir '.s:escape(remove(a:dict, 'prev_dir'))
|
||||
function! s:popd(dict, lines)
|
||||
" Since anything can be done in the sink function, there is no telling that
|
||||
" the change of the working directory was made by &autochdir setting.
|
||||
"
|
||||
" We use the following heuristic to determine whether to restore CWD:
|
||||
" - Always restore the current directory when &autochdir is disabled.
|
||||
" FIXME This makes it impossible to change directory from inside the sink
|
||||
" function when &autochdir is not used.
|
||||
" - In case of an error or an interrupt, a:lines will be empty.
|
||||
" And it will be an array of a single empty string when fzf was finished
|
||||
" without a match. In these cases, we presume that the change of the
|
||||
" directory is not expected and should be undone.
|
||||
if has_key(a:dict, 'prev_dir') &&
|
||||
\ (!&autochdir || (empty(a:lines) || len(a:lines) == 1 && empty(a:lines[0])))
|
||||
execute 'chdir' s:escape(remove(a:dict, 'prev_dir'))
|
||||
endif
|
||||
endfunction
|
||||
|
||||
function! s:xterm_launcher()
|
||||
let fmt = 'xterm -T "[fzf]" -bg "\%s" -fg "\%s" -geometry %dx%d+%d+%d -e bash -ic %%s'
|
||||
if has('gui_macvim')
|
||||
let fmt .= '; osascript -e "tell application \"MacVim\" to activate"'
|
||||
let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'
|
||||
endif
|
||||
return printf(fmt,
|
||||
\ synIDattr(hlID("Normal"), "bg"), synIDattr(hlID("Normal"), "fg"),
|
||||
@@ -208,31 +226,36 @@ endfunction
|
||||
unlet! s:launcher
|
||||
let s:launcher = function('s:xterm_launcher')
|
||||
|
||||
function! s:execute(dict, command, temps)
|
||||
function! s:exit_handler(code, command, ...)
|
||||
if a:code == 130
|
||||
return 0
|
||||
elseif a:code > 1
|
||||
call s:error('Error running ' . a:command)
|
||||
if !empty(a:000)
|
||||
sleep
|
||||
endif
|
||||
return 0
|
||||
endif
|
||||
return 1
|
||||
endfunction
|
||||
|
||||
function! s:execute(dict, command, temps) abort
|
||||
call s:pushd(a:dict)
|
||||
silent! !clear 2> /dev/null
|
||||
let escaped = escape(substitute(a:command, '\n', '\\n', 'g'), '%#')
|
||||
if has('gui_running')
|
||||
let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))
|
||||
let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher
|
||||
let command = printf(fmt, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
||||
let command = printf(fmt, "'".substitute(escaped, "'", "'\"'\"'", 'g')."'")
|
||||
else
|
||||
let command = a:command
|
||||
let command = escaped
|
||||
endif
|
||||
execute 'silent !'.command
|
||||
redraw!
|
||||
if v:shell_error
|
||||
" Do not print error message on exit status 1
|
||||
if v:shell_error > 1
|
||||
echohl ErrorMsg
|
||||
echo 'Error running ' . command
|
||||
endif
|
||||
return []
|
||||
else
|
||||
return s:callback(a:dict, a:temps)
|
||||
endif
|
||||
return s:exit_handler(v:shell_error, command) ? s:callback(a:dict, a:temps) : []
|
||||
endfunction
|
||||
|
||||
function! s:execute_tmux(dict, command, temps)
|
||||
function! s:execute_tmux(dict, command, temps) abort
|
||||
let command = a:command
|
||||
if s:pushd(a:dict)
|
||||
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
||||
@@ -241,19 +264,28 @@ function! s:execute_tmux(dict, command, temps)
|
||||
|
||||
call system(command)
|
||||
redraw!
|
||||
return s:callback(a:dict, a:temps)
|
||||
return s:exit_handler(v:shell_error, command) ? s:callback(a:dict, a:temps) : []
|
||||
endfunction
|
||||
|
||||
function! s:calc_size(max, val)
|
||||
function! s:calc_size(max, val, dict)
|
||||
if a:val =~ '%$'
|
||||
return a:max * str2nr(a:val[:-2]) / 100
|
||||
let size = a:max * str2nr(a:val[:-2]) / 100
|
||||
else
|
||||
return min([a:max, a:val])
|
||||
let size = min([a:max, str2nr(a:val)])
|
||||
endif
|
||||
|
||||
let srcsz = -1
|
||||
if type(get(a:dict, 'source', 0)) == type([])
|
||||
let srcsz = len(a:dict.source)
|
||||
endif
|
||||
|
||||
let opts = get(a:dict, 'options', '').$FZF_DEFAULT_OPTS
|
||||
let margin = stridx(opts, '--inline-info') > stridx(opts, '--no-inline-info') ? 1 : 2
|
||||
return srcsz >= 0 ? min([srcsz + margin, size]) : size
|
||||
endfunction
|
||||
|
||||
function! s:getpos()
|
||||
return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$')}
|
||||
return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}
|
||||
endfunction
|
||||
|
||||
function! s:split(dict)
|
||||
@@ -268,7 +300,11 @@ function! s:split(dict)
|
||||
let val = get(a:dict, dir, '')
|
||||
if !empty(val)
|
||||
let [cmd, resz, max] = triple
|
||||
let sz = s:calc_size(max, val)
|
||||
if (dir == 'up' || dir == 'down') && val[0] == '~'
|
||||
let sz = s:calc_size(max, val[1:], a:dict)
|
||||
else
|
||||
let sz = s:calc_size(max, val, {})
|
||||
endif
|
||||
execute cmd sz.'new'
|
||||
execute resz sz
|
||||
return
|
||||
@@ -277,18 +313,18 @@ function! s:split(dict)
|
||||
if s:present(a:dict, 'window')
|
||||
execute a:dict.window
|
||||
else
|
||||
tabnew
|
||||
execute (tabpagenr()-1).'tabnew'
|
||||
endif
|
||||
finally
|
||||
setlocal winfixwidth winfixheight buftype=nofile bufhidden=wipe nobuflisted
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
function! s:execute_term(dict, command, temps)
|
||||
function! s:execute_term(dict, command, temps) abort
|
||||
call s:split(a:dict)
|
||||
call s:pushd(a:dict)
|
||||
|
||||
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps, 'name': 'FZF' }
|
||||
let s:command = a:command
|
||||
function! fzf.on_exit(id, code)
|
||||
let pos = s:getpos()
|
||||
let inplace = pos == s:ppos " {'window': 'enew'}
|
||||
@@ -302,10 +338,15 @@ function! s:execute_term(dict, command, temps)
|
||||
wincmd p
|
||||
endif
|
||||
endif
|
||||
|
||||
if !s:exit_handler(a:code, s:command, 1)
|
||||
return
|
||||
endif
|
||||
|
||||
call s:pushd(self.dict)
|
||||
let ret = []
|
||||
try
|
||||
redraw!
|
||||
call s:callback(self.dict, self.temps)
|
||||
let ret = s:callback(self.dict, self.temps)
|
||||
|
||||
if inplace && bufnr('') == self.buf
|
||||
execute "normal! \<c-^>"
|
||||
@@ -315,20 +356,23 @@ function! s:execute_term(dict, command, temps)
|
||||
endif
|
||||
endif
|
||||
finally
|
||||
call s:popd(self.dict)
|
||||
call s:popd(self.dict, ret)
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
call s:pushd(a:dict)
|
||||
call termopen(a:command, fzf)
|
||||
call s:popd(a:dict, [])
|
||||
setlocal nospell
|
||||
setf fzf
|
||||
startinsert
|
||||
return []
|
||||
endfunction
|
||||
|
||||
function! s:callback(dict, temps)
|
||||
function! s:callback(dict, temps) abort
|
||||
let lines = []
|
||||
try
|
||||
if !filereadable(a:temps.result)
|
||||
let lines = []
|
||||
else
|
||||
if filereadable(a:temps.result)
|
||||
let lines = readfile(a:temps.result)
|
||||
if has_key(a:dict, 'sink')
|
||||
for line in lines
|
||||
@@ -347,18 +391,18 @@ try
|
||||
for tf in values(a:temps)
|
||||
silent! call delete(tf)
|
||||
endfor
|
||||
|
||||
return lines
|
||||
catch
|
||||
if stridx(v:exception, ':E325:') < 0
|
||||
echoerr v:exception
|
||||
endif
|
||||
finally
|
||||
return lines
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
let s:default_action = {
|
||||
\ 'ctrl-m': 'e',
|
||||
\ 'ctrl-t': 'tabedit',
|
||||
\ 'ctrl-t': 'tab split',
|
||||
\ 'ctrl-x': 'split',
|
||||
\ 'ctrl-v': 'vsplit' }
|
||||
|
||||
@@ -368,14 +412,30 @@ function! s:cmd_callback(lines) abort
|
||||
endif
|
||||
let key = remove(a:lines, 0)
|
||||
let cmd = get(s:action, key, 'e')
|
||||
if len(a:lines) > 1
|
||||
augroup fzf_swap
|
||||
autocmd SwapExists * let v:swapchoice='o'
|
||||
\| call s:warn('fzf: E325: swap file exists: '.expand('<afile>'))
|
||||
augroup END
|
||||
endif
|
||||
try
|
||||
let empty = empty(expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified
|
||||
let autochdir = &autochdir
|
||||
set noautochdir
|
||||
for item in a:lines
|
||||
execute cmd s:escape(item)
|
||||
if empty
|
||||
execute 'e' s:escape(item)
|
||||
let empty = 0
|
||||
else
|
||||
execute cmd s:escape(item)
|
||||
endif
|
||||
if exists('#BufEnter') && isdirectory(item)
|
||||
doautocmd BufEnter
|
||||
endif
|
||||
endfor
|
||||
finally
|
||||
let &autochdir = autochdir
|
||||
silent! autocmd! fzf_swap
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
@@ -384,7 +444,7 @@ function! s:cmd(bang, ...) abort
|
||||
let args = extend(['--expect='.join(keys(s:action), ',')], a:000)
|
||||
let opts = {}
|
||||
if len(args) > 0 && isdirectory(expand(args[-1]))
|
||||
let opts.dir = remove(args, -1)
|
||||
let opts.dir = substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g')
|
||||
endif
|
||||
if !a:bang
|
||||
let opts.down = get(g:, 'fzf_height', get(g:, 'fzf_tmux_height', s:default_height))
|
||||
|
@@ -10,9 +10,29 @@
|
||||
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||
|
||||
# To use custom commands instead of find, override _fzf_compgen_{path,dir}
|
||||
if ! declare -f _fzf_compgen_path > /dev/null; then
|
||||
_fzf_compgen_path() {
|
||||
echo "$1"
|
||||
\find -L "$1" \
|
||||
-name .git -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \
|
||||
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||
}
|
||||
fi
|
||||
|
||||
if ! declare -f _fzf_compgen_dir > /dev/null; then
|
||||
_fzf_compgen_dir() {
|
||||
\find -L "$1" \
|
||||
-name .git -prune -o -name .svn -prune -o -type d \
|
||||
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||
}
|
||||
fi
|
||||
|
||||
###########################################################
|
||||
|
||||
_fzf_orig_completion_filter() {
|
||||
sed 's/.*-F *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\2=\1;/' |
|
||||
sed 's/[^a-z0-9_= ;]/_/g'
|
||||
sed 's/^\(.*-F\) *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\3="\1 %s \3 #\2";/' |
|
||||
awk -F= '{gsub(/[^a-z0-9_= ;]/, "_", $1); print $1"="$2}'
|
||||
}
|
||||
|
||||
_fzf_opts_completion() {
|
||||
@@ -22,7 +42,7 @@ _fzf_opts_completion() {
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
opts="
|
||||
-x --extended
|
||||
-e --extended-exact
|
||||
-e --exact
|
||||
-i +i
|
||||
-n --nth
|
||||
-d --delimiter
|
||||
@@ -49,27 +69,27 @@ _fzf_opts_completion() {
|
||||
--cycle
|
||||
--history
|
||||
--history-size
|
||||
--header-file
|
||||
--header
|
||||
--header-lines
|
||||
--margin"
|
||||
|
||||
case "${prev}" in
|
||||
--tiebreak)
|
||||
COMPREPLY=( $(compgen -W "length begin end index" -- ${cur}) )
|
||||
COMPREPLY=( $(compgen -W "length begin end index" -- "$cur") )
|
||||
return 0
|
||||
;;
|
||||
--color)
|
||||
COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )
|
||||
COMPREPLY=( $(compgen -W "dark light 16 bw" -- "$cur") )
|
||||
return 0
|
||||
;;
|
||||
--history|--header-file)
|
||||
--history)
|
||||
COMPREPLY=()
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
if [[ "$cur" =~ ^-|\+ ]]; then
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )
|
||||
return 0
|
||||
fi
|
||||
|
||||
@@ -77,42 +97,43 @@ _fzf_opts_completion() {
|
||||
}
|
||||
|
||||
_fzf_handle_dynamic_completion() {
|
||||
local cmd orig ret orig_cmd
|
||||
local cmd orig_var orig ret orig_cmd
|
||||
cmd="$1"
|
||||
shift
|
||||
orig_cmd="$1"
|
||||
|
||||
orig=$(eval "echo \$_fzf_orig_completion_$cmd")
|
||||
orig_var="_fzf_orig_completion_$cmd"
|
||||
orig="${!orig_var##*#}"
|
||||
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
||||
$orig "$@"
|
||||
elif [ -n "$_fzf_completion_loader" ]; then
|
||||
_completion_loader "$@"
|
||||
ret=$?
|
||||
eval $(complete | \grep "\-F.* $orig_cmd$" | _fzf_orig_completion_filter)
|
||||
source $BASH_SOURCE
|
||||
eval "$(complete | \grep "\-F.* $orig_cmd$" | _fzf_orig_completion_filter)"
|
||||
source "${BASH_SOURCE[0]}"
|
||||
return $ret
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion() {
|
||||
local cur base dir leftover matches trigger cmd fzf
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||
[ "${FZF_TMUX:-1}" != 0 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
cmd=$(echo "${COMP_WORDS[0]}" | sed 's/[^a-z0-9_=]/_/g')
|
||||
COMPREPLY=()
|
||||
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
if [[ ${cur} == *"$trigger" ]]; then
|
||||
if [[ "$cur" == *"$trigger" ]]; then
|
||||
base=${cur:0:${#cur}-${#trigger}}
|
||||
eval base=$base
|
||||
eval "base=$base"
|
||||
|
||||
dir="$base"
|
||||
while [ 1 ]; do
|
||||
if [ -z "$dir" -o -d "$dir" ]; then
|
||||
while true; do
|
||||
if [ -z "$dir" ] || [ -d "$dir" ]; then
|
||||
leftover=${base/#"$dir"}
|
||||
leftover=${leftover/#\/}
|
||||
[ "$dir" = './' ] && dir=''
|
||||
[ -z "$dir" ] && dir='.'
|
||||
[ "$dir" != "/" ] && dir="${dir/%\//}"
|
||||
tput sc
|
||||
matches=$(find -L "$dir"* $1 2> /dev/null | $fzf $FZF_COMPLETION_OPTS $2 -q "$leftover" | while read item; do
|
||||
matches=$(eval "$1 $(printf %q "$dir")" | $fzf $FZF_COMPLETION_OPTS $2 -q "$leftover" | while read -r item; do
|
||||
printf "%q$3 " "$item"
|
||||
done)
|
||||
matches=${matches% }
|
||||
@@ -135,19 +156,21 @@ _fzf_path_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_list_completion() {
|
||||
local cur selected trigger cmd src fzf
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
read -r src
|
||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||
_fzf_complete() {
|
||||
local cur selected trigger cmd fzf post
|
||||
post="$(caller 0 | awk '{print $2}')_post"
|
||||
type -t "$post" > /dev/null 2>&1 || post=cat
|
||||
[ "${FZF_TMUX:-1}" != 0 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
|
||||
cmd=$(echo "${COMP_WORDS[0]}" | sed 's/[^a-z0-9_=]/_/g')
|
||||
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
if [[ ${cur} == *"$trigger" ]]; then
|
||||
if [[ "$cur" == *"$trigger" ]]; then
|
||||
cur=${cur:0:${#cur}-${#trigger}}
|
||||
|
||||
tput sc
|
||||
selected=$(eval "$src | $fzf $FZF_COMPLETION_OPTS $1 -q '$cur'" | tr '\n' ' ')
|
||||
selected=${selected% }
|
||||
selected=$(cat | $fzf $FZF_COMPLETION_OPTS $1 -q "$cur" | $post | tr '\n' ' ')
|
||||
selected=${selected% } # Strip trailing space not to repeat "-o nospace"
|
||||
tput rc
|
||||
|
||||
if [ -n "$selected" ]; then
|
||||
@@ -160,29 +183,24 @@ _fzf_list_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_all_completion() {
|
||||
_fzf_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||
"-m" "" "$@"
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"
|
||||
}
|
||||
|
||||
# Deprecated. No file only completion.
|
||||
_fzf_file_completion() {
|
||||
_fzf_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type f -print -o -type l -print" \
|
||||
"-m" "" "$@"
|
||||
_fzf_path_completion "$@"
|
||||
}
|
||||
|
||||
_fzf_dir_completion() {
|
||||
_fzf_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||
"" "/" "$@"
|
||||
__fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"
|
||||
}
|
||||
|
||||
_fzf_kill_completion() {
|
||||
_fzf_complete_kill() {
|
||||
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
||||
|
||||
local selected fzf
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
[ "${FZF_TMUX:-1}" != 0 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
tput sc
|
||||
selected=$(ps -ef | sed 1d | $fzf -m $FZF_COMPLETION_OPTS | awk '{print $2}' | tr '\n' ' ')
|
||||
tput rc
|
||||
@@ -193,40 +211,48 @@ _fzf_kill_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_telnet_completion() {
|
||||
_fzf_list_completion '+m' "$@" << "EOF"
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_telnet() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_ssh_completion() {
|
||||
_fzf_list_completion '+m' "$@" << "EOF"
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_ssh() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') \
|
||||
<(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_env_var_completion() {
|
||||
_fzf_list_completion '-m' "$@" << "EOF"
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
EOF
|
||||
_fzf_complete_unset() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_alias_completion() {
|
||||
_fzf_list_completion '-m' "$@" << "EOF"
|
||||
alias | sed 's/=.*//' | sed 's/.* //'
|
||||
EOF
|
||||
_fzf_complete_export() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_complete_unalias() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
alias | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
# fzf options
|
||||
complete -o default -F _fzf_opts_completion fzf
|
||||
|
||||
d_cmds="cd pushd rmdir"
|
||||
f_cmds="
|
||||
awk cat diff diff3
|
||||
emacs ex file ftp g++ gcc gvim head hg java
|
||||
javac ld less more mvim patch perl python ruby
|
||||
sed sftp sort source tail tee uniq vi view vim wc"
|
||||
d_cmds="${FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir}"
|
||||
a_cmds="
|
||||
awk cat diff diff3
|
||||
emacs emacsclient ex file ftp g++ gcc gvim head hg java
|
||||
javac ld less more mvim nvim patch perl python ruby
|
||||
sed sftp sort source tail tee uniq vi view vim wc xdg-open
|
||||
basename bunzip2 bzip2 chmod chown curl cp dirname du
|
||||
find git grep gunzip gzip hg jar
|
||||
ln ls mv open rm rsync scp
|
||||
@@ -234,42 +260,53 @@ a_cmds="
|
||||
x_cmds="kill ssh telnet unset unalias export"
|
||||
|
||||
# Preserve existing completion
|
||||
if [ "$_fzf_completion_loaded" != '0.9.12' ]; then
|
||||
if [ "$_fzf_completion_loaded" != '0.11.3' ]; then
|
||||
# Really wish I could use associative array but OSX comes with bash 3.2 :(
|
||||
eval $(complete | \grep '\-F' | \grep -v _fzf_ |
|
||||
\grep -E " ($(echo $d_cmds $f_cmds $a_cmds $x_cmds | sed 's/ /|/g' | sed 's/+/\\+/g'))$" | _fzf_orig_completion_filter)
|
||||
export _fzf_completion_loaded=0.9.12
|
||||
\grep -E " ($(echo $d_cmds $a_cmds $x_cmds | sed 's/ /|/g' | sed 's/+/\\+/g'))$" | _fzf_orig_completion_filter)
|
||||
export _fzf_completion_loaded=0.11.3
|
||||
fi
|
||||
|
||||
if type _completion_loader > /dev/null 2>&1; then
|
||||
_fzf_completion_loader=1
|
||||
fi
|
||||
|
||||
# Directory
|
||||
for cmd in $d_cmds; do
|
||||
complete -F _fzf_dir_completion -o nospace -o plusdirs $cmd
|
||||
done
|
||||
|
||||
# File
|
||||
for cmd in $f_cmds; do
|
||||
complete -F _fzf_file_completion -o default -o bashdefault $cmd
|
||||
done
|
||||
_fzf_defc() {
|
||||
local cmd func opts orig_var orig
|
||||
cmd="$1"
|
||||
func="$2"
|
||||
opts="$3"
|
||||
orig_var="_fzf_orig_completion_$cmd"
|
||||
orig="${!orig_var}"
|
||||
if [ -n "$orig" ]; then
|
||||
eval "$(printf "$orig" "$func")"
|
||||
else
|
||||
complete -F "$func" $opts "$cmd"
|
||||
fi
|
||||
}
|
||||
|
||||
# Anything
|
||||
for cmd in $a_cmds; do
|
||||
complete -F _fzf_all_completion -o default -o bashdefault $cmd
|
||||
_fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"
|
||||
done
|
||||
|
||||
# Directory
|
||||
for cmd in $d_cmds; do
|
||||
_fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o plusdirs"
|
||||
done
|
||||
|
||||
unset _fzf_defc
|
||||
|
||||
# Kill completion
|
||||
complete -F _fzf_kill_completion -o nospace -o default -o bashdefault kill
|
||||
complete -F _fzf_complete_kill -o nospace -o default -o bashdefault kill
|
||||
|
||||
# Host completion
|
||||
complete -F _fzf_ssh_completion -o default -o bashdefault ssh
|
||||
complete -F _fzf_telnet_completion -o default -o bashdefault telnet
|
||||
complete -F _fzf_complete_ssh -o default -o bashdefault ssh
|
||||
complete -F _fzf_complete_telnet -o default -o bashdefault telnet
|
||||
|
||||
# Environment variables / Aliases
|
||||
complete -F _fzf_env_var_completion -o default -o bashdefault unset
|
||||
complete -F _fzf_env_var_completion -o default -o bashdefault export
|
||||
complete -F _fzf_alias_completion -o default -o bashdefault unalias
|
||||
complete -F _fzf_complete_unset -o default -o bashdefault unset
|
||||
complete -F _fzf_complete_export -o default -o bashdefault export
|
||||
complete -F _fzf_complete_unalias -o default -o bashdefault unalias
|
||||
|
||||
unset cmd d_cmds f_cmds a_cmds x_cmds
|
||||
unset cmd d_cmds a_cmds x_cmds
|
||||
|
@@ -10,17 +10,38 @@
|
||||
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||
|
||||
_fzf_path_completion() {
|
||||
local base lbuf find_opts fzf_opts suffix tail fzf dir leftover matches nnm
|
||||
# To use custom commands instead of find, override _fzf_compgen_{path,dir}
|
||||
if ! declare -f _fzf_compgen_path > /dev/null; then
|
||||
_fzf_compgen_path() {
|
||||
echo "$1"
|
||||
\find -L "$1" \
|
||||
-name .git -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \
|
||||
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||
}
|
||||
fi
|
||||
|
||||
if ! declare -f _fzf_compgen_dir > /dev/null; then
|
||||
_fzf_compgen_dir() {
|
||||
\find -L "$1" \
|
||||
-name .git -prune -o -name .svn -prune -o -type d \
|
||||
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||
}
|
||||
fi
|
||||
|
||||
###########################################################
|
||||
|
||||
__fzf_generic_path_completion() {
|
||||
local base lbuf compgen fzf_opts suffix tail fzf dir leftover matches nnm
|
||||
# (Q) flag removes a quoting level: "foo\ bar" => "foo bar"
|
||||
base=${(Q)1}
|
||||
lbuf=$2
|
||||
find_opts=$3
|
||||
compgen=$3
|
||||
fzf_opts=$4
|
||||
suffix=$5
|
||||
tail=$6
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
|
||||
if ! setopt | grep nonomatch > /dev/null; then
|
||||
if ! setopt | \grep nonomatch > /dev/null; then
|
||||
nnm=1
|
||||
setopt nonomatch
|
||||
fi
|
||||
@@ -29,9 +50,10 @@ _fzf_path_completion() {
|
||||
if [ -z "$dir" -o -d ${~dir} ]; then
|
||||
leftover=${base/#"$dir"}
|
||||
leftover=${leftover/#\/}
|
||||
[ "$dir" = './' ] && dir=''
|
||||
[ -z "$dir" ] && dir='.'
|
||||
[ "$dir" != "/" ] && dir="${dir/%\//}"
|
||||
dir=${~dir}
|
||||
matches=$(\find -L $dir* ${=find_opts} 2> /dev/null | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$leftover" | while read item; do
|
||||
matches=$(eval "$compgen $(printf %q "$dir")" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$leftover" | while read item; do
|
||||
printf "%q$suffix " "$item"
|
||||
done)
|
||||
matches=${matches% }
|
||||
@@ -47,65 +69,83 @@ _fzf_path_completion() {
|
||||
[ -n "$nnm" ] && unsetopt nonomatch
|
||||
}
|
||||
|
||||
_fzf_all_completion() {
|
||||
_fzf_path_completion "$1" "$2" \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion "$1" "$2" _fzf_compgen_path \
|
||||
"-m" "" " "
|
||||
}
|
||||
|
||||
_fzf_dir_completion() {
|
||||
_fzf_path_completion "$1" "$2" \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||
__fzf_generic_path_completion "$1" "$2" _fzf_compgen_dir \
|
||||
"" "/" ""
|
||||
}
|
||||
|
||||
_fzf_list_completion() {
|
||||
local prefix lbuf fzf_opts src fzf matches
|
||||
prefix=$1
|
||||
_fzf_feed_fifo() (
|
||||
rm -f "$1"
|
||||
mkfifo "$1"
|
||||
cat <&0 > "$1" &
|
||||
)
|
||||
|
||||
_fzf_complete() {
|
||||
local fifo fzf_opts lbuf fzf matches post
|
||||
fifo="${TMPDIR:-/tmp}/fzf-complete-fifo-$$"
|
||||
fzf_opts=$1
|
||||
lbuf=$2
|
||||
fzf_opts=$3
|
||||
read -r src
|
||||
post="${funcstack[2]}_post"
|
||||
type $post > /dev/null 2>&1 || post=cat
|
||||
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
|
||||
matches=$(eval "$src" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$prefix")
|
||||
_fzf_feed_fifo "$fifo"
|
||||
matches=$(cat "$fifo" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "${(Q)prefix}" | $post | tr '\n' ' ')
|
||||
if [ -n "$matches" ]; then
|
||||
LBUFFER="$lbuf$matches "
|
||||
LBUFFER="$lbuf$matches"
|
||||
fi
|
||||
zle redisplay
|
||||
rm -f "$fifo"
|
||||
}
|
||||
|
||||
_fzf_telnet_completion() {
|
||||
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_telnet() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_ssh_completion() {
|
||||
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_ssh() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') \
|
||||
<(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_env_var_completion() {
|
||||
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
EOF
|
||||
_fzf_complete_export() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_alias_completion() {
|
||||
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||
alias | sed 's/=.*//'
|
||||
EOF
|
||||
_fzf_complete_unset() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_complete_unalias() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
alias | sed 's/=.*//'
|
||||
)
|
||||
}
|
||||
|
||||
fzf-completion() {
|
||||
local tokens cmd prefix trigger tail fzf matches lbuf d_cmds
|
||||
setopt localoptions noshwordsplit
|
||||
|
||||
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
||||
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
||||
tokens=(${(z)LBUFFER})
|
||||
if [ ${#tokens} -lt 1 ]; then
|
||||
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||
zle ${fzf_default_completion:-expand-or-complete}
|
||||
return
|
||||
fi
|
||||
|
||||
@@ -126,33 +166,26 @@ fzf-completion() {
|
||||
zle redisplay
|
||||
# Trigger sequence given
|
||||
elif [ ${#tokens} -gt 1 -a "$tail" = "$trigger" ]; then
|
||||
d_cmds=(cd pushd rmdir)
|
||||
d_cmds=(${=FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir})
|
||||
|
||||
[ -z "$trigger" ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}
|
||||
[ -z "${tokens[-1]}" ] && lbuf=$LBUFFER || lbuf=${LBUFFER:0:-${#tokens[-1]}}
|
||||
|
||||
if [ ${d_cmds[(i)$cmd]} -le ${#d_cmds} ]; then
|
||||
_fzf_dir_completion "$prefix" $lbuf
|
||||
elif [ $cmd = telnet ]; then
|
||||
_fzf_telnet_completion "$prefix" $lbuf
|
||||
elif [ $cmd = ssh ]; then
|
||||
_fzf_ssh_completion "$prefix" $lbuf
|
||||
elif [ $cmd = unset -o $cmd = export ]; then
|
||||
_fzf_env_var_completion "$prefix" $lbuf
|
||||
elif [ $cmd = unalias ]; then
|
||||
_fzf_alias_completion "$prefix" $lbuf
|
||||
if eval "type _fzf_complete_${cmd} > /dev/null"; then
|
||||
eval "prefix=\"$prefix\" _fzf_complete_${cmd} \"$lbuf\""
|
||||
elif [ ${d_cmds[(i)$cmd]} -le ${#d_cmds} ]; then
|
||||
_fzf_dir_completion "$prefix" "$lbuf"
|
||||
else
|
||||
_fzf_all_completion "$prefix" $lbuf
|
||||
_fzf_path_completion "$prefix" "$lbuf"
|
||||
fi
|
||||
# Fall back to default completion
|
||||
else
|
||||
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||
zle ${fzf_default_completion:-expand-or-complete}
|
||||
fi
|
||||
}
|
||||
|
||||
[ -z "$fzf_default_completion" ] &&
|
||||
fzf_default_completion=$(bindkey '^I' | grep -v undefined-key | awk '{print $2}')
|
||||
fzf_default_completion=$(bindkey '^I' | \grep -v undefined-key | awk '{print $2}')
|
||||
|
||||
zle -N fzf-completion
|
||||
bindkey '^I' fzf-completion
|
||||
|
||||
|
@@ -1,11 +1,11 @@
|
||||
# Key bindings
|
||||
# ------------
|
||||
__fzf_select__() {
|
||||
local cmd="${FZF_CTRL_T_COMMAND:-"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 d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
eval "$cmd" | fzf -m | while read item; do
|
||||
eval "$cmd" | fzf -m | while read -r item; do
|
||||
printf '%q ' "$item"
|
||||
done
|
||||
echo
|
||||
@@ -14,7 +14,7 @@ __fzf_select__() {
|
||||
if [[ $- =~ i ]]; then
|
||||
|
||||
__fzfcmd() {
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||
[ "${FZF_TMUX:-1}" != 0 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||
}
|
||||
|
||||
__fzf_select_tmux__() {
|
||||
@@ -25,13 +25,23 @@ __fzf_select_tmux__() {
|
||||
else
|
||||
height="-l $height"
|
||||
fi
|
||||
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__)\"'"
|
||||
|
||||
tmux split-window $height "cd $(printf %q "$PWD"); FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS") PATH=$(printf %q "$PATH") FZF_CTRL_T_COMMAND=$(printf %q "$FZF_CTRL_T_COMMAND") bash -c 'source \"${BASH_SOURCE[0]}\"; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||
}
|
||||
|
||||
__fzf_select_tmux_auto__() {
|
||||
if [ "${FZF_TMUX:-1}" != 0 ] && [ ${LINES:-40} -gt 15 ]; then
|
||||
__fzf_select_tmux__
|
||||
else
|
||||
tmux send-keys -t "$TMUX_PANE" "$(__fzf_select__)"
|
||||
fi
|
||||
}
|
||||
|
||||
__fzf_cd__() {
|
||||
local dir
|
||||
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"
|
||||
local cmd dir
|
||||
cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
dir=$(eval "$cmd" | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||
}
|
||||
|
||||
__fzf_history__() (
|
||||
@@ -39,7 +49,7 @@ __fzf_history__() (
|
||||
shopt -u nocaseglob nocasematch
|
||||
line=$(
|
||||
HISTTIMEFORMAT= history |
|
||||
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r |
|
||||
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r $FZF_CTRL_R_OPTS |
|
||||
\grep '^ *[0-9]') &&
|
||||
if [[ $- =~ H ]]; then
|
||||
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||
@@ -49,7 +59,11 @@ __fzf_history__() (
|
||||
)
|
||||
|
||||
__use_tmux=0
|
||||
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
||||
__use_tmux_auto=0
|
||||
if [ -n "$TMUX_PANE" ]; then
|
||||
[ "${FZF_TMUX:-1}" != 0 ] && [ ${LINES:-40} -gt 15 ] && __use_tmux=1
|
||||
[ $BASH_VERSINFO -gt 3 ] && __use_tmux_auto=1
|
||||
fi
|
||||
|
||||
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||
# Required to refresh the prompt after fzf
|
||||
@@ -57,7 +71,9 @@ if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||
bind '"\e^": history-expand-line'
|
||||
|
||||
# CTRL-T - Paste the selected file path into the command line
|
||||
if [ $__use_tmux -eq 1 ]; then
|
||||
if [ $__use_tmux_auto -eq 1 ]; then
|
||||
bind -x '"\C-t": "__fzf_select_tmux_auto__"'
|
||||
elif [ $__use_tmux -eq 1 ]; then
|
||||
bind '"\C-t": " \C-u \C-a\C-k$(__fzf_select_tmux__)\e\C-e\C-y\C-a\C-d\C-y\ey\C-h"'
|
||||
else
|
||||
bind '"\C-t": " \C-u \C-a\C-k$(__fzf_select__)\e\C-e\C-y\C-a\C-y\ey\C-h\C-e\er \C-h"'
|
||||
@@ -69,28 +85,39 @@ if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||
# ALT-C - cd into the selected directory
|
||||
bind '"\ec": " \C-e\C-u$(__fzf_cd__)\e\C-e\er\C-m"'
|
||||
else
|
||||
# We'd usually use "\e" to enter vi-movement-mode so we can do our magic,
|
||||
# but this incurs a very noticeable delay of a half second or so,
|
||||
# because many other commands start with "\e".
|
||||
# Instead, we bind an unused key, "\C-x\C-a",
|
||||
# to also enter vi-movement-mode,
|
||||
# and then use that thereafter.
|
||||
# (We imagine that "\C-x\C-a" is relatively unlikely to be in use.)
|
||||
bind '"\C-x\C-a": vi-movement-mode'
|
||||
|
||||
bind '"\C-x\C-e": shell-expand-line'
|
||||
bind '"\C-x\C-r": redraw-current-line'
|
||||
bind '"\C-x^": history-expand-line'
|
||||
|
||||
# CTRL-T - Paste the selected file path into the command line
|
||||
# - FIXME: Selected items are attached to the end regardless of cursor position
|
||||
if [ $__use_tmux -eq 1 ]; then
|
||||
bind '"\C-t": "\e$a \eddi$(__fzf_select_tmux__)\C-x\C-e\e0P$xa"'
|
||||
if [ $__use_tmux_auto -eq 1 ]; then
|
||||
bind -x '"\C-t": "__fzf_select_tmux_auto__"'
|
||||
elif [ $__use_tmux -eq 1 ]; then
|
||||
bind '"\C-t": "\C-x\C-a$a \C-x\C-addi$(__fzf_select_tmux__)\C-x\C-e\C-x\C-a0P$xa"'
|
||||
else
|
||||
bind '"\C-t": "\e$a \eddi$(__fzf_select__)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
||||
bind '"\C-t": "\C-x\C-a$a \C-x\C-addi$(__fzf_select__)\C-x\C-e\C-x\C-a0Px$a \C-x\C-r\C-x\C-axa "'
|
||||
fi
|
||||
bind -m vi-command '"\C-t": "i\C-t"'
|
||||
|
||||
# CTRL-R - Paste the selected command from history into the command line
|
||||
bind '"\C-r": "\eddi$(__fzf_history__)\C-x\C-e\C-x^\e$a\C-x\C-r"'
|
||||
bind '"\C-r": "\C-x\C-addi$(__fzf_history__)\C-x\C-e\C-x^\C-x\C-a$a\C-x\C-r"'
|
||||
bind -m vi-command '"\C-r": "i\C-r"'
|
||||
|
||||
# ALT-C - cd into the selected directory
|
||||
bind '"\ec": "\eddi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||
bind -m vi-command '"\ec": "i\ec"'
|
||||
bind '"\ec": "\C-x\C-addi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||
bind -m vi-command '"\ec": "ddi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||
fi
|
||||
|
||||
unset __use_tmux
|
||||
unset -v __use_tmux __use_tmux_auto
|
||||
|
||||
fi
|
||||
|
@@ -19,23 +19,26 @@ function fzf_key_bindings
|
||||
-o -type f -print \
|
||||
-o -type d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"
|
||||
eval $FZF_CTRL_T_COMMAND | eval (__fzfcmd) -m > $TMPDIR/fzf.result
|
||||
eval "$FZF_CTRL_T_COMMAND | "(__fzfcmd)" -m > $TMPDIR/fzf.result"
|
||||
and sleep 0
|
||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||
commandline -f repaint
|
||||
rm -f $TMPDIR/fzf.result
|
||||
end
|
||||
|
||||
function __fzf_ctrl_r
|
||||
history | eval (__fzfcmd) +s +m --tiebreak=index --toggle-sort=ctrl-r > $TMPDIR/fzf.result
|
||||
history | eval (__fzfcmd) +s +m --tiebreak=index --toggle-sort=ctrl-r $FZF_CTRL_R_OPTS > $TMPDIR/fzf.result
|
||||
and commandline (cat $TMPDIR/fzf.result)
|
||||
commandline -f repaint
|
||||
rm -f $TMPDIR/fzf.result
|
||||
end
|
||||
|
||||
function __fzf_alt_c
|
||||
set -q FZF_ALT_C_COMMAND; or set -l FZF_ALT_C_COMMAND "
|
||||
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"
|
||||
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) \
|
||||
-prune -o -type d -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) +m > $TMPDIR/fzf.result
|
||||
eval "$FZF_ALT_C_COMMAND | "(__fzfcmd)" +m > $TMPDIR/fzf.result"
|
||||
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
||||
and cd (cat $TMPDIR/fzf.result)
|
||||
commandline -f repaint
|
||||
|
@@ -1,10 +1,10 @@
|
||||
# Key bindings
|
||||
# ------------
|
||||
if [[ $- =~ i ]]; then
|
||||
if [[ $- == *i* ]]; then
|
||||
|
||||
# CTRL-T - Paste the selected file path(s) into the command line
|
||||
__fsel() {
|
||||
local cmd="${FZF_CTRL_T_COMMAND:-"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 d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
@@ -27,8 +27,9 @@ bindkey '^T' fzf-file-widget
|
||||
|
||||
# ALT-C - cd into the selected directory
|
||||
fzf-cd-widget() {
|
||||
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):-.}"
|
||||
local cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
cd "${$(eval "$cmd" | $(__fzfcmd) +m):-.}"
|
||||
zle reset-prompt
|
||||
}
|
||||
zle -N fzf-cd-widget
|
||||
@@ -36,8 +37,9 @@ bindkey '\ec' fzf-cd-widget
|
||||
|
||||
# CTRL-R - Paste the selected command from history into the command line
|
||||
fzf-history-widget() {
|
||||
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
|
||||
local selected num
|
||||
selected=( $(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r ${=FZF_CTRL_R_OPTS} -q "${LBUFFER//$/\\$}") )
|
||||
if [ -n "$selected" ]; then
|
||||
num=$selected[1]
|
||||
if [ -n "$num" ]; then
|
||||
zle vi-fetch-history -n $num
|
||||
|
40
src/Dockerfile.android
Normal file
40
src/Dockerfile.android
Normal file
@@ -0,0 +1,40 @@
|
||||
FROM ubuntu:14.04
|
||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# apt-get
|
||||
RUN apt-get update && apt-get -y upgrade && \
|
||||
apt-get install -y --force-yes git curl build-essential
|
||||
|
||||
# Install Go 1.4
|
||||
RUN cd / && curl \
|
||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||
tar -xz && mv go go1.4 && \
|
||||
sed -i 's@#define PTHREAD_KEYS_MAX 128@@' /go1.4/src/runtime/cgo/gcc_android_arm.c
|
||||
|
||||
ENV GOROOT /go1.4
|
||||
ENV PATH /go1.4/bin:$PATH
|
||||
|
||||
RUN cd / && \
|
||||
curl -O http://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin && \
|
||||
chmod 755 /android-ndk* && /android-ndk-r10e-linux-x86_64.bin && \
|
||||
mv android-ndk-r10e /android-ndk
|
||||
|
||||
RUN cd /android-ndk && bash ./build/tools/make-standalone-toolchain.sh --platform=android-21 --install-dir=/ndk --arch=arm
|
||||
|
||||
ENV NDK_CC /ndk/bin/arm-linux-androideabi-gcc
|
||||
|
||||
RUN cd $GOROOT/src && \
|
||||
CC_FOR_TARGET=$NDK_CC GOOS=android GOARCH=arm GOARM=7 ./make.bash
|
||||
|
||||
RUN cd / && curl \
|
||||
http://ftp.gnu.org/gnu/ncurses/ncurses-5.9.tar.gz | \
|
||||
tar -xz && cd /ncurses-5.9 && \
|
||||
./configure CC=$NDK_CC CFLAGS="-fPIE -march=armv7-a -mfpu=neon -mhard-float -Wl,--no-warn-mismatch" LDFLAGS="-march=armv7-a -Wl,--no-warn-mismatch" --host=arm-linux --enable-overwrite --enable-const --without-cxx-binding --without-shared --without-debug --enable-widec --enable-ext-colors --enable-ext-mouse --enable-pc-files --with-pkg-config-libdir=$PKG_CONFIG_LIBDIR --without-manpages --without-ada --disable-shared --without-tests --prefix=/ndk/sysroot/usr --with-default-terminfo-dirs=/usr/share/terminfo --with-terminfo-dirs=/usr/share/terminfo ac_cv_header_locale_h=n ac_cv_func_getpwent=no ac_cv_func_getpwnam=no ac_cv_func_getpwuid=no && \
|
||||
sed -i 's@#define HAVE_LOCALE_H 1@/* #undef HAVE_LOCALE_H */@' include/ncurses_cfg.h && \
|
||||
make && \
|
||||
sed -i '0,/echo.*/{s/echo.*/exit 0/}' misc/run_tic.sh && \
|
||||
make install && \
|
||||
mv /ndk/sysroot/usr/lib/libncursesw.a /ndk/sysroot/usr/lib/libncurses.a
|
||||
|
||||
# Default CMD
|
||||
CMD cd /fzf/src && /bin/bash
|
@@ -2,6 +2,7 @@ FROM base/archlinux:2014.07.03
|
||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# apt-get
|
||||
RUN pacman-key --populate archlinux && pacman-key --refresh-keys
|
||||
RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git
|
||||
|
||||
# Install Go 1.4
|
||||
@@ -9,7 +10,6 @@ RUN cd / && curl \
|
||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||
tar -xz && mv go go1.4
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV GOROOT /go1.4
|
||||
ENV PATH /go1.4/bin:$PATH
|
||||
|
||||
@@ -19,9 +19,6 @@ RUN echo '[multilib]' >> /etc/pacman.conf && \
|
||||
pacman-db-upgrade && yes | pacman -Sy gcc-multilib lib32-ncurses && \
|
||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||
|
||||
# Volume
|
||||
VOLUME /go
|
||||
|
||||
# Default CMD
|
||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
||||
CMD cd /fzf/src && /bin/bash
|
||||
|
||||
|
@@ -1,21 +1,32 @@
|
||||
FROM centos:centos7
|
||||
FROM centos:centos6
|
||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# yum
|
||||
RUN yum install -y git gcc make tar ncurses-devel
|
||||
RUN yum install -y git gcc make tar glibc-devel glibc-devel.i686 \
|
||||
ncurses-devel ncurses-static ncurses-devel.i686 \
|
||||
gpm-devel gpm-static libgcc.i686
|
||||
|
||||
# Install Go 1.4
|
||||
RUN cd / && curl \
|
||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||
tar -xz && mv go go1.4
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV GOROOT /go1.4
|
||||
ENV PATH /go1.4/bin:$PATH
|
||||
# Install Go 1.5
|
||||
RUN cd / && curl \
|
||||
https://storage.googleapis.com/golang/go1.5.3.linux-amd64.tar.gz | \
|
||||
tar -xz && mv go go1.5
|
||||
|
||||
# Volume
|
||||
VOLUME /go
|
||||
# Install RPMs for building static 32-bit binary
|
||||
RUN curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.7/os/i386/Packages/ncurses-static-5.7-4.20090207.el6.i686.rpm -o rpm && rpm -i rpm && \
|
||||
curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.7/os/i386/Packages/gpm-static-1.20.6-12.el6.i686.rpm -o rpm && rpm -i rpm
|
||||
|
||||
ENV GOROOT_BOOTSTRAP /go1.4
|
||||
ENV GOROOT /go1.5
|
||||
ENV PATH /go1.5/bin:$PATH
|
||||
|
||||
# For i386 build
|
||||
RUN cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||
|
||||
# Default CMD
|
||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
||||
CMD cd /fzf/src && /bin/bash
|
||||
|
||||
|
@@ -3,14 +3,13 @@ MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# apt-get
|
||||
RUN apt-get update && apt-get -y upgrade && \
|
||||
apt-get install -y --force-yes git curl build-essential libncurses-dev
|
||||
apt-get install -y --force-yes git curl build-essential libncurses-dev libgpm-dev
|
||||
|
||||
# Install Go 1.4
|
||||
RUN cd / && curl \
|
||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||
tar -xz && mv go go1.4
|
||||
|
||||
ENV GOPATH /go
|
||||
ENV GOROOT /go1.4
|
||||
ENV PATH /go1.4/bin:$PATH
|
||||
|
||||
@@ -18,9 +17,6 @@ ENV PATH /go1.4/bin:$PATH
|
||||
RUN apt-get install -y lib32ncurses5-dev && \
|
||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||
|
||||
# Volume
|
||||
VOLUME /go
|
||||
|
||||
# Default CMD
|
||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
||||
CMD cd /fzf/src && /bin/bash
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Junegunn Choi
|
||||
Copyright (c) 2016 Junegunn Choi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
113
src/Makefile
113
src/Makefile
@@ -1,40 +1,55 @@
|
||||
ifndef GOPATH
|
||||
$(error GOPATH is undefined)
|
||||
endif
|
||||
|
||||
ifndef GOOS
|
||||
UNAME_S := $(shell uname -s)
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
GOOS := darwin
|
||||
else ifeq ($(UNAME_S),Linux)
|
||||
GOOS := linux
|
||||
endif
|
||||
endif
|
||||
|
||||
ifneq ($(shell uname -m),x86_64)
|
||||
$(error "Build on $(UNAME_M) is not supported, yet.")
|
||||
endif
|
||||
|
||||
SOURCES := $(wildcard *.go */*.go)
|
||||
BINDIR := ../bin
|
||||
|
||||
BINARY32 := fzf-$(GOOS)_386
|
||||
BINARY64 := fzf-$(GOOS)_amd64
|
||||
VERSION = $(shell fzf/$(BINARY64) --version)
|
||||
RELEASE32 = fzf-$(VERSION)-$(GOOS)_386
|
||||
RELEASE64 = fzf-$(VERSION)-$(GOOS)_amd64
|
||||
SOURCES := $(wildcard *.go */*.go)
|
||||
ROOTDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
|
||||
BINDIR := $(shell dirname $(ROOTDIR))/bin
|
||||
GOPATH := $(shell dirname $(ROOTDIR))/gopath
|
||||
SRCDIR := $(GOPATH)/src/github.com/junegunn/fzf/src
|
||||
DOCKEROPTS := -i -t -v $(ROOTDIR):/fzf/src
|
||||
BINARY32 := fzf-$(GOOS)_386
|
||||
BINARY64 := fzf-$(GOOS)_amd64
|
||||
BINARYARM7 := fzf-$(GOOS)_arm7
|
||||
VERSION := $(shell awk -F= '/version =/ {print $$2}' constants.go | tr -d "\" ")
|
||||
RELEASE32 := fzf-$(VERSION)-$(GOOS)_386
|
||||
RELEASE64 := fzf-$(VERSION)-$(GOOS)_amd64
|
||||
RELEASEARM7 := fzf-$(VERSION)-$(GOOS)_arm7
|
||||
export GOPATH
|
||||
|
||||
all: release
|
||||
|
||||
release: build
|
||||
cd fzf && \
|
||||
cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32) && \
|
||||
cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
||||
rm $(RELEASE32) $(RELEASE64)
|
||||
release: test build
|
||||
-cd fzf && cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32)
|
||||
cd fzf && cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
||||
rm -f $(RELEASE32) $(RELEASE64)
|
||||
|
||||
build: test fzf/$(BINARY32) fzf/$(BINARY64)
|
||||
build: fzf/$(BINARY32) fzf/$(BINARY64)
|
||||
|
||||
test:
|
||||
go get
|
||||
go test -v ./...
|
||||
$(SRCDIR):
|
||||
mkdir -p $(shell dirname $(SRCDIR))
|
||||
ln -s $(ROOTDIR) $(SRCDIR)
|
||||
|
||||
deps: $(SRCDIR) $(SOURCES)
|
||||
cd $(SRCDIR) && go get
|
||||
|
||||
android-build: $(SRCDIR)
|
||||
cd $(SRCDIR) && GOARCH=arm GOARM=7 CGO_ENABLED=1 go get
|
||||
cd $(SRCDIR)/fzf && GOARCH=arm GOARM=7 CGO_ENABLED=1 go build -a -ldflags="-extldflags=-pie" -o $(BINARYARM7)
|
||||
cd $(SRCDIR)/fzf && cp $(BINARYARM7) $(RELEASEARM7) && tar -czf $(RELEASEARM7).tgz $(RELEASEARM7) && \
|
||||
rm -f $(RELEASEARM7)
|
||||
|
||||
test: deps
|
||||
SHELL=/bin/sh go test -v ./...
|
||||
|
||||
install: $(BINDIR)/fzf
|
||||
|
||||
@@ -42,13 +57,13 @@ uninstall:
|
||||
rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY64)
|
||||
|
||||
clean:
|
||||
cd fzf && rm -f $(BINARY32) $(BINARY64) $(RELEASE32).tgz $(RELEASE64).tgz
|
||||
cd fzf && rm -f fzf-*
|
||||
|
||||
fzf/$(BINARY32): $(SOURCES)
|
||||
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -o $(BINARY32)
|
||||
fzf/$(BINARY32): deps
|
||||
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -a -tags "$(TAGS)" -o $(BINARY32)
|
||||
|
||||
fzf/$(BINARY64): $(SOURCES)
|
||||
cd fzf && go build -o $(BINARY64)
|
||||
fzf/$(BINARY64): deps
|
||||
cd fzf && go build -a -tags "$(TAGS)" -o $(BINARY64)
|
||||
|
||||
$(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)
|
||||
cp -f fzf/$(BINARY64) $(BINDIR)
|
||||
@@ -57,18 +72,42 @@ $(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)
|
||||
$(BINDIR):
|
||||
mkdir -p $@
|
||||
|
||||
# Linux distribution to build fzf on
|
||||
DISTRO := arch
|
||||
docker-arch:
|
||||
docker build -t junegunn/arch-sandbox - < Dockerfile.arch
|
||||
|
||||
docker:
|
||||
docker build -t junegunn/$(DISTRO)-sandbox - < Dockerfile.$(DISTRO)
|
||||
docker-ubuntu:
|
||||
docker build -t junegunn/ubuntu-sandbox - < Dockerfile.ubuntu
|
||||
|
||||
linux: docker
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
||||
/bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make'
|
||||
docker-centos:
|
||||
docker build -t junegunn/centos-sandbox - < Dockerfile.centos
|
||||
|
||||
$(DISTRO): docker
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
||||
sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'
|
||||
docker-android:
|
||||
docker build -t junegunn/android-sandbox - < Dockerfile.android
|
||||
|
||||
.PHONY: all build release test install uninstall clean docker linux $(DISTRO)
|
||||
arch: docker-arch
|
||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||
sh -c 'cd /fzf/src; /bin/bash'
|
||||
|
||||
ubuntu: docker-ubuntu
|
||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||
sh -c 'cd /fzf/src; /bin/bash'
|
||||
|
||||
centos: docker-centos
|
||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||
sh -c 'cd /fzf/src; /bin/bash'
|
||||
|
||||
linux: docker-centos
|
||||
docker run $(DOCKEROPTS) junegunn/centos-sandbox \
|
||||
/bin/bash -ci 'cd /fzf/src; make TAGS=static'
|
||||
|
||||
ubuntu-android: docker-android
|
||||
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
||||
sh -c 'cd /fzf/src; /bin/bash'
|
||||
|
||||
android: docker-android
|
||||
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
||||
/bin/bash -ci 'cd /fzf/src; GOOS=android make android-build'
|
||||
|
||||
.PHONY: all build deps release test install uninstall clean \
|
||||
linux arch ubuntu centos docker-arch docker-ubuntu docker-centos \
|
||||
android-build docker-android ubuntu-android android
|
||||
|
176
src/algo/algo.go
176
src/algo/algo.go
@@ -15,10 +15,37 @@ import (
|
||||
* In short: They try to do as little work as possible.
|
||||
*/
|
||||
|
||||
func runeAt(runes []rune, index int, max int, forward bool) rune {
|
||||
if forward {
|
||||
return runes[index]
|
||||
}
|
||||
return runes[max-index-1]
|
||||
}
|
||||
|
||||
// Result conatins the results of running a match function.
|
||||
type Result struct {
|
||||
Start int32
|
||||
End int32
|
||||
|
||||
// Items are basically sorted by the lengths of matched substrings.
|
||||
// But we slightly adjust the score with bonus for better results.
|
||||
Bonus int32
|
||||
}
|
||||
|
||||
type charClass int
|
||||
|
||||
const (
|
||||
charNonWord charClass = iota
|
||||
charLower
|
||||
charUpper
|
||||
charLetter
|
||||
charNumber
|
||||
)
|
||||
|
||||
// FuzzyMatch performs fuzzy-match
|
||||
func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
func FuzzyMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||
if len(pattern) == 0 {
|
||||
return 0, 0
|
||||
return Result{0, 0, 0}
|
||||
}
|
||||
|
||||
// 0. (FIXME) How to find the shortest match?
|
||||
@@ -34,7 +61,11 @@ func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
sidx := -1
|
||||
eidx := -1
|
||||
|
||||
for index, char := range runes {
|
||||
lenRunes := len(runes)
|
||||
lenPattern := len(pattern)
|
||||
|
||||
for index := range runes {
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
// This is considerably faster than blindly applying strings.ToLower to the
|
||||
// whole string
|
||||
if !caseSensitive {
|
||||
@@ -47,11 +78,12 @@ func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if char == pattern[pidx] {
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if char == pchar {
|
||||
if sidx < 0 {
|
||||
sidx = index
|
||||
}
|
||||
if pidx++; pidx == len(pattern) {
|
||||
if pidx++; pidx == lenPattern {
|
||||
eidx = index + 1
|
||||
break
|
||||
}
|
||||
@@ -61,7 +93,7 @@ func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
if sidx >= 0 && eidx >= 0 {
|
||||
pidx--
|
||||
for index := eidx - 1; index >= sidx; index-- {
|
||||
char := runes[index]
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
if !caseSensitive {
|
||||
if char >= 'A' && char <= 'Z' {
|
||||
char += 32
|
||||
@@ -69,16 +101,85 @@ func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if char == pattern[pidx] {
|
||||
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if char == pchar {
|
||||
if pidx--; pidx < 0 {
|
||||
sidx = index
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return sidx, eidx
|
||||
|
||||
// Calculate the bonus. This can't be done at the same time as the
|
||||
// pattern scan above because 'forward' may be false.
|
||||
if !forward {
|
||||
sidx, eidx = lenRunes-eidx, lenRunes-sidx
|
||||
}
|
||||
|
||||
var bonus int32
|
||||
pidx := 0
|
||||
consecutive := false
|
||||
prevClass := charNonWord
|
||||
for index := 0; index < eidx; index++ {
|
||||
char := runes[index]
|
||||
var class charClass
|
||||
if unicode.IsLower(char) {
|
||||
class = charLower
|
||||
} else if unicode.IsUpper(char) {
|
||||
class = charUpper
|
||||
} else if unicode.IsLetter(char) {
|
||||
class = charLetter
|
||||
} else if unicode.IsNumber(char) {
|
||||
class = charNumber
|
||||
} else {
|
||||
class = charNonWord
|
||||
}
|
||||
|
||||
var point int32
|
||||
if prevClass == charNonWord && class != charNonWord {
|
||||
// Word boundary
|
||||
point = 2
|
||||
} else if prevClass == charLower && class == charUpper ||
|
||||
prevClass != charNumber && class == charNumber {
|
||||
// camelCase letter123
|
||||
point = 1
|
||||
}
|
||||
prevClass = class
|
||||
|
||||
if index >= sidx {
|
||||
if !caseSensitive {
|
||||
if char >= 'A' && char <= 'Z' {
|
||||
char += 32
|
||||
} else if char > unicode.MaxASCII {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
pchar := pattern[pidx]
|
||||
if pchar == char {
|
||||
// Boost bonus for the first character in the pattern
|
||||
if pidx == 0 {
|
||||
point *= 2
|
||||
}
|
||||
// Bonus to consecutive matching chars
|
||||
if consecutive {
|
||||
point++
|
||||
}
|
||||
bonus += point
|
||||
|
||||
if pidx++; pidx == lenPattern {
|
||||
break
|
||||
}
|
||||
consecutive = true
|
||||
} else {
|
||||
consecutive = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Result{int32(sidx), int32(eidx), bonus}
|
||||
}
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
||||
// ExactMatchNaive is a basic string searching algorithm that handles case
|
||||
@@ -88,20 +189,22 @@ func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
//
|
||||
// We might try to implement better algorithms in the future:
|
||||
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
||||
func ExactMatchNaive(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
func ExactMatchNaive(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||
// Note: ExactMatchNaive always return a zero bonus.
|
||||
if len(pattern) == 0 {
|
||||
return 0, 0
|
||||
return Result{0, 0, 0}
|
||||
}
|
||||
|
||||
numRunes := len(runes)
|
||||
plen := len(pattern)
|
||||
if numRunes < plen {
|
||||
return -1, -1
|
||||
lenRunes := len(runes)
|
||||
lenPattern := len(pattern)
|
||||
|
||||
if lenRunes < lenPattern {
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
||||
pidx := 0
|
||||
for index := 0; index < numRunes; index++ {
|
||||
char := runes[index]
|
||||
for index := 0; index < lenRunes; index++ {
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
if !caseSensitive {
|
||||
if char >= 'A' && char <= 'Z' {
|
||||
char += 32
|
||||
@@ -109,23 +212,28 @@ func ExactMatchNaive(caseSensitive bool, runes []rune, pattern []rune) (int, int
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if pattern[pidx] == char {
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if pchar == char {
|
||||
pidx++
|
||||
if pidx == plen {
|
||||
return index - plen + 1, index + 1
|
||||
if pidx == lenPattern {
|
||||
if forward {
|
||||
return Result{int32(index - lenPattern + 1), int32(index + 1), 0}
|
||||
}
|
||||
return Result{int32(lenRunes - (index + 1)), int32(lenRunes - (index - lenPattern + 1)), 0}
|
||||
}
|
||||
} else {
|
||||
index -= pidx
|
||||
pidx = 0
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
||||
// PrefixMatch performs prefix-match
|
||||
func PrefixMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
func PrefixMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||
// Note: PrefixMatch always return a zero bonus.
|
||||
if len(runes) < len(pattern) {
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
||||
for index, r := range pattern {
|
||||
@@ -134,19 +242,20 @@ func PrefixMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
char = unicode.ToLower(char)
|
||||
}
|
||||
if char != r {
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
}
|
||||
return 0, len(pattern)
|
||||
return Result{0, int32(len(pattern)), 0}
|
||||
}
|
||||
|
||||
// SuffixMatch performs suffix-match
|
||||
func SuffixMatch(caseSensitive bool, input []rune, pattern []rune) (int, int) {
|
||||
func SuffixMatch(caseSensitive bool, forward bool, input []rune, pattern []rune) Result {
|
||||
// Note: SuffixMatch always return a zero bonus.
|
||||
runes := util.TrimRight(input)
|
||||
trimmedLen := len(runes)
|
||||
diff := trimmedLen - len(pattern)
|
||||
if diff < 0 {
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
||||
for index, r := range pattern {
|
||||
@@ -155,23 +264,24 @@ func SuffixMatch(caseSensitive bool, input []rune, pattern []rune) (int, int) {
|
||||
char = unicode.ToLower(char)
|
||||
}
|
||||
if char != r {
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
}
|
||||
return trimmedLen - len(pattern), trimmedLen
|
||||
return Result{int32(trimmedLen - len(pattern)), int32(trimmedLen), 0}
|
||||
}
|
||||
|
||||
// EqualMatch performs equal-match
|
||||
func EqualMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {
|
||||
func EqualMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||
// Note: EqualMatch always return a zero bonus.
|
||||
if len(runes) != len(pattern) {
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
runesStr := string(runes)
|
||||
if !caseSensitive {
|
||||
runesStr = strings.ToLower(runesStr)
|
||||
}
|
||||
if runesStr == string(pattern) {
|
||||
return 0, len(pattern)
|
||||
return Result{0, int32(len(pattern)), 0}
|
||||
}
|
||||
return -1, -1
|
||||
return Result{-1, -1, 0}
|
||||
}
|
||||
|
@@ -5,47 +5,84 @@ import (
|
||||
"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, bool, []rune, []rune) Result, caseSensitive, forward bool, input, pattern string, sidx int32, eidx int32, bonus int32) {
|
||||
if !caseSensitive {
|
||||
pattern = strings.ToLower(pattern)
|
||||
}
|
||||
s, e := fun(caseSensitive, []rune(input), []rune(pattern))
|
||||
if s != sidx {
|
||||
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
||||
res := fun(caseSensitive, forward, []rune(input), []rune(pattern))
|
||||
if res.Start != sidx {
|
||||
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", res.Start, sidx, input, pattern)
|
||||
}
|
||||
if e != eidx {
|
||||
t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", e, eidx, input, pattern)
|
||||
if res.End != eidx {
|
||||
t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", res.End, eidx, input, pattern)
|
||||
}
|
||||
if res.Bonus != bonus {
|
||||
t.Errorf("Invalid bonus: %d (expected: %d, %s / %s)", res.Bonus, bonus, input, pattern)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFuzzyMatch(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, false, "fooBarbaz", "oBZ", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBZ", -1, -1)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBz", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
assertMatch(t, FuzzyMatch, false, true, "fooBarbaz", "oBZ", 2, 9, 2)
|
||||
assertMatch(t, FuzzyMatch, false, true, "foo bar baz", "fbb", 0, 9, 8)
|
||||
assertMatch(t, FuzzyMatch, false, true, "/AutomatorDocument.icns", "rdoc", 9, 13, 4)
|
||||
assertMatch(t, FuzzyMatch, false, true, "/man1/zshcompctl.1", "zshc", 6, 10, 7)
|
||||
assertMatch(t, FuzzyMatch, false, true, "/.oh-my-zsh/cache", "zshc", 8, 13, 8)
|
||||
assertMatch(t, FuzzyMatch, false, true, "ab0123 456", "12356", 3, 10, 3)
|
||||
assertMatch(t, FuzzyMatch, false, true, "abc123 456", "12356", 3, 10, 5)
|
||||
|
||||
assertMatch(t, FuzzyMatch, false, true, "foo/bar/baz", "fbb", 0, 9, 8)
|
||||
assertMatch(t, FuzzyMatch, false, true, "fooBarBaz", "fbb", 0, 7, 6)
|
||||
assertMatch(t, FuzzyMatch, false, true, "foo barbaz", "fbb", 0, 8, 6)
|
||||
assertMatch(t, FuzzyMatch, false, true, "fooBar Baz", "foob", 0, 4, 8)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBZ", -1, -1, 0)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBz", 2, 9, 2)
|
||||
assertMatch(t, FuzzyMatch, true, true, "Foo Bar Baz", "fbb", -1, -1, 0)
|
||||
assertMatch(t, FuzzyMatch, true, true, "Foo/Bar/Baz", "FBB", 0, 9, 8)
|
||||
assertMatch(t, FuzzyMatch, true, true, "FooBarBaz", "FBB", 0, 7, 6)
|
||||
assertMatch(t, FuzzyMatch, true, true, "foo BarBaz", "fBB", 0, 8, 7)
|
||||
assertMatch(t, FuzzyMatch, true, true, "FooBar Baz", "FooB", 0, 4, 8)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "fooBarbazz", -1, -1, 0)
|
||||
}
|
||||
|
||||
func TestFuzzyMatchBackward(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, false, true, "foobar fb", "fb", 0, 4, 4)
|
||||
assertMatch(t, FuzzyMatch, false, false, "foobar fb", "fb", 7, 9, 5)
|
||||
}
|
||||
|
||||
func TestExactMatchNaive(t *testing.T) {
|
||||
assertMatch(t, ExactMatchNaive, false, "fooBarbaz", "oBA", 2, 5)
|
||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "oBA", -1, -1)
|
||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExactMatchNaiveBackward(t *testing.T) {
|
||||
assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3, 0)
|
||||
assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10, 0)
|
||||
}
|
||||
|
||||
func TestPrefixMatch(t *testing.T) {
|
||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "Foo", 0, 3)
|
||||
assertMatch(t, PrefixMatch, true, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "baz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, 0)
|
||||
assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1, 0)
|
||||
assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "baz", -1, -1, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuffixMatch(t *testing.T) {
|
||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)
|
||||
assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0)
|
||||
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9, 0)
|
||||
assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyPattern(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, FuzzyMatch, true, dir, "foobar", "", 0, 0, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0, 0)
|
||||
assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0, 0)
|
||||
assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6, 0)
|
||||
}
|
||||
}
|
||||
|
@@ -6,8 +6,11 @@ import (
|
||||
)
|
||||
|
||||
func TestChunkList(t *testing.T) {
|
||||
// FIXME global
|
||||
sortCriteria = []criterion{byMatchLen, byLength}
|
||||
|
||||
cl := NewChunkList(func(s []byte, i int) *Item {
|
||||
return &Item{text: []rune(string(s)), rank: Rank{0, 0, uint32(i * 2)}}
|
||||
return &Item{text: []rune(string(s)), rank: buildEmptyRank(int32(i * 2))}
|
||||
})
|
||||
|
||||
// Snapshot
|
||||
@@ -36,8 +39,11 @@ func TestChunkList(t *testing.T) {
|
||||
if len(*chunk1) != 2 {
|
||||
t.Error("Snapshot should contain only two items")
|
||||
}
|
||||
if string((*chunk1)[0].text) != "hello" || (*chunk1)[0].rank.index != 0 ||
|
||||
string((*chunk1)[1].text) != "world" || (*chunk1)[1].rank.index != 2 {
|
||||
last := func(arr [5]int32) int32 {
|
||||
return arr[len(arr)-1]
|
||||
}
|
||||
if string((*chunk1)[0].text) != "hello" || last((*chunk1)[0].rank) != 0 ||
|
||||
string((*chunk1)[1].text) != "world" || last((*chunk1)[1].rank) != 2 {
|
||||
t.Error("Invalid data")
|
||||
}
|
||||
if chunk1.IsFull() {
|
||||
|
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
const (
|
||||
// Current version
|
||||
version = "0.10.3"
|
||||
version = "0.12.0"
|
||||
|
||||
// Core
|
||||
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
||||
@@ -18,7 +18,8 @@ const (
|
||||
defaultCommand = `find . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
|
||||
|
||||
// Terminal
|
||||
initialDelay = 100 * time.Millisecond
|
||||
initialDelay = 20 * time.Millisecond
|
||||
initialDelayTac = 100 * time.Millisecond
|
||||
spinnerDuration = 200 * time.Millisecond
|
||||
|
||||
// Matcher
|
||||
@@ -47,3 +48,10 @@ const (
|
||||
EvtHeader
|
||||
EvtClose
|
||||
)
|
||||
|
||||
const (
|
||||
exitOk = 0
|
||||
exitNoMatch = 1
|
||||
exitError = 2
|
||||
exitInterrupt = 130
|
||||
)
|
||||
|
44
src/core.go
44
src/core.go
@@ -3,7 +3,7 @@ Package fzf implements fzf, a command-line fuzzy finder.
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Junegunn Choi
|
||||
Copyright (c) 2016 Junegunn Choi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -52,11 +52,11 @@ func Run(opts *Options) {
|
||||
initProcs()
|
||||
|
||||
sort := opts.Sort > 0
|
||||
rankTiebreak = opts.Tiebreak
|
||||
sortCriteria = opts.Criteria
|
||||
|
||||
if opts.Version {
|
||||
fmt.Println(version)
|
||||
os.Exit(0)
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
|
||||
// Event channel
|
||||
@@ -103,9 +103,8 @@ func Run(opts *Options) {
|
||||
runes, colors := ansiProcessor(data)
|
||||
return &Item{
|
||||
text: runes,
|
||||
index: uint32(index),
|
||||
colors: colors,
|
||||
rank: Rank{0, 0, uint32(index)}}
|
||||
rank: buildEmptyRank(int32(index))}
|
||||
})
|
||||
} else {
|
||||
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||
@@ -120,9 +119,8 @@ func Run(opts *Options) {
|
||||
item := Item{
|
||||
text: joinTokens(trans),
|
||||
origText: &runes,
|
||||
index: uint32(index),
|
||||
colors: nil,
|
||||
rank: Rank{0, 0, uint32(index)}}
|
||||
rank: buildEmptyRank(int32(index))}
|
||||
|
||||
trimmed, colors := ansiProcessorRunes(item.text)
|
||||
item.text = trimmed
|
||||
@@ -141,9 +139,20 @@ func Run(opts *Options) {
|
||||
}
|
||||
|
||||
// Matcher
|
||||
forward := true
|
||||
for _, cri := range opts.Criteria[1:] {
|
||||
if cri == byEnd {
|
||||
forward = false
|
||||
break
|
||||
}
|
||||
if cri == byBegin {
|
||||
break
|
||||
}
|
||||
}
|
||||
patternBuilder := func(runes []rune) *Pattern {
|
||||
return BuildPattern(
|
||||
opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)
|
||||
opts.Fuzzy, opts.Extended, opts.Case, forward,
|
||||
opts.Nth, opts.Delimiter, runes)
|
||||
}
|
||||
matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)
|
||||
|
||||
@@ -155,12 +164,14 @@ func Run(opts *Options) {
|
||||
|
||||
pattern := patternBuilder([]rune(*opts.Filter))
|
||||
|
||||
found := false
|
||||
if streamingFilter {
|
||||
reader := Reader{
|
||||
func(runes []byte) bool {
|
||||
item := chunkList.trans(runes, 0)
|
||||
if item != nil && pattern.MatchItem(item) {
|
||||
fmt.Println(string(item.text))
|
||||
found = true
|
||||
}
|
||||
return false
|
||||
}, eventBox, opts.ReadZero}
|
||||
@@ -174,10 +185,14 @@ func Run(opts *Options) {
|
||||
chunks: snapshot,
|
||||
pattern: pattern})
|
||||
for i := 0; i < merger.Length(); i++ {
|
||||
fmt.Println(merger.Get(i).AsString())
|
||||
fmt.Println(merger.Get(i).AsString(opts.Ansi))
|
||||
found = true
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
if found {
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
os.Exit(exitNoMatch)
|
||||
}
|
||||
|
||||
// Synchronous search
|
||||
@@ -231,7 +246,7 @@ func Run(opts *Options) {
|
||||
}
|
||||
|
||||
case EvtHeader:
|
||||
terminal.UpdateHeader(value.([]string), opts.HeaderLines)
|
||||
terminal.UpdateHeader(value.([]string))
|
||||
|
||||
case EvtSearchFin:
|
||||
switch val := value.(type) {
|
||||
@@ -250,9 +265,12 @@ func Run(opts *Options) {
|
||||
fmt.Println()
|
||||
}
|
||||
for i := 0; i < count; i++ {
|
||||
fmt.Println(val.Get(i).AsString())
|
||||
fmt.Println(val.Get(i).AsString(opts.Ansi))
|
||||
}
|
||||
os.Exit(0)
|
||||
if count > 0 {
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
os.Exit(exitNoMatch)
|
||||
}
|
||||
deferred = false
|
||||
terminal.startChan <- true
|
||||
|
@@ -3,14 +3,21 @@ package curses
|
||||
/*
|
||||
#include <ncurses.h>
|
||||
#include <locale.h>
|
||||
#cgo LDFLAGS: -lncurses
|
||||
#cgo !static LDFLAGS: -lncurses
|
||||
#cgo static LDFLAGS: -l:libncursesw.a -l:libtinfo.a -l:libgpm.a -ldl
|
||||
#cgo android static LDFLAGS: -l:libncurses.a -fPIE -march=armv7-a -mfpu=neon -mhard-float -Wl,--no-warn-mismatch
|
||||
|
||||
SCREEN *c_newterm () {
|
||||
return newterm(NULL, stderr, stdin);
|
||||
}
|
||||
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -50,6 +57,7 @@ const (
|
||||
|
||||
Invalid
|
||||
Mouse
|
||||
DoubleClick
|
||||
|
||||
BTab
|
||||
BSpace
|
||||
@@ -258,10 +266,10 @@ func Init(theme *ColorTheme, black bool, mouse bool) {
|
||||
}
|
||||
|
||||
C.setlocale(C.LC_ALL, C.CString(""))
|
||||
_screen = C.newterm(nil, C.stderr, C.stdin)
|
||||
_screen = C.c_newterm()
|
||||
if _screen == nil {
|
||||
fmt.Println("Invalid $TERM: " + os.Getenv("TERM"))
|
||||
os.Exit(1)
|
||||
os.Exit(2)
|
||||
}
|
||||
C.set_term(_screen)
|
||||
if mouse {
|
||||
@@ -270,14 +278,6 @@ func Init(theme *ColorTheme, black bool, mouse bool) {
|
||||
C.noecho()
|
||||
C.raw() // stty dsusp undef
|
||||
|
||||
intChan := make(chan os.Signal, 1)
|
||||
signal.Notify(intChan, os.Interrupt, os.Kill)
|
||||
go func() {
|
||||
<-intChan
|
||||
Close()
|
||||
os.Exit(1)
|
||||
}()
|
||||
|
||||
if theme != nil {
|
||||
C.start_color()
|
||||
initPairs(theme, black)
|
||||
@@ -521,7 +521,12 @@ func MoveAndClear(y int, x int) {
|
||||
}
|
||||
|
||||
func Print(text string) {
|
||||
C.addstr(C.CString(text))
|
||||
C.addstr(C.CString(strings.Map(func(r rune) rune {
|
||||
if r < 32 {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, text)))
|
||||
}
|
||||
|
||||
func CPrint(pair int, bold bool, text string) {
|
||||
|
148
src/item.go
148
src/item.go
@@ -6,8 +6,8 @@ import (
|
||||
"github.com/junegunn/fzf/src/curses"
|
||||
)
|
||||
|
||||
// Offset holds two 32-bit integers denoting the offsets of a matched substring
|
||||
type Offset [2]int32
|
||||
// Offset holds three 32-bit integers denoting the offsets of a matched substring
|
||||
type Offset [3]int32
|
||||
|
||||
type colorOffset struct {
|
||||
offset [2]int32
|
||||
@@ -20,33 +20,47 @@ type Item struct {
|
||||
text []rune
|
||||
origText *[]rune
|
||||
transformed []Token
|
||||
index uint32
|
||||
offsets []Offset
|
||||
colors []ansiOffset
|
||||
rank Rank
|
||||
rank [5]int32
|
||||
bonus int32
|
||||
}
|
||||
|
||||
// Rank is used to sort the search result
|
||||
type Rank struct {
|
||||
matchlen uint16
|
||||
tiebreak uint16
|
||||
index uint32
|
||||
// Sort criteria to use. Never changes once fzf is started.
|
||||
var sortCriteria []criterion
|
||||
|
||||
func isRankValid(rank [5]int32) bool {
|
||||
// Exclude ordinal index
|
||||
for _, r := range rank[:4] {
|
||||
if r > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Tiebreak criterion to use. Never changes once fzf is started.
|
||||
var rankTiebreak tiebreak
|
||||
func buildEmptyRank(index int32) [5]int32 {
|
||||
return [5]int32{0, 0, 0, 0, index}
|
||||
}
|
||||
|
||||
func (item *Item) Index() int32 {
|
||||
return item.rank[4]
|
||||
}
|
||||
|
||||
// Rank calculates rank of the Item
|
||||
func (item *Item) Rank(cache bool) Rank {
|
||||
if cache && (item.rank.matchlen > 0 || item.rank.tiebreak > 0) {
|
||||
func (item *Item) Rank(cache bool) [5]int32 {
|
||||
if cache && isRankValid(item.rank) {
|
||||
return item.rank
|
||||
}
|
||||
matchlen := 0
|
||||
prevEnd := 0
|
||||
minBegin := math.MaxUint16
|
||||
lenSum := 0
|
||||
minBegin := math.MaxInt32
|
||||
for _, offset := range item.offsets {
|
||||
begin := int(offset[0])
|
||||
end := int(offset[1])
|
||||
trimLen := int(offset[2])
|
||||
lenSum += trimLen
|
||||
if prevEnd > begin {
|
||||
begin = prevEnd
|
||||
}
|
||||
@@ -60,33 +74,45 @@ func (item *Item) Rank(cache bool) Rank {
|
||||
matchlen += end - begin
|
||||
}
|
||||
}
|
||||
var tiebreak uint16
|
||||
switch rankTiebreak {
|
||||
case byLength:
|
||||
// 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)
|
||||
rank := buildEmptyRank(item.Index())
|
||||
for idx, criterion := range sortCriteria {
|
||||
var val int32
|
||||
switch criterion {
|
||||
case byMatchLen:
|
||||
if matchlen == 0 {
|
||||
val = math.MaxInt32
|
||||
} else {
|
||||
// It is extremely unlikely that bonus exceeds 128
|
||||
val = 128*int32(matchlen) - item.bonus
|
||||
}
|
||||
case byLength:
|
||||
// It is guaranteed that .transformed in not null in normal execution
|
||||
if item.transformed != nil {
|
||||
// If offsets is empty, lenSum will be 0, but we don't care
|
||||
val = int32(lenSum)
|
||||
} else {
|
||||
val = int32(len(item.text))
|
||||
}
|
||||
case byBegin:
|
||||
// We can't just look at item.offsets[0][0] because it can be an inverse term
|
||||
whitePrefixLen := 0
|
||||
for idx, r := range item.text {
|
||||
whitePrefixLen = idx
|
||||
if idx == minBegin || r != ' ' && r != '\t' {
|
||||
break
|
||||
}
|
||||
}
|
||||
val = int32(minBegin - whitePrefixLen)
|
||||
case byEnd:
|
||||
if prevEnd > 0 {
|
||||
val = int32(1 + len(item.text) - prevEnd)
|
||||
} else {
|
||||
// Empty offsets due to inverse terms.
|
||||
val = 1
|
||||
}
|
||||
tiebreak = uint16(lenSum)
|
||||
} else {
|
||||
tiebreak = uint16(len(item.text))
|
||||
}
|
||||
case byBegin:
|
||||
// We can't just look at item.offsets[0][0] because it can be an inverse term
|
||||
tiebreak = uint16(minBegin)
|
||||
case byEnd:
|
||||
if prevEnd > 0 {
|
||||
tiebreak = uint16(1 + len(item.text) - prevEnd)
|
||||
} else {
|
||||
// Empty offsets due to inverse terms.
|
||||
tiebreak = 1
|
||||
}
|
||||
case byIndex:
|
||||
tiebreak = 1
|
||||
rank[idx] = val
|
||||
}
|
||||
rank := Rank{uint16(matchlen), tiebreak, item.index}
|
||||
if cache {
|
||||
item.rank = rank
|
||||
}
|
||||
@@ -94,17 +120,21 @@ func (item *Item) Rank(cache bool) Rank {
|
||||
}
|
||||
|
||||
// AsString returns the original string
|
||||
func (item *Item) AsString() string {
|
||||
return *item.StringPtr()
|
||||
func (item *Item) AsString(stripAnsi bool) string {
|
||||
return *item.StringPtr(stripAnsi)
|
||||
}
|
||||
|
||||
// StringPtr returns the pointer to the original string
|
||||
func (item *Item) StringPtr() *string {
|
||||
runes := item.text
|
||||
func (item *Item) StringPtr(stripAnsi bool) *string {
|
||||
if item.origText != nil {
|
||||
runes = *item.origText
|
||||
if stripAnsi {
|
||||
trimmed, _, _ := extractColor(string(*item.origText), nil)
|
||||
return &trimmed
|
||||
}
|
||||
orig := string(*item.origText)
|
||||
return &orig
|
||||
}
|
||||
str := string(runes)
|
||||
str := string(item.text)
|
||||
return &str
|
||||
}
|
||||
|
||||
@@ -112,7 +142,8 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
||||
if len(item.colors) == 0 {
|
||||
var offsets []colorOffset
|
||||
for _, off := range item.offsets {
|
||||
offsets = append(offsets, colorOffset{offset: off, color: color, bold: bold})
|
||||
|
||||
offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, bold: bold})
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
@@ -156,7 +187,7 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
||||
if curr != 0 && idx > start {
|
||||
if curr == -1 {
|
||||
offsets = append(offsets, colorOffset{
|
||||
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
||||
offset: [2]int32{int32(start), int32(idx)}, color: color, bold: bold})
|
||||
} else {
|
||||
ansi := item.colors[curr-1]
|
||||
fg := ansi.color.fg
|
||||
@@ -176,7 +207,7 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
||||
}
|
||||
}
|
||||
offsets = append(offsets, colorOffset{
|
||||
offset: Offset{int32(start), int32(idx)},
|
||||
offset: [2]int32{int32(start), int32(idx)},
|
||||
color: curses.PairFor(fg, bg),
|
||||
bold: ansi.color.bold || bold})
|
||||
}
|
||||
@@ -246,18 +277,15 @@ func (a ByRelevanceTac) Less(i, j int) bool {
|
||||
return compareRanks(irank, jrank, true)
|
||||
}
|
||||
|
||||
func compareRanks(irank Rank, jrank Rank, tac bool) bool {
|
||||
if irank.matchlen < jrank.matchlen {
|
||||
return true
|
||||
} else if irank.matchlen > jrank.matchlen {
|
||||
return false
|
||||
func compareRanks(irank [5]int32, jrank [5]int32, tac bool) bool {
|
||||
for idx := 0; idx < 4; idx++ {
|
||||
left := irank[idx]
|
||||
right := jrank[idx]
|
||||
if left < right {
|
||||
return true
|
||||
} else if left > right {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if irank.tiebreak < jrank.tiebreak {
|
||||
return true
|
||||
} else if irank.tiebreak > jrank.tiebreak {
|
||||
return false
|
||||
}
|
||||
|
||||
return (irank.index <= jrank.index) != tac
|
||||
return (irank[4] <= jrank[4]) != tac
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
@@ -22,31 +23,34 @@ func TestOffsetSort(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRankComparison(t *testing.T) {
|
||||
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, false) ||
|
||||
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||
|
||||
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, false) ||
|
||||
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {
|
||||
if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, false) ||
|
||||
!compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||
|
||||
!compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, false) ||
|
||||
!compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {
|
||||
t.Error("Invalid order")
|
||||
}
|
||||
|
||||
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, true) ||
|
||||
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||
|
||||
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, true) ||
|
||||
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {
|
||||
if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, true) ||
|
||||
!compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||
|
||||
!compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, true) ||
|
||||
!compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {
|
||||
t.Error("Invalid order (tac)")
|
||||
}
|
||||
}
|
||||
|
||||
// Match length, string length, index
|
||||
func TestItemRank(t *testing.T) {
|
||||
// FIXME global
|
||||
sortCriteria = []criterion{byMatchLen, byLength}
|
||||
|
||||
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
||||
item1 := Item{text: strs[0], index: 1, offsets: []Offset{}}
|
||||
item1 := Item{text: strs[0], offsets: []Offset{}, rank: [5]int32{0, 0, 0, 0, 1}}
|
||||
rank1 := item1.Rank(true)
|
||||
if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {
|
||||
if rank1[0] != math.MaxInt32 || rank1[1] != 3 || rank1[4] != 1 {
|
||||
t.Error(item1.Rank(true))
|
||||
}
|
||||
// Only differ in index
|
||||
item2 := Item{text: strs[0], index: 0, offsets: []Offset{}}
|
||||
item2 := Item{text: strs[0], offsets: []Offset{}}
|
||||
|
||||
items := []*Item{&item1, &item2}
|
||||
sort.Sort(ByRelevance(items))
|
||||
@@ -62,15 +66,15 @@ func TestItemRank(t *testing.T) {
|
||||
}
|
||||
|
||||
// Sort by relevance
|
||||
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}}}
|
||||
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}}}
|
||||
item3 := Item{text: strs[1], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item4 := Item{text: strs[1], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
item5 := Item{text: strs[2], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item6 := Item{text: strs[2], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
||||
sort.Sort(ByRelevance(items))
|
||||
if items[0] != &item2 || items[1] != &item1 ||
|
||||
items[2] != &item6 || items[3] != &item4 ||
|
||||
items[4] != &item5 || items[5] != &item3 {
|
||||
if items[0] != &item6 || items[1] != &item4 ||
|
||||
items[2] != &item5 || items[3] != &item3 ||
|
||||
items[4] != &item2 || items[5] != &item1 {
|
||||
t.Error(items)
|
||||
}
|
||||
}
|
||||
|
@@ -200,7 +200,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
||||
}
|
||||
|
||||
partialResults := make([][]*Item, numSlices)
|
||||
for range slices {
|
||||
for _, _ = range slices {
|
||||
partialResult := <-resultChan
|
||||
partialResults[partialResult.index] = partialResult.matches
|
||||
}
|
||||
|
@@ -88,7 +88,7 @@ func (mg *Merger) cacheable() bool {
|
||||
|
||||
func (mg *Merger) mergedGet(idx int) *Item {
|
||||
for i := len(mg.merged); i <= idx; i++ {
|
||||
minRank := Rank{0, 0, 0}
|
||||
minRank := buildEmptyRank(0)
|
||||
minIdx := -1
|
||||
for listIdx, list := range mg.lists {
|
||||
cursor := mg.cursors[listIdx]
|
||||
|
@@ -23,7 +23,7 @@ func randItem() *Item {
|
||||
}
|
||||
return &Item{
|
||||
text: []rune(str),
|
||||
index: rand.Uint32(),
|
||||
rank: buildEmptyRank(rand.Int31()),
|
||||
offsets: offsets}
|
||||
}
|
||||
|
||||
|
258
src/options.go
258
src/options.go
@@ -1,7 +1,6 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -17,17 +16,19 @@ const usage = `usage: fzf [options]
|
||||
|
||||
Search
|
||||
-x, --extended Extended-search mode
|
||||
-e, --extended-exact Extended-search mode (exact match)
|
||||
(enabled by default; +x or --no-extended to disable)
|
||||
-e, --exact Enable Exact-match
|
||||
-i Case-insensitive match (default: smart-case match)
|
||||
+i Case-sensitive match
|
||||
-n, --nth=N[,..] Comma-separated list of field index expressions
|
||||
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 item using index expressions within finder
|
||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||
+s, --no-sort Do not sort the result
|
||||
--tac Reverse the order of the input
|
||||
--tiebreak=CRITERION Sort criterion when the scores are tied;
|
||||
--tiebreak=CRI[,..] Comma-separated list of sort criteria to apply
|
||||
when the scores are tied;
|
||||
[length|begin|end|index] (default: length)
|
||||
|
||||
Interface
|
||||
@@ -38,14 +39,17 @@ const usage = `usage: fzf [options]
|
||||
--black Use black background
|
||||
--reverse Reverse orientation
|
||||
--margin=MARGIN Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)
|
||||
--tabstop=SPACES Number of spaces for a tab character (default: 8)
|
||||
--cycle Enable cyclic scroll
|
||||
--no-hscroll Disable horizontal scroll
|
||||
--hscroll-off=COL Number of screen columns to keep to the right of the
|
||||
highlighted substring (default: 10)
|
||||
--inline-info Display finder info inline with the query
|
||||
--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=STR String to print as header
|
||||
--header-lines=N The first N lines of the input are treated as header
|
||||
|
||||
Scripting
|
||||
@@ -59,20 +63,10 @@ const usage = `usage: fzf [options]
|
||||
|
||||
Environment variables
|
||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||
FZF_DEFAULT_OPTS Defaults options. (e.g. '-x -m')
|
||||
FZF_DEFAULT_OPTS Default options (e.g. '--reverse --inline-info')
|
||||
|
||||
`
|
||||
|
||||
// Mode denotes the current search mode
|
||||
type Mode int
|
||||
|
||||
// Search modes
|
||||
const (
|
||||
ModeFuzzy Mode = iota
|
||||
ModeExtended
|
||||
ModeExtendedExact
|
||||
)
|
||||
|
||||
// Case denotes case-sensitivity of search
|
||||
type Case int
|
||||
|
||||
@@ -84,13 +78,13 @@ const (
|
||||
)
|
||||
|
||||
// Sort criteria
|
||||
type tiebreak int
|
||||
type criterion int
|
||||
|
||||
const (
|
||||
byLength tiebreak = iota
|
||||
byMatchLen criterion = iota
|
||||
byLength
|
||||
byBegin
|
||||
byEnd
|
||||
byIndex
|
||||
)
|
||||
|
||||
func defaultMargin() [4]string {
|
||||
@@ -99,14 +93,15 @@ func defaultMargin() [4]string {
|
||||
|
||||
// Options stores the values of command-line options
|
||||
type Options struct {
|
||||
Mode Mode
|
||||
Fuzzy bool
|
||||
Extended bool
|
||||
Case Case
|
||||
Nth []Range
|
||||
WithNth []Range
|
||||
Delimiter Delimiter
|
||||
Sort int
|
||||
Tac bool
|
||||
Tiebreak tiebreak
|
||||
Criteria []criterion
|
||||
Multi bool
|
||||
Ansi bool
|
||||
Mouse bool
|
||||
@@ -115,6 +110,7 @@ type Options struct {
|
||||
Reverse bool
|
||||
Cycle bool
|
||||
Hscroll bool
|
||||
HscrollOff int
|
||||
InlineInfo bool
|
||||
Prompt string
|
||||
Query string
|
||||
@@ -132,6 +128,7 @@ type Options struct {
|
||||
Header []string
|
||||
HeaderLines int
|
||||
Margin [4]string
|
||||
Tabstop int
|
||||
Version bool
|
||||
}
|
||||
|
||||
@@ -144,14 +141,15 @@ func defaultTheme() *curses.ColorTheme {
|
||||
|
||||
func defaultOptions() *Options {
|
||||
return &Options{
|
||||
Mode: ModeFuzzy,
|
||||
Fuzzy: true,
|
||||
Extended: true,
|
||||
Case: CaseSmart,
|
||||
Nth: make([]Range, 0),
|
||||
WithNth: make([]Range, 0),
|
||||
Delimiter: Delimiter{},
|
||||
Sort: 1000,
|
||||
Tac: false,
|
||||
Tiebreak: byLength,
|
||||
Criteria: []criterion{byMatchLen, byLength},
|
||||
Multi: false,
|
||||
Ansi: false,
|
||||
Mouse: true,
|
||||
@@ -160,6 +158,7 @@ func defaultOptions() *Options {
|
||||
Reverse: false,
|
||||
Cycle: false,
|
||||
Hscroll: true,
|
||||
HscrollOff: 10,
|
||||
InlineInfo: false,
|
||||
Prompt: "> ",
|
||||
Query: "",
|
||||
@@ -168,7 +167,7 @@ func defaultOptions() *Options {
|
||||
Filter: nil,
|
||||
ToggleSort: false,
|
||||
Expect: make(map[int]string),
|
||||
Keymap: defaultKeymap(),
|
||||
Keymap: make(map[int]actionType),
|
||||
Execmap: make(map[int]string),
|
||||
PrintQuery: false,
|
||||
ReadZero: false,
|
||||
@@ -177,17 +176,18 @@ func defaultOptions() *Options {
|
||||
Header: make([]string, 0),
|
||||
HeaderLines: 0,
|
||||
Margin: defaultMargin(),
|
||||
Tabstop: 8,
|
||||
Version: false}
|
||||
}
|
||||
|
||||
func help(ok int) {
|
||||
func help(code int) {
|
||||
os.Stderr.WriteString(usage)
|
||||
os.Exit(ok)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func errorExit(msg string) {
|
||||
os.Stderr.WriteString(msg + "\n")
|
||||
os.Exit(1)
|
||||
os.Exit(exitError)
|
||||
}
|
||||
|
||||
func optString(arg string, prefixes ...string) (bool, string) {
|
||||
@@ -344,6 +344,8 @@ func parseKeyChords(str string, message string) map[int]string {
|
||||
chord = curses.SLeft
|
||||
case "shift-right":
|
||||
chord = curses.SRight
|
||||
case "double-click":
|
||||
chord = curses.DoubleClick
|
||||
default:
|
||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||
chord = curses.CtrlA + int(lkey[5]) - 'a'
|
||||
@@ -364,25 +366,47 @@ func parseKeyChords(str string, message string) map[int]string {
|
||||
return chords
|
||||
}
|
||||
|
||||
func parseTiebreak(str string) tiebreak {
|
||||
switch strings.ToLower(str) {
|
||||
case "length":
|
||||
return byLength
|
||||
case "index":
|
||||
return byIndex
|
||||
case "begin":
|
||||
return byBegin
|
||||
case "end":
|
||||
return byEnd
|
||||
default:
|
||||
errorExit("invalid sort criterion: " + str)
|
||||
func parseTiebreak(str string) []criterion {
|
||||
criteria := []criterion{byMatchLen}
|
||||
hasIndex := false
|
||||
hasLength := false
|
||||
hasBegin := false
|
||||
hasEnd := false
|
||||
check := func(notExpected *bool, name string) {
|
||||
if *notExpected {
|
||||
errorExit("duplicate sort criteria: " + name)
|
||||
}
|
||||
if hasIndex {
|
||||
errorExit("index should be the last criterion")
|
||||
}
|
||||
*notExpected = true
|
||||
}
|
||||
return byLength
|
||||
for _, str := range strings.Split(strings.ToLower(str), ",") {
|
||||
switch str {
|
||||
case "index":
|
||||
check(&hasIndex, "index")
|
||||
case "length":
|
||||
check(&hasLength, "length")
|
||||
criteria = append(criteria, byLength)
|
||||
case "begin":
|
||||
check(&hasBegin, "begin")
|
||||
criteria = append(criteria, byBegin)
|
||||
case "end":
|
||||
check(&hasEnd, "end")
|
||||
criteria = append(criteria, byEnd)
|
||||
default:
|
||||
errorExit("invalid sort criterion: " + str)
|
||||
}
|
||||
}
|
||||
return criteria
|
||||
}
|
||||
|
||||
func dupeTheme(theme *curses.ColorTheme) *curses.ColorTheme {
|
||||
dupe := *theme
|
||||
return &dupe
|
||||
if theme != nil {
|
||||
dupe := *theme
|
||||
return &dupe
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme {
|
||||
@@ -403,7 +427,7 @@ func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme
|
||||
}
|
||||
// Color is disabled
|
||||
if theme == nil {
|
||||
errorExit("colors disabled; cannot customize colors")
|
||||
continue
|
||||
}
|
||||
|
||||
pair := strings.Split(str, ":")
|
||||
@@ -464,15 +488,18 @@ const (
|
||||
escapedComma = 1
|
||||
)
|
||||
|
||||
func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {
|
||||
func parseKeymap(keymap map[int]actionType, execmap map[int]string, str string) {
|
||||
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(\\([^)]*\\)|\\[[^\\]]*\\]|~[^~]*~|![^!]*!|@[^@]*@|\\#[^\\#]*\\#|\\$[^\\$]*\\$|%[^%]*%|\\^[^\\^]*\\^|&[^&]*&|\\*[^\\*]*\\*|;[^;]*;|/[^/]*/|\\|[^\\|]*\\|)")
|
||||
"(?s):execute(-multi)?:.*|:execute(-multi)?(\\([^)]*\\)|\\[[^\\]]*\\]|~[^~]*~|![^!]*!|@[^@]*@|\\#[^\\#]*\\#|\\$[^\\$]*\\$|%[^%]*%|\\^[^\\^]*\\^|&[^&]*&|\\*[^\\*]*\\*|;[^;]*;|/[^/]*/|\\|[^\\|]*\\|)")
|
||||
}
|
||||
masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {
|
||||
return ":execute(" + strings.Repeat(" ", len(src)-10) + ")"
|
||||
if strings.HasPrefix(src, ":execute-multi") {
|
||||
return ":execute-multi(" + strings.Repeat(" ", len(src)-len(":execute-multi()")) + ")"
|
||||
}
|
||||
return ":execute(" + strings.Repeat(" ", len(src)-len(":execute()")) + ")"
|
||||
})
|
||||
masked = strings.Replace(masked, "::", string([]rune{escapedColon, ':'}), -1)
|
||||
masked = strings.Replace(masked, ",:", string([]rune{escapedComma, ':'}), -1)
|
||||
@@ -543,6 +570,10 @@ func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort b
|
||||
keymap[key] = actToggleDown
|
||||
case "toggle-up":
|
||||
keymap[key] = actToggleUp
|
||||
case "toggle-in":
|
||||
keymap[key] = actToggleIn
|
||||
case "toggle-out":
|
||||
keymap[key] = actToggleOut
|
||||
case "toggle-all":
|
||||
keymap[key] = actToggleAll
|
||||
case "select-all":
|
||||
@@ -565,28 +596,39 @@ func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort b
|
||||
keymap[key] = actNextHistory
|
||||
case "toggle-sort":
|
||||
keymap[key] = actToggleSort
|
||||
toggleSort = true
|
||||
default:
|
||||
if isExecuteAction(actLower) {
|
||||
keymap[key] = actExecute
|
||||
if act[7] == ':' {
|
||||
execmap[key] = act[8:]
|
||||
var offset int
|
||||
if strings.HasPrefix(actLower, "execute-multi") {
|
||||
keymap[key] = actExecuteMulti
|
||||
offset = len("execute-multi")
|
||||
} else {
|
||||
execmap[key] = act[8 : len(act)-1]
|
||||
keymap[key] = actExecute
|
||||
offset = len("execute")
|
||||
}
|
||||
if act[offset] == ':' {
|
||||
execmap[key] = act[offset+1:]
|
||||
} else {
|
||||
execmap[key] = act[offset+1 : len(act)-1]
|
||||
}
|
||||
} else {
|
||||
errorExit("unknown action: " + act)
|
||||
}
|
||||
}
|
||||
}
|
||||
return keymap, execmap, toggleSort
|
||||
}
|
||||
|
||||
func isExecuteAction(str string) bool {
|
||||
if !strings.HasPrefix(str, "execute") || len(str) < 9 {
|
||||
if !strings.HasPrefix(str, "execute") || len(str) < len("execute()") {
|
||||
return false
|
||||
}
|
||||
b := str[7]
|
||||
b := str[len("execute")]
|
||||
if strings.HasPrefix(str, "execute-multi") {
|
||||
if len(str) < len("execute-multi()") {
|
||||
return false
|
||||
}
|
||||
b = str[len("execute-multi")]
|
||||
}
|
||||
e := str[len(str)-1]
|
||||
if b == ':' || b == '(' && e == ')' || b == '[' && e == ']' ||
|
||||
b == e && strings.ContainsAny(string(b), "~!@#$%^&*;/|") {
|
||||
@@ -595,21 +637,16 @@ func isExecuteAction(str string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
||||
func parseToggleSort(keymap map[int]actionType, str string) {
|
||||
keys := parseKeyChords(str, "key name required")
|
||||
if len(keys) != 1 {
|
||||
errorExit("multiple keys specified")
|
||||
}
|
||||
keymap[firstKey(keys)] = actToggleSort
|
||||
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 strLines(str string) []string {
|
||||
return strings.Split(strings.TrimSuffix(str, "\n"), "\n")
|
||||
}
|
||||
|
||||
func parseMargin(margin string) [4]string {
|
||||
@@ -655,7 +692,6 @@ func parseMargin(margin string) [4]string {
|
||||
}
|
||||
|
||||
func parseOptions(opts *Options, allArgs []string) {
|
||||
keymap := make(map[int]actionType)
|
||||
var historyMax int
|
||||
if opts.History == nil {
|
||||
historyMax = defaultHistoryMax
|
||||
@@ -682,13 +718,19 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
arg := allArgs[i]
|
||||
switch arg {
|
||||
case "-h", "--help":
|
||||
help(0)
|
||||
help(exitOk)
|
||||
case "-x", "--extended":
|
||||
opts.Mode = ModeExtended
|
||||
case "-e", "--extended-exact":
|
||||
opts.Mode = ModeExtendedExact
|
||||
case "+x", "--no-extended", "+e", "--no-extended-exact":
|
||||
opts.Mode = ModeFuzzy
|
||||
opts.Extended = true
|
||||
case "-e", "--exact":
|
||||
opts.Fuzzy = false
|
||||
case "--extended-exact":
|
||||
// Note that we now don't have --no-extended-exact
|
||||
opts.Fuzzy = false
|
||||
opts.Extended = true
|
||||
case "+x", "--no-extended":
|
||||
opts.Extended = false
|
||||
case "+e", "--no-exact":
|
||||
opts.Fuzzy = true
|
||||
case "-q", "--query":
|
||||
opts.Query = nextString(allArgs, &i, "query string required")
|
||||
case "-f", "--filter":
|
||||
@@ -697,10 +739,9 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
case "--expect":
|
||||
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
||||
case "--tiebreak":
|
||||
opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||
opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||
case "--bind":
|
||||
keymap, opts.Execmap, opts.ToggleSort =
|
||||
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))
|
||||
parseKeymap(opts.Keymap, opts.Execmap, nextString(allArgs, &i, "bind expression required"))
|
||||
case "--color":
|
||||
spec := optionalNextString(allArgs, &i)
|
||||
if len(spec) == 0 {
|
||||
@@ -709,8 +750,7 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Theme = parseTheme(opts.Theme, spec)
|
||||
}
|
||||
case "--toggle-sort":
|
||||
keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))
|
||||
opts.ToggleSort = true
|
||||
parseToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))
|
||||
case "-d", "--delimiter":
|
||||
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
||||
case "-n", "--nth":
|
||||
@@ -759,6 +799,8 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Hscroll = true
|
||||
case "--no-hscroll":
|
||||
opts.Hscroll = false
|
||||
case "--hscroll-off":
|
||||
opts.HscrollOff = nextInt(allArgs, &i, "hscroll offset required")
|
||||
case "--inline-info":
|
||||
opts.InlineInfo = true
|
||||
case "--no-inline-info":
|
||||
@@ -793,16 +835,13 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
setHistory(nextString(allArgs, &i, "history file path required"))
|
||||
case "--history-size":
|
||||
setHistoryMax(nextInt(allArgs, &i, "history max size required"))
|
||||
case "--no-header-file":
|
||||
case "--no-header":
|
||||
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":
|
||||
opts.Header = strLines(nextString(allArgs, &i, "header string required"))
|
||||
case "--header-lines":
|
||||
opts.Header = []string{}
|
||||
opts.HeaderLines = atoi(
|
||||
nextString(allArgs, &i, "number of header lines required"))
|
||||
case "--no-margin":
|
||||
@@ -810,6 +849,8 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
case "--margin":
|
||||
opts.Margin = parseMargin(
|
||||
nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))
|
||||
case "--tabstop":
|
||||
opts.Tabstop = nextInt(allArgs, &i, "tab stop required")
|
||||
case "--version":
|
||||
opts.Version = true
|
||||
default:
|
||||
@@ -828,29 +869,29 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
} else if match, _ := optString(arg, "-s", "--sort="); match {
|
||||
opts.Sort = 1 // Don't care
|
||||
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||
keymap = checkToggleSort(keymap, value)
|
||||
opts.ToggleSort = true
|
||||
parseToggleSort(opts.Keymap, value)
|
||||
} else if match, value := optString(arg, "--expect="); match {
|
||||
opts.Expect = parseKeyChords(value, "key names required")
|
||||
} else if match, value := optString(arg, "--tiebreak="); match {
|
||||
opts.Tiebreak = parseTiebreak(value)
|
||||
opts.Criteria = parseTiebreak(value)
|
||||
} else if match, value := optString(arg, "--color="); match {
|
||||
opts.Theme = parseTheme(opts.Theme, value)
|
||||
} else if match, value := optString(arg, "--bind="); match {
|
||||
keymap, opts.Execmap, opts.ToggleSort =
|
||||
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)
|
||||
parseKeymap(opts.Keymap, opts.Execmap, 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="); match {
|
||||
opts.Header = strLines(value)
|
||||
} 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 if match, value := optString(arg, "--tabstop="); match {
|
||||
opts.Tabstop = atoi(value)
|
||||
} else if match, value := optString(arg, "--hscroll-off="); match {
|
||||
opts.HscrollOff = atoi(value)
|
||||
} else {
|
||||
errorExit("unknown option: " + arg)
|
||||
}
|
||||
@@ -861,24 +902,39 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
errorExit("header lines must be a non-negative integer")
|
||||
}
|
||||
|
||||
// Change default actions for CTRL-N / CTRL-P when --history is used
|
||||
if opts.HscrollOff < 0 {
|
||||
errorExit("hscroll offset must be a non-negative integer")
|
||||
}
|
||||
|
||||
if opts.Tabstop < 1 {
|
||||
errorExit("tab stop must be a positive integer")
|
||||
}
|
||||
}
|
||||
|
||||
func postProcessOptions(opts *Options) {
|
||||
// Default actions for CTRL-N / CTRL-P when --history is set
|
||||
if opts.History != nil {
|
||||
if _, prs := keymap[curses.CtrlP]; !prs {
|
||||
keymap[curses.CtrlP] = actPreviousHistory
|
||||
if _, prs := opts.Keymap[curses.CtrlP]; !prs {
|
||||
opts.Keymap[curses.CtrlP] = actPreviousHistory
|
||||
}
|
||||
if _, prs := keymap[curses.CtrlN]; !prs {
|
||||
keymap[curses.CtrlN] = actNextHistory
|
||||
if _, prs := opts.Keymap[curses.CtrlN]; !prs {
|
||||
opts.Keymap[curses.CtrlN] = actNextHistory
|
||||
}
|
||||
}
|
||||
|
||||
// Override default key bindings
|
||||
for key, act := range keymap {
|
||||
opts.Keymap[key] = act
|
||||
// Extend the default key map
|
||||
keymap := defaultKeymap()
|
||||
for key, act := range opts.Keymap {
|
||||
if act == actToggleSort {
|
||||
opts.ToggleSort = true
|
||||
}
|
||||
keymap[key] = act
|
||||
}
|
||||
opts.Keymap = keymap
|
||||
|
||||
// If we're not using extended search mode, --nth option becomes irrelevant
|
||||
// if it contains the whole range
|
||||
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
||||
if !opts.Extended || len(opts.Nth) == 1 {
|
||||
for _, r := range opts.Nth {
|
||||
if r.begin == rangeEllipsis && r.end == rangeEllipsis {
|
||||
opts.Nth = make([]Range, 0)
|
||||
@@ -894,9 +950,13 @@ func ParseOptions() *Options {
|
||||
|
||||
// Options from Env var
|
||||
words, _ := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))
|
||||
parseOptions(opts, words)
|
||||
if len(words) > 0 {
|
||||
parseOptions(opts, words)
|
||||
}
|
||||
|
||||
// Options from command-line arguments
|
||||
parseOptions(opts, os.Args[1:])
|
||||
|
||||
postProcessOptions(opts)
|
||||
return opts
|
||||
}
|
||||
|
@@ -96,14 +96,16 @@ func TestIrrelevantNth(t *testing.T) {
|
||||
opts := defaultOptions()
|
||||
words := []string{"--nth", "..", "-x"}
|
||||
parseOptions(opts, words)
|
||||
postProcessOptions(opts)
|
||||
if len(opts.Nth) != 0 {
|
||||
t.Errorf("nth should be empty: %s", opts.Nth)
|
||||
}
|
||||
}
|
||||
for _, words := range [][]string{[]string{"--nth", "..,3"}, []string{"--nth", "3,1.."}, []string{"--nth", "..-1,1"}} {
|
||||
for _, words := range [][]string{[]string{"--nth", "..,3", "+x"}, []string{"--nth", "3,1..", "+x"}, []string{"--nth", "..-1,1", "+x"}} {
|
||||
{
|
||||
opts := defaultOptions()
|
||||
parseOptions(opts, words)
|
||||
postProcessOptions(opts)
|
||||
if len(opts.Nth) != 0 {
|
||||
t.Errorf("nth should be empty: %s", opts.Nth)
|
||||
}
|
||||
@@ -112,6 +114,7 @@ func TestIrrelevantNth(t *testing.T) {
|
||||
opts := defaultOptions()
|
||||
words = append(words, "-x")
|
||||
parseOptions(opts, words)
|
||||
postProcessOptions(opts)
|
||||
if len(opts.Nth) != 2 {
|
||||
t.Errorf("nth should not be empty: %s", opts.Nth)
|
||||
}
|
||||
@@ -231,15 +234,11 @@ func TestBind(t *testing.T) {
|
||||
keymap := defaultKeymap()
|
||||
execmap := make(map[int]string)
|
||||
check(actBeginningOfLine, keymap[curses.CtrlA])
|
||||
keymap, execmap, toggleSort :=
|
||||
parseKeymap(keymap, execmap, false,
|
||||
"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 {
|
||||
t.Errorf("toggleSort not set")
|
||||
}
|
||||
parseKeymap(keymap, execmap,
|
||||
"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)")
|
||||
check(actKillLine, keymap[curses.CtrlA])
|
||||
check(actToggleSort, keymap[curses.CtrlB])
|
||||
check(actPageUp, keymap[curses.AltZ+'c'])
|
||||
@@ -259,15 +258,11 @@ func TestBind(t *testing.T) {
|
||||
checkString("\nfoobar,Y:execute(baz)", execmap[curses.AltZ+'X'])
|
||||
|
||||
for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {
|
||||
keymap, execmap, toggleSort =
|
||||
parseKeymap(keymap, execmap, false, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))
|
||||
parseKeymap(keymap, execmap, 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 {
|
||||
t.Errorf("toggleSort set")
|
||||
}
|
||||
parseKeymap(keymap, execmap, "f1:abort")
|
||||
check(actAbort, keymap[curses.F1])
|
||||
}
|
||||
|
||||
@@ -316,3 +311,65 @@ func TestColorSpec(t *testing.T) {
|
||||
t.Errorf("using default colors")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNilTheme(t *testing.T) {
|
||||
var theme *curses.ColorTheme
|
||||
newTheme := parseTheme(theme, "prompt:12")
|
||||
if newTheme != nil {
|
||||
t.Errorf("color is disabled. keep it that way.")
|
||||
}
|
||||
newTheme = parseTheme(theme, "prompt:12,dark,prompt:13")
|
||||
if newTheme.Prompt != 13 {
|
||||
t.Errorf("color should now be enabled and customized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultCtrlNP(t *testing.T) {
|
||||
check := func(words []string, key int, expected actionType) {
|
||||
opts := defaultOptions()
|
||||
parseOptions(opts, words)
|
||||
postProcessOptions(opts)
|
||||
if opts.Keymap[key] != expected {
|
||||
t.Error()
|
||||
}
|
||||
}
|
||||
check([]string{}, curses.CtrlN, actDown)
|
||||
check([]string{}, curses.CtrlP, actUp)
|
||||
|
||||
check([]string{"--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)
|
||||
check([]string{"--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)
|
||||
|
||||
hist := "--history=/tmp/foo"
|
||||
check([]string{hist}, curses.CtrlN, actNextHistory)
|
||||
check([]string{hist}, curses.CtrlP, actPreviousHistory)
|
||||
|
||||
check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)
|
||||
check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlP, actPreviousHistory)
|
||||
|
||||
check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlN, actNextHistory)
|
||||
check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)
|
||||
}
|
||||
|
||||
func TestToggle(t *testing.T) {
|
||||
optsFor := func(words ...string) *Options {
|
||||
opts := defaultOptions()
|
||||
parseOptions(opts, words)
|
||||
postProcessOptions(opts)
|
||||
return opts
|
||||
}
|
||||
|
||||
opts := optsFor()
|
||||
if opts.ToggleSort {
|
||||
t.Error()
|
||||
}
|
||||
|
||||
opts = optsFor("--bind=a:toggle-sort")
|
||||
if !opts.ToggleSort {
|
||||
t.Error()
|
||||
}
|
||||
|
||||
opts = optsFor("--bind=a:toggle-sort", "--bind=a:up")
|
||||
if opts.ToggleSort {
|
||||
t.Error()
|
||||
}
|
||||
}
|
||||
|
183
src/pattern.go
183
src/pattern.go
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/junegunn/fzf/src/algo"
|
||||
"github.com/junegunn/fzf/src/util"
|
||||
)
|
||||
|
||||
// fuzzy
|
||||
@@ -35,16 +36,20 @@ type term struct {
|
||||
origText []rune
|
||||
}
|
||||
|
||||
type termSet []term
|
||||
|
||||
// Pattern represents search pattern
|
||||
type Pattern struct {
|
||||
mode Mode
|
||||
fuzzy bool
|
||||
extended bool
|
||||
caseSensitive bool
|
||||
forward bool
|
||||
text []rune
|
||||
terms []term
|
||||
hasInvTerm bool
|
||||
termSets []termSet
|
||||
cacheable bool
|
||||
delimiter Delimiter
|
||||
nth []Range
|
||||
procFun map[termType]func(bool, []rune, []rune) (int, int)
|
||||
procFun map[termType]func(bool, bool, []rune, []rune) algo.Result
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -61,7 +66,7 @@ func init() {
|
||||
|
||||
func clearPatternCache() {
|
||||
// We can uniquely identify the pattern for a given string since
|
||||
// mode and caseMode do not change while the program is running
|
||||
// search mode and caseMode do not change while the program is running
|
||||
_patternCache = make(map[string]*Pattern)
|
||||
}
|
||||
|
||||
@@ -70,14 +75,13 @@ func clearChunkCache() {
|
||||
}
|
||||
|
||||
// BuildPattern builds Pattern object from the given arguments
|
||||
func BuildPattern(mode Mode, caseMode Case,
|
||||
func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,
|
||||
nth []Range, delimiter Delimiter, runes []rune) *Pattern {
|
||||
|
||||
var asString string
|
||||
switch mode {
|
||||
case ModeExtended, ModeExtendedExact:
|
||||
if extended {
|
||||
asString = strings.Trim(string(runes), " ")
|
||||
default:
|
||||
} else {
|
||||
asString = string(runes)
|
||||
}
|
||||
|
||||
@@ -86,18 +90,23 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
return cached
|
||||
}
|
||||
|
||||
caseSensitive, hasInvTerm := true, false
|
||||
terms := []term{}
|
||||
caseSensitive, cacheable := true, true
|
||||
termSets := []termSet{}
|
||||
|
||||
switch mode {
|
||||
case ModeExtended, ModeExtendedExact:
|
||||
terms = parseTerms(mode, caseMode, asString)
|
||||
for _, term := range terms {
|
||||
if term.inv {
|
||||
hasInvTerm = true
|
||||
if extended {
|
||||
termSets = parseTerms(fuzzy, caseMode, asString)
|
||||
Loop:
|
||||
for _, termSet := range termSets {
|
||||
for idx, term := range termSet {
|
||||
// If the query contains inverse search terms or OR operators,
|
||||
// we cannot cache the search scope
|
||||
if idx > 0 || term.inv {
|
||||
cacheable = false
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
lowerString := strings.ToLower(asString)
|
||||
caseSensitive = caseMode == CaseRespect ||
|
||||
caseMode == CaseSmart && lowerString != asString
|
||||
@@ -107,14 +116,16 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
}
|
||||
|
||||
ptr := &Pattern{
|
||||
mode: mode,
|
||||
fuzzy: fuzzy,
|
||||
extended: extended,
|
||||
caseSensitive: caseSensitive,
|
||||
forward: forward,
|
||||
text: []rune(asString),
|
||||
terms: terms,
|
||||
hasInvTerm: hasInvTerm,
|
||||
termSets: termSets,
|
||||
cacheable: cacheable,
|
||||
nth: nth,
|
||||
delimiter: delimiter,
|
||||
procFun: make(map[termType]func(bool, []rune, []rune) (int, int))}
|
||||
procFun: make(map[termType]func(bool, bool, []rune, []rune) algo.Result)}
|
||||
|
||||
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
||||
ptr.procFun[termEqual] = algo.EqualMatch
|
||||
@@ -126,9 +137,11 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
return ptr
|
||||
}
|
||||
|
||||
func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||
func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {
|
||||
tokens := _splitRegex.Split(str, -1)
|
||||
terms := []term{}
|
||||
sets := []termSet{}
|
||||
set := termSet{}
|
||||
switchSet := false
|
||||
for _, token := range tokens {
|
||||
typ, inv, text := termFuzzy, false, token
|
||||
lowerText := strings.ToLower(text)
|
||||
@@ -138,19 +151,28 @@ func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||
text = lowerText
|
||||
}
|
||||
origText := []rune(text)
|
||||
if mode == ModeExtendedExact {
|
||||
if !fuzzy {
|
||||
typ = termExact
|
||||
}
|
||||
|
||||
if text == "|" {
|
||||
switchSet = false
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(text, "!") {
|
||||
inv = true
|
||||
text = text[1:]
|
||||
}
|
||||
|
||||
if strings.HasPrefix(text, "'") {
|
||||
if mode == ModeExtended {
|
||||
// Flip exactness
|
||||
if fuzzy {
|
||||
typ = termExact
|
||||
text = text[1:]
|
||||
} else {
|
||||
typ = termFuzzy
|
||||
text = text[1:]
|
||||
}
|
||||
} else if strings.HasPrefix(text, "^") {
|
||||
if strings.HasSuffix(text, "$") {
|
||||
@@ -166,23 +188,31 @@ func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||
}
|
||||
|
||||
if len(text) > 0 {
|
||||
terms = append(terms, term{
|
||||
if switchSet {
|
||||
sets = append(sets, set)
|
||||
set = termSet{}
|
||||
}
|
||||
set = append(set, term{
|
||||
typ: typ,
|
||||
inv: inv,
|
||||
text: []rune(text),
|
||||
caseSensitive: caseSensitive,
|
||||
origText: origText})
|
||||
switchSet = true
|
||||
}
|
||||
}
|
||||
return terms
|
||||
if len(set) > 0 {
|
||||
sets = append(sets, set)
|
||||
}
|
||||
return sets
|
||||
}
|
||||
|
||||
// IsEmpty returns true if the pattern is effectively empty
|
||||
func (p *Pattern) IsEmpty() bool {
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
return len(p.text) == 0
|
||||
}
|
||||
return len(p.terms) == 0
|
||||
return len(p.termSets) == 0
|
||||
}
|
||||
|
||||
// AsString returns the search query in string type
|
||||
@@ -192,15 +222,14 @@ func (p *Pattern) AsString() string {
|
||||
|
||||
// CacheKey is used to build string to be used as the key of result cache
|
||||
func (p *Pattern) CacheKey() string {
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
return p.AsString()
|
||||
}
|
||||
cacheableTerms := []string{}
|
||||
for _, term := range p.terms {
|
||||
if term.inv {
|
||||
continue
|
||||
for _, termSet := range p.termSets {
|
||||
if len(termSet) == 1 && !termSet[0].inv {
|
||||
cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
|
||||
}
|
||||
cacheableTerms = append(cacheableTerms, string(term.origText))
|
||||
}
|
||||
return strings.Join(cacheableTerms, " ")
|
||||
}
|
||||
@@ -211,7 +240,7 @@ func (p *Pattern) Match(chunk *Chunk) []*Item {
|
||||
|
||||
// ChunkCache: Exact match
|
||||
cacheKey := p.CacheKey()
|
||||
if !p.hasInvTerm { // Because we're excluding Inv-term from cache key
|
||||
if p.cacheable {
|
||||
if cached, found := _cache.Find(chunk, cacheKey); found {
|
||||
return cached
|
||||
}
|
||||
@@ -236,7 +265,7 @@ Loop:
|
||||
|
||||
matches := p.matchChunk(space)
|
||||
|
||||
if !p.hasInvTerm {
|
||||
if p.cacheable {
|
||||
_cache.Add(chunk, cacheKey, matches)
|
||||
}
|
||||
return matches
|
||||
@@ -244,17 +273,18 @@ Loop:
|
||||
|
||||
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||
matches := []*Item{}
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
for _, item := range *chunk {
|
||||
if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {
|
||||
offset, bonus := p.basicMatch(item)
|
||||
if sidx := offset[0]; sidx >= 0 {
|
||||
matches = append(matches,
|
||||
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
|
||||
dupItem(item, []Offset{offset}, bonus))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, item := range *chunk {
|
||||
if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {
|
||||
matches = append(matches, dupItem(item, offsets))
|
||||
if offsets, bonus := p.extendedMatch(item); len(offsets) == len(p.termSets) {
|
||||
matches = append(matches, dupItem(item, offsets, bonus))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -263,46 +293,62 @@ func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||
|
||||
// MatchItem returns true if the Item is a match
|
||||
func (p *Pattern) MatchItem(item *Item) bool {
|
||||
if p.mode == ModeFuzzy {
|
||||
sidx, _ := p.fuzzyMatch(item)
|
||||
if !p.extended {
|
||||
offset, _ := p.basicMatch(item)
|
||||
sidx := offset[0]
|
||||
return sidx >= 0
|
||||
}
|
||||
offsets := p.extendedMatch(item)
|
||||
return len(offsets) == len(p.terms)
|
||||
offsets, _ := p.extendedMatch(item)
|
||||
return len(offsets) == len(p.termSets)
|
||||
}
|
||||
|
||||
func dupItem(item *Item, offsets []Offset) *Item {
|
||||
func dupItem(item *Item, offsets []Offset, bonus int32) *Item {
|
||||
sort.Sort(ByOrder(offsets))
|
||||
return &Item{
|
||||
text: item.text,
|
||||
origText: item.origText,
|
||||
transformed: item.transformed,
|
||||
index: item.index,
|
||||
offsets: offsets,
|
||||
bonus: bonus,
|
||||
colors: item.colors,
|
||||
rank: Rank{0, 0, item.index}}
|
||||
rank: buildEmptyRank(item.Index())}
|
||||
}
|
||||
|
||||
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
||||
func (p *Pattern) basicMatch(item *Item) (Offset, int32) {
|
||||
input := p.prepareInput(item)
|
||||
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)
|
||||
if p.fuzzy {
|
||||
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)
|
||||
}
|
||||
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)
|
||||
}
|
||||
|
||||
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
||||
func (p *Pattern) extendedMatch(item *Item) ([]Offset, int32) {
|
||||
input := p.prepareInput(item)
|
||||
offsets := []Offset{}
|
||||
for _, term := range p.terms {
|
||||
pfun := p.procFun[term.typ]
|
||||
if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {
|
||||
if term.inv {
|
||||
var totalBonus int32
|
||||
for _, termSet := range p.termSets {
|
||||
var offset *Offset
|
||||
var bonus int32
|
||||
for _, term := range termSet {
|
||||
pfun := p.procFun[term.typ]
|
||||
off, pen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)
|
||||
if sidx := off[0]; sidx >= 0 {
|
||||
if term.inv {
|
||||
continue
|
||||
}
|
||||
offset, bonus = &off, pen
|
||||
break
|
||||
} else if term.inv {
|
||||
offset, bonus = &Offset{0, 0, 0}, 0
|
||||
continue
|
||||
}
|
||||
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
|
||||
} else if term.inv {
|
||||
offsets = append(offsets, Offset{0, 0})
|
||||
}
|
||||
if offset != nil {
|
||||
offsets = append(offsets, *offset)
|
||||
totalBonus += bonus
|
||||
}
|
||||
}
|
||||
return offsets
|
||||
return offsets, totalBonus
|
||||
}
|
||||
|
||||
func (p *Pattern) prepareInput(item *Item) []Token {
|
||||
@@ -315,19 +361,22 @@ func (p *Pattern) prepareInput(item *Item) []Token {
|
||||
tokens := Tokenize(item.text, p.delimiter)
|
||||
ret = Transform(tokens, p.nth)
|
||||
} else {
|
||||
ret = []Token{Token{text: item.text, prefixLength: 0}}
|
||||
ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}
|
||||
}
|
||||
item.transformed = ret
|
||||
return ret
|
||||
}
|
||||
|
||||
func (p *Pattern) iter(pfun func(bool, []rune, []rune) (int, int),
|
||||
tokens []Token, caseSensitive bool, pattern []rune) (int, int) {
|
||||
func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) algo.Result,
|
||||
tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int32) {
|
||||
for _, part := range tokens {
|
||||
prefixLength := part.prefixLength
|
||||
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
|
||||
return sidx + prefixLength, eidx + prefixLength
|
||||
prefixLength := int32(part.prefixLength)
|
||||
if res := pfun(caseSensitive, forward, part.text, pattern); res.Start >= 0 {
|
||||
var sidx int32 = res.Start + prefixLength
|
||||
var eidx int32 = res.End + prefixLength
|
||||
return Offset{sidx, eidx, int32(part.trimLength)}, res.Bonus
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
// TODO: math.MaxUint16
|
||||
return Offset{-1, -1, -1}, 0.0
|
||||
}
|
||||
|
@@ -8,21 +8,26 @@ import (
|
||||
)
|
||||
|
||||
func TestParseTermsExtended(t *testing.T) {
|
||||
terms := parseTerms(ModeExtended, CaseSmart,
|
||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ ^iii$")
|
||||
terms := parseTerms(true, CaseSmart,
|
||||
"| aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | | zzz$ | !ZZZ |")
|
||||
if len(terms) != 9 ||
|
||||
terms[0].typ != termFuzzy || terms[0].inv ||
|
||||
terms[1].typ != termExact || terms[1].inv ||
|
||||
terms[2].typ != termPrefix || terms[2].inv ||
|
||||
terms[3].typ != termSuffix || terms[3].inv ||
|
||||
terms[4].typ != termFuzzy || !terms[4].inv ||
|
||||
terms[5].typ != termExact || !terms[5].inv ||
|
||||
terms[6].typ != termPrefix || !terms[6].inv ||
|
||||
terms[7].typ != termSuffix || !terms[7].inv ||
|
||||
terms[8].typ != termEqual || terms[8].inv {
|
||||
terms[0][0].typ != termFuzzy || terms[0][0].inv ||
|
||||
terms[1][0].typ != termExact || terms[1][0].inv ||
|
||||
terms[2][0].typ != termPrefix || terms[2][0].inv ||
|
||||
terms[3][0].typ != termSuffix || terms[3][0].inv ||
|
||||
terms[4][0].typ != termFuzzy || !terms[4][0].inv ||
|
||||
terms[5][0].typ != termExact || !terms[5][0].inv ||
|
||||
terms[6][0].typ != termPrefix || !terms[6][0].inv ||
|
||||
terms[7][0].typ != termSuffix || !terms[7][0].inv ||
|
||||
terms[7][1].typ != termEqual || terms[7][1].inv ||
|
||||
terms[8][0].typ != termPrefix || terms[8][0].inv ||
|
||||
terms[8][1].typ != termExact || terms[8][1].inv ||
|
||||
terms[8][2].typ != termSuffix || terms[8][2].inv ||
|
||||
terms[8][3].typ != termFuzzy || !terms[8][3].inv {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
for idx, term := range terms {
|
||||
for idx, termSet := range terms[:8] {
|
||||
term := termSet[0]
|
||||
if len(term.text) != 3 {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
@@ -30,26 +35,31 @@ func TestParseTermsExtended(t *testing.T) {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
}
|
||||
for _, term := range terms[8] {
|
||||
if len(term.origText) != 4 {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTermsExtendedExact(t *testing.T) {
|
||||
terms := parseTerms(ModeExtendedExact, CaseSmart,
|
||||
terms := parseTerms(false, CaseSmart,
|
||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
||||
if len(terms) != 8 ||
|
||||
terms[0].typ != termExact || terms[0].inv || len(terms[0].text) != 3 ||
|
||||
terms[1].typ != termExact || terms[1].inv || len(terms[1].text) != 4 ||
|
||||
terms[2].typ != termPrefix || terms[2].inv || len(terms[2].text) != 3 ||
|
||||
terms[3].typ != termSuffix || terms[3].inv || len(terms[3].text) != 3 ||
|
||||
terms[4].typ != termExact || !terms[4].inv || len(terms[4].text) != 3 ||
|
||||
terms[5].typ != termExact || !terms[5].inv || len(terms[5].text) != 4 ||
|
||||
terms[6].typ != termPrefix || !terms[6].inv || len(terms[6].text) != 3 ||
|
||||
terms[7].typ != termSuffix || !terms[7].inv || len(terms[7].text) != 3 {
|
||||
terms[0][0].typ != termExact || terms[0][0].inv || len(terms[0][0].text) != 3 ||
|
||||
terms[1][0].typ != termFuzzy || terms[1][0].inv || len(terms[1][0].text) != 3 ||
|
||||
terms[2][0].typ != termPrefix || terms[2][0].inv || len(terms[2][0].text) != 3 ||
|
||||
terms[3][0].typ != termSuffix || terms[3][0].inv || len(terms[3][0].text) != 3 ||
|
||||
terms[4][0].typ != termExact || !terms[4][0].inv || len(terms[4][0].text) != 3 ||
|
||||
terms[5][0].typ != termFuzzy || !terms[5][0].inv || len(terms[5][0].text) != 3 ||
|
||||
terms[6][0].typ != termPrefix || !terms[6][0].inv || len(terms[6][0].text) != 3 ||
|
||||
terms[7][0].typ != termSuffix || !terms[7][0].inv || len(terms[7][0].text) != 3 {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTermsEmpty(t *testing.T) {
|
||||
terms := parseTerms(ModeExtended, CaseSmart, "' $ ^ !' !^ !$")
|
||||
terms := parseTerms(true, CaseSmart, "' $ ^ !' !^ !$")
|
||||
if len(terms) != 0 {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
@@ -58,25 +68,25 @@ func TestParseTermsEmpty(t *testing.T) {
|
||||
func TestExact(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pattern := BuildPattern(ModeExtended, CaseSmart,
|
||||
pattern := BuildPattern(true, true, CaseSmart, true,
|
||||
[]Range{}, Delimiter{}, []rune("'abc"))
|
||||
sidx, eidx := algo.ExactMatchNaive(
|
||||
pattern.caseSensitive, []rune("aabbcc abc"), pattern.terms[0].text)
|
||||
if sidx != 7 || eidx != 10 {
|
||||
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||
res := algo.ExactMatchNaive(
|
||||
pattern.caseSensitive, pattern.forward, []rune("aabbcc abc"), pattern.termSets[0][0].text)
|
||||
if res.Start != 7 || res.End != 10 {
|
||||
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEqual(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, Delimiter{}, []rune("^AbC$"))
|
||||
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []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 := func(str string, sidxExpected int32, eidxExpected int32) {
|
||||
res := algo.EqualMatch(
|
||||
pattern.caseSensitive, pattern.forward, []rune(str), pattern.termSets[0][0].text)
|
||||
if res.Start != sidxExpected || res.End != eidxExpected {
|
||||
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||
}
|
||||
}
|
||||
match("ABC", -1, -1)
|
||||
@@ -86,17 +96,17 @@ func TestEqual(t *testing.T) {
|
||||
func TestCaseSensitivity(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pat1 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, Delimiter{}, []rune("abc"))
|
||||
pat1 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
clearPatternCache()
|
||||
pat2 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
pat2 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
clearPatternCache()
|
||||
pat3 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, Delimiter{}, []rune("abc"))
|
||||
pat3 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
clearPatternCache()
|
||||
pat4 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
pat4 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
clearPatternCache()
|
||||
pat5 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, Delimiter{}, []rune("abc"))
|
||||
pat5 := BuildPattern(true, false, CaseRespect, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
clearPatternCache()
|
||||
pat6 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
pat6 := BuildPattern(true, false, CaseRespect, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
|
||||
if string(pat1.text) != "abc" || pat1.caseSensitive != false ||
|
||||
string(pat2.text) != "Abc" || pat2.caseSensitive != true ||
|
||||
@@ -109,19 +119,19 @@ func TestCaseSensitivity(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestOrigTextAndTransformed(t *testing.T) {
|
||||
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, Delimiter{}, []rune("jg"))
|
||||
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("jg"))
|
||||
tokens := Tokenize([]rune("junegunn"), Delimiter{})
|
||||
trans := Transform(tokens, []Range{Range{1, 1}})
|
||||
|
||||
origRunes := []rune("junegunn.choi")
|
||||
for _, mode := range []Mode{ModeFuzzy, ModeExtended} {
|
||||
for _, extended := range []bool{false, true} {
|
||||
chunk := Chunk{
|
||||
&Item{
|
||||
text: []rune("junegunn"),
|
||||
origText: &origRunes,
|
||||
transformed: trans},
|
||||
}
|
||||
pattern.mode = mode
|
||||
pattern.extended = extended
|
||||
matches := pattern.matchChunk(&chunk)
|
||||
if string(matches[0].text) != "junegunn" || string(*matches[0].origText) != "junegunn.choi" ||
|
||||
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
||||
@@ -130,3 +140,25 @@ func TestOrigTextAndTransformed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheKey(t *testing.T) {
|
||||
test := func(extended bool, patStr string, expected string, cacheable bool) {
|
||||
pat := BuildPattern(true, extended, CaseSmart, true, []Range{}, Delimiter{}, []rune(patStr))
|
||||
if pat.CacheKey() != expected {
|
||||
t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())
|
||||
}
|
||||
if pat.cacheable != cacheable {
|
||||
t.Errorf("Expected: %s, actual: %s (%s)", cacheable, pat.cacheable, patStr)
|
||||
}
|
||||
clearPatternCache()
|
||||
}
|
||||
test(false, "foo !bar", "foo !bar", true)
|
||||
test(false, "foo | bar !baz", "foo | bar !baz", true)
|
||||
test(true, "foo bar baz", "foo bar baz", true)
|
||||
test(true, "foo !bar", "foo", false)
|
||||
test(true, "foo !bar baz", "foo baz", false)
|
||||
test(true, "foo | bar baz", "baz", false)
|
||||
test(true, "foo | bar | baz", "", false)
|
||||
test(true, "foo | bar !baz", "", false)
|
||||
test(true, "| | | foo", "foo", true)
|
||||
}
|
||||
|
@@ -4,7 +4,6 @@ import (
|
||||
"bufio"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/junegunn/fzf/src/util"
|
||||
)
|
||||
@@ -59,7 +58,7 @@ func (r *Reader) readFromStdin() {
|
||||
}
|
||||
|
||||
func (r *Reader) readFromCommand(cmd string) {
|
||||
listCommand := exec.Command("sh", "-c", cmd)
|
||||
listCommand := util.ExecCommand(cmd)
|
||||
out, err := listCommand.StdoutPipe()
|
||||
if err != nil {
|
||||
return
|
||||
|
590
src/terminal.go
590
src/terminal.go
@@ -4,7 +4,6 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"regexp"
|
||||
"sort"
|
||||
@@ -22,10 +21,12 @@ import (
|
||||
|
||||
// Terminal represents terminal input/output
|
||||
type Terminal struct {
|
||||
initDelay time.Duration
|
||||
inlineInfo bool
|
||||
prompt string
|
||||
reverse bool
|
||||
hscroll bool
|
||||
hscrollOff int
|
||||
cx int
|
||||
cy int
|
||||
offset int
|
||||
@@ -42,13 +43,15 @@ type Terminal struct {
|
||||
history *History
|
||||
cycle bool
|
||||
header []string
|
||||
header0 []string
|
||||
ansi bool
|
||||
margin [4]string
|
||||
marginInt [4]int
|
||||
count int
|
||||
progress int
|
||||
reading bool
|
||||
merger *Merger
|
||||
selected map[uint32]selectedItem
|
||||
selected map[int32]selectedItem
|
||||
reqBox *util.EventBox
|
||||
eventBox *util.EventBox
|
||||
mutex sync.Mutex
|
||||
@@ -78,6 +81,7 @@ func (a byTimeOrder) Less(i, j int) bool {
|
||||
|
||||
var _spinner = []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}
|
||||
var _runeWidths = make(map[rune]int)
|
||||
var _tabStop int
|
||||
|
||||
const (
|
||||
reqPrompt util.EventType = iota
|
||||
@@ -122,6 +126,8 @@ const (
|
||||
actToggleAll
|
||||
actToggleDown
|
||||
actToggleUp
|
||||
actToggleIn
|
||||
actToggleOut
|
||||
actDown
|
||||
actUp
|
||||
actPageUp
|
||||
@@ -130,6 +136,7 @@ const (
|
||||
actPreviousHistory
|
||||
actNextHistory
|
||||
actExecute
|
||||
actExecuteMulti
|
||||
)
|
||||
|
||||
func defaultKeymap() map[int]actionType {
|
||||
@@ -178,17 +185,33 @@ func defaultKeymap() map[int]actionType {
|
||||
|
||||
keymap[C.Rune] = actRune
|
||||
keymap[C.Mouse] = actMouse
|
||||
keymap[C.DoubleClick] = actAccept
|
||||
return keymap
|
||||
}
|
||||
|
||||
// NewTerminal returns new Terminal object
|
||||
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||
input := []rune(opts.Query)
|
||||
var header []string
|
||||
if opts.Reverse {
|
||||
header = opts.Header
|
||||
} else {
|
||||
header = reverseStringArray(opts.Header)
|
||||
}
|
||||
_tabStop = opts.Tabstop
|
||||
var delay time.Duration
|
||||
if opts.Tac {
|
||||
delay = initialDelayTac
|
||||
} else {
|
||||
delay = initialDelay
|
||||
}
|
||||
return &Terminal{
|
||||
initDelay: delay,
|
||||
inlineInfo: opts.InlineInfo,
|
||||
prompt: opts.Prompt,
|
||||
reverse: opts.Reverse,
|
||||
hscroll: opts.Hscroll,
|
||||
hscrollOff: opts.HscrollOff,
|
||||
cx: len(input),
|
||||
cy: 0,
|
||||
offset: 0,
|
||||
@@ -206,10 +229,12 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||
margin: opts.Margin,
|
||||
marginInt: [4]int{0, 0, 0, 0},
|
||||
cycle: opts.Cycle,
|
||||
header: opts.Header,
|
||||
header: header,
|
||||
header0: header,
|
||||
ansi: opts.Ansi,
|
||||
reading: true,
|
||||
merger: EmptyMerger,
|
||||
selected: make(map[uint32]selectedItem),
|
||||
selected: make(map[int32]selectedItem),
|
||||
reqBox: util.NewEventBox(),
|
||||
eventBox: eventBox,
|
||||
mutex: sync.Mutex{},
|
||||
@@ -239,18 +264,19 @@ 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
|
||||
func reverseStringArray(input []string) []string {
|
||||
size := len(input)
|
||||
reversed := make([]string, size)
|
||||
for idx, str := range input {
|
||||
reversed[size-idx-1] = str
|
||||
}
|
||||
return reversed
|
||||
}
|
||||
|
||||
// UpdateHeader updates the header
|
||||
func (t *Terminal) UpdateHeader(header []string) {
|
||||
t.mutex.Lock()
|
||||
t.header = append(append([]string{}, t.header0...), header...)
|
||||
t.mutex.Unlock()
|
||||
t.reqBox.Set(reqHeader, nil)
|
||||
}
|
||||
@@ -278,33 +304,40 @@ func (t *Terminal) UpdateList(merger *Merger) {
|
||||
t.reqBox.Set(reqList, nil)
|
||||
}
|
||||
|
||||
func (t *Terminal) output() {
|
||||
func (t *Terminal) output() bool {
|
||||
if t.printQuery {
|
||||
fmt.Println(string(t.input))
|
||||
}
|
||||
if len(t.expect) > 0 {
|
||||
fmt.Println(t.pressed)
|
||||
}
|
||||
if len(t.selected) == 0 {
|
||||
found := len(t.selected) > 0
|
||||
if !found {
|
||||
cnt := t.merger.Length()
|
||||
if cnt > 0 && cnt > t.cy {
|
||||
fmt.Println(t.merger.Get(t.cy).AsString())
|
||||
fmt.Println(t.merger.Get(t.cy).AsString(t.ansi))
|
||||
found = true
|
||||
}
|
||||
} else {
|
||||
sels := make([]selectedItem, 0, len(t.selected))
|
||||
for _, sel := range t.selected {
|
||||
sels = append(sels, sel)
|
||||
}
|
||||
sort.Sort(byTimeOrder(sels))
|
||||
for _, sel := range sels {
|
||||
for _, sel := range t.sortSelected() {
|
||||
fmt.Println(*sel.text)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (t *Terminal) sortSelected() []selectedItem {
|
||||
sels := make([]selectedItem, 0, len(t.selected))
|
||||
for _, sel := range t.selected {
|
||||
sels = append(sels, sel)
|
||||
}
|
||||
sort.Sort(byTimeOrder(sels))
|
||||
return sels
|
||||
}
|
||||
|
||||
func runeWidth(r rune, prefixWidth int) int {
|
||||
if r == '\t' {
|
||||
return 8 - prefixWidth%8
|
||||
return _tabStop - prefixWidth%_tabStop
|
||||
} else if w, found := _runeWidths[r]; found {
|
||||
return w
|
||||
} else {
|
||||
@@ -376,7 +409,7 @@ func (t *Terminal) move(y int, x int, clear bool) {
|
||||
}
|
||||
|
||||
func (t *Terminal) placeCursor() {
|
||||
t.move(0, len(t.prompt)+displayWidth(t.input[:t.cx]), false)
|
||||
t.move(0, displayWidth([]rune(t.prompt))+displayWidth(t.input[:t.cx]), false)
|
||||
}
|
||||
|
||||
func (t *Terminal) printPrompt() {
|
||||
@@ -387,7 +420,7 @@ func (t *Terminal) printPrompt() {
|
||||
|
||||
func (t *Terminal) printInfo() {
|
||||
if t.inlineInfo {
|
||||
t.move(0, len(t.prompt)+displayWidth(t.input)+1, true)
|
||||
t.move(0, displayWidth([]rune(t.prompt))+displayWidth(t.input)+1, true)
|
||||
if t.reading {
|
||||
C.CPrint(C.ColSpinner, true, " < ")
|
||||
} else {
|
||||
@@ -431,9 +464,6 @@ func (t *Terminal) printHeader() {
|
||||
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--
|
||||
@@ -445,9 +475,8 @@ func (t *Terminal) printHeader() {
|
||||
state = newState
|
||||
item := &Item{
|
||||
text: []rune(trimmed),
|
||||
index: 0,
|
||||
colors: colors,
|
||||
rank: Rank{0, 0, 0}}
|
||||
rank: buildEmptyRank(0)}
|
||||
|
||||
t.move(line, 2, true)
|
||||
t.printHighlighted(item, false, C.ColHeader, 0, false)
|
||||
@@ -472,7 +501,7 @@ func (t *Terminal) printList() {
|
||||
}
|
||||
|
||||
func (t *Terminal) printItem(item *Item, current bool) {
|
||||
_, selected := t.selected[item.index]
|
||||
_, selected := t.selected[item.Index()]
|
||||
if current {
|
||||
C.CPrint(C.ColCursor, true, ">")
|
||||
if selected {
|
||||
@@ -529,11 +558,9 @@ func trimLeft(runes []rune, width int) ([]rune, int32) {
|
||||
}
|
||||
|
||||
func (t *Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, current bool) {
|
||||
var maxe int32
|
||||
var maxe int
|
||||
for _, offset := range item.offsets {
|
||||
if offset[1] > maxe {
|
||||
maxe = offset[1]
|
||||
}
|
||||
maxe = util.Max(maxe, int(offset[1]))
|
||||
}
|
||||
|
||||
// Overflow
|
||||
@@ -541,6 +568,7 @@ func (t *Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, c
|
||||
copy(text, item.text)
|
||||
offsets := item.colorOffsets(col2, bold, current)
|
||||
maxWidth := C.MaxX() - 3 - t.marginInt[1] - t.marginInt[3]
|
||||
maxe = util.Constrain(maxe+util.Min(maxWidth/2-2, t.hscrollOff), 0, len(text))
|
||||
fullWidth := displayWidth(text)
|
||||
if fullWidth > maxWidth {
|
||||
if t.hscroll {
|
||||
@@ -683,12 +711,18 @@ func (t *Terminal) rubout(pattern string) {
|
||||
}
|
||||
|
||||
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 ||
|
||||
event.Type == C.Mouse && key == C.DoubleClick && event.MouseEvent.Double
|
||||
}
|
||||
|
||||
func executeCommand(template string, current string) {
|
||||
command := strings.Replace(template, "{}", fmt.Sprintf("%q", current), -1)
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
func quoteEntry(entry string) string {
|
||||
return fmt.Sprintf("%q", entry)
|
||||
}
|
||||
|
||||
func executeCommand(template string, replacement string) {
|
||||
command := strings.Replace(template, "{}", replacement, -1)
|
||||
cmd := util.ExecCommand(command)
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
@@ -701,6 +735,22 @@ func executeCommand(template string, current string) {
|
||||
func (t *Terminal) Loop() {
|
||||
<-t.startChan
|
||||
{ // Late initialization
|
||||
intChan := make(chan os.Signal, 1)
|
||||
signal.Notify(intChan, os.Interrupt, os.Kill, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-intChan
|
||||
t.reqBox.Set(reqQuit, nil)
|
||||
}()
|
||||
|
||||
resizeChan := make(chan os.Signal, 1)
|
||||
signal.Notify(resizeChan, syscall.SIGWINCH)
|
||||
go func() {
|
||||
for {
|
||||
<-resizeChan
|
||||
t.reqBox.Set(reqRedraw, nil)
|
||||
}
|
||||
}()
|
||||
|
||||
t.mutex.Lock()
|
||||
t.initFunc()
|
||||
t.calculateMargins()
|
||||
@@ -711,20 +761,11 @@ func (t *Terminal) Loop() {
|
||||
t.printHeader()
|
||||
t.mutex.Unlock()
|
||||
go func() {
|
||||
timer := time.NewTimer(initialDelay)
|
||||
timer := time.NewTimer(t.initDelay)
|
||||
<-timer.C
|
||||
t.reqBox.Set(reqRefresh, nil)
|
||||
}()
|
||||
|
||||
resizeChan := make(chan os.Signal, 1)
|
||||
signal.Notify(resizeChan, syscall.SIGWINCH)
|
||||
go func() {
|
||||
for {
|
||||
<-resizeChan
|
||||
t.reqBox.Set(reqRedraw, nil)
|
||||
}
|
||||
}()
|
||||
|
||||
// Keep the spinner spinning
|
||||
go func() {
|
||||
for {
|
||||
@@ -741,7 +782,7 @@ func (t *Terminal) Loop() {
|
||||
}
|
||||
|
||||
exit := func(code int) {
|
||||
if code == 0 && t.history != nil {
|
||||
if code <= exitNoMatch && t.history != nil {
|
||||
t.history.append(string(t.input))
|
||||
}
|
||||
os.Exit(code)
|
||||
@@ -774,11 +815,13 @@ func (t *Terminal) Loop() {
|
||||
t.printAll()
|
||||
case reqClose:
|
||||
C.Close()
|
||||
t.output()
|
||||
exit(0)
|
||||
if t.output() {
|
||||
exit(exitOk)
|
||||
}
|
||||
exit(exitNoMatch)
|
||||
case reqQuit:
|
||||
C.Close()
|
||||
exit(1)
|
||||
exit(exitInterrupt)
|
||||
}
|
||||
}
|
||||
t.placeCursor()
|
||||
@@ -804,8 +847,8 @@ 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()}
|
||||
if _, found := t.selected[item.Index()]; !found {
|
||||
t.selected[item.Index()] = selectedItem{time.Now(), item.StringPtr(t.ansi)}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -813,7 +856,7 @@ func (t *Terminal) Loop() {
|
||||
toggleY := func(y int) {
|
||||
item := t.merger.Get(y)
|
||||
if !selectItem(item) {
|
||||
delete(t.selected, item.index)
|
||||
delete(t.selected, item.Index())
|
||||
}
|
||||
}
|
||||
toggle := func() {
|
||||
@@ -830,6 +873,229 @@ func (t *Terminal) Loop() {
|
||||
}
|
||||
}
|
||||
|
||||
var doAction func(actionType, int) bool
|
||||
doAction = func(action actionType, mapkey int) bool {
|
||||
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], quoteEntry(item.AsString(t.ansi)))
|
||||
}
|
||||
case actExecuteMulti:
|
||||
if len(t.selected) > 0 {
|
||||
sels := make([]string, len(t.selected))
|
||||
for i, sel := range t.sortSelected() {
|
||||
sels[i] = quoteEntry(*sel.text)
|
||||
}
|
||||
executeCommand(t.execmap[mapkey], strings.Join(sels, " "))
|
||||
} else {
|
||||
return doAction(actExecute, mapkey)
|
||||
}
|
||||
case actInvalid:
|
||||
t.mutex.Unlock()
|
||||
return false
|
||||
case actToggleSort:
|
||||
t.sort = !t.sort
|
||||
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||
t.mutex.Unlock()
|
||||
return false
|
||||
case actBeginningOfLine:
|
||||
t.cx = 0
|
||||
case actBackwardChar:
|
||||
if t.cx > 0 {
|
||||
t.cx--
|
||||
}
|
||||
case actAbort:
|
||||
req(reqQuit)
|
||||
case actDeleteChar:
|
||||
t.delChar()
|
||||
case actDeleteCharEOF:
|
||||
if !t.delChar() && t.cx == 0 {
|
||||
req(reqQuit)
|
||||
}
|
||||
case actEndOfLine:
|
||||
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:
|
||||
if t.cx < len(t.input) {
|
||||
t.cx++
|
||||
}
|
||||
case actBackwardDeleteChar:
|
||||
if t.cx > 0 {
|
||||
t.input = append(t.input[:t.cx-1], t.input[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:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleAll:
|
||||
if t.multi {
|
||||
for i := 0; i < t.merger.Length(); i++ {
|
||||
toggleY(i)
|
||||
}
|
||||
req(reqList, reqInfo)
|
||||
}
|
||||
case actToggleIn:
|
||||
if t.reverse {
|
||||
return doAction(actToggleUp, mapkey)
|
||||
}
|
||||
return doAction(actToggleDown, mapkey)
|
||||
case actToggleOut:
|
||||
if t.reverse {
|
||||
return doAction(actToggleDown, mapkey)
|
||||
}
|
||||
return doAction(actToggleUp, mapkey)
|
||||
case actToggleDown:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleUp:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
}
|
||||
case actDown:
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
case actUp:
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
case actAccept:
|
||||
req(reqClose)
|
||||
case actClearScreen:
|
||||
req(reqRedraw)
|
||||
case actUnixLineDiscard:
|
||||
if t.cx > 0 {
|
||||
t.yanked = copySlice(t.input[:t.cx])
|
||||
t.input = t.input[t.cx:]
|
||||
t.cx = 0
|
||||
}
|
||||
case actUnixWordRubout:
|
||||
if t.cx > 0 {
|
||||
t.rubout("\\s\\S")
|
||||
}
|
||||
case actBackwardKillWord:
|
||||
if t.cx > 0 {
|
||||
t.rubout("[^[:alnum:]][[:alnum:]]")
|
||||
}
|
||||
case actYank:
|
||||
suffix := copySlice(t.input[t.cx:])
|
||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||
t.cx += len(t.yanked)
|
||||
case actPageUp:
|
||||
t.vmove(t.maxItems() - 1)
|
||||
req(reqList)
|
||||
case actPageDown:
|
||||
t.vmove(-(t.maxItems() - 1))
|
||||
req(reqList)
|
||||
case actBackwardWord:
|
||||
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
||||
case actForwardWord:
|
||||
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
case actKillWord:
|
||||
ncx := t.cx +
|
||||
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
if ncx > t.cx {
|
||||
t.yanked = copySlice(t.input[t.cx:ncx])
|
||||
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
||||
}
|
||||
case actKillLine:
|
||||
if t.cx < len(t.input) {
|
||||
t.yanked = copySlice(t.input[t.cx:])
|
||||
t.input = t.input[:t.cx]
|
||||
}
|
||||
case actRune:
|
||||
prefix := copySlice(t.input[:t.cx])
|
||||
t.input = append(append(prefix, event.Char), t.input[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:
|
||||
me := event.MouseEvent
|
||||
mx, my := me.X, me.Y
|
||||
if me.S != 0 {
|
||||
// Scroll
|
||||
if t.merger.Length() > 0 {
|
||||
if t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
t.vmove(me.S)
|
||||
req(reqList)
|
||||
}
|
||||
} else if mx >= t.marginInt[3] && mx < C.MaxX()-t.marginInt[1] &&
|
||||
my >= t.marginInt[0] && my < C.MaxY()-t.marginInt[2] {
|
||||
mx -= t.marginInt[3]
|
||||
my -= t.marginInt[0]
|
||||
mx = util.Constrain(mx-displayWidth([]rune(t.prompt)), 0, len(t.input))
|
||||
if !t.reverse {
|
||||
my = t.maxHeight() - my - 1
|
||||
}
|
||||
min := 2 + len(t.header)
|
||||
if t.inlineInfo {
|
||||
min--
|
||||
}
|
||||
if me.Double {
|
||||
// Double-click
|
||||
if my >= min {
|
||||
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
||||
return doAction(t.keymap[C.DoubleClick], C.DoubleClick)
|
||||
}
|
||||
}
|
||||
} 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
action := t.keymap[event.Type]
|
||||
mapkey := event.Type
|
||||
if event.Type == C.Rune {
|
||||
@@ -838,204 +1104,8 @@ func (t *Terminal) Loop() {
|
||||
action = act
|
||||
}
|
||||
}
|
||||
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:
|
||||
t.mutex.Unlock()
|
||||
if !doAction(action, mapkey) {
|
||||
continue
|
||||
case actToggleSort:
|
||||
t.sort = !t.sort
|
||||
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||
t.mutex.Unlock()
|
||||
continue
|
||||
case actBeginningOfLine:
|
||||
t.cx = 0
|
||||
case actBackwardChar:
|
||||
if t.cx > 0 {
|
||||
t.cx--
|
||||
}
|
||||
case actAbort:
|
||||
req(reqQuit)
|
||||
case actDeleteChar:
|
||||
t.delChar()
|
||||
case actDeleteCharEOF:
|
||||
if !t.delChar() && t.cx == 0 {
|
||||
req(reqQuit)
|
||||
}
|
||||
case actEndOfLine:
|
||||
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:
|
||||
if t.cx < len(t.input) {
|
||||
t.cx++
|
||||
}
|
||||
case actBackwardDeleteChar:
|
||||
if t.cx > 0 {
|
||||
t.input = append(t.input[:t.cx-1], t.input[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:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleAll:
|
||||
if t.multi {
|
||||
for i := 0; i < t.merger.Length(); i++ {
|
||||
toggleY(i)
|
||||
}
|
||||
req(reqList, reqInfo)
|
||||
}
|
||||
case actToggleDown:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleUp:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
}
|
||||
case actDown:
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
case actUp:
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
case actAccept:
|
||||
req(reqClose)
|
||||
case actClearScreen:
|
||||
req(reqRedraw)
|
||||
case actUnixLineDiscard:
|
||||
if t.cx > 0 {
|
||||
t.yanked = copySlice(t.input[:t.cx])
|
||||
t.input = t.input[t.cx:]
|
||||
t.cx = 0
|
||||
}
|
||||
case actUnixWordRubout:
|
||||
if t.cx > 0 {
|
||||
t.rubout("\\s\\S")
|
||||
}
|
||||
case actBackwardKillWord:
|
||||
if t.cx > 0 {
|
||||
t.rubout("[^[:alnum:]][[:alnum:]]")
|
||||
}
|
||||
case actYank:
|
||||
suffix := copySlice(t.input[t.cx:])
|
||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||
t.cx += len(t.yanked)
|
||||
case actPageUp:
|
||||
t.vmove(t.maxItems() - 1)
|
||||
req(reqList)
|
||||
case actPageDown:
|
||||
t.vmove(-(t.maxItems() - 1))
|
||||
req(reqList)
|
||||
case actBackwardWord:
|
||||
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
||||
case actForwardWord:
|
||||
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
case actKillWord:
|
||||
ncx := t.cx +
|
||||
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
if ncx > t.cx {
|
||||
t.yanked = copySlice(t.input[t.cx:ncx])
|
||||
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
||||
}
|
||||
case actKillLine:
|
||||
if t.cx < len(t.input) {
|
||||
t.yanked = copySlice(t.input[t.cx:])
|
||||
t.input = t.input[:t.cx]
|
||||
}
|
||||
case actRune:
|
||||
prefix := copySlice(t.input[:t.cx])
|
||||
t.input = append(append(prefix, event.Char), t.input[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:
|
||||
me := event.MouseEvent
|
||||
mx, my := me.X, me.Y
|
||||
if me.S != 0 {
|
||||
// Scroll
|
||||
if t.merger.Length() > 0 {
|
||||
if t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
t.vmove(me.S)
|
||||
req(reqList)
|
||||
}
|
||||
} else if mx >= t.marginInt[3] && mx < C.MaxX()-t.marginInt[1] &&
|
||||
my >= t.marginInt[0] && my < C.MaxY()-t.marginInt[2] {
|
||||
mx -= t.marginInt[3]
|
||||
my -= t.marginInt[0]
|
||||
mx = util.Constrain(mx-len(t.prompt), 0, len(t.input))
|
||||
if !t.reverse {
|
||||
my = t.maxHeight() - my - 1
|
||||
}
|
||||
min := 2 + len(t.header)
|
||||
if t.inlineInfo {
|
||||
min--
|
||||
}
|
||||
if me.Double {
|
||||
// Double-click
|
||||
if my >= min {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changed := string(previousInput) != string(t.input)
|
||||
t.mutex.Unlock() // Must be unlocked before touching reqBox
|
||||
@@ -1055,15 +1125,7 @@ func (t *Terminal) constrain() {
|
||||
diffpos := t.cy - t.offset
|
||||
|
||||
t.cy = util.Constrain(t.cy, 0, count-1)
|
||||
|
||||
if t.cy > t.offset+(height-1) {
|
||||
// Ceil
|
||||
t.offset = t.cy - (height - 1)
|
||||
} else if t.offset > t.cy {
|
||||
// Floor
|
||||
t.offset = t.cy
|
||||
}
|
||||
|
||||
t.offset = util.Constrain(t.offset, t.cy-height+1, t.cy)
|
||||
// Adjustment
|
||||
if count-t.offset < height {
|
||||
t.offset = util.Max(0, count-height)
|
||||
|
@@ -20,6 +20,7 @@ type Range struct {
|
||||
type Token struct {
|
||||
text []rune
|
||||
prefixLength int
|
||||
trimLength int
|
||||
}
|
||||
|
||||
// Delimiter for tokenizing the input
|
||||
@@ -81,7 +82,7 @@ func withPrefixLengths(tokens [][]rune, begin int) []Token {
|
||||
for idx, token := range tokens {
|
||||
// Need to define a new local variable instead of the reused token to take
|
||||
// the pointer to it
|
||||
ret[idx] = Token{text: token, prefixLength: prefixLength}
|
||||
ret[idx] = Token{token, prefixLength, util.TrimLen(token)}
|
||||
prefixLength += len(token)
|
||||
}
|
||||
return ret
|
||||
@@ -233,7 +234,7 @@ func Transform(tokens []Token, withNth []Range) []Token {
|
||||
} else {
|
||||
prefixLength = 0
|
||||
}
|
||||
transTokens[idx] = Token{part, prefixLength}
|
||||
transTokens[idx] = Token{part, prefixLength, util.TrimLen(part)}
|
||||
}
|
||||
return transTokens
|
||||
}
|
||||
|
@@ -44,22 +44,22 @@ func TestTokenize(t *testing.T) {
|
||||
// AWK-style
|
||||
input := " abc: def: ghi "
|
||||
tokens := Tokenize([]rune(input), Delimiter{})
|
||||
if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {
|
||||
if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 || tokens[0].trimLength != 4 {
|
||||
t.Errorf("%s", tokens)
|
||||
}
|
||||
|
||||
// With delimiter
|
||||
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 || tokens[0].trimLength != 4 {
|
||||
t.Errorf("%s", tokens)
|
||||
}
|
||||
|
||||
// With delimiter regex
|
||||
tokens = Tokenize([]rune(input), delimiterRegexp("\\s+"))
|
||||
if string(tokens[0].text) != " " || tokens[0].prefixLength != 0 ||
|
||||
string(tokens[1].text) != "abc: " || tokens[1].prefixLength != 2 ||
|
||||
string(tokens[2].text) != "def: " || tokens[2].prefixLength != 8 ||
|
||||
string(tokens[3].text) != "ghi " || tokens[3].prefixLength != 14 {
|
||||
if string(tokens[0].text) != " " || tokens[0].prefixLength != 0 || tokens[0].trimLength != 0 ||
|
||||
string(tokens[1].text) != "abc: " || tokens[1].prefixLength != 2 || tokens[1].trimLength != 4 ||
|
||||
string(tokens[2].text) != "def: " || tokens[2].prefixLength != 8 || tokens[2].trimLength != 4 ||
|
||||
string(tokens[3].text) != "ghi " || tokens[3].prefixLength != 14 || tokens[3].trimLength != 3 {
|
||||
t.Errorf("%s", tokens)
|
||||
}
|
||||
}
|
||||
|
@@ -5,6 +5,7 @@ import "C"
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
@@ -20,6 +21,14 @@ func Max(first int, items ...int) int {
|
||||
return max
|
||||
}
|
||||
|
||||
// Min returns the smallest integer
|
||||
func Min(first int, second int) int {
|
||||
if first <= second {
|
||||
return first
|
||||
}
|
||||
return second
|
||||
}
|
||||
|
||||
// Min32 returns the smallest 32-bit integer
|
||||
func Min32(first int32, second int32) int32 {
|
||||
if first <= second {
|
||||
@@ -75,6 +84,7 @@ func IsTty() bool {
|
||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||
}
|
||||
|
||||
// TrimRight returns rune array with trailing white spaces cut off
|
||||
func TrimRight(runes []rune) []rune {
|
||||
var i int
|
||||
for i = len(runes) - 1; i >= 0; i-- {
|
||||
@@ -86,6 +96,7 @@ func TrimRight(runes []rune) []rune {
|
||||
return runes[0 : i+1]
|
||||
}
|
||||
|
||||
// BytesToRunes converts byte array into rune array
|
||||
func BytesToRunes(bytea []byte) []rune {
|
||||
runes := make([]rune, 0, len(bytea))
|
||||
for i := 0; i < len(bytea); {
|
||||
@@ -100,3 +111,36 @@ func BytesToRunes(bytea []byte) []rune {
|
||||
}
|
||||
return runes
|
||||
}
|
||||
|
||||
// TrimLen returns the length of trimmed rune array
|
||||
func TrimLen(runes []rune) int {
|
||||
var i int
|
||||
for i = len(runes) - 1; i >= 0; i-- {
|
||||
char := runes[i]
|
||||
if char != ' ' && char != '\t' {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Completely empty
|
||||
if i < 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
var j int
|
||||
for j = 0; j < len(runes); j++ {
|
||||
char := runes[j]
|
||||
if char != ' ' && char != '\t' {
|
||||
break
|
||||
}
|
||||
}
|
||||
return i - j + 1
|
||||
}
|
||||
|
||||
// ExecCommand executes the given command with $SHELL
|
||||
func ExecCommand(command string) *exec.Cmd {
|
||||
shell := os.Getenv("SHELL")
|
||||
if len(shell) == 0 {
|
||||
shell = "sh"
|
||||
}
|
||||
return exec.Command(shell, "-c", command)
|
||||
}
|
||||
|
@@ -20,3 +20,23 @@ func TestContrain(t *testing.T) {
|
||||
t.Error("Expected", 3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrimLen(t *testing.T) {
|
||||
check := func(str string, exp int) {
|
||||
trimmed := TrimLen([]rune(str))
|
||||
if trimmed != exp {
|
||||
t.Errorf("Invalid TrimLen result for '%s': %d (expected %d)",
|
||||
str, trimmed, exp)
|
||||
}
|
||||
}
|
||||
check("hello", 5)
|
||||
check("hello ", 5)
|
||||
check("hello ", 5)
|
||||
check(" hello", 5)
|
||||
check(" hello", 5)
|
||||
check(" hello ", 5)
|
||||
check(" hello ", 5)
|
||||
check("h o", 5)
|
||||
check(" h o ", 5)
|
||||
check(" ", 0)
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
Execute (Setup):
|
||||
let g:dir = fnamemodify(g:vader_file, ':p:h')
|
||||
Log 'Test directory: ' . g:dir
|
||||
Save &acd
|
||||
|
||||
Execute (fzf#run with dir option):
|
||||
let cwd = getcwd()
|
||||
@@ -35,6 +36,34 @@ Execute (fzf#run with string source):
|
||||
let result = sort(fzf#run({ 'source': 'echo hi', 'options': '-f i' }))
|
||||
AssertEqual ['hi'], result
|
||||
|
||||
Execute (fzf#run with dir option and noautochdir):
|
||||
set noacd
|
||||
let cwd = getcwd()
|
||||
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})
|
||||
" No change in working directory
|
||||
AssertEqual cwd, getcwd()
|
||||
|
||||
Execute (Incomplete fzf#run with dir option and autochdir):
|
||||
set acd
|
||||
let cwd = getcwd()
|
||||
call fzf#run({'source': [], 'sink': 'e', 'dir': '/tmp', 'options': '-0'})
|
||||
" No change in working directory even if &acd is set
|
||||
AssertEqual cwd, getcwd()
|
||||
|
||||
Execute (fzf#run with dir option and autochdir):
|
||||
set acd
|
||||
let cwd = getcwd()
|
||||
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})
|
||||
" Working directory changed due to &acd
|
||||
AssertEqual '/', getcwd()
|
||||
|
||||
Execute (fzf#run with dir option and autochdir when final cwd is same as dir):
|
||||
set acd
|
||||
cd /tmp
|
||||
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/', 'options': '-1'})
|
||||
" Working directory changed due to &acd
|
||||
AssertEqual '/', getcwd()
|
||||
|
||||
Execute (Cleanup):
|
||||
unlet g:dir
|
||||
Restore
|
||||
|
519
test/test_go.rb
519
test/test_go.rb
@@ -6,9 +6,10 @@ require 'fileutils'
|
||||
|
||||
DEFAULT_TIMEOUT = 20
|
||||
|
||||
FILE = File.expand_path(__FILE__)
|
||||
base = File.expand_path('../../', __FILE__)
|
||||
Dir.chdir base
|
||||
FZF = "#{base}/bin/fzf"
|
||||
FZF = "FZF_DEFAULT_OPTS= FZF_DEFAULT_COMMAND= #{base}/bin/fzf"
|
||||
|
||||
class NilClass
|
||||
def include? str
|
||||
@@ -142,8 +143,10 @@ class TestBase < Minitest::Test
|
||||
attr_reader :tmux
|
||||
|
||||
def tempname
|
||||
@temp_suffix ||= 0
|
||||
[TEMPNAME,
|
||||
caller_locations.map(&:label).find { |l| l =~ /^test_/ }].join '-'
|
||||
caller_locations.map(&:label).find { |l| l =~ /^test_/ },
|
||||
@temp_suffix].join '-'
|
||||
end
|
||||
|
||||
def setup
|
||||
@@ -157,6 +160,7 @@ class TestBase < Minitest::Test
|
||||
File.read(tempname)
|
||||
ensure
|
||||
File.unlink tempname while File.exists?(tempname)
|
||||
@temp_suffix += 1
|
||||
tmux.prepare
|
||||
end
|
||||
|
||||
@@ -203,17 +207,17 @@ class TestGoFZF < TestBase
|
||||
tmux.send_keys '99', 'C-a', '1', 'C-f', '3', 'C-b', 'C-h', 'C-u', 'C-e', 'C-y', 'C-k', 'Tab', 'BTab'
|
||||
tmux.until { |lines| lines[-2] == ' 856/100000' }
|
||||
lines = tmux.capture
|
||||
assert_equal '> 1391', lines[-4]
|
||||
assert_equal '> 3910', lines[-4]
|
||||
assert_equal ' 391', lines[-3]
|
||||
assert_equal ' 856/100000', lines[-2]
|
||||
assert_equal '> 391', lines[-1]
|
||||
|
||||
tmux.send_keys :Enter
|
||||
assert_equal '1391', readonce.chomp
|
||||
assert_equal '3910', readonce.chomp
|
||||
end
|
||||
|
||||
def test_fzf_default_command
|
||||
tmux.send_keys "FZF_DEFAULT_COMMAND='echo hello' #{fzf}", :Enter
|
||||
tmux.send_keys fzf.sub('FZF_DEFAULT_COMMAND=', "FZF_DEFAULT_COMMAND='echo hello'"), :Enter
|
||||
tmux.until { |lines| lines.last =~ /^>/ }
|
||||
|
||||
tmux.send_keys :Enter
|
||||
@@ -353,7 +357,7 @@ class TestGoFZF < TestBase
|
||||
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', '50', '51'], readonce.split($/)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -374,7 +378,7 @@ class TestGoFZF < TestBase
|
||||
tmux.send_keys :Enter
|
||||
tmux.until { |lines| lines[-1] == '>' }
|
||||
tmux.send_keys 'C-K', :Enter
|
||||
assert_equal ['1919'], readonce.split($/)
|
||||
assert_equal ['9090'], readonce.split($/)
|
||||
end
|
||||
|
||||
def test_tac
|
||||
@@ -390,6 +394,7 @@ class TestGoFZF < TestBase
|
||||
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
||||
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||
tmux.send_keys '99'
|
||||
tmux.until { |lines| lines[-2].include? '28/1000' }
|
||||
tmux.send_keys :BTab, :BTab, :BTab
|
||||
tmux.until { |lines| lines[-2].include?('(3)') }
|
||||
tmux.send_keys :Enter
|
||||
@@ -409,11 +414,12 @@ class TestGoFZF < TestBase
|
||||
|
||||
def test_expect
|
||||
test = lambda do |key, feed, expected = key|
|
||||
tmux.send_keys "seq 1 100 | #{fzf :expect, key}", :Enter
|
||||
tmux.send_keys "seq 1 100 | #{fzf :expect, key}; sync", :Enter
|
||||
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||
tmux.send_keys '55'
|
||||
tmux.until { |lines| lines[-2].include? '1/100' }
|
||||
tmux.send_keys *feed
|
||||
tmux.prepare
|
||||
assert_equal [expected, '55'], readonce.split($/)
|
||||
end
|
||||
test.call 'ctrl-t', 'C-T'
|
||||
@@ -458,8 +464,8 @@ class TestGoFZF < TestBase
|
||||
|
||||
def test_unicode_case
|
||||
writelines tempname, %w[строКА1 СТРОКА2 строка3 Строка4]
|
||||
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[СТРОКА2 Строка4], `#{FZF} -fС < #{tempname}`.split($/)
|
||||
assert_equal %w[строКА1 СТРОКА2 строка3 Строка4], `#{FZF} -fс < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_tiebreak
|
||||
@@ -471,7 +477,7 @@ class TestGoFZF < TestBase
|
||||
]
|
||||
writelines tempname, input
|
||||
|
||||
assert_equal input, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=index`.split($/)
|
||||
assert_equal input, `#{FZF} -ffoobar --tiebreak=index < #{tempname}`.split($/)
|
||||
|
||||
by_length = %w[
|
||||
----foobar--
|
||||
@@ -479,8 +485,8 @@ class TestGoFZF < TestBase
|
||||
-------foobar-
|
||||
--foobar--------
|
||||
]
|
||||
assert_equal by_length, `cat #{tempname} | #{FZF} -ffoobar`.split($/)
|
||||
assert_equal by_length, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=length`.split($/)
|
||||
assert_equal by_length, `#{FZF} -ffoobar < #{tempname}`.split($/)
|
||||
assert_equal by_length, `#{FZF} -ffoobar --tiebreak=length < #{tempname}`.split($/)
|
||||
|
||||
by_begin = %w[
|
||||
--foobar--------
|
||||
@@ -488,17 +494,175 @@ class TestGoFZF < TestBase
|
||||
-----foobar---
|
||||
-------foobar-
|
||||
]
|
||||
assert_equal by_begin, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=begin`.split($/)
|
||||
assert_equal by_begin, `cat #{tempname} | #{FZF} -f"!z foobar" -x --tiebreak begin`.split($/)
|
||||
assert_equal by_begin, `#{FZF} -ffoobar --tiebreak=begin < #{tempname}`.split($/)
|
||||
assert_equal by_begin, `#{FZF} -f"!z foobar" -x --tiebreak begin < #{tempname}`.split($/)
|
||||
|
||||
assert_equal %w[
|
||||
-------foobar-
|
||||
----foobar--
|
||||
-----foobar---
|
||||
--foobar--------
|
||||
], `cat #{tempname} | #{FZF} -ffoobar --tiebreak end`.split($/)
|
||||
], `#{FZF} -ffoobar --tiebreak end < #{tempname}`.split($/)
|
||||
|
||||
assert_equal input, `cat #{tempname} | #{FZF} -f"!z" -x --tiebreak end`.split($/)
|
||||
assert_equal input, `#{FZF} -f"!z" -x --tiebreak end < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
# Since 0.11.2
|
||||
def test_tiebreak_list
|
||||
input = %w[
|
||||
f-o-o-b-a-r
|
||||
foobar----
|
||||
--foobar
|
||||
----foobar
|
||||
foobar--
|
||||
--foobar--
|
||||
foobar
|
||||
]
|
||||
writelines tempname, input
|
||||
|
||||
assert_equal %w[
|
||||
foobar----
|
||||
--foobar
|
||||
----foobar
|
||||
foobar--
|
||||
--foobar--
|
||||
foobar
|
||||
f-o-o-b-a-r
|
||||
], `#{FZF} -ffb --tiebreak=index < #{tempname}`.split($/)
|
||||
|
||||
by_length = %w[
|
||||
foobar
|
||||
--foobar
|
||||
foobar--
|
||||
foobar----
|
||||
----foobar
|
||||
--foobar--
|
||||
f-o-o-b-a-r
|
||||
]
|
||||
assert_equal by_length, `#{FZF} -ffb < #{tempname}`.split($/)
|
||||
assert_equal by_length, `#{FZF} -ffb --tiebreak=length < #{tempname}`.split($/)
|
||||
|
||||
assert_equal %w[
|
||||
foobar
|
||||
foobar--
|
||||
--foobar
|
||||
foobar----
|
||||
--foobar--
|
||||
----foobar
|
||||
f-o-o-b-a-r
|
||||
], `#{FZF} -ffb --tiebreak=length,begin < #{tempname}`.split($/)
|
||||
|
||||
assert_equal %w[
|
||||
foobar
|
||||
--foobar
|
||||
foobar--
|
||||
----foobar
|
||||
--foobar--
|
||||
foobar----
|
||||
f-o-o-b-a-r
|
||||
], `#{FZF} -ffb --tiebreak=length,end < #{tempname}`.split($/)
|
||||
|
||||
assert_equal %w[
|
||||
foobar----
|
||||
foobar--
|
||||
foobar
|
||||
--foobar
|
||||
--foobar--
|
||||
----foobar
|
||||
f-o-o-b-a-r
|
||||
], `#{FZF} -ffb --tiebreak=begin < #{tempname}`.split($/)
|
||||
|
||||
by_begin_end = %w[
|
||||
foobar
|
||||
foobar--
|
||||
foobar----
|
||||
--foobar
|
||||
--foobar--
|
||||
----foobar
|
||||
f-o-o-b-a-r
|
||||
]
|
||||
assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=begin,length < #{tempname}`.split($/)
|
||||
assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=begin,end < #{tempname}`.split($/)
|
||||
|
||||
assert_equal %w[
|
||||
--foobar
|
||||
----foobar
|
||||
foobar
|
||||
foobar--
|
||||
--foobar--
|
||||
foobar----
|
||||
f-o-o-b-a-r
|
||||
], `#{FZF} -ffb --tiebreak=end < #{tempname}`.split($/)
|
||||
|
||||
by_begin_end = %w[
|
||||
foobar
|
||||
--foobar
|
||||
----foobar
|
||||
foobar--
|
||||
--foobar--
|
||||
foobar----
|
||||
f-o-o-b-a-r
|
||||
]
|
||||
assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=end,begin < #{tempname}`.split($/)
|
||||
assert_equal by_begin_end, `#{FZF} -ffb --tiebreak=end,length < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_tiebreak_white_prefix
|
||||
writelines tempname, [
|
||||
'f o o b a r',
|
||||
' foo bar',
|
||||
' foobar',
|
||||
'----foo bar',
|
||||
'----foobar',
|
||||
' foo bar',
|
||||
' foobar--',
|
||||
' foobar',
|
||||
'--foo bar',
|
||||
'--foobar',
|
||||
'foobar',
|
||||
]
|
||||
|
||||
assert_equal [
|
||||
' foobar',
|
||||
' foobar',
|
||||
'foobar',
|
||||
' foobar--',
|
||||
'--foobar',
|
||||
'----foobar',
|
||||
' foo bar',
|
||||
' foo bar',
|
||||
'--foo bar',
|
||||
'----foo bar',
|
||||
'f o o b a r',
|
||||
], `#{FZF} -ffb < #{tempname}`.split($/)
|
||||
|
||||
assert_equal [
|
||||
' foobar',
|
||||
' foobar--',
|
||||
' foobar',
|
||||
'foobar',
|
||||
'--foobar',
|
||||
'----foobar',
|
||||
' foo bar',
|
||||
' foo bar',
|
||||
'--foo bar',
|
||||
'----foo bar',
|
||||
'f o o b a r',
|
||||
], `#{FZF} -ffb --tiebreak=begin < #{tempname}`.split($/)
|
||||
|
||||
assert_equal [
|
||||
' foobar',
|
||||
' foobar',
|
||||
'foobar',
|
||||
' foobar--',
|
||||
'--foobar',
|
||||
'----foobar',
|
||||
' foo bar',
|
||||
' foo bar',
|
||||
'--foo bar',
|
||||
'----foo bar',
|
||||
'f o o b a r',
|
||||
], `#{FZF} -ffb --tiebreak=begin,length < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_tiebreak_length_with_nth
|
||||
@@ -516,7 +680,7 @@ class TestGoFZF < TestBase
|
||||
123:hello
|
||||
1234567:h
|
||||
]
|
||||
assert_equal output, `cat #{tempname} | #{FZF} -fh`.split($/)
|
||||
assert_equal output, `#{FZF} -fh < #{tempname}`.split($/)
|
||||
|
||||
output = %w[
|
||||
1234567:h
|
||||
@@ -524,7 +688,65 @@ class TestGoFZF < TestBase
|
||||
1:hell
|
||||
123:hello
|
||||
]
|
||||
assert_equal output, `cat #{tempname} | #{FZF} -fh -n2 -d:`.split($/)
|
||||
assert_equal output, `#{FZF} -fh -n2 -d: < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_tiebreak_length_with_nth_trim_length
|
||||
input = [
|
||||
"apple juice bottle 1",
|
||||
"apple ui bottle 2",
|
||||
"app ice bottle 3",
|
||||
"app ic bottle 4",
|
||||
]
|
||||
writelines tempname, input
|
||||
|
||||
# len(1)
|
||||
output = [
|
||||
"app ice bottle 3",
|
||||
"app ic bottle 4",
|
||||
"apple juice bottle 1",
|
||||
"apple ui bottle 2",
|
||||
]
|
||||
assert_equal output, `#{FZF} -fa -n1 < #{tempname}`.split($/)
|
||||
|
||||
# len(1 ~ 2)
|
||||
output = [
|
||||
"app ic bottle 4",
|
||||
"app ice bottle 3",
|
||||
"apple ui bottle 2",
|
||||
"apple juice bottle 1",
|
||||
]
|
||||
assert_equal output, `#{FZF} -fai -n1..2 < #{tempname}`.split($/)
|
||||
|
||||
# len(1) + len(2)
|
||||
output = [
|
||||
"app ic bottle 4",
|
||||
"app ice bottle 3",
|
||||
"apple ui bottle 2",
|
||||
"apple juice bottle 1",
|
||||
]
|
||||
assert_equal output, `#{FZF} -x -f"a i" -n1,2 < #{tempname}`.split($/)
|
||||
|
||||
# len(2)
|
||||
output = [
|
||||
"app ic bottle 4",
|
||||
"app ice bottle 3",
|
||||
"apple ui bottle 2",
|
||||
"apple juice bottle 1",
|
||||
]
|
||||
assert_equal output, `#{FZF} -fi -n2 < #{tempname}`.split($/)
|
||||
assert_equal output, `#{FZF} -fi -n2,1..2 < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_tiebreak_end_backward_scan
|
||||
input = %w[
|
||||
foobar-fb
|
||||
fubar
|
||||
]
|
||||
writelines tempname, input
|
||||
|
||||
assert_equal input.reverse, `#{FZF} -f fb < #{tempname}`.split($/)
|
||||
assert_equal input, `#{FZF} -f fb --tiebreak=end < #{tempname}`.split($/)
|
||||
end
|
||||
|
||||
def test_invalid_cache
|
||||
@@ -554,7 +776,7 @@ class TestGoFZF < TestBase
|
||||
File.open(tempname, 'w') do |f|
|
||||
f << data
|
||||
end
|
||||
assert_equal data, `cat #{tempname} | #{FZF} -f .`.chomp
|
||||
assert_equal data, `#{FZF} -f . < #{tempname}`.chomp
|
||||
end
|
||||
|
||||
def test_read0
|
||||
@@ -655,6 +877,46 @@ class TestGoFZF < TestBase
|
||||
File.unlink output rescue nil
|
||||
end
|
||||
|
||||
def test_execute_multi
|
||||
output = '/tmp/fzf-test-execute-multi'
|
||||
opts = %[--multi --bind \\"alt-a:execute-multi(echo '[{}], @{}@' >> #{output}; sync)\\"]
|
||||
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||
tmux.send_keys :Escape, :a
|
||||
tmux.until { |lines| lines[-2].include? '/100' }
|
||||
tmux.send_keys :BTab, :BTab, :BTab
|
||||
tmux.send_keys :Escape, :a
|
||||
tmux.until { |lines| lines[-2].include? '/100' }
|
||||
tmux.send_keys :Tab, :Tab
|
||||
tmux.send_keys :Escape, :a
|
||||
tmux.until { |lines| lines[-2].include? '/100' }
|
||||
tmux.send_keys :Enter
|
||||
tmux.prepare
|
||||
readonce
|
||||
assert_equal ['["1"], @"1"@', '["1" "2" "3"], @"1" "2" "3"@', '["1" "2" "4"], @"1" "2" "4"@'],
|
||||
File.readlines(output).map(&:chomp)
|
||||
ensure
|
||||
File.unlink output rescue nil
|
||||
end
|
||||
|
||||
def test_execute_shell
|
||||
# Custom script to use as $SHELL
|
||||
output = tempname + '.out'
|
||||
File.unlink output rescue nil
|
||||
writelines tempname, ['#!/usr/bin/env bash', "echo $1 / $2 > #{output}", "sync"]
|
||||
system "chmod +x #{tempname}"
|
||||
|
||||
tmux.send_keys "echo foo | SHELL=#{tempname} fzf --bind 'enter:execute:{}bar'", :Enter
|
||||
tmux.until { |lines| lines[-2].include? '1/1' }
|
||||
tmux.send_keys :Enter
|
||||
tmux.until { |lines| lines[-2].include? '1/1' }
|
||||
tmux.send_keys 'C-c'
|
||||
tmux.prepare
|
||||
assert_equal ['-c / "foo"bar'], 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' }
|
||||
@@ -681,12 +943,12 @@ class TestGoFZF < TestBase
|
||||
lines[-2].include?('/90') &&
|
||||
lines[-3] == ' 1' &&
|
||||
lines[-4] == ' 2' &&
|
||||
lines[-13] == '> 15'
|
||||
lines[-13] == '> 50'
|
||||
end
|
||||
tmux.send_keys :Down
|
||||
end
|
||||
tmux.send_keys :Enter
|
||||
assert_equal '15', readonce.chomp
|
||||
assert_equal '50', readonce.chomp
|
||||
end
|
||||
|
||||
def test_header_lines_reverse
|
||||
@@ -696,12 +958,12 @@ class TestGoFZF < TestBase
|
||||
lines[1].include?('/90') &&
|
||||
lines[2] == ' 1' &&
|
||||
lines[3] == ' 2' &&
|
||||
lines[12] == '> 15'
|
||||
lines[12] == '> 50'
|
||||
end
|
||||
tmux.send_keys :Up
|
||||
end
|
||||
tmux.send_keys :Enter
|
||||
assert_equal '15', readonce.chomp
|
||||
assert_equal '50', readonce.chomp
|
||||
end
|
||||
|
||||
def test_header_lines_overflow
|
||||
@@ -726,24 +988,44 @@ class TestGoFZF < TestBase
|
||||
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)
|
||||
def test_header
|
||||
tmux.send_keys "seq 100 | #{fzf "--header \\\"\\$(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)
|
||||
def test_header_reverse
|
||||
tmux.send_keys "seq 100 | #{fzf "--header=\\\"\\$(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_header_and_header_lines
|
||||
tmux.send_keys "seq 100 | #{fzf "--header-lines 10 --header \\\"\\$(head -5 #{FILE})\\\""}", :Enter
|
||||
header = File.readlines(FILE).take(5).map(&:strip)
|
||||
tmux.until do |lines|
|
||||
lines[-2].include?('90/90') &&
|
||||
lines[-7...-2].map(&:strip) == header &&
|
||||
lines[-17...-7].map(&:strip) == (1..10).map(&:to_s).reverse
|
||||
end
|
||||
end
|
||||
|
||||
def test_header_and_header_lines_reverse
|
||||
tmux.send_keys "seq 100 | #{fzf "--reverse --header-lines 10 --header \\\"\\$(head -5 #{FILE})\\\""}", :Enter
|
||||
header = File.readlines(FILE).take(5).map(&:strip)
|
||||
tmux.until do |lines|
|
||||
lines[1].include?('90/90') &&
|
||||
lines[2...7].map(&:strip) == header &&
|
||||
lines[7...17].map(&:strip) == (1..10).map(&:to_s)
|
||||
end
|
||||
end
|
||||
|
||||
def test_canel
|
||||
tmux.send_keys "seq 10 | #{fzf "--bind 2:cancel"}", :Enter
|
||||
tmux.until { |lines| lines[-2].include?('10/10') }
|
||||
@@ -769,15 +1051,116 @@ class TestGoFZF < TestBase
|
||||
tmux.send_keys :Enter
|
||||
end
|
||||
|
||||
def test_tabstop
|
||||
writelines tempname, ["f\too\tba\tr\tbaz\tbarfooq\tux"]
|
||||
{
|
||||
1 => '> f oo ba r baz barfooq ux',
|
||||
2 => '> f oo ba r baz barfooq ux',
|
||||
3 => '> f oo ba r baz barfooq ux',
|
||||
4 => '> f oo ba r baz barfooq ux',
|
||||
5 => '> f oo ba r baz barfooq ux',
|
||||
6 => '> f oo ba r baz barfooq ux',
|
||||
7 => '> f oo ba r baz barfooq ux',
|
||||
8 => '> f oo ba r baz barfooq ux',
|
||||
9 => '> f oo ba r baz barfooq ux',
|
||||
}.each do |ts, exp|
|
||||
tmux.prepare
|
||||
tmux.send_keys %[cat #{tempname} | fzf --tabstop=#{ts}], :Enter
|
||||
tmux.until { |lines| exp.start_with? lines[-3].to_s.strip.sub(/\.\.$/, '') }
|
||||
tmux.send_keys :Enter
|
||||
end
|
||||
end
|
||||
|
||||
def test_with_nth
|
||||
writelines tempname, ['hello world ', 'byebye']
|
||||
assert_equal 'hello world ', `#{FZF} -f"^he hehe" -x -n 2.. --with-nth 2,1,1 < #{tempname}`.chomp
|
||||
end
|
||||
|
||||
def test_with_nth_ansi
|
||||
writelines tempname, ["\x1b[33mhello \x1b[34;1mworld\x1b[m ", 'byebye']
|
||||
assert_equal 'hello world ', `#{FZF} -f"^he hehe" -x -n 2.. --with-nth 2,1,1 --ansi < #{tempname}`.chomp
|
||||
end
|
||||
|
||||
def test_with_nth_no_ansi
|
||||
src = "\x1b[33mhello \x1b[34;1mworld\x1b[m "
|
||||
writelines tempname, [src, 'byebye']
|
||||
assert_equal src, `#{FZF} -fhehe -x -n 2.. --with-nth 2,1,1 --no-ansi < #{tempname}`.chomp
|
||||
end
|
||||
|
||||
def test_exit_0_exit_code
|
||||
`echo foo | #{FZF} -q bar -0`
|
||||
assert_equal 1, $?.exitstatus
|
||||
end
|
||||
|
||||
def test_invalid_term
|
||||
tmux.send_keys "TERM=xxx fzf", :Enter
|
||||
tmux.until { |lines| lines.any? { |l| l.include? 'Invalid $TERM: xxx' } }
|
||||
lines = `TERM=xxx #{FZF}`
|
||||
assert_equal 2, $?.exitstatus
|
||||
assert lines.include?('Invalid $TERM: xxx')
|
||||
end
|
||||
|
||||
def test_invalid_option
|
||||
lines = `#{FZF} --foobar 2>&1`
|
||||
assert_equal 2, $?.exitstatus
|
||||
assert lines.include?('unknown option: --foobar'), lines
|
||||
end
|
||||
|
||||
def test_filter_exitstatus
|
||||
# filter / streaming filter
|
||||
["", "--no-sort"].each do |opts|
|
||||
assert `echo foo | #{FZF} -f foo #{opts}`.include?('foo')
|
||||
assert_equal 0, $?.exitstatus
|
||||
|
||||
assert `echo foo | #{FZF} -f bar #{opts}`.empty?
|
||||
assert_equal 1, $?.exitstatus
|
||||
end
|
||||
end
|
||||
|
||||
def test_exitstatus_empty
|
||||
{ '99' => '0', '999' => '1' }.each do |query, status|
|
||||
tmux.send_keys "seq 100 | #{FZF} -q #{query}", :Enter
|
||||
tmux.until { |lines| lines[-2] =~ %r{ [10]/100} }
|
||||
tmux.send_keys :Enter
|
||||
|
||||
tmux.send_keys 'echo --\$?--'
|
||||
tmux.until { |lines| lines.last.include? "echo --$?--" }
|
||||
tmux.send_keys :Enter
|
||||
tmux.until { |lines| lines.last.include? "--#{status}--" }
|
||||
end
|
||||
end
|
||||
|
||||
def test_default_extended
|
||||
assert_equal '100', `seq 100 | #{FZF} -f "1 00$"`.chomp
|
||||
assert_equal '', `seq 100 | #{FZF} -f "1 00$" +x`.chomp
|
||||
end
|
||||
|
||||
def test_exact
|
||||
assert_equal 4, `seq 123 | #{FZF} -f 13`.lines.length
|
||||
assert_equal 2, `seq 123 | #{FZF} -f 13 -e`.lines.length
|
||||
assert_equal 4, `seq 123 | #{FZF} -f 13 +e`.lines.length
|
||||
end
|
||||
|
||||
def test_or_operator
|
||||
assert_equal %w[1 5 10], `seq 10 | #{FZF} -f "1 | 5"`.lines.map(&:chomp)
|
||||
assert_equal %w[1 10 2 3 4 5 6 7 8 9],
|
||||
`seq 10 | #{FZF} -f '1 | !1'`.lines.map(&:chomp)
|
||||
end
|
||||
|
||||
def test_hscroll_off
|
||||
writelines tempname, ['=' * 10000 + '0123456789']
|
||||
[0, 3, 6].each do |off|
|
||||
tmux.prepare
|
||||
tmux.send_keys "#{FZF} --hscroll-off=#{off} -q 0 < #{tempname}", :Enter
|
||||
tmux.until { |lines| lines[-3].end_with?((0..off).to_a.join + '..') }
|
||||
tmux.send_keys '9'
|
||||
tmux.until { |lines| lines[-3].end_with? '789' }
|
||||
tmux.send_keys :Enter
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def writelines path, lines
|
||||
File.unlink path while File.exists? path
|
||||
File.open(path, 'w') { |f| f << lines.join($/) }
|
||||
File.open(path, 'w') { |f| f << lines.join($/) + $/ }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -840,6 +1223,22 @@ module TestShell
|
||||
tmux.until { |lines| lines[-1].end_with?(expected) }
|
||||
end
|
||||
|
||||
def test_alt_c_command
|
||||
set_var 'FZF_ALT_C_COMMAND', 'echo /tmp'
|
||||
|
||||
tmux.prepare
|
||||
tmux.send_keys 'cd /', :Enter
|
||||
|
||||
tmux.prepare
|
||||
tmux.send_keys :Escape, :c, pane: 0
|
||||
lines = tmux.until(1) { |lines| lines.item_count == 1 }
|
||||
tmux.send_keys :Enter, pane: 1
|
||||
|
||||
tmux.prepare
|
||||
tmux.send_keys :pwd, :Enter
|
||||
tmux.until { |lines| lines[-1].end_with? '/tmp' }
|
||||
end
|
||||
|
||||
def test_ctrl_r
|
||||
tmux.prepare
|
||||
tmux.send_keys 'echo 1st', :Enter; tmux.prepare
|
||||
@@ -869,6 +1268,8 @@ module CompletionTest
|
||||
tmux.prepare
|
||||
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab, pane: 0
|
||||
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||
tmux.send_keys ' !d'
|
||||
tmux.until(1) { |lines| lines[-2].include?(' 2/') }
|
||||
tmux.send_keys :BTab, :BTab
|
||||
tmux.until(1) { |lines| lines[-2].include?('(2)') }
|
||||
tmux.send_keys :Enter
|
||||
@@ -904,17 +1305,34 @@ module CompletionTest
|
||||
tmux.send_keys 'C-u'
|
||||
tmux.send_keys 'cat /tmp/fzf\ test/**', :Tab, pane: 0
|
||||
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||
tmux.send_keys :Enter
|
||||
tmux.send_keys 'C-K', :Enter
|
||||
tmux.until do |lines|
|
||||
tmux.send_keys 'C-L'
|
||||
lines[-1].end_with?('/tmp/fzf\ test/foobar')
|
||||
end
|
||||
|
||||
# Should include hidden files
|
||||
(1..100).each { |i| FileUtils.touch "/tmp/fzf-test/.hidden-#{i}" }
|
||||
tmux.send_keys 'C-u'
|
||||
tmux.send_keys 'cat /tmp/fzf-test/hidden**', :Tab, pane: 0
|
||||
tmux.until(1) do |lines|
|
||||
tmux.send_keys 'C-L'
|
||||
lines[-2].include?('100/') &&
|
||||
lines[-3].include?('/tmp/fzf-test/.hidden-')
|
||||
end
|
||||
tmux.send_keys :Enter
|
||||
ensure
|
||||
['/tmp/fzf-test', '/tmp/fzf test', '~/.fzf-home', 'no~such~user'].each do |f|
|
||||
FileUtils.rm_rf File.expand_path(f)
|
||||
end
|
||||
end
|
||||
|
||||
def test_file_completion_root
|
||||
tmux.send_keys 'ls /**', :Tab, pane: 0
|
||||
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||
tmux.send_keys :Enter
|
||||
end
|
||||
|
||||
def test_dir_completion
|
||||
tmux.send_keys 'mkdir -p /tmp/fzf-test/d{1..100}; touch /tmp/fzf-test/d55/xxx', :Enter
|
||||
tmux.prepare
|
||||
@@ -961,6 +1379,39 @@ module CompletionTest
|
||||
ensure
|
||||
Process.kill 'KILL', pid.to_i rescue nil if pid
|
||||
end
|
||||
|
||||
def test_custom_completion
|
||||
tmux.send_keys '_fzf_compgen_path() { echo "\$1"; seq 10; }', :Enter
|
||||
tmux.prepare
|
||||
tmux.send_keys 'ls /tmp/**', :Tab, pane: 0
|
||||
tmux.until(1) { |lines| lines.item_count == 11 }
|
||||
tmux.send_keys :BTab, :BTab, :BTab
|
||||
tmux.until(1) { |lines| lines[-2].include? '(3)' }
|
||||
tmux.send_keys :Enter
|
||||
tmux.until do |lines|
|
||||
tmux.send_keys 'C-L'
|
||||
lines[-1] == "ls /tmp 1 2"
|
||||
end
|
||||
end
|
||||
|
||||
def test_unset_completion
|
||||
tmux.send_keys 'export FOO=BAR', :Enter
|
||||
tmux.prepare
|
||||
|
||||
# Using tmux
|
||||
tmux.send_keys 'unset FOO**', :Tab, pane: 0
|
||||
tmux.until(1) { |lines| lines[-2].include? ' 1/' }
|
||||
tmux.send_keys :Enter
|
||||
tmux.until { |lines| lines[-1] == 'unset FOO' }
|
||||
tmux.send_keys 'C-c'
|
||||
|
||||
# FZF_TMUX=0
|
||||
new_shell
|
||||
tmux.send_keys 'unset FOO**', :Tab
|
||||
tmux.until { |lines| lines[-2].include? ' 1/' }
|
||||
tmux.send_keys :Enter
|
||||
tmux.until { |lines| lines[-1] == 'unset FOO' }
|
||||
end
|
||||
end
|
||||
|
||||
class TestBash < TestBase
|
||||
|
Reference in New Issue
Block a user