mirror of
https://github.com/junegunn/fzf.git
synced 2025-08-01 12:42:01 -07:00
Compare commits
76 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
467a22dd36 | ||
|
50292adacb | ||
|
84a7499ae3 | ||
|
39d7177bd3 | ||
|
1c65139888 | ||
|
8a4db3c004 | ||
|
cef93f700b | ||
|
0a3d3460b1 | ||
|
d988f3fa50 | ||
|
e865144ace | ||
|
2a167aa030 | ||
|
9cfecf7f0b | ||
|
f9d6b83f5e | ||
|
ce7d4a1c53 | ||
|
9bba6bd172 | ||
|
4ad92e3a0b | ||
|
c4bf820dc3 | ||
|
39f43587d0 | ||
|
fdaa4e9b18 | ||
|
91876e98cd | ||
|
eb8fef0031 | ||
|
87447ddd6d | ||
|
9d138173be | ||
|
eae53576bd | ||
|
f8c49effd4 | ||
|
618706a5f5 | ||
|
9ffcd26d50 | ||
|
b431e227da | ||
|
d94dfe0876 | ||
|
6130026786 | ||
|
a723977b9f | ||
|
3dddbfd8fa | ||
|
e70a2a5817 | ||
|
d80a41bb6d | ||
|
2bebd5cdb4 | ||
|
7bb75b0213 | ||
|
bc2e82efc1 | ||
|
c04e8de9b0 | ||
|
4977174def | ||
|
5eef0acea1 | ||
|
3935aa84d8 | ||
|
dd6138a655 | ||
|
68c5bea3f8 | ||
|
0f474d541d | ||
|
c4d59aeec4 | ||
|
b2c423d1ff | ||
|
49c752b1f7 | ||
|
daa79a6df2 | ||
|
48e0c1e721 | ||
|
12d81e212f | ||
|
c22e729d9c | ||
|
2b8a1c0d70 | ||
|
e4b56b9702 | ||
|
789a474b28 | ||
|
fb2959c514 | ||
|
62a28468a7 | ||
|
23dba99eda | ||
|
5f62d224b0 | ||
|
6728870071 | ||
|
87c71a3ea6 | ||
|
06ab399497 | ||
|
f7b52d2541 | ||
|
c111af0ed2 | ||
|
07e2bd673e | ||
|
e4ce64d10b | ||
|
5f3326a888 | ||
|
1304428003 | ||
|
55828f389a | ||
|
7e2c18a1f6 | ||
|
79c147ed78 | ||
|
d4b41c5e03 | ||
|
b15a0e9650 | ||
|
fe09559ee9 | ||
|
94e8e6419f | ||
|
4d2d18649c | ||
|
c1aa5c5f33 |
@@ -1,11 +1,15 @@
|
|||||||
language: ruby
|
language: ruby
|
||||||
|
rvm:
|
||||||
|
- 2.2.0
|
||||||
|
|
||||||
install:
|
install:
|
||||||
- sudo apt-get update
|
- sudo apt-get update
|
||||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev
|
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev
|
||||||
- sudo add-apt-repository -y ppa:pi-rho/dev
|
- sudo add-apt-repository -y ppa:pi-rho/dev
|
||||||
|
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
||||||
- sudo apt-get update
|
- sudo apt-get update
|
||||||
- sudo apt-get install -y tmux=1.9a-1~ppa1~p
|
- sudo apt-get install -y tmux=1.9a-1~ppa1~p
|
||||||
|
- sudo apt-get install -y zsh fish
|
||||||
|
|
||||||
script: |
|
script: |
|
||||||
export GOROOT=~/go1.4
|
export GOROOT=~/go1.4
|
||||||
@@ -21,4 +25,4 @@ script: |
|
|||||||
cd $FZF_BASE/src && make test fzf/fzf-linux_amd64 install &&
|
cd $FZF_BASE/src && make test fzf/fzf-linux_amd64 install &&
|
||||||
cd $FZF_BASE/bin && ln -sf fzf-linux_amd64 fzf-$(./fzf --version)-linux_amd64 &&
|
cd $FZF_BASE/bin && ln -sf fzf-linux_amd64 fzf-$(./fzf --version)-linux_amd64 &&
|
||||||
cd $FZF_BASE && yes | ./install &&
|
cd $FZF_BASE && yes | ./install &&
|
||||||
tmux new "rake test > out && touch ok" && cat out && [ -e ok ]
|
tmux new "ruby test/test_go.rb > out && touch ok" && cat out && [ -e ok ]
|
||||||
|
122
CHANGELOG.md
Normal file
122
CHANGELOG.md
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
CHANGELOG
|
||||||
|
=========
|
||||||
|
|
||||||
|
0.9.7
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--toggle-sort` option (#173)
|
||||||
|
- `--toggle-sort=ctrl-r` is applied to `CTRL-R` shell extension
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed to print empty line if `--expect` is set and fzf is completed by
|
||||||
|
`--select-1` or `--exit-0` (#172)
|
||||||
|
- Fixed to allow comma character as an argument to `--expect` option
|
||||||
|
|
||||||
|
0.9.6
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
#### Added `--expect` option (#163)
|
||||||
|
|
||||||
|
If you provide a comma-separated list of keys with `--expect` option, fzf will
|
||||||
|
allow you to select the match and complete the finder when any of the keys is
|
||||||
|
pressed. Additionally, fzf will print the name of the key pressed as the first
|
||||||
|
line of the output so that your script can decide what to do next based on the
|
||||||
|
information.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
fzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@
|
||||||
|
```
|
||||||
|
|
||||||
|
The updated vim plugin uses this option to implement
|
||||||
|
[ctrlp](https://github.com/kien/ctrlp.vim)-compatible key bindings.
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed to ignore ANSI escape code `\e[K` (#162)
|
||||||
|
|
||||||
|
0.9.5
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
#### Added `--ansi` option (#150)
|
||||||
|
|
||||||
|
If you give `--ansi` option to fzf, fzf will interpret ANSI color codes from
|
||||||
|
the input, display the item with the ANSI colors (true colors are not
|
||||||
|
supported), and strips the codes from the output. This option is off by
|
||||||
|
default as it entails some overhead.
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
#### Reduced initial memory footprint (#151)
|
||||||
|
|
||||||
|
By removing unnecessary copy of pointers, fzf will use significantly smaller
|
||||||
|
amount of memory when it's started. The difference is hugely noticeable when
|
||||||
|
the input is extremely large. (e.g. `locate / | fzf`)
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed panic on `--no-sort --filter ''` (#149)
|
||||||
|
|
||||||
|
0.9.4
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
#### Added `--tac` option to reverse the order of the input.
|
||||||
|
|
||||||
|
One might argue that this option is unnecessary since we can already put `tac`
|
||||||
|
or `tail -r` in the command pipeline to achieve the same result. However, the
|
||||||
|
advantage of `--tac` is that it does not block until the input is complete.
|
||||||
|
|
||||||
|
### *Backward incompatible changes*
|
||||||
|
|
||||||
|
#### Changed behavior on `--no-sort`
|
||||||
|
|
||||||
|
`--no-sort` option will no longer reverse the display order within finder. You
|
||||||
|
may want to use the new `--tac` option with `--no-sort`.
|
||||||
|
|
||||||
|
```
|
||||||
|
history | fzf +s --tac
|
||||||
|
```
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
#### `--filter` will not block when sort is disabled
|
||||||
|
|
||||||
|
When fzf works in filtering mode (`--filter`) and sort is disabled
|
||||||
|
(`--no-sort`), there's no need to block until input is complete. The new
|
||||||
|
version of fzf will print the matches on-the-fly when the following condition
|
||||||
|
is met:
|
||||||
|
|
||||||
|
--filter TERM --no-sort [--no-tac --no-sync]
|
||||||
|
|
||||||
|
or simply:
|
||||||
|
|
||||||
|
-f TERM +s
|
||||||
|
|
||||||
|
This change removes unnecessary delay in the use cases like the following:
|
||||||
|
|
||||||
|
fzf -f xxx +s | head -5
|
||||||
|
|
||||||
|
However, in this case, fzf processes the lines sequentially, so it cannot
|
||||||
|
utilize multiple cores, and fzf will run slightly slower than the previous
|
||||||
|
mode of execution where filtering is done in parallel after the entire input
|
||||||
|
is loaded. If the user is concerned about this performance problem, one can
|
||||||
|
add `--sync` option to re-enable buffering.
|
||||||
|
|
||||||
|
0.9.3
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
- Added `--sync` option for multi-staged filtering
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
- `--select-1` and `--exit-0` will start finder immediately when the condition
|
||||||
|
cannot be met
|
||||||
|
|
280
README.md
280
README.md
@@ -1,12 +1,22 @@
|
|||||||
fzf - Fuzzy finder for your shell
|
<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 fuzzy finder for your shell.
|
fzf is a general-purpose command-line fuzzy finder.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
It was heavily inspired by [ctrlp.vim](https://github.com/kien/ctrlp.vim) and
|
Pros
|
||||||
the likes.
|
----
|
||||||
|
|
||||||
|
- No dependency
|
||||||
|
- Blazingly fast
|
||||||
|
- e.g. `locate / | fzf`
|
||||||
|
- Flexible layout
|
||||||
|
- Runs in fullscreen or in horizontal/vertical split using tmux
|
||||||
|
- The most comprehensive feature set
|
||||||
|
- Try `fzf --help` and be surprised
|
||||||
|
- Batteries included
|
||||||
|
- Vim plugin, key bindings and fuzzy auto-completion
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
@@ -14,26 +24,27 @@ Installation
|
|||||||
fzf project consists of the followings:
|
fzf project consists of the followings:
|
||||||
|
|
||||||
- `fzf` executable
|
- `fzf` executable
|
||||||
|
- `fzf-tmux` script for launching fzf in a tmux pane
|
||||||
- Shell extensions
|
- Shell extensions
|
||||||
- Key bindings (`CTRL-T`, `CTRL-R`, and `ALT-C`) (bash, zsh, fish)
|
- Key bindings (`CTRL-T`, `CTRL-R`, and `ALT-C`) (bash, zsh, fish)
|
||||||
- Fuzzy auto-completion (bash)
|
- Fuzzy auto-completion (bash only)
|
||||||
|
|
||||||
You can [download fzf executable][bin] alone, but it's recommended that you
|
You can [download fzf executable][bin] alone, but it's recommended that you
|
||||||
install the extra stuff using the attached install script.
|
install the extra stuff using the attached install script.
|
||||||
|
|
||||||
[bin]: https://github.com/junegunn/fzf-bin/releases
|
[bin]: https://github.com/junegunn/fzf-bin/releases
|
||||||
|
|
||||||
### Using git (recommended)
|
#### Using git (recommended)
|
||||||
|
|
||||||
Clone this repository and run
|
Clone this repository and run
|
||||||
[install](https://github.com/junegunn/fzf/blob/master/install) script.
|
[install](https://github.com/junegunn/fzf/blob/master/install) script.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://github.com/junegunn/fzf.git ~/.fzf
|
git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
|
||||||
~/.fzf/install
|
~/.fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using curl
|
#### Using curl
|
||||||
|
|
||||||
In case you don't have git installed:
|
In case you don't have git installed:
|
||||||
|
|
||||||
@@ -44,7 +55,7 @@ curl -L https://github.com/junegunn/fzf/archive/master.tar.gz |
|
|||||||
~/.fzf/install
|
~/.fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using Homebrew
|
#### Using Homebrew
|
||||||
|
|
||||||
On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
||||||
|
|
||||||
@@ -52,10 +63,10 @@ On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
|||||||
brew install fzf
|
brew install fzf
|
||||||
|
|
||||||
# Install shell extensions - this should be done whenever fzf is updated
|
# Install shell extensions - this should be done whenever fzf is updated
|
||||||
/usr/local/Cellar/fzf/$(fzf --version)/install
|
$(brew info fzf | grep /install)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Install as Vim plugin
|
#### Install as Vim plugin
|
||||||
|
|
||||||
Once you have cloned the repository, add the following line to your .vimrc.
|
Once you have cloned the repository, add the following line to your .vimrc.
|
||||||
|
|
||||||
@@ -63,56 +74,26 @@ Once you have cloned the repository, add the following line to your .vimrc.
|
|||||||
set rtp+=~/.fzf
|
set rtp+=~/.fzf
|
||||||
```
|
```
|
||||||
|
|
||||||
Or you can have [vim-plug](https://github.com/junegunn/vim-plug) manage fzf:
|
Or you can have [vim-plug](https://github.com/junegunn/vim-plug) manage fzf
|
||||||
|
(recommended):
|
||||||
|
|
||||||
```vim
|
```vim
|
||||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
|
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Upgrading fzf
|
||||||
|
|
||||||
|
fzf is being actively developed and you might want to upgrade it once in a
|
||||||
|
while. Please follow the instruction below depending on the installation
|
||||||
|
method.
|
||||||
|
|
||||||
|
- git: `cd ~/.fzf && git pull && ./install`
|
||||||
|
- brew: `brew update && brew upgrade fzf && $(brew info fzf | grep /install)`
|
||||||
|
- vim-plug: `:PlugUpdate fzf`
|
||||||
|
|
||||||
Usage
|
Usage
|
||||||
-----
|
-----
|
||||||
|
|
||||||
```
|
|
||||||
usage: fzf [options]
|
|
||||||
|
|
||||||
Search
|
|
||||||
-x, --extended Extended-search mode
|
|
||||||
-e, --extended-exact Extended-search mode (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])
|
|
||||||
--with-nth=N[,..] Transform the item using index expressions for search
|
|
||||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
|
||||||
|
|
||||||
Search result
|
|
||||||
-s, --sort Sort the result
|
|
||||||
+s, --no-sort Do not sort the result. Keep the sequence unchanged.
|
|
||||||
|
|
||||||
Interface
|
|
||||||
-m, --multi Enable multi-select with tab/shift-tab
|
|
||||||
--no-mouse Disable mouse
|
|
||||||
+c, --no-color Disable colors
|
|
||||||
+2, --no-256 Disable 256-color
|
|
||||||
--black Use black background
|
|
||||||
--reverse Reverse orientation
|
|
||||||
--prompt=STR Input prompt (default: '> ')
|
|
||||||
|
|
||||||
Scripting
|
|
||||||
-q, --query=STR Start the finder with the given query
|
|
||||||
-1, --select-1 Automatically select the only match
|
|
||||||
-0, --exit-0 Exit immediately when there's no match
|
|
||||||
-f, --filter=STR Filter mode. Do not start interactive finder.
|
|
||||||
--print-query Print query as the first line
|
|
||||||
--sync Synchronous search for multi-staged filtering
|
|
||||||
(e.g. 'fzf --multi | fzf --sync')
|
|
||||||
|
|
||||||
Environment variables
|
|
||||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
|
||||||
FZF_DEFAULT_OPTS Defaults options. (e.g. '-x -m')
|
|
||||||
```
|
|
||||||
|
|
||||||
fzf will launch curses-based finder, read the list from STDIN, and write the
|
fzf will launch curses-based finder, read the list from STDIN, and write the
|
||||||
selected item to STDOUT.
|
selected item to STDOUT.
|
||||||
|
|
||||||
@@ -128,34 +109,16 @@ files excluding hidden ones. (You can override the default command with
|
|||||||
vim $(fzf)
|
vim $(fzf)
|
||||||
```
|
```
|
||||||
|
|
||||||
If you want to preserve the exact sequence of the input, provide `--no-sort` (or
|
#### Using the finder
|
||||||
`+s`) option.
|
|
||||||
|
|
||||||
```sh
|
- `CTRL-J` / `CTRL-K` (or `CTRL-N` / `CTRL-P)` to move cursor up and down
|
||||||
history | fzf +s
|
- `Enter` key to select the item, `CTRL-C` / `CTRL-G` / `ESC` to exit
|
||||||
```
|
- On multi-select mode (`-m`), `TAB` and `Shift-TAB` to mark multiple items
|
||||||
|
- Emacs style key bindings
|
||||||
|
- Mouse: scroll, click, double-click; shift-click and shift-scroll on
|
||||||
|
multi-select mode
|
||||||
|
|
||||||
### Keys
|
#### Extended-search mode
|
||||||
|
|
||||||
Use CTRL-J and CTRL-K (or CTRL-N and CTRL-P) to change the selection, press
|
|
||||||
enter key to select the item. CTRL-C, CTRL-G, or ESC will terminate the finder.
|
|
||||||
|
|
||||||
The following readline key bindings should also work as expected.
|
|
||||||
|
|
||||||
- CTRL-A / CTRL-E
|
|
||||||
- CTRL-B / CTRL-F
|
|
||||||
- CTRL-H / CTRL-D
|
|
||||||
- CTRL-W / CTRL-U / CTRL-Y
|
|
||||||
- ALT-B / ALT-F
|
|
||||||
|
|
||||||
If you enable multi-select mode with `-m` option, you can select multiple items
|
|
||||||
with TAB or Shift-TAB key.
|
|
||||||
|
|
||||||
You can also use mouse. Double-click on an item to select it or shift-click (or
|
|
||||||
ctrl-click) to select multiple items. Use mouse wheel to move the cursor up and
|
|
||||||
down.
|
|
||||||
|
|
||||||
### Extended-search mode
|
|
||||||
|
|
||||||
With `-x` or `--extended` option, fzf will start in "extended-search mode".
|
With `-x` or `--extended` option, fzf will start in "extended-search mode".
|
||||||
|
|
||||||
@@ -174,40 +137,12 @@ such as: `^music .mp3$ sbtrkt !rmx`
|
|||||||
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
||||||
fzf with `-e` or `--extended-exact` option.
|
fzf with `-e` or `--extended-exact` option.
|
||||||
|
|
||||||
Useful examples
|
Examples
|
||||||
---------------
|
--------
|
||||||
|
|
||||||
```sh
|
Many useful examples can be found on [the wiki
|
||||||
# fe [FUZZY PATTERN] - Open the selected file with the default editor
|
page](https://github.com/junegunn/fzf/wiki/examples). Feel free to add your
|
||||||
# - Bypass fuzzy finder if there's only one match (--select-1)
|
own as well.
|
||||||
# - Exit if there's no match (--exit-0)
|
|
||||||
fe() {
|
|
||||||
local file
|
|
||||||
file=$(fzf --query="$1" --select-1 --exit-0)
|
|
||||||
[ -n "$file" ] && ${EDITOR:-vim} "$file"
|
|
||||||
}
|
|
||||||
|
|
||||||
# fd - cd to selected directory
|
|
||||||
fd() {
|
|
||||||
local dir
|
|
||||||
dir=$(find ${1:-*} -path '*/\.*' -prune \
|
|
||||||
-o -type d -print 2> /dev/null | fzf +m) &&
|
|
||||||
cd "$dir"
|
|
||||||
}
|
|
||||||
|
|
||||||
# fh - repeat history
|
|
||||||
fh() {
|
|
||||||
eval $(([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf +s | sed 's/ *[0-9]* *//')
|
|
||||||
}
|
|
||||||
|
|
||||||
# fkill - kill process
|
|
||||||
fkill() {
|
|
||||||
ps -ef | sed 1d | fzf -m | awk '{print $2}' | xargs kill -${1:-9}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
For more examples, see [the wiki
|
|
||||||
page](https://github.com/junegunn/fzf/wiki/examples).
|
|
||||||
|
|
||||||
Key bindings for command line
|
Key bindings for command line
|
||||||
-----------------------------
|
-----------------------------
|
||||||
@@ -217,6 +152,7 @@ fish.
|
|||||||
|
|
||||||
- `CTRL-T` - Paste the selected file path(s) into the command line
|
- `CTRL-T` - Paste the selected file path(s) into the command line
|
||||||
- `CTRL-R` - Paste the selected command from history into the command line
|
- `CTRL-R` - Paste the selected command from history into the command line
|
||||||
|
- Sort is disabled by default. Press `CTRL-R` again to toggle sort.
|
||||||
- `ALT-C` - cd into the selected directory
|
- `ALT-C` - cd into the selected directory
|
||||||
|
|
||||||
If you're on a tmux session, `CTRL-T` will launch fzf in a new split-window. You
|
If you're on a tmux session, `CTRL-T` will launch fzf in a new split-window. You
|
||||||
@@ -231,13 +167,27 @@ If you want to customize the key bindings, consider editing the
|
|||||||
installer-generated source code: `~/.fzf.bash`, `~/.fzf.zsh`, and
|
installer-generated source code: `~/.fzf.bash`, `~/.fzf.zsh`, and
|
||||||
`~/.config/fish/functions/fzf_key_bindings.fish`.
|
`~/.config/fish/functions/fzf_key_bindings.fish`.
|
||||||
|
|
||||||
Auto-completion
|
`fzf-tmux` script
|
||||||
---------------
|
-----------------
|
||||||
|
|
||||||
Disclaimer: *Auto-completion feature is currently experimental, it can change
|
[fzf-tmux](bin/fzf-tmux) is a bash script that opens fzf in a tmux pane.
|
||||||
over time*
|
|
||||||
|
|
||||||
### bash
|
```sh
|
||||||
|
# usage: fzf-tmux [-u|-d [HEIGHT[%]]] [-l|-r [WIDTH[%]]] [--] [FZF OPTIONS]
|
||||||
|
# (-[udlr]: up/down/left/right)
|
||||||
|
|
||||||
|
# select git branches in horizontal split below (15 lines)
|
||||||
|
git branch | fzf-tmux -d 15
|
||||||
|
|
||||||
|
# select multiple words in vertical split on the left (20% of screen width)
|
||||||
|
cat /usr/share/dict/words | fzf-tmux -l 20% --multi --reverse
|
||||||
|
```
|
||||||
|
|
||||||
|
It will still work even when you're not on tmux, silently ignoring `-[udlr]`
|
||||||
|
options, so you can invariably use `fzf-tmux` in your scripts.
|
||||||
|
|
||||||
|
Fuzzy completion for bash
|
||||||
|
-------------------------
|
||||||
|
|
||||||
#### Files and directories
|
#### Files and directories
|
||||||
|
|
||||||
@@ -306,18 +256,12 @@ export FZF_COMPLETION_TRIGGER='~~'
|
|||||||
export FZF_COMPLETION_OPTS='+c -x'
|
export FZF_COMPLETION_OPTS='+c -x'
|
||||||
```
|
```
|
||||||
|
|
||||||
### zsh
|
|
||||||
|
|
||||||
TODO :smiley:
|
|
||||||
|
|
||||||
(Pull requests are appreciated.)
|
|
||||||
|
|
||||||
Usage as Vim plugin
|
Usage as Vim plugin
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
||||||
|
|
||||||
### `:FZF[!]`
|
#### `:FZF[!]`
|
||||||
|
|
||||||
If you have set up fzf for Vim, `:FZF` command will be added.
|
If you have set up fzf for Vim, `:FZF` command will be added.
|
||||||
|
|
||||||
@@ -332,6 +276,10 @@ If you have set up fzf for Vim, `:FZF` command will be added.
|
|||||||
:FZF --no-sort -m /tmp
|
:FZF --no-sort -m /tmp
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Similarly to [ctrlp.vim](https://github.com/kien/ctrlp.vim), use enter key,
|
||||||
|
`CTRL-T`, `CTRL-X` or `CTRL-V` to open selected files in the current window,
|
||||||
|
in new tabs, in horizontal splits, or in vertical splits respectively.
|
||||||
|
|
||||||
Note that the environment variables `FZF_DEFAULT_COMMAND` and `FZF_DEFAULT_OPTS`
|
Note that the environment variables `FZF_DEFAULT_COMMAND` and `FZF_DEFAULT_OPTS`
|
||||||
also apply here.
|
also apply here.
|
||||||
|
|
||||||
@@ -352,29 +300,29 @@ let g:fzf_launcher = 'urxvt -geometry 120x30 -e sh -c %s'
|
|||||||
|
|
||||||
If you're running MacVim on OSX, I recommend you to use iTerm2 as the launcher.
|
If you're running MacVim on OSX, I recommend you to use iTerm2 as the launcher.
|
||||||
Refer to the [this wiki
|
Refer to the [this wiki
|
||||||
page](https://github.com/junegunn/fzf/wiki/fzf-with-MacVim-and-iTerm2) to see
|
page](https://github.com/junegunn/fzf/wiki/On-MacVim-with-iTerm2) to see
|
||||||
|
|
||||||
how to set up.
|
how to set up.
|
||||||
|
|
||||||
### `fzf#run([options])`
|
#### `fzf#run([options])`
|
||||||
|
|
||||||
For more advanced uses, you can call `fzf#run()` function which returns the list
|
For more advanced uses, you can call `fzf#run()` function which returns the list
|
||||||
of the selected items.
|
of the selected items.
|
||||||
|
|
||||||
`fzf#run()` may take an options-dictionary:
|
`fzf#run()` may take an options-dictionary:
|
||||||
|
|
||||||
| Option name | Type | Description |
|
| Option name | Type | Description |
|
||||||
| --------------- | ------------- | ------------------------------------------------------------------ |
|
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
||||||
| `source` | string | External command to generate input to fzf (e.g. `find .`) |
|
| `source` | string | External command to generate input to fzf (e.g. `find .`) |
|
||||||
| `source` | list | Vim list as input to fzf |
|
| `source` | list | Vim list as input to fzf |
|
||||||
| `sink` | string | Vim command to handle the selected item (e.g. `e`, `tabe`) |
|
| `sink` | string | Vim command to handle the selected item (e.g. `e`, `tabe`) |
|
||||||
| `sink` | funcref | Reference to function to process each selected item |
|
| `sink` | funcref | Reference to function to process each selected item |
|
||||||
| `options` | string | Options to fzf |
|
| `options` | string | Options to fzf |
|
||||||
| `dir` | string | Working directory |
|
| `dir` | string | Working directory |
|
||||||
| `tmux_width` | number/string | Use tmux vertical split with the given height (e.g. `20`, `50%`) |
|
| `up`/`down`/`left`/`right` | number/string | Use tmux pane with the given size (e.g. `20`, `50%`) |
|
||||||
| `tmux_height` | number/string | Use tmux horizontal split with the given height (e.g. `20`, `50%`) |
|
| `launcher` | string | External terminal emulator to start fzf with (Only used in GVim) |
|
||||||
| `launcher` | string | External terminal emulator to start fzf with (Only used in GVim) |
|
|
||||||
|
|
||||||
#### Examples
|
##### Examples
|
||||||
|
|
||||||
If `sink` option is not given, `fzf#run` will simply return the list.
|
If `sink` option is not given, `fzf#run` will simply return the list.
|
||||||
|
|
||||||
@@ -398,10 +346,10 @@ nnoremap <silent> <Leader>C :call fzf#run({
|
|||||||
\ 'source':
|
\ 'source':
|
||||||
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
|
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
|
||||||
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
|
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
|
||||||
\ 'sink': 'colo',
|
\ 'sink': 'colo',
|
||||||
\ 'options': '+m',
|
\ 'options': '+m',
|
||||||
\ 'tmux_width': 20,
|
\ 'left': 20,
|
||||||
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
|
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
|
||||||
\ })<CR>
|
\ })<CR>
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -422,21 +370,24 @@ function! BufOpen(e)
|
|||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
||||||
\ 'source': reverse(BufList()),
|
\ 'source': reverse(BufList()),
|
||||||
\ 'sink': function('BufOpen'),
|
\ 'sink': function('BufOpen'),
|
||||||
\ 'options': '+m',
|
\ 'options': '+m',
|
||||||
\ 'tmux_height': '40%'
|
\ 'down': '40%'
|
||||||
\ })<CR>
|
\ })<CR>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Articles
|
More examples can be found on [the wiki
|
||||||
|
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
||||||
|
|
||||||
|
#### Articles
|
||||||
|
|
||||||
- [fzf+vim+tmux](http://junegunn.kr/2014/04/fzf+vim+tmux)
|
- [fzf+vim+tmux](http://junegunn.kr/2014/04/fzf+vim+tmux)
|
||||||
|
|
||||||
Tips
|
Tips
|
||||||
----
|
----
|
||||||
|
|
||||||
### Rendering issues
|
#### Rendering issues
|
||||||
|
|
||||||
If you have any rendering issues, check the followings:
|
If you have any rendering issues, check the followings:
|
||||||
|
|
||||||
@@ -450,7 +401,7 @@ If you have any rendering issues, check the followings:
|
|||||||
`FZF_DEFAULT_OPTS` for further convenience.
|
`FZF_DEFAULT_OPTS` for further convenience.
|
||||||
4. If you still have problem, try `--no-256` option or even `--no-color`.
|
4. If you still have problem, try `--no-256` option or even `--no-color`.
|
||||||
|
|
||||||
### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`
|
#### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`
|
||||||
|
|
||||||
[ag](https://github.com/ggreer/the_silver_searcher) or
|
[ag](https://github.com/ggreer/the_silver_searcher) or
|
||||||
[pt](https://github.com/monochromegane/the_platinum_searcher) will do the
|
[pt](https://github.com/monochromegane/the_platinum_searcher) will do the
|
||||||
@@ -467,30 +418,23 @@ export FZF_DEFAULT_COMMAND='ag -l -g ""'
|
|||||||
fzf
|
fzf
|
||||||
```
|
```
|
||||||
|
|
||||||
### `git ls-tree` for fast traversal
|
#### `git ls-tree` for fast traversal
|
||||||
|
|
||||||
If you're running fzf in a large git repository, `git ls-tree` can boost up the
|
If you're running fzf in a large git repository, `git ls-tree` can boost up the
|
||||||
speed of the traversal.
|
speed of the traversal.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Copy the original fzf function to __fzf
|
export FZF_DEFAULT_COMMAND='
|
||||||
declare -f __fzf > /dev/null ||
|
(git ls-tree -r --name-only HEAD ||
|
||||||
eval "$(echo "__fzf() {"; declare -f fzf | \grep -v '^{' | tail -n +2)"
|
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
||||||
|
|
||||||
# Use git ls-tree when possible
|
|
||||||
fzf() {
|
|
||||||
if [ -n "$(git rev-parse HEAD 2> /dev/null)" ]; then
|
|
||||||
FZF_DEFAULT_COMMAND="git ls-tree -r --name-only HEAD" __fzf "$@"
|
|
||||||
else
|
|
||||||
__fzf "$@"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using fzf with tmux splits
|
#### Using fzf with tmux panes
|
||||||
|
|
||||||
It isn't too hard to write your own fzf-tmux combo like the default
|
The supplied [fzf-tmux](bin/fzf-tmux) script should suffice in most of the
|
||||||
CTRL-T key binding. (Or is it?)
|
cases, but if you want to be able to update command line like the default
|
||||||
|
`CTRL-T` key binding, you'll have to use `send-keys` command of tmux. The
|
||||||
|
following example will show you how it can be done.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# This is a helper function that splits the current pane to start the given
|
# This is a helper function that splits the current pane to start the given
|
||||||
@@ -520,7 +464,7 @@ fzf_tmux_dir() {
|
|||||||
bind '"\C-x\C-d": "$(fzf_tmux_dir)\e\C-e"'
|
bind '"\C-x\C-d": "$(fzf_tmux_dir)\e\C-e"'
|
||||||
```
|
```
|
||||||
|
|
||||||
### Fish shell
|
#### Fish shell
|
||||||
|
|
||||||
It's [a known bug of fish](https://github.com/fish-shell/fish-shell/issues/1362)
|
It's [a known bug of fish](https://github.com/fish-shell/fish-shell/issues/1362)
|
||||||
that it doesn't allow reading from STDIN in command substitution, which means
|
that it doesn't allow reading from STDIN in command substitution, which means
|
||||||
@@ -543,7 +487,7 @@ function fe
|
|||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
### Handling UTF-8 NFD paths on OSX
|
#### Handling UTF-8 NFD paths on OSX
|
||||||
|
|
||||||
Use iconv to convert NFD paths to NFC:
|
Use iconv to convert NFD paths to NFC:
|
||||||
|
|
||||||
|
12
Rakefile
12
Rakefile
@@ -1,12 +0,0 @@
|
|||||||
require "bundler/gem_tasks"
|
|
||||||
require 'rake/testtask'
|
|
||||||
|
|
||||||
Rake::TestTask.new(:test) do |test|
|
|
||||||
test.pattern = 'test/test_go.rb'
|
|
||||||
end
|
|
||||||
|
|
||||||
Rake::TestTask.new(:testall) do |test|
|
|
||||||
test.pattern = 'test/test_*.rb'
|
|
||||||
end
|
|
||||||
|
|
||||||
task :default => :test
|
|
127
bin/fzf-tmux
Executable file
127
bin/fzf-tmux
Executable file
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# fzf-tmux: starts fzf in a tmux pane
|
||||||
|
# usage: fzf-tmux [-u|-d [HEIGHT[%]]] [-l|-r [WIDTH[%]]] [--] [FZF OPTIONS]
|
||||||
|
|
||||||
|
args=()
|
||||||
|
opt=""
|
||||||
|
skip=""
|
||||||
|
swap=""
|
||||||
|
close=""
|
||||||
|
term=""
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
arg="$1"
|
||||||
|
case "$arg" in
|
||||||
|
-)
|
||||||
|
term=1
|
||||||
|
;;
|
||||||
|
-w*|-h*|-d*|-u*|-r*|-l*)
|
||||||
|
if [ -n "$skip" ]; then
|
||||||
|
args+=("$1")
|
||||||
|
shift
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [[ "$arg" =~ ^.[lrw] ]]; then
|
||||||
|
opt="-h"
|
||||||
|
if [[ "$arg" =~ ^.l ]]; then
|
||||||
|
opt="$opt -d"
|
||||||
|
swap="; swap-pane -D ; select-pane -L"
|
||||||
|
close="; tmux swap-pane -D"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
opt=""
|
||||||
|
if [[ "$arg" =~ ^.u ]]; then
|
||||||
|
opt="$opt -d"
|
||||||
|
swap="; swap-pane -D ; select-pane -U"
|
||||||
|
close="; tmux swap-pane -D"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ ${#arg} -gt 2 ]; then
|
||||||
|
size="${arg:2}"
|
||||||
|
else
|
||||||
|
shift
|
||||||
|
if [[ "$1" =~ ^[0-9]+%?$ ]]; then
|
||||||
|
size="$1"
|
||||||
|
else
|
||||||
|
[ -n "$1" -a "$1" != "--" ] && args+=("$1")
|
||||||
|
shift
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$size" =~ %$ ]]; then
|
||||||
|
size=${size:0:((${#size}-1))}
|
||||||
|
if [ -n "$swap" ]; then
|
||||||
|
opt="$opt -p $(( 100 - size ))"
|
||||||
|
else
|
||||||
|
opt="$opt -p $size"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
if [ -n "$swap" ]; then
|
||||||
|
if [[ "$arg" =~ ^.l ]]; then
|
||||||
|
[ -n "$COLUMNS" ] && max=$COLUMNS || max=$(tput cols)
|
||||||
|
else
|
||||||
|
[ -n "$LINES" ] && max=$LINES || max=$(tput lines)
|
||||||
|
fi
|
||||||
|
size=$(( max - size ))
|
||||||
|
[ $size -lt 0 ] && size=0
|
||||||
|
opt="$opt -l $size"
|
||||||
|
else
|
||||||
|
opt="$opt -l $size"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
--)
|
||||||
|
# "--" can be used to separate fzf-tmux options from fzf options to
|
||||||
|
# avoid conflicts
|
||||||
|
skip=1
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
args+=("$1")
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
shift
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$TMUX_PANE" ]; then
|
||||||
|
fzf "${args[@]}"
|
||||||
|
exit $?
|
||||||
|
fi
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Build arguments to fzf
|
||||||
|
[ ${#args[@]} -gt 0 ] && fzf_args=$(printf '\\"%s\\" ' "${args[@]}"; echo '')
|
||||||
|
|
||||||
|
# Clean up named pipes on exit
|
||||||
|
id=$RANDOM
|
||||||
|
fifo1=/tmp/fzf-fifo1-$id
|
||||||
|
fifo2=/tmp/fzf-fifo2-$id
|
||||||
|
fifo3=/tmp/fzf-fifo3-$id
|
||||||
|
cleanup() {
|
||||||
|
rm -f $fifo1 $fifo2 $fifo3
|
||||||
|
}
|
||||||
|
trap cleanup EXIT SIGINT SIGTERM
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
>&2 echo "$1"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
fzf=$(which fzf 2> /dev/null) || fail "fzf executable not found"
|
||||||
|
envs=""
|
||||||
|
[ -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
|
||||||
|
if [ -n "$term" -o -t 0 ]; then
|
||||||
|
tmux set-window-option -q synchronize-panes off \;\
|
||||||
|
split-window $opt "cd $(printf %q "$PWD");$envs"' sh -c "'$fzf' '"$fzf_args"' > '$fifo2'; echo \$? > '$fifo3' '"$close"'"' $swap
|
||||||
|
else
|
||||||
|
mkfifo $fifo1
|
||||||
|
tmux set-window-option -q synchronize-panes off \;\
|
||||||
|
split-window $opt "$envs"' sh -c "'$fzf' '"$fzf_args"' < '$fifo1' > '$fifo2'; echo \$? > '$fifo3' '"$close"'"' $swap
|
||||||
|
cat <&0 > $fifo1 &
|
||||||
|
fi
|
||||||
|
cat $fifo2
|
||||||
|
[ "$(cat $fifo3)" = '0' ]
|
||||||
|
|
@@ -1,9 +0,0 @@
|
|||||||
require 'rubygems/dependency_installer'
|
|
||||||
|
|
||||||
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.1.0')
|
|
||||||
Gem::DependencyInstaller.new.install 'curses', '~> 1.0'
|
|
||||||
end
|
|
||||||
|
|
||||||
File.open(File.expand_path('../Rakefile', __FILE__), 'w') do |f|
|
|
||||||
f.puts 'task :default'
|
|
||||||
end
|
|
18
fzf
18
fzf
@@ -8,6 +8,8 @@
|
|||||||
# /_/ /___/_/ Fuzzy finder for your shell
|
# /_/ /___/_/ Fuzzy finder for your shell
|
||||||
#
|
#
|
||||||
# Version: 0.8.9 (Dec 24, 2014)
|
# Version: 0.8.9 (Dec 24, 2014)
|
||||||
|
# Deprecation alert:
|
||||||
|
# This script is no longer maintained. Use the new Go version.
|
||||||
#
|
#
|
||||||
# Author: Junegunn Choi
|
# Author: Junegunn Choi
|
||||||
# URL: https://github.com/junegunn/fzf
|
# URL: https://github.com/junegunn/fzf
|
||||||
@@ -124,6 +126,7 @@ class FZF
|
|||||||
@reverse = false
|
@reverse = false
|
||||||
@prompt = '> '
|
@prompt = '> '
|
||||||
@shr_mtx = Mutex.new
|
@shr_mtx = Mutex.new
|
||||||
|
@expect = false
|
||||||
@print_query = false
|
@print_query = false
|
||||||
|
|
||||||
argv =
|
argv =
|
||||||
@@ -198,6 +201,15 @@ class FZF
|
|||||||
when '--no-print-query' then @print_query = false
|
when '--no-print-query' then @print_query = false
|
||||||
when '-e', '--extended-exact' then @extended = :exact
|
when '-e', '--extended-exact' then @extended = :exact
|
||||||
when '+e', '--no-extended-exact' then @extended = nil
|
when '+e', '--no-extended-exact' then @extended = nil
|
||||||
|
when '--expect'
|
||||||
|
argv.shift
|
||||||
|
@expect = true
|
||||||
|
when /^--expect=(.*)$/
|
||||||
|
@expect = true
|
||||||
|
when '--toggle-sort'
|
||||||
|
argv.shift
|
||||||
|
when '--tac', '--sync', '--toggle-sort', /^--toggle-sort=(.*)$/
|
||||||
|
# XXX
|
||||||
else
|
else
|
||||||
usage 1, "illegal option: #{o}"
|
usage 1, "illegal option: #{o}"
|
||||||
end
|
end
|
||||||
@@ -272,10 +284,12 @@ class FZF
|
|||||||
if loaded
|
if loaded
|
||||||
if @select1 && len == 1
|
if @select1 && len == 1
|
||||||
puts @query if @print_query
|
puts @query if @print_query
|
||||||
|
puts if @expect
|
||||||
burp(empty ? matches.first : matches.first.first)
|
burp(empty ? matches.first : matches.first.first)
|
||||||
exit 0
|
exit 0
|
||||||
elsif @exit0 && len == 0
|
elsif @exit0 && len == 0
|
||||||
puts @query if @print_query
|
puts @query if @print_query
|
||||||
|
puts if @expect
|
||||||
exit 0
|
exit 0
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -619,7 +633,8 @@ class FZF
|
|||||||
def start_reader
|
def start_reader
|
||||||
stream =
|
stream =
|
||||||
if @source.tty?
|
if @source.tty?
|
||||||
if default_command = ENV['FZF_DEFAULT_COMMAND']
|
default_command = ENV['FZF_DEFAULT_COMMAND']
|
||||||
|
if default_command && !default_command.empty?
|
||||||
IO.popen(default_command)
|
IO.popen(default_command)
|
||||||
elsif !`which find`.empty?
|
elsif !`which find`.empty?
|
||||||
IO.popen("find * -path '*/\\.*' -prune -o -type f -print -o -type l -print 2> /dev/null")
|
IO.popen("find * -path '*/\\.*' -prune -o -type f -print -o -type l -print 2> /dev/null")
|
||||||
@@ -1148,6 +1163,7 @@ class FZF
|
|||||||
C.close_screen
|
C.close_screen
|
||||||
q, selects = geta(:@query, :@selects)
|
q, selects = geta(:@query, :@selects)
|
||||||
@stdout.puts q if @print_query
|
@stdout.puts q if @print_query
|
||||||
|
@stdout.puts if @expect
|
||||||
if got
|
if got
|
||||||
if selects.empty?
|
if selects.empty?
|
||||||
burp got
|
burp got
|
||||||
|
@@ -1,9 +0,0 @@
|
|||||||
#!/bin/zsh
|
|
||||||
# ____ ____
|
|
||||||
# / __/___ / __/
|
|
||||||
# / /_/_ / / /_
|
|
||||||
# / __/ / /_/ __/
|
|
||||||
# /_/ /___/_/-completion.zsh
|
|
||||||
#
|
|
||||||
|
|
||||||
# TODO
|
|
17
fzf.gemspec
17
fzf.gemspec
@@ -1,17 +0,0 @@
|
|||||||
# coding: utf-8
|
|
||||||
Gem::Specification.new do |spec|
|
|
||||||
spec.name = 'fzf'
|
|
||||||
spec.version = '0.8.4'
|
|
||||||
spec.authors = ['Junegunn Choi']
|
|
||||||
spec.email = ['junegunn.c@gmail.com']
|
|
||||||
spec.description = %q{Fuzzy finder for your shell}
|
|
||||||
spec.summary = %q{Fuzzy finder for your shell}
|
|
||||||
spec.homepage = 'https://github.com/junegunn/fzf'
|
|
||||||
spec.license = 'MIT'
|
|
||||||
|
|
||||||
spec.bindir = '.'
|
|
||||||
spec.files = %w[fzf.gemspec]
|
|
||||||
spec.executables = 'fzf'
|
|
||||||
|
|
||||||
spec.extensions += ['ext/mkrf_conf.rb']
|
|
||||||
end
|
|
314
install
314
install
@@ -1,6 +1,6 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
version=0.9.3
|
version=0.9.7
|
||||||
|
|
||||||
cd $(dirname $BASH_SOURCE)
|
cd $(dirname $BASH_SOURCE)
|
||||||
fzf_base=$(pwd)
|
fzf_base=$(pwd)
|
||||||
@@ -77,7 +77,7 @@ case "$archi" in
|
|||||||
Darwin\ i*86) download fzf-$version-darwin_386 ;;
|
Darwin\ i*86) download fzf-$version-darwin_386 ;;
|
||||||
Linux\ x86_64) download fzf-$version-linux_amd64 ;;
|
Linux\ x86_64) download fzf-$version-linux_amd64 ;;
|
||||||
Linux\ i*86) download fzf-$version-linux_386 ;;
|
Linux\ i*86) download fzf-$version-linux_386 ;;
|
||||||
*) binary_available=0 ;;
|
*) binary_available=0 binary_error=1 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
cd "$fzf_base"
|
cd "$fzf_base"
|
||||||
@@ -144,6 +144,14 @@ if [ -n "$binary_error" ]; then
|
|||||||
echo "< 1.9"
|
echo "< 1.9"
|
||||||
fzf_cmd="$ruby $fzf_base/fzf"
|
fzf_cmd="$ruby $fzf_base/fzf"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Create fzf script
|
||||||
|
echo -n "Creating wrapper script for fzf ... "
|
||||||
|
rm -f "$fzf_base"/bin/fzf
|
||||||
|
echo "#!/bin/sh" > "$fzf_base"/bin/fzf
|
||||||
|
echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf
|
||||||
|
chmod +x "$fzf_base"/bin/fzf
|
||||||
|
echo "OK"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Auto-completion
|
# Auto-completion
|
||||||
@@ -159,294 +167,62 @@ for shell in bash zsh; do
|
|||||||
echo -n "Generate ~/.fzf.$shell ... "
|
echo -n "Generate ~/.fzf.$shell ... "
|
||||||
src=~/.fzf.${shell}
|
src=~/.fzf.${shell}
|
||||||
|
|
||||||
fzf_completion="[[ \$- =~ i ]] && source \"$fzf_base/fzf-completion.${shell}\""
|
fzf_completion="[[ \$- =~ i ]] && source \"$fzf_base/shell/completion.${shell}\""
|
||||||
if [ $auto_completion -ne 0 ]; then
|
if [ $shell != bash -o $auto_completion -ne 0 ]; then
|
||||||
fzf_completion="# $fzf_completion"
|
fzf_completion="# $fzf_completion"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -n "$binary_error" ]; then
|
fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""
|
||||||
cat > $src << EOF
|
if [ $key_bindings -ne 0 ]; then
|
||||||
# Setup fzf function
|
fzf_key_bindings="# $fzf_key_bindings"
|
||||||
# ------------------
|
fi
|
||||||
unalias fzf 2> /dev/null
|
|
||||||
fzf() {
|
|
||||||
$fzf_cmd "\$@"
|
|
||||||
}
|
|
||||||
export -f fzf > /dev/null
|
|
||||||
|
|
||||||
# Auto-completion
|
cat > $src << EOF
|
||||||
# ---------------
|
|
||||||
$fzf_completion
|
|
||||||
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
cat > $src << EOF
|
|
||||||
# Setup fzf
|
# Setup fzf
|
||||||
# ---------
|
# ---------
|
||||||
unalias fzf 2> /dev/null
|
|
||||||
unset fzf 2> /dev/null
|
|
||||||
if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then
|
if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then
|
||||||
export PATH="$fzf_base/bin:\$PATH"
|
export PATH="\$PATH:$fzf_base/bin"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Man path
|
||||||
|
# --------
|
||||||
|
if [[ ! "\$MANPATH" =~ "$fzf_base/man" && -d "$fzf_base/man" ]]; then
|
||||||
|
export MANPATH="\$MANPATH:$fzf_base/man"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Auto-completion
|
# Auto-completion
|
||||||
# ---------------
|
# ---------------
|
||||||
$fzf_completion
|
$fzf_completion
|
||||||
|
|
||||||
|
# Key bindings
|
||||||
|
# ------------
|
||||||
|
$fzf_key_bindings
|
||||||
|
|
||||||
EOF
|
EOF
|
||||||
fi
|
|
||||||
|
|
||||||
if [ $key_bindings -eq 0 ]; then
|
|
||||||
if [ $shell = bash ]; then
|
|
||||||
cat >> $src << "EOFZF"
|
|
||||||
# Key bindings
|
|
||||||
# ------------
|
|
||||||
__fsel() {
|
|
||||||
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- | fzf -m | while read item; do
|
|
||||||
printf '%q ' "$item"
|
|
||||||
done
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
|
||||||
|
|
||||||
__fsel_tmux() {
|
|
||||||
local height
|
|
||||||
height=${FZF_TMUX_HEIGHT:-40%}
|
|
||||||
if [[ $height =~ %$ ]]; then
|
|
||||||
height="-p ${height%\%}"
|
|
||||||
else
|
|
||||||
height="-l $height"
|
|
||||||
fi
|
|
||||||
tmux split-window $height "bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
|
||||||
}
|
|
||||||
|
|
||||||
__fcd() {
|
|
||||||
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- | fzf +m) && printf 'cd %q' "$dir"
|
|
||||||
}
|
|
||||||
|
|
||||||
__use_tmux=0
|
|
||||||
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
|
||||||
|
|
||||||
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
|
||||||
# Required to refresh the prompt after fzf
|
|
||||||
bind '"\er": redraw-current-line'
|
|
||||||
|
|
||||||
# CTRL-T - Paste the selected file path into the command line
|
|
||||||
if [ $__use_tmux -eq 1 ]; then
|
|
||||||
bind '"\C-t": " \C-u \C-a\C-k$(__fsel_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$(__fsel)\e\C-e\C-y\C-a\C-y\ey\C-h\C-e\er \C-h"'
|
|
||||||
fi
|
|
||||||
|
|
||||||
# CTRL-R - Paste the selected command from history into the command line
|
|
||||||
bind '"\C-r": " \C-e\C-u$(HISTTIMEFORMAT= history | fzf +s +m -n2..,.. | sed \"s/ *[0-9]* *//\")\e\C-e\er"'
|
|
||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
|
||||||
bind '"\ec": " \C-e\C-u$(__fcd)\e\C-e\er\C-m"'
|
|
||||||
else
|
|
||||||
bind '"\C-x\C-e": shell-expand-line'
|
|
||||||
bind '"\C-x\C-r": redraw-current-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$(__fsel_tmux)\C-x\C-e\e0P$xa"'
|
|
||||||
else
|
|
||||||
bind '"\C-t": "\e$a \eddi$(__fsel)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
|
||||||
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$(HISTTIMEFORMAT= history | fzf +s +m -n2..,.. | sed \"s/ *[0-9]* *//\")\C-x\C-e\e$a\C-x\C-r"'
|
|
||||||
bind -m vi-command '"\C-r": "i\C-r"'
|
|
||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
|
||||||
bind '"\ec": "\eddi$(__fcd)\C-x\C-e\C-x\C-r\C-m"'
|
|
||||||
bind -m vi-command '"\ec": "i\ec"'
|
|
||||||
fi
|
|
||||||
|
|
||||||
unset __use_tmux
|
|
||||||
|
|
||||||
fi
|
|
||||||
EOFZF
|
|
||||||
else # zsh
|
|
||||||
cat >> $src << "EOFZF"
|
|
||||||
# Key bindings
|
|
||||||
# ------------
|
|
||||||
# CTRL-T - Paste the selected file path(s) into the command line
|
|
||||||
__fsel() {
|
|
||||||
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- | fzf -m | while read item; do
|
|
||||||
printf '%q ' "$item"
|
|
||||||
done
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
|
||||||
|
|
||||||
if [ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ]; then
|
|
||||||
fzf-file-widget() {
|
|
||||||
local height
|
|
||||||
height=${FZF_TMUX_HEIGHT:-40%}
|
|
||||||
if [[ $height =~ %$ ]]; then
|
|
||||||
height="-p ${height%\%}"
|
|
||||||
else
|
|
||||||
height="-l $height"
|
|
||||||
fi
|
|
||||||
tmux split-window $height "zsh -c 'source ~/.fzf.zsh; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
|
||||||
}
|
|
||||||
else
|
|
||||||
fzf-file-widget() {
|
|
||||||
LBUFFER="${LBUFFER}$(__fsel)"
|
|
||||||
zle redisplay
|
|
||||||
}
|
|
||||||
fi
|
|
||||||
zle -N fzf-file-widget
|
|
||||||
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- | fzf +m):-.}"
|
|
||||||
zle reset-prompt
|
|
||||||
}
|
|
||||||
zle -N fzf-cd-widget
|
|
||||||
bindkey '\ec' fzf-cd-widget
|
|
||||||
|
|
||||||
# CTRL-R - Paste the selected command from history into the command line
|
|
||||||
fzf-history-widget() {
|
|
||||||
LBUFFER=$(fc -l 1 | fzf +s +m -n2..,.. | sed "s/ *[0-9*]* *//")
|
|
||||||
zle redisplay
|
|
||||||
}
|
|
||||||
zle -N fzf-history-widget
|
|
||||||
bindkey '^R' fzf-history-widget
|
|
||||||
|
|
||||||
fi
|
|
||||||
EOFZF
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "OK"
|
echo "OK"
|
||||||
done
|
done
|
||||||
|
|
||||||
# fish
|
# fish
|
||||||
has_fish=0
|
has_fish=0
|
||||||
if [ -n "$(which fish)" ]; then
|
if [ -n "$(which fish 2> /dev/null)" ]; then
|
||||||
has_fish=1
|
has_fish=1
|
||||||
echo -n "Generate ~/.config/fish/functions/fzf.fish ... "
|
echo -n "Update fish_user_paths ... "
|
||||||
|
fish << EOF
|
||||||
|
echo \$fish_user_paths | grep $fzf_base/bin > /dev/null
|
||||||
|
or set --universal fish_user_paths \$fish_user_paths $fzf_base/bin
|
||||||
|
EOF
|
||||||
|
[ $? -eq 0 ] && echo "OK" || echo "Failed"
|
||||||
|
|
||||||
mkdir -p ~/.config/fish/functions
|
mkdir -p ~/.config/fish/functions
|
||||||
if [ -n "$binary_error" ]; then
|
if [ -e ~/.config/fish/functions/fzf.fish ]; then
|
||||||
cat > ~/.config/fish/functions/fzf.fish << EOFZF
|
echo -n "Remove unnecessary ~/.config/fish/functions/fzf.fish ... "
|
||||||
function fzf
|
rm -f ~/.config/fish/functions/fzf.fish && echo "OK" || echo "Failed"
|
||||||
$fzf_cmd \$argv
|
|
||||||
end
|
|
||||||
EOFZF
|
|
||||||
else
|
|
||||||
cat > ~/.config/fish/functions/fzf.fish << EOFZF
|
|
||||||
function fzf
|
|
||||||
$fzf_base/bin/fzf \$argv
|
|
||||||
end
|
|
||||||
EOFZF
|
|
||||||
fi
|
fi
|
||||||
echo "OK"
|
|
||||||
|
|
||||||
if [ $key_bindings -eq 0 ]; then
|
if [ $key_bindings -eq 0 ]; then
|
||||||
echo -n "Generate ~/.config/fish/functions/fzf_key_bindings.fish ... "
|
echo -n "Symlink ~/.config/fish/functions/fzf_key_bindings.fish ... "
|
||||||
cat > ~/.config/fish/functions/fzf_key_bindings.fish << "EOFZF"
|
ln -sf $fzf_base/shell/key-bindings.fish \
|
||||||
function fzf_key_bindings
|
~/.config/fish/functions/fzf_key_bindings.fish && echo "OK" || echo "Failed"
|
||||||
# Due to a bug of fish, we cannot use command substitution,
|
|
||||||
# so we use temporary file instead
|
|
||||||
if [ -z "$TMPDIR" ]
|
|
||||||
set -g TMPDIR /tmp
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_list
|
|
||||||
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-
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_list_dir
|
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) \
|
|
||||||
-prune -o -type d -print 2> /dev/null | sed 1d | cut -b3-
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_escape
|
|
||||||
while read item
|
|
||||||
echo -n (echo -n "$item" | sed -E 's/([ "$~'\''([{<>})])/\\\\\\1/g')' '
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_ctrl_t
|
|
||||||
if [ -n "$TMUX_PANE" -a "$FZF_TMUX" != "0" ]
|
|
||||||
tmux split-window (__fzf_tmux_height) "fish -c 'fzf_key_bindings; __fzf_ctrl_t_tmux \\$TMUX_PANE'"
|
|
||||||
else
|
|
||||||
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
|
||||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
|
||||||
commandline -f repaint
|
|
||||||
rm -f $TMPDIR/fzf.result
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_ctrl_t_tmux
|
|
||||||
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
|
||||||
and tmux send-keys -t $argv[1] (cat $TMPDIR/fzf.result | __fzf_escape)
|
|
||||||
rm -f $TMPDIR/fzf.result
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_reverse
|
|
||||||
if which tac > /dev/null
|
|
||||||
tac $argv
|
|
||||||
else
|
|
||||||
tail -r $argv
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_ctrl_r
|
|
||||||
history | __fzf_reverse | fzf +s +m > $TMPDIR/fzf.result
|
|
||||||
and commandline (cat $TMPDIR/fzf.result)
|
|
||||||
commandline -f repaint
|
|
||||||
rm -f $TMPDIR/fzf.result
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_alt_c
|
|
||||||
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
|
||||||
__fzf_list_dir | fzf +m > $TMPDIR/fzf.result
|
|
||||||
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
|
||||||
and cd (cat $TMPDIR/fzf.result)
|
|
||||||
commandline -f repaint
|
|
||||||
rm -f $TMPDIR/fzf.result
|
|
||||||
end
|
|
||||||
|
|
||||||
function __fzf_tmux_height
|
|
||||||
if set -q FZF_TMUX_HEIGHT
|
|
||||||
set height $FZF_TMUX_HEIGHT
|
|
||||||
else
|
|
||||||
set height 40%
|
|
||||||
end
|
|
||||||
if echo $height | \grep -q -E '%$'
|
|
||||||
echo "-p "(echo $height | sed 's/%$//')
|
|
||||||
else
|
|
||||||
echo "-l $height"
|
|
||||||
end
|
|
||||||
set -e height
|
|
||||||
end
|
|
||||||
|
|
||||||
bind \ct '__fzf_ctrl_t'
|
|
||||||
bind \cr '__fzf_ctrl_r'
|
|
||||||
bind \ec '__fzf_alt_c'
|
|
||||||
end
|
|
||||||
EOFZF
|
|
||||||
echo "OK"
|
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -476,12 +252,6 @@ done
|
|||||||
if [ $key_bindings -eq 0 -a $has_fish -eq 1 ]; then
|
if [ $key_bindings -eq 0 -a $has_fish -eq 1 ]; then
|
||||||
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
||||||
append_line "fzf_key_bindings" "$bind_file"
|
append_line "fzf_key_bindings" "$bind_file"
|
||||||
|
|
||||||
echo ' * Due to a known bug of fish, you may have issues running fzf on fish.'
|
|
||||||
echo ' * If that happens, try the following:'
|
|
||||||
echo ' - Remove ~/.config/fish/functions/fzf.fish'
|
|
||||||
echo ' - Place fzf executable in a directory included in $PATH'
|
|
||||||
echo
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat << EOF
|
cat << EOF
|
||||||
|
203
man/man1/fzf.1
Normal file
203
man/man1/fzf.1
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
.ig
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2015 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
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
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 "March 2015" "fzf 0.9.6" "fzf - a command-line fuzzy finder"
|
||||||
|
|
||||||
|
.SH NAME
|
||||||
|
fzf - a command-line fuzzy finder
|
||||||
|
|
||||||
|
.SH SYNOPSIS
|
||||||
|
fzf [options]
|
||||||
|
|
||||||
|
.SH DESCRIPTION
|
||||||
|
fzf is a general-purpose command-line fuzzy finder.
|
||||||
|
|
||||||
|
.SH OPTIONS
|
||||||
|
.SS Search mode
|
||||||
|
.TP
|
||||||
|
.B "-x, --extended"
|
||||||
|
Extended-search mode
|
||||||
|
.TP
|
||||||
|
.B "-e, --extended-exact"
|
||||||
|
Extended-search mode (exact match)
|
||||||
|
.TP
|
||||||
|
.B "-i"
|
||||||
|
Case-insensitive match (default: smart-case match)
|
||||||
|
.TP
|
||||||
|
.B "+i"
|
||||||
|
Case-sensitive match
|
||||||
|
.TP
|
||||||
|
.BI "-n, --nth=" "N[,..]"
|
||||||
|
Comma-separated list of field index expressions for limiting search scope.
|
||||||
|
See \fBFIELD INDEX EXPRESSION\fR for details.
|
||||||
|
.TP
|
||||||
|
.BI "--with-nth=" "N[,..]"
|
||||||
|
Transform the item using the list of index expressions for search
|
||||||
|
.TP
|
||||||
|
.BI "-d, --delimiter=" "STR"
|
||||||
|
Field delimiter regex for \fI--nth\fR and \fI--with-nth\fR (default: AWK-style)
|
||||||
|
.SS Search result
|
||||||
|
.TP
|
||||||
|
.B "+s, --no-sort"
|
||||||
|
Do not sort the result
|
||||||
|
.TP
|
||||||
|
.B "--tac"
|
||||||
|
Reverse the order of the input
|
||||||
|
.RS
|
||||||
|
e.g. \fBhistory | fzf --tac --no-sort\fR
|
||||||
|
.RE
|
||||||
|
.SS Interface
|
||||||
|
.TP
|
||||||
|
.B "-m, --multi"
|
||||||
|
Enable multi-select with tab/shift-tab
|
||||||
|
.TP
|
||||||
|
.B "--ansi"
|
||||||
|
Enable processing of ANSI color codes
|
||||||
|
.TP
|
||||||
|
.B "--no-mouse"
|
||||||
|
Disable mouse
|
||||||
|
.TP
|
||||||
|
.B "+c, --no-color"
|
||||||
|
Disable colors
|
||||||
|
.TP
|
||||||
|
.B "+2, --no-256"
|
||||||
|
Disable 256-color
|
||||||
|
.TP
|
||||||
|
.B "--black"
|
||||||
|
Use black background
|
||||||
|
.TP
|
||||||
|
.B "--reverse"
|
||||||
|
Reverse orientation
|
||||||
|
.TP
|
||||||
|
.BI "--prompt=" "STR"
|
||||||
|
Input prompt (default: '> ')
|
||||||
|
.SS Scripting
|
||||||
|
.TP
|
||||||
|
.BI "-q, --query=" "STR"
|
||||||
|
Start the finder with the given query
|
||||||
|
.TP
|
||||||
|
.B "-1, --select-1"
|
||||||
|
Automatically select the only match
|
||||||
|
.TP
|
||||||
|
.B "-0, --exit-0"
|
||||||
|
Exit immediately when there's no match
|
||||||
|
.TP
|
||||||
|
.BI "-f, --filter=" "STR"
|
||||||
|
Filter mode. Do not start interactive finder. When used with \fB--no-sort\fR,
|
||||||
|
fzf becomes a fuzzy-version of grep.
|
||||||
|
.TP
|
||||||
|
.B "--print-query"
|
||||||
|
Print query as the first line
|
||||||
|
.TP
|
||||||
|
.BI "--expect=" "KEY[,..]"
|
||||||
|
Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
||||||
|
or any single character) that can be used to complete fzf in addition to the
|
||||||
|
default enter key. When this option is set, fzf will print the name of the key
|
||||||
|
pressed as the first line of its output (or as the second line if
|
||||||
|
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
||||||
|
with the default enter key.
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.BI "--toggle-sort=" "KEY"
|
||||||
|
Key to toggle sort (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
||||||
|
or any single character)
|
||||||
|
.TP
|
||||||
|
.B "--sync"
|
||||||
|
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
||||||
|
ncurses finder only after the input stream is complete.
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --multi | fzf --sync\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.SH ENVIRONMENT
|
||||||
|
.TP
|
||||||
|
.B FZF_DEFAULT_COMMAND
|
||||||
|
Default command to use when input is tty
|
||||||
|
.TP
|
||||||
|
.B FZF_DEFAULT_OPTS
|
||||||
|
Default options. e.g. \fB--extended --ansi\fR
|
||||||
|
|
||||||
|
.SH EXIT STATUS
|
||||||
|
.BR 0 " Normal exit"
|
||||||
|
.br
|
||||||
|
.BR 1 " Interrupted with \fBCTRL-C\fR or \fBESC\fR"
|
||||||
|
|
||||||
|
.SH FIELD INDEX EXPRESSION
|
||||||
|
|
||||||
|
A field index expression can be a non-zero integer or a range expression
|
||||||
|
([BEGIN]..[END]). \fI--nth\fR and \fI--with-nth\fR take a comma-separated list
|
||||||
|
of field index expressions.
|
||||||
|
|
||||||
|
.SS Examples
|
||||||
|
.BR 1 " The 1st field"
|
||||||
|
.br
|
||||||
|
.BR 2 " The 2nd field"
|
||||||
|
.br
|
||||||
|
.BR -1 " The last field"
|
||||||
|
.br
|
||||||
|
.BR -2 " The 2nd to last field"
|
||||||
|
.br
|
||||||
|
.BR 3..5 " From the 3rd field to the 5th field"
|
||||||
|
.br
|
||||||
|
.BR 2.. " From the 2nd field to the last field"
|
||||||
|
.br
|
||||||
|
.BR ..-3 " From the 1st field to the 3rd to the last field"
|
||||||
|
.br
|
||||||
|
.BR .. " All the fields"
|
||||||
|
.br
|
||||||
|
|
||||||
|
.SH EXTENDED SEARCH MODE
|
||||||
|
|
||||||
|
With \fI-x\fR or \fI--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
|
||||||
|
|
||||||
|
.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.
|
||||||
|
|
||||||
|
.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.
|
||||||
|
|
||||||
|
.SS Negation
|
||||||
|
If a term is prefixed by !, 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 \fI-e\fR or \fI--extended-exact\fR option
|
||||||
|
(instead of \fI-x\fR or \fI--extended\fR).
|
||||||
|
|
||||||
|
.SH AUTHOR
|
||||||
|
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||||
|
|
||||||
|
.SH SEE ALSO
|
||||||
|
.I https://github.com/junegunn/fzf
|
||||||
|
|
||||||
|
.SH LICENSE
|
||||||
|
MIT
|
167
plugin/fzf.vim
167
plugin/fzf.vim
@@ -21,29 +21,37 @@
|
|||||||
" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||||
" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
let s:min_tmux_width = 10
|
|
||||||
let s:min_tmux_height = 3
|
|
||||||
let s:default_tmux_height = '40%'
|
let s:default_tmux_height = '40%'
|
||||||
let s:launcher = 'xterm -e bash -ic %s'
|
let s:launcher = 'xterm -e bash -ic %s'
|
||||||
let s:fzf_go = expand('<sfile>:h:h').'/bin/fzf'
|
let s:fzf_go = expand('<sfile>:h:h').'/bin/fzf'
|
||||||
let s:fzf_rb = expand('<sfile>:h:h').'/fzf'
|
let s:fzf_rb = expand('<sfile>:h:h').'/fzf'
|
||||||
|
let s:fzf_tmux = expand('<sfile>:h:h').'/bin/fzf-tmux'
|
||||||
|
let s:legacy = 0
|
||||||
|
|
||||||
let s:cpo_save = &cpo
|
let s:cpo_save = &cpo
|
||||||
set cpo&vim
|
set cpo&vim
|
||||||
|
|
||||||
function! s:fzf_exec()
|
function! s:fzf_exec()
|
||||||
if !exists('s:exec')
|
if !exists('s:exec')
|
||||||
call system('type fzf')
|
if executable(s:fzf_go)
|
||||||
if v:shell_error
|
let s:exec = s:fzf_go
|
||||||
let s:exec = executable(s:fzf_go) ?
|
|
||||||
\ s:fzf_go : (executable(s:fzf_rb) ? s:fzf_rb : '')
|
|
||||||
else
|
else
|
||||||
let s:exec = 'fzf'
|
let path = split(system('which fzf 2> /dev/null'), '\n')
|
||||||
|
if !v:shell_error && !empty(path)
|
||||||
|
let s:exec = path[0]
|
||||||
|
elseif executable(s:fzf_rb)
|
||||||
|
let s:exec = s:fzf_rb
|
||||||
|
let s:legacy = 1
|
||||||
|
else
|
||||||
|
call system('type fzf')
|
||||||
|
if v:shell_error
|
||||||
|
throw 'fzf executable not found'
|
||||||
|
else
|
||||||
|
let s:exec = 'fzf'
|
||||||
|
endif
|
||||||
|
endif
|
||||||
endif
|
endif
|
||||||
return s:fzf_exec()
|
return s:exec
|
||||||
elseif empty(s:exec)
|
|
||||||
unlet s:exec
|
|
||||||
throw 'fzf executable not found'
|
|
||||||
else
|
else
|
||||||
return s:exec
|
return s:exec
|
||||||
endif
|
endif
|
||||||
@@ -59,7 +67,7 @@ function! s:tmux_enabled()
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
let s:tmux = 0
|
let s:tmux = 0
|
||||||
if exists('$TMUX')
|
if exists('$TMUX') && executable(s:fzf_tmux)
|
||||||
let output = system('tmux -V')
|
let output = system('tmux -V')
|
||||||
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
||||||
endif
|
endif
|
||||||
@@ -74,8 +82,23 @@ function! s:escape(path)
|
|||||||
return substitute(a:path, ' ', '\\ ', 'g')
|
return substitute(a:path, ' ', '\\ ', 'g')
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
" Upgrade legacy options
|
||||||
|
function! s:upgrade(dict)
|
||||||
|
let copy = copy(a:dict)
|
||||||
|
if has_key(copy, 'tmux')
|
||||||
|
let copy.down = remove(copy, 'tmux')
|
||||||
|
endif
|
||||||
|
if has_key(copy, 'tmux_height')
|
||||||
|
let copy.down = remove(copy, 'tmux_height')
|
||||||
|
endif
|
||||||
|
if has_key(copy, 'tmux_width')
|
||||||
|
let copy.right = remove(copy, 'tmux_width')
|
||||||
|
endif
|
||||||
|
return copy
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! fzf#run(...) abort
|
function! fzf#run(...) abort
|
||||||
let dict = exists('a:1') ? a:1 : {}
|
let dict = exists('a:1') ? s:upgrade(a:1) : {}
|
||||||
let temps = { 'result': tempname() }
|
let temps = { 'result': tempname() }
|
||||||
let optstr = get(dict, 'options', '')
|
let optstr = get(dict, 'options', '')
|
||||||
try
|
try
|
||||||
@@ -99,26 +122,47 @@ function! fzf#run(...) abort
|
|||||||
else
|
else
|
||||||
let prefix = ''
|
let prefix = ''
|
||||||
endif
|
endif
|
||||||
let command = prefix.fzf_exec.' '.optstr.' > '.temps.result
|
let split = s:tmux_enabled() && s:tmux_splittable(dict)
|
||||||
|
let command = prefix.(split ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result
|
||||||
|
|
||||||
if s:tmux_enabled() && s:tmux_splittable(dict)
|
if split
|
||||||
return s:execute_tmux(dict, command, temps)
|
return s:execute_tmux(dict, command, temps)
|
||||||
else
|
else
|
||||||
return s:execute(dict, command, temps)
|
return s:execute(dict, command, temps)
|
||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:present(dict, ...)
|
||||||
|
for key in a:000
|
||||||
|
if !empty(get(a:dict, key, ''))
|
||||||
|
return 1
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
return 0
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
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])
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
return printf('LINES=%d COLUMNS=%d %s %s %s --',
|
||||||
|
\ &lines, &columns, s:fzf_tmux, size, (has_key(a:dict, 'source') ? '' : '-'))
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_splittable(dict)
|
function! s:tmux_splittable(dict)
|
||||||
return
|
return s:present(a:dict, 'up', 'down', 'left', 'right')
|
||||||
\ min([&columns, get(a:dict, 'tmux_width', 0)]) >= s:min_tmux_width ||
|
|
||||||
\ min([&lines, get(a:dict, 'tmux_height', get(a:dict, 'tmux', 0))]) >= s:min_tmux_height
|
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:pushd(dict)
|
function! s:pushd(dict)
|
||||||
if !empty(get(a:dict, 'dir', ''))
|
if s:present(a:dict, 'dir')
|
||||||
let a:dict.prev_dir = getcwd()
|
let a:dict.prev_dir = getcwd()
|
||||||
execute 'chdir '.s:escape(a:dict.dir)
|
execute 'chdir '.s:escape(a:dict.dir)
|
||||||
|
return 1
|
||||||
endif
|
endif
|
||||||
|
return 0
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:popd(dict)
|
function! s:popd(dict)
|
||||||
@@ -129,7 +173,7 @@ endfunction
|
|||||||
|
|
||||||
function! s:execute(dict, command, temps)
|
function! s:execute(dict, command, temps)
|
||||||
call s:pushd(a:dict)
|
call s:pushd(a:dict)
|
||||||
silent !clear
|
silent! !clear 2> /dev/null
|
||||||
if has('gui_running')
|
if has('gui_running')
|
||||||
let launcher = get(a:dict, 'launcher', get(g:, 'fzf_launcher', s:launcher))
|
let launcher = get(a:dict, 'launcher', get(g:, 'fzf_launcher', s:launcher))
|
||||||
let command = printf(launcher, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
let command = printf(launcher, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
||||||
@@ -146,7 +190,7 @@ function! s:execute(dict, command, temps)
|
|||||||
endif
|
endif
|
||||||
return []
|
return []
|
||||||
else
|
else
|
||||||
return s:callback(a:dict, a:temps, 0)
|
return s:callback(a:dict, a:temps)
|
||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
@@ -159,65 +203,27 @@ function! s:env_var(name)
|
|||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:execute_tmux(dict, command, temps)
|
function! s:execute_tmux(dict, command, temps)
|
||||||
let command = s:env_var('FZF_DEFAULT_OPTS').s:env_var('FZF_DEFAULT_COMMAND').a:command
|
let command = a:command
|
||||||
if !empty(get(a:dict, 'dir', ''))
|
if s:pushd(a:dict)
|
||||||
|
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
||||||
let command = 'cd '.s:escape(a:dict.dir).' && '.command
|
let command = 'cd '.s:escape(a:dict.dir).' && '.command
|
||||||
endif
|
endif
|
||||||
|
|
||||||
let splitopt = '-v'
|
call system(command)
|
||||||
if has_key(a:dict, 'tmux_width')
|
return s:callback(a:dict, a:temps)
|
||||||
let splitopt = '-h'
|
|
||||||
let size = a:dict.tmux_width
|
|
||||||
else
|
|
||||||
let size = get(a:dict, 'tmux_height', get(a:dict, 'tmux'))
|
|
||||||
endif
|
|
||||||
|
|
||||||
if type(size) == 1 && size =~ '%$'
|
|
||||||
let sizeopt = '-p '.size[0:-2]
|
|
||||||
else
|
|
||||||
let sizeopt = '-l '.size
|
|
||||||
endif
|
|
||||||
|
|
||||||
let s:pane = substitute(
|
|
||||||
\ system(
|
|
||||||
\ printf(
|
|
||||||
\ 'tmux split-window %s %s -P -F "#{pane_id}" %s',
|
|
||||||
\ splitopt, sizeopt, s:shellesc(command))), '\n', '', 'g')
|
|
||||||
let s:dict = a:dict
|
|
||||||
let s:temps = a:temps
|
|
||||||
|
|
||||||
augroup fzf_tmux
|
|
||||||
autocmd!
|
|
||||||
autocmd VimResized * nested call s:tmux_check()
|
|
||||||
augroup END
|
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_check()
|
function! s:callback(dict, temps)
|
||||||
let panes = split(system('tmux list-panes -a -F "#{pane_id}"'), '\n')
|
|
||||||
|
|
||||||
if index(panes, s:pane) < 0
|
|
||||||
augroup fzf_tmux
|
|
||||||
autocmd!
|
|
||||||
augroup END
|
|
||||||
|
|
||||||
call s:callback(s:dict, s:temps, 1)
|
|
||||||
redraw
|
|
||||||
endif
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
function! s:callback(dict, temps, cd)
|
|
||||||
if !filereadable(a:temps.result)
|
if !filereadable(a:temps.result)
|
||||||
let lines = []
|
let lines = []
|
||||||
else
|
else
|
||||||
if a:cd | call s:pushd(a:dict) | endif
|
|
||||||
|
|
||||||
let lines = readfile(a:temps.result)
|
let lines = readfile(a:temps.result)
|
||||||
if has_key(a:dict, 'sink')
|
if has_key(a:dict, 'sink')
|
||||||
for line in lines
|
for line in lines
|
||||||
if type(a:dict.sink) == 2
|
if type(a:dict.sink) == 2
|
||||||
call a:dict.sink(line)
|
call a:dict.sink(line)
|
||||||
else
|
else
|
||||||
execute a:dict.sink.' '.s:escape(line)
|
execute a:dict.sink s:escape(line)
|
||||||
endif
|
endif
|
||||||
endfor
|
endfor
|
||||||
endif
|
endif
|
||||||
@@ -234,14 +240,39 @@ endfunction
|
|||||||
|
|
||||||
function! s:cmd(bang, ...) abort
|
function! s:cmd(bang, ...) abort
|
||||||
let args = copy(a:000)
|
let args = copy(a:000)
|
||||||
|
if !s:legacy
|
||||||
|
let args = insert(args, '--expect=ctrl-t,ctrl-x,ctrl-v', 0)
|
||||||
|
endif
|
||||||
let opts = {}
|
let opts = {}
|
||||||
if len(args) > 0 && isdirectory(expand(args[-1]))
|
if len(args) > 0 && isdirectory(expand(args[-1]))
|
||||||
let opts.dir = remove(args, -1)
|
let opts.dir = remove(args, -1)
|
||||||
endif
|
endif
|
||||||
if !a:bang
|
if !a:bang
|
||||||
let opts.tmux = get(g:, 'fzf_tmux_height', s:default_tmux_height)
|
let opts.down = get(g:, 'fzf_tmux_height', s:default_tmux_height)
|
||||||
|
endif
|
||||||
|
|
||||||
|
if s:legacy
|
||||||
|
call fzf#run(extend({ 'sink': 'e', 'options': join(args) }, opts))
|
||||||
|
else
|
||||||
|
let output = fzf#run(extend({ 'options': join(args) }, opts))
|
||||||
|
if empty(output)
|
||||||
|
return
|
||||||
|
endif
|
||||||
|
let key = remove(output, 0)
|
||||||
|
if key == 'ctrl-t' | let cmd = 'tabedit'
|
||||||
|
elseif key == 'ctrl-x' | let cmd = 'split'
|
||||||
|
elseif key == 'ctrl-v' | let cmd = 'vsplit'
|
||||||
|
else | let cmd = 'e'
|
||||||
|
endif
|
||||||
|
try
|
||||||
|
call s:pushd(opts)
|
||||||
|
for item in output
|
||||||
|
execute cmd s:escape(item)
|
||||||
|
endfor
|
||||||
|
finally
|
||||||
|
call s:popd(opts)
|
||||||
|
endtry
|
||||||
endif
|
endif
|
||||||
call fzf#run(extend({ 'sink': 'e', 'options': join(args) }, opts))
|
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
command! -nargs=* -complete=dir -bang FZF call s:cmd('<bang>' == '!', <f-args>)
|
command! -nargs=* -complete=dir -bang FZF call s:cmd('<bang>' == '!', <f-args>)
|
||||||
|
@@ -14,17 +14,17 @@ _fzf_orig_completion_filter() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_opts_completion() {
|
_fzf_opts_completion() {
|
||||||
local cur prev opts
|
local cur opts
|
||||||
COMPREPLY=()
|
COMPREPLY=()
|
||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
|
||||||
opts="
|
opts="
|
||||||
-x --extended
|
-x --extended
|
||||||
-e --extended-exact
|
-e --extended-exact
|
||||||
-i +i
|
-i +i
|
||||||
-n --nth
|
-n --nth
|
||||||
-d --delimiter
|
-d --delimiter
|
||||||
-s --sort +s
|
+s --no-sort
|
||||||
|
--tac
|
||||||
-m --multi
|
-m --multi
|
||||||
--no-mouse
|
--no-mouse
|
||||||
+c --no-color
|
+c --no-color
|
||||||
@@ -36,14 +36,8 @@ _fzf_opts_completion() {
|
|||||||
-1 --select-1
|
-1 --select-1
|
||||||
-0 --exit-0
|
-0 --exit-0
|
||||||
-f --filter
|
-f --filter
|
||||||
--print-query"
|
--print-query
|
||||||
|
--sync"
|
||||||
case "${prev}" in
|
|
||||||
--sort|-s)
|
|
||||||
COMPREPLY=( $(compgen -W "$(seq 2000 1000 10000)" -- ${cur}) )
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
if [[ ${cur} =~ ^-|\+ ]]; then
|
||||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||||
@@ -88,7 +82,7 @@ _fzf_path_completion() {
|
|||||||
[ "$dir" = './' ] && dir=''
|
[ "$dir" = './' ] && dir=''
|
||||||
tput sc
|
tput sc
|
||||||
matches=$(find -L "$dir"* $1 2> /dev/null | fzf $FZF_COMPLETION_OPTS $2 -q "$leftover" | while read item; do
|
matches=$(find -L "$dir"* $1 2> /dev/null | fzf $FZF_COMPLETION_OPTS $2 -q "$leftover" | while read item; do
|
||||||
printf '%q ' "$item"
|
printf "%q$3 " "$item"
|
||||||
done)
|
done)
|
||||||
matches=${matches% }
|
matches=${matches% }
|
||||||
if [ -n "$matches" ]; then
|
if [ -n "$matches" ]; then
|
||||||
@@ -103,6 +97,7 @@ _fzf_path_completion() {
|
|||||||
[[ "$dir" =~ /$ ]] || dir="$dir"/
|
[[ "$dir" =~ /$ ]] || dir="$dir"/
|
||||||
done
|
done
|
||||||
else
|
else
|
||||||
|
shift
|
||||||
shift
|
shift
|
||||||
shift
|
shift
|
||||||
_fzf_handle_dynamic_completion "$cmd" "$@"
|
_fzf_handle_dynamic_completion "$cmd" "$@"
|
||||||
@@ -136,19 +131,19 @@ _fzf_list_completion() {
|
|||||||
_fzf_all_completion() {
|
_fzf_all_completion() {
|
||||||
_fzf_path_completion \
|
_fzf_path_completion \
|
||||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||||
"-m" "$@"
|
"-m" "" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_file_completion() {
|
_fzf_file_completion() {
|
||||||
_fzf_path_completion \
|
_fzf_path_completion \
|
||||||
"-name .git -prune -o -name .svn -prune -o -type f -print -o -type l -print" \
|
"-name .git -prune -o -name .svn -prune -o -type f -print -o -type l -print" \
|
||||||
"-m" "$@"
|
"-m" "" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_dir_completion() {
|
_fzf_dir_completion() {
|
||||||
_fzf_path_completion \
|
_fzf_path_completion \
|
||||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||||
"" "$@"
|
"" "/" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_kill_completion() {
|
_fzf_kill_completion() {
|
||||||
@@ -219,7 +214,7 @@ fi
|
|||||||
|
|
||||||
# Directory
|
# Directory
|
||||||
for cmd in $d_cmds; do
|
for cmd in $d_cmds; do
|
||||||
complete -F _fzf_dir_completion -o default -o bashdefault $cmd
|
complete -F _fzf_dir_completion -o nospace -o plusdirs $cmd
|
||||||
done
|
done
|
||||||
|
|
||||||
# File
|
# File
|
75
shell/key-bindings.bash
Normal file
75
shell/key-bindings.bash
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
# Key bindings
|
||||||
|
# ------------
|
||||||
|
__fsel() {
|
||||||
|
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- | fzf -m | while read item; do
|
||||||
|
printf '%q ' "$item"
|
||||||
|
done
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
|
__fsel_tmux() {
|
||||||
|
local height
|
||||||
|
height=${FZF_TMUX_HEIGHT:-40%}
|
||||||
|
if [[ $height =~ %$ ]]; then
|
||||||
|
height="-p ${height%\%}"
|
||||||
|
else
|
||||||
|
height="-l $height"
|
||||||
|
fi
|
||||||
|
tmux split-window $height "cd $(printf %q "$PWD");bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
||||||
|
}
|
||||||
|
|
||||||
|
__fcd() {
|
||||||
|
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- | fzf +m) && printf 'cd %q' "$dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
__use_tmux=0
|
||||||
|
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
||||||
|
|
||||||
|
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||||
|
# Required to refresh the prompt after fzf
|
||||||
|
bind '"\er": redraw-current-line'
|
||||||
|
|
||||||
|
# CTRL-T - Paste the selected file path into the command line
|
||||||
|
if [ $__use_tmux -eq 1 ]; then
|
||||||
|
bind '"\C-t": " \C-u \C-a\C-k$(__fsel_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$(__fsel)\e\C-e\C-y\C-a\C-y\ey\C-h\C-e\er \C-h"'
|
||||||
|
fi
|
||||||
|
|
||||||
|
# CTRL-R - Paste the selected command from history into the command line
|
||||||
|
bind '"\C-r": " \C-e\C-u$(HISTTIMEFORMAT= history | fzf +s --tac +m -n2..,.. --toggle-sort=ctrl-r | sed \"s/ *[0-9]* *//\")\e\C-e\er"'
|
||||||
|
|
||||||
|
# ALT-C - cd into the selected directory
|
||||||
|
bind '"\ec": " \C-e\C-u$(__fcd)\e\C-e\er\C-m"'
|
||||||
|
else
|
||||||
|
bind '"\C-x\C-e": shell-expand-line'
|
||||||
|
bind '"\C-x\C-r": redraw-current-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$(__fsel_tmux)\C-x\C-e\e0P$xa"'
|
||||||
|
else
|
||||||
|
bind '"\C-t": "\e$a \eddi$(__fsel)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
||||||
|
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$(HISTTIMEFORMAT= history | fzf +s --tac +m -n2..,.. | sed \"s/ *[0-9]* *//\")\C-x\C-e\e$a\C-x\C-r"'
|
||||||
|
bind -m vi-command '"\C-r": "i\C-r"'
|
||||||
|
|
||||||
|
# ALT-C - cd into the selected directory
|
||||||
|
bind '"\ec": "\eddi$(__fcd)\C-x\C-e\C-x\C-r\C-m"'
|
||||||
|
bind -m vi-command '"\ec": "i\ec"'
|
||||||
|
fi
|
||||||
|
|
||||||
|
unset __use_tmux
|
||||||
|
|
||||||
|
fi
|
80
shell/key-bindings.fish
Normal file
80
shell/key-bindings.fish
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
# Key bindings
|
||||||
|
# ------------
|
||||||
|
function fzf_key_bindings
|
||||||
|
# Due to a bug of fish, we cannot use command substitution,
|
||||||
|
# so we use temporary file instead
|
||||||
|
if [ -z "$TMPDIR" ]
|
||||||
|
set -g TMPDIR /tmp
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_list
|
||||||
|
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-
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_list_dir
|
||||||
|
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) \
|
||||||
|
-prune -o -type d -print 2> /dev/null | sed 1d | cut -b3-
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_escape
|
||||||
|
while read item
|
||||||
|
echo -n (echo -n "$item" | sed -E 's/([ "$~'\''([{<>})])/\\\\\\1/g')' '
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_ctrl_t
|
||||||
|
if [ -n "$TMUX_PANE" -a "$FZF_TMUX" != "0" ]
|
||||||
|
# FIXME need to handle directory with double-quotes
|
||||||
|
tmux split-window (__fzf_tmux_height) "cd \"$PWD\";fish -c 'fzf_key_bindings; __fzf_ctrl_t_tmux \\$TMUX_PANE'"
|
||||||
|
else
|
||||||
|
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
||||||
|
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||||
|
commandline -f repaint
|
||||||
|
rm -f $TMPDIR/fzf.result
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_ctrl_t_tmux
|
||||||
|
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
||||||
|
and tmux send-keys -t $argv[1] (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||||
|
rm -f $TMPDIR/fzf.result
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_ctrl_r
|
||||||
|
history | fzf +s +m --toggle-sort=ctrl-r > $TMPDIR/fzf.result
|
||||||
|
and commandline (cat $TMPDIR/fzf.result)
|
||||||
|
commandline -f repaint
|
||||||
|
rm -f $TMPDIR/fzf.result
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_alt_c
|
||||||
|
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
||||||
|
__fzf_list_dir | fzf +m > $TMPDIR/fzf.result
|
||||||
|
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
||||||
|
and cd (cat $TMPDIR/fzf.result)
|
||||||
|
commandline -f repaint
|
||||||
|
rm -f $TMPDIR/fzf.result
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_tmux_height
|
||||||
|
if set -q FZF_TMUX_HEIGHT
|
||||||
|
set height $FZF_TMUX_HEIGHT
|
||||||
|
else
|
||||||
|
set height 40%
|
||||||
|
end
|
||||||
|
if echo $height | \grep -q -E '%$'
|
||||||
|
echo "-p "(echo $height | sed 's/%$//')
|
||||||
|
else
|
||||||
|
echo "-l $height"
|
||||||
|
end
|
||||||
|
set -e height
|
||||||
|
end
|
||||||
|
|
||||||
|
bind \ct '__fzf_ctrl_t'
|
||||||
|
bind \cr '__fzf_ctrl_r'
|
||||||
|
bind \ec '__fzf_alt_c'
|
||||||
|
end
|
||||||
|
|
59
shell/key-bindings.zsh
Normal file
59
shell/key-bindings.zsh
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
# Key bindings
|
||||||
|
# ------------
|
||||||
|
# CTRL-T - Paste the selected file path(s) into the command line
|
||||||
|
__fsel() {
|
||||||
|
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- | fzf -m | while read item; do
|
||||||
|
printf '%q ' "$item"
|
||||||
|
done
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
|
if [ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ]; then
|
||||||
|
fzf-file-widget() {
|
||||||
|
local height
|
||||||
|
height=${FZF_TMUX_HEIGHT:-40%}
|
||||||
|
if [[ $height =~ %$ ]]; then
|
||||||
|
height="-p ${height%\%}"
|
||||||
|
else
|
||||||
|
height="-l $height"
|
||||||
|
fi
|
||||||
|
tmux split-window $height "cd $(printf %q "$PWD");zsh -c 'source ~/.fzf.zsh; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
||||||
|
}
|
||||||
|
else
|
||||||
|
fzf-file-widget() {
|
||||||
|
LBUFFER="${LBUFFER}$(__fsel)"
|
||||||
|
zle redisplay
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
zle -N fzf-file-widget
|
||||||
|
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- | fzf +m):-.}"
|
||||||
|
zle reset-prompt
|
||||||
|
}
|
||||||
|
zle -N fzf-cd-widget
|
||||||
|
bindkey '\ec' fzf-cd-widget
|
||||||
|
|
||||||
|
# CTRL-R - Paste the selected command from history into the command line
|
||||||
|
fzf-history-widget() {
|
||||||
|
local selected
|
||||||
|
if selected=$(fc -l 1 | fzf +s --tac +m -n2..,.. --toggle-sort=ctrl-r -q "$LBUFFER"); then
|
||||||
|
num=$(echo "$selected" | head -1 | awk '{print $1}' | sed 's/[^0-9]//g')
|
||||||
|
LBUFFER=!$num
|
||||||
|
zle expand-history
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
}
|
||||||
|
zle -N fzf-history-widget
|
||||||
|
bindkey '^R' fzf-history-widget
|
||||||
|
|
||||||
|
fi
|
||||||
|
|
@@ -6,7 +6,7 @@ RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git
|
|||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
RUN cd / && curl \
|
RUN cd / && curl \
|
||||||
https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
ENV GOPATH /go
|
||||||
|
@@ -6,7 +6,7 @@ RUN yum install -y git gcc make tar ncurses-devel
|
|||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
RUN cd / && curl \
|
RUN cd / && curl \
|
||||||
https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
ENV GOPATH /go
|
||||||
|
@@ -7,7 +7,7 @@ RUN apt-get update && apt-get -y upgrade && \
|
|||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
RUN cd / && curl \
|
RUN cd / && curl \
|
||||||
https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
ENV GOPATH /go
|
||||||
|
@@ -12,6 +12,10 @@ import "strings"
|
|||||||
|
|
||||||
// FuzzyMatch performs fuzzy-match
|
// FuzzyMatch performs fuzzy-match
|
||||||
func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
||||||
|
if len(pattern) == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
runes := []rune(*input)
|
||||||
|
|
||||||
// 0. (FIXME) How to find the shortest match?
|
// 0. (FIXME) How to find the shortest match?
|
||||||
@@ -66,6 +70,10 @@ func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
// ExactMatchStrings performs exact-match using strings package.
|
// ExactMatchStrings performs exact-match using strings package.
|
||||||
// Currently not used.
|
// Currently not used.
|
||||||
func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
||||||
|
if len(pattern) == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
var str string
|
var str string
|
||||||
if caseSensitive {
|
if caseSensitive {
|
||||||
str = *input
|
str = *input
|
||||||
@@ -88,6 +96,10 @@ func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int,
|
|||||||
// We might try to implement better algorithms in the future:
|
// We might try to implement better algorithms in the future:
|
||||||
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
||||||
func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
||||||
|
if len(pattern) == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
runes := []rune(*input)
|
||||||
numRunes := len(runes)
|
numRunes := len(runes)
|
||||||
plen := len(pattern)
|
plen := len(pattern)
|
||||||
|
@@ -42,3 +42,11 @@ func TestSuffixMatch(t *testing.T) {
|
|||||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)
|
assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)
|
||||||
assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)
|
assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEmptyPattern(t *testing.T) {
|
||||||
|
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
||||||
|
assertMatch(t, ExactMatchStrings, 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)
|
||||||
|
}
|
||||||
|
148
src/ansi.go
Normal file
148
src/ansi.go
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ansiOffset struct {
|
||||||
|
offset [2]int32
|
||||||
|
color ansiState
|
||||||
|
}
|
||||||
|
|
||||||
|
type ansiState struct {
|
||||||
|
fg int
|
||||||
|
bg int
|
||||||
|
bold bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ansiState) colored() bool {
|
||||||
|
return s.fg != -1 || s.bg != -1 || s.bold
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ansiState) equals(t *ansiState) bool {
|
||||||
|
if t == nil {
|
||||||
|
return !s.colored()
|
||||||
|
}
|
||||||
|
return s.fg == t.fg && s.bg == t.bg && s.bold == t.bold
|
||||||
|
}
|
||||||
|
|
||||||
|
var ansiRegex *regexp.Regexp
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractColor(str *string) (*string, []ansiOffset) {
|
||||||
|
var offsets []ansiOffset
|
||||||
|
|
||||||
|
var output bytes.Buffer
|
||||||
|
var state *ansiState
|
||||||
|
|
||||||
|
idx := 0
|
||||||
|
for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {
|
||||||
|
output.WriteString((*str)[idx:offset[0]])
|
||||||
|
newState := interpretCode((*str)[offset[0]:offset[1]], state)
|
||||||
|
|
||||||
|
if !newState.equals(state) {
|
||||||
|
if state != nil {
|
||||||
|
// Update last offset
|
||||||
|
(&offsets[len(offsets)-1]).offset[1] = int32(output.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
if newState.colored() {
|
||||||
|
// Append new offset
|
||||||
|
state = newState
|
||||||
|
newLen := int32(utf8.RuneCount(output.Bytes()))
|
||||||
|
offsets = append(offsets, ansiOffset{[2]int32{newLen, newLen}, *state})
|
||||||
|
} else {
|
||||||
|
// Discard state
|
||||||
|
state = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idx = offset[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
rest := (*str)[idx:]
|
||||||
|
if len(rest) > 0 {
|
||||||
|
output.WriteString(rest)
|
||||||
|
if state != nil {
|
||||||
|
// Update last offset
|
||||||
|
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outputStr := output.String()
|
||||||
|
return &outputStr, offsets
|
||||||
|
}
|
||||||
|
|
||||||
|
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
||||||
|
// State
|
||||||
|
var state *ansiState
|
||||||
|
if prevState == nil {
|
||||||
|
state = &ansiState{-1, -1, false}
|
||||||
|
} else {
|
||||||
|
state = &ansiState{prevState.fg, prevState.bg, prevState.bold}
|
||||||
|
}
|
||||||
|
if ansiCode[len(ansiCode)-1] == 'K' {
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
ptr := &state.fg
|
||||||
|
state256 := 0
|
||||||
|
|
||||||
|
init := func() {
|
||||||
|
state.fg = -1
|
||||||
|
state.bg = -1
|
||||||
|
state.bold = false
|
||||||
|
state256 = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
ansiCode = ansiCode[2 : len(ansiCode)-1]
|
||||||
|
if len(ansiCode) == 0 {
|
||||||
|
init()
|
||||||
|
}
|
||||||
|
for _, code := range strings.Split(ansiCode, ";") {
|
||||||
|
if num, err := strconv.Atoi(code); err == nil {
|
||||||
|
switch state256 {
|
||||||
|
case 0:
|
||||||
|
switch num {
|
||||||
|
case 38:
|
||||||
|
ptr = &state.fg
|
||||||
|
state256++
|
||||||
|
case 48:
|
||||||
|
ptr = &state.bg
|
||||||
|
state256++
|
||||||
|
case 39:
|
||||||
|
state.fg = -1
|
||||||
|
case 49:
|
||||||
|
state.bg = -1
|
||||||
|
case 1:
|
||||||
|
state.bold = true
|
||||||
|
case 0:
|
||||||
|
init()
|
||||||
|
default:
|
||||||
|
if num >= 30 && num <= 37 {
|
||||||
|
state.fg = num - 30
|
||||||
|
} else if num >= 40 && num <= 47 {
|
||||||
|
state.bg = num - 40
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 1:
|
||||||
|
switch num {
|
||||||
|
case 5:
|
||||||
|
state256++
|
||||||
|
default:
|
||||||
|
state256 = 0
|
||||||
|
}
|
||||||
|
case 2:
|
||||||
|
*ptr = num
|
||||||
|
state256 = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return state
|
||||||
|
}
|
107
src/ansi_test.go
Normal file
107
src/ansi_test.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestExtractColor(t *testing.T) {
|
||||||
|
assert := func(offset ansiOffset, b int32, e int32, fg int, bg int, bold bool) {
|
||||||
|
if offset.offset[0] != b || offset.offset[1] != e ||
|
||||||
|
offset.color.fg != fg || offset.color.bg != bg || offset.color.bold != bold {
|
||||||
|
t.Error(offset, b, e, fg, bg, bold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
src := "hello world"
|
||||||
|
clean := "\x1b[0m"
|
||||||
|
check := func(assertion func(ansiOffsets []ansiOffset)) {
|
||||||
|
output, ansiOffsets := extractColor(&src)
|
||||||
|
if *output != "hello world" {
|
||||||
|
t.Errorf("Invalid output: {}", output)
|
||||||
|
}
|
||||||
|
fmt.Println(src, ansiOffsets, clean)
|
||||||
|
assertion(ansiOffsets)
|
||||||
|
}
|
||||||
|
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) > 0 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "\x1b[0mhello world"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) > 0 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "\x1b[1mhello world"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "\x1b[1mhello \x1b[mworld"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 6, -1, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "\x1b[1mhello \x1b[Kworld"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[34;45;1mworld"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 9, 4, 5, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 3 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 8, 4, 233, true)
|
||||||
|
assert(offsets[1], 8, 9, 161, 233, true)
|
||||||
|
assert(offsets[2], 10, 11, 161, -1, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
// {38,48};5;{38,48}
|
||||||
|
src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
|
||||||
|
check(func(offsets []ansiOffset) {
|
||||||
|
if len(offsets) != 2 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 9, 38, 48, true)
|
||||||
|
assert(offsets[1], 9, 10, 48, 38, true)
|
||||||
|
})
|
||||||
|
}
|
@@ -5,7 +5,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Current version
|
// Current version
|
||||||
const Version = "0.9.3"
|
const Version = "0.9.7"
|
||||||
|
|
||||||
// fzf events
|
// fzf events
|
||||||
const (
|
const (
|
||||||
|
90
src/core.go
90
src/core.go
@@ -44,7 +44,7 @@ func initProcs() {
|
|||||||
/*
|
/*
|
||||||
Reader -> EvtReadFin
|
Reader -> EvtReadFin
|
||||||
Reader -> EvtReadNew -> Matcher (restart)
|
Reader -> EvtReadNew -> Matcher (restart)
|
||||||
Terminal -> EvtSearchNew -> Matcher (restart)
|
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
||||||
Matcher -> EvtSearchProgress -> Terminal (update info)
|
Matcher -> EvtSearchProgress -> Terminal (update info)
|
||||||
Matcher -> EvtSearchFin -> Terminal (update list)
|
Matcher -> EvtSearchFin -> Terminal (update list)
|
||||||
*/
|
*/
|
||||||
@@ -54,6 +54,7 @@ func Run(options *Options) {
|
|||||||
initProcs()
|
initProcs()
|
||||||
|
|
||||||
opts := ParseOptions()
|
opts := ParseOptions()
|
||||||
|
sort := opts.Sort > 0
|
||||||
|
|
||||||
if opts.Version {
|
if opts.Version {
|
||||||
fmt.Println(Version)
|
fmt.Println(Version)
|
||||||
@@ -63,14 +64,36 @@ func Run(options *Options) {
|
|||||||
// Event channel
|
// Event channel
|
||||||
eventBox := util.NewEventBox()
|
eventBox := util.NewEventBox()
|
||||||
|
|
||||||
|
// ANSI code processor
|
||||||
|
ansiProcessor := func(data *string) (*string, []ansiOffset) {
|
||||||
|
// By default, we do nothing
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if opts.Ansi {
|
||||||
|
if opts.Color {
|
||||||
|
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
||||||
|
return extractColor(data)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// When color is disabled but ansi option is given,
|
||||||
|
// we simply strip out ANSI codes from the input
|
||||||
|
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
||||||
|
trimmed, _ := extractColor(data)
|
||||||
|
return trimmed, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Chunk list
|
// Chunk list
|
||||||
var chunkList *ChunkList
|
var chunkList *ChunkList
|
||||||
if len(opts.WithNth) == 0 {
|
if len(opts.WithNth) == 0 {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data *string, index int) *Item {
|
||||||
|
data, colors := ansiProcessor(data)
|
||||||
return &Item{
|
return &Item{
|
||||||
text: data,
|
text: data,
|
||||||
index: uint32(index),
|
index: uint32(index),
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
colors: colors,
|
||||||
|
rank: Rank{0, 0, uint32(index)}}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data *string, index int) *Item {
|
||||||
@@ -79,39 +102,58 @@ func Run(options *Options) {
|
|||||||
text: Transform(tokens, opts.WithNth).whole,
|
text: Transform(tokens, opts.WithNth).whole,
|
||||||
origText: data,
|
origText: data,
|
||||||
index: uint32(index),
|
index: uint32(index),
|
||||||
|
colors: nil,
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
rank: Rank{0, 0, uint32(index)}}
|
||||||
|
|
||||||
|
trimmed, colors := ansiProcessor(item.text)
|
||||||
|
item.text = trimmed
|
||||||
|
item.colors = colors
|
||||||
return &item
|
return &item
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reader
|
// Reader
|
||||||
reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}
|
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
||||||
go reader.ReadSource()
|
if !streamingFilter {
|
||||||
|
reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}
|
||||||
|
go reader.ReadSource()
|
||||||
|
}
|
||||||
|
|
||||||
// Matcher
|
// Matcher
|
||||||
patternBuilder := func(runes []rune) *Pattern {
|
patternBuilder := func(runes []rune) *Pattern {
|
||||||
return BuildPattern(
|
return BuildPattern(
|
||||||
opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)
|
opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)
|
||||||
}
|
}
|
||||||
matcher := NewMatcher(patternBuilder, opts.Sort > 0, eventBox)
|
matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)
|
||||||
|
|
||||||
// Filtering mode
|
// Filtering mode
|
||||||
if opts.Filter != nil {
|
if opts.Filter != nil {
|
||||||
pattern := patternBuilder([]rune(*opts.Filter))
|
|
||||||
|
|
||||||
eventBox.Unwatch(EvtReadNew)
|
|
||||||
eventBox.WaitFor(EvtReadFin)
|
|
||||||
|
|
||||||
snapshot, _ := chunkList.Snapshot()
|
|
||||||
merger, _ := matcher.scan(MatchRequest{
|
|
||||||
chunks: snapshot,
|
|
||||||
pattern: pattern})
|
|
||||||
|
|
||||||
if opts.PrintQuery {
|
if opts.PrintQuery {
|
||||||
fmt.Println(*opts.Filter)
|
fmt.Println(*opts.Filter)
|
||||||
}
|
}
|
||||||
for i := 0; i < merger.Length(); i++ {
|
|
||||||
fmt.Println(merger.Get(i).AsString())
|
pattern := patternBuilder([]rune(*opts.Filter))
|
||||||
|
|
||||||
|
if streamingFilter {
|
||||||
|
reader := Reader{
|
||||||
|
func(str string) {
|
||||||
|
item := chunkList.trans(&str, 0)
|
||||||
|
if pattern.MatchItem(item) {
|
||||||
|
fmt.Println(*item.text)
|
||||||
|
}
|
||||||
|
}, eventBox}
|
||||||
|
reader.ReadSource()
|
||||||
|
} else {
|
||||||
|
eventBox.Unwatch(EvtReadNew)
|
||||||
|
eventBox.WaitFor(EvtReadFin)
|
||||||
|
|
||||||
|
snapshot, _ := chunkList.Snapshot()
|
||||||
|
merger, _ := matcher.scan(MatchRequest{
|
||||||
|
chunks: snapshot,
|
||||||
|
pattern: pattern})
|
||||||
|
for i := 0; i < merger.Length(); i++ {
|
||||||
|
fmt.Println(merger.Get(i).AsString())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
@@ -149,11 +191,14 @@ func Run(options *Options) {
|
|||||||
reading = reading && evt == EvtReadNew
|
reading = reading && evt == EvtReadNew
|
||||||
snapshot, count := chunkList.Snapshot()
|
snapshot, count := chunkList.Snapshot()
|
||||||
terminal.UpdateCount(count, !reading)
|
terminal.UpdateCount(count, !reading)
|
||||||
matcher.Reset(snapshot, terminal.Input(), false, !reading)
|
matcher.Reset(snapshot, terminal.Input(), false, !reading, sort)
|
||||||
|
|
||||||
case EvtSearchNew:
|
case EvtSearchNew:
|
||||||
|
if value.(bool) {
|
||||||
|
sort = !sort
|
||||||
|
}
|
||||||
snapshot, _ := chunkList.Snapshot()
|
snapshot, _ := chunkList.Snapshot()
|
||||||
matcher.Reset(snapshot, terminal.Input(), true, !reading)
|
matcher.Reset(snapshot, terminal.Input(), true, !reading, sort)
|
||||||
delay = false
|
delay = false
|
||||||
|
|
||||||
case EvtSearchProgress:
|
case EvtSearchProgress:
|
||||||
@@ -175,6 +220,9 @@ func Run(options *Options) {
|
|||||||
if opts.PrintQuery {
|
if opts.PrintQuery {
|
||||||
fmt.Println(opts.Query)
|
fmt.Println(opts.Query)
|
||||||
}
|
}
|
||||||
|
if len(opts.Expect) > 0 {
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
fmt.Println(val.Get(i).AsString())
|
fmt.Println(val.Get(i).AsString())
|
||||||
}
|
}
|
||||||
|
@@ -61,10 +61,20 @@ const (
|
|||||||
PgUp
|
PgUp
|
||||||
PgDn
|
PgDn
|
||||||
|
|
||||||
AltB
|
F1
|
||||||
AltF
|
F2
|
||||||
AltD
|
F3
|
||||||
|
F4
|
||||||
|
|
||||||
AltBS
|
AltBS
|
||||||
|
AltA
|
||||||
|
AltB
|
||||||
|
AltC
|
||||||
|
AltD
|
||||||
|
AltE
|
||||||
|
AltF
|
||||||
|
|
||||||
|
AltZ = AltA + 'z' - 'a'
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pallete
|
// Pallete
|
||||||
@@ -78,6 +88,7 @@ const (
|
|||||||
ColInfo
|
ColInfo
|
||||||
ColCursor
|
ColCursor
|
||||||
ColSelected
|
ColSelected
|
||||||
|
ColUser
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -103,14 +114,17 @@ var (
|
|||||||
_buf []byte
|
_buf []byte
|
||||||
_in *os.File
|
_in *os.File
|
||||||
_color func(int, bool) C.int
|
_color func(int, bool) C.int
|
||||||
|
_colorMap map[int]int
|
||||||
_prevDownTime time.Time
|
_prevDownTime time.Time
|
||||||
_prevDownY int
|
_prevDownY int
|
||||||
_clickY []int
|
_clickY []int
|
||||||
|
DarkBG C.short
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
_prevDownTime = time.Unix(0, 0)
|
_prevDownTime = time.Unix(0, 0)
|
||||||
_clickY = []int{}
|
_clickY = []int{}
|
||||||
|
_colorMap = make(map[int]int)
|
||||||
}
|
}
|
||||||
|
|
||||||
func attrColored(pair int, bold bool) C.int {
|
func attrColored(pair int, bold bool) C.int {
|
||||||
@@ -200,23 +214,25 @@ func Init(color bool, color256 bool, black bool, mouse bool) {
|
|||||||
bg = -1
|
bg = -1
|
||||||
}
|
}
|
||||||
if color256 {
|
if color256 {
|
||||||
|
DarkBG = 236
|
||||||
C.init_pair(ColPrompt, 110, bg)
|
C.init_pair(ColPrompt, 110, bg)
|
||||||
C.init_pair(ColMatch, 108, bg)
|
C.init_pair(ColMatch, 108, bg)
|
||||||
C.init_pair(ColCurrent, 254, 236)
|
C.init_pair(ColCurrent, 254, DarkBG)
|
||||||
C.init_pair(ColCurrentMatch, 151, 236)
|
C.init_pair(ColCurrentMatch, 151, DarkBG)
|
||||||
C.init_pair(ColSpinner, 148, bg)
|
C.init_pair(ColSpinner, 148, bg)
|
||||||
C.init_pair(ColInfo, 144, bg)
|
C.init_pair(ColInfo, 144, bg)
|
||||||
C.init_pair(ColCursor, 161, 236)
|
C.init_pair(ColCursor, 161, DarkBG)
|
||||||
C.init_pair(ColSelected, 168, 236)
|
C.init_pair(ColSelected, 168, DarkBG)
|
||||||
} else {
|
} else {
|
||||||
|
DarkBG = C.COLOR_BLACK
|
||||||
C.init_pair(ColPrompt, C.COLOR_BLUE, bg)
|
C.init_pair(ColPrompt, C.COLOR_BLUE, bg)
|
||||||
C.init_pair(ColMatch, C.COLOR_GREEN, bg)
|
C.init_pair(ColMatch, C.COLOR_GREEN, bg)
|
||||||
C.init_pair(ColCurrent, C.COLOR_YELLOW, C.COLOR_BLACK)
|
C.init_pair(ColCurrent, C.COLOR_YELLOW, DarkBG)
|
||||||
C.init_pair(ColCurrentMatch, C.COLOR_GREEN, C.COLOR_BLACK)
|
C.init_pair(ColCurrentMatch, C.COLOR_GREEN, DarkBG)
|
||||||
C.init_pair(ColSpinner, C.COLOR_GREEN, bg)
|
C.init_pair(ColSpinner, C.COLOR_GREEN, bg)
|
||||||
C.init_pair(ColInfo, C.COLOR_WHITE, bg)
|
C.init_pair(ColInfo, C.COLOR_WHITE, bg)
|
||||||
C.init_pair(ColCursor, C.COLOR_RED, C.COLOR_BLACK)
|
C.init_pair(ColCursor, C.COLOR_RED, DarkBG)
|
||||||
C.init_pair(ColSelected, C.COLOR_MAGENTA, C.COLOR_BLACK)
|
C.init_pair(ColSelected, C.COLOR_MAGENTA, DarkBG)
|
||||||
}
|
}
|
||||||
_color = attrColored
|
_color = attrColored
|
||||||
} else {
|
} else {
|
||||||
@@ -318,6 +334,14 @@ func escSequence(sz *int) Event {
|
|||||||
return Event{CtrlE, 0, nil}
|
return Event{CtrlE, 0, nil}
|
||||||
case 77:
|
case 77:
|
||||||
return mouseSequence(sz)
|
return mouseSequence(sz)
|
||||||
|
case 80:
|
||||||
|
return Event{F1, 0, nil}
|
||||||
|
case 81:
|
||||||
|
return Event{F2, 0, nil}
|
||||||
|
case 82:
|
||||||
|
return Event{F3, 0, nil}
|
||||||
|
case 83:
|
||||||
|
return Event{F4, 0, nil}
|
||||||
case 49, 50, 51, 52, 53, 54:
|
case 49, 50, 51, 52, 53, 54:
|
||||||
if len(_buf) < 4 {
|
if len(_buf) < 4 {
|
||||||
return Event{Invalid, 0, nil}
|
return Event{Invalid, 0, nil}
|
||||||
@@ -363,6 +387,9 @@ func escSequence(sz *int) Event {
|
|||||||
} // _buf[2]
|
} // _buf[2]
|
||||||
} // _buf[2]
|
} // _buf[2]
|
||||||
} // _buf[1]
|
} // _buf[1]
|
||||||
|
if _buf[1] >= 'a' && _buf[1] <= 'z' {
|
||||||
|
return Event{AltA + int(_buf[1]) - 'a', 0, nil}
|
||||||
|
}
|
||||||
return Event{Invalid, 0, nil}
|
return Event{Invalid, 0, nil}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -428,3 +455,15 @@ func Endwin() {
|
|||||||
func Refresh() {
|
func Refresh() {
|
||||||
C.refresh()
|
C.refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func PairFor(fg int, bg int) int {
|
||||||
|
key := (fg << 8) + bg
|
||||||
|
if found, prs := _colorMap[key]; prs {
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
id := len(_colorMap) + ColUser
|
||||||
|
C.init_pair(C.short(id), C.short(fg), C.short(bg))
|
||||||
|
_colorMap[key] = id
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
14
src/curses/curses_test.go
Normal file
14
src/curses/curses_test.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package curses
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPairFor(t *testing.T) {
|
||||||
|
if PairFor(30, 50) != PairFor(30, 50) {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if PairFor(-1, 10) != PairFor(-1, 10) {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
}
|
111
src/item.go
111
src/item.go
@@ -1,8 +1,18 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/junegunn/fzf/src/curses"
|
||||||
|
)
|
||||||
|
|
||||||
// Offset holds two 32-bit integers denoting the offsets of a matched substring
|
// Offset holds two 32-bit integers denoting the offsets of a matched substring
|
||||||
type Offset [2]int32
|
type Offset [2]int32
|
||||||
|
|
||||||
|
type colorOffset struct {
|
||||||
|
offset [2]int32
|
||||||
|
color int
|
||||||
|
bold bool
|
||||||
|
}
|
||||||
|
|
||||||
// Item represents each input line
|
// Item represents each input line
|
||||||
type Item struct {
|
type Item struct {
|
||||||
text *string
|
text *string
|
||||||
@@ -10,6 +20,7 @@ type Item struct {
|
|||||||
transformed *Transformed
|
transformed *Transformed
|
||||||
index uint32
|
index uint32
|
||||||
offsets []Offset
|
offsets []Offset
|
||||||
|
colors []ansiOffset
|
||||||
rank Rank
|
rank Rank
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +66,79 @@ func (i *Item) AsString() string {
|
|||||||
return *i.text
|
return *i.text
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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})
|
||||||
|
}
|
||||||
|
return offsets
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find max column
|
||||||
|
var maxCol int32
|
||||||
|
for _, off := range item.offsets {
|
||||||
|
if off[1] > maxCol {
|
||||||
|
maxCol = off[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, ansi := range item.colors {
|
||||||
|
if ansi.offset[1] > maxCol {
|
||||||
|
maxCol = ansi.offset[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cols := make([]int, maxCol)
|
||||||
|
|
||||||
|
for colorIndex, ansi := range item.colors {
|
||||||
|
for i := ansi.offset[0]; i < ansi.offset[1]; i++ {
|
||||||
|
cols[i] = colorIndex + 1 // XXX
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, off := range item.offsets {
|
||||||
|
for i := off[0]; i < off[1]; i++ {
|
||||||
|
cols[i] = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sort.Sort(ByOrder(offsets))
|
||||||
|
|
||||||
|
// Merge offsets
|
||||||
|
// ------------ ---- -- ----
|
||||||
|
// ++++++++ ++++++++++
|
||||||
|
// --++++++++-- --++++++++++---
|
||||||
|
curr := 0
|
||||||
|
start := 0
|
||||||
|
var offsets []colorOffset
|
||||||
|
add := func(idx int) {
|
||||||
|
if curr != 0 && idx > start {
|
||||||
|
if curr == -1 {
|
||||||
|
offsets = append(offsets, colorOffset{
|
||||||
|
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
||||||
|
} else {
|
||||||
|
ansi := item.colors[curr-1]
|
||||||
|
bg := ansi.color.bg
|
||||||
|
if current && bg == -1 {
|
||||||
|
bg = int(curses.DarkBG)
|
||||||
|
}
|
||||||
|
offsets = append(offsets, colorOffset{
|
||||||
|
offset: Offset{int32(start), int32(idx)},
|
||||||
|
color: curses.PairFor(ansi.color.fg, bg),
|
||||||
|
bold: ansi.color.bold || bold})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for idx, col := range cols {
|
||||||
|
if col != curr {
|
||||||
|
add(idx)
|
||||||
|
start = idx
|
||||||
|
curr = col
|
||||||
|
}
|
||||||
|
}
|
||||||
|
add(int(maxCol))
|
||||||
|
return offsets
|
||||||
|
}
|
||||||
|
|
||||||
// ByOrder is for sorting substring offsets
|
// ByOrder is for sorting substring offsets
|
||||||
type ByOrder []Offset
|
type ByOrder []Offset
|
||||||
|
|
||||||
@@ -87,10 +171,28 @@ func (a ByRelevance) Less(i, j int) bool {
|
|||||||
irank := a[i].Rank(true)
|
irank := a[i].Rank(true)
|
||||||
jrank := a[j].Rank(true)
|
jrank := a[j].Rank(true)
|
||||||
|
|
||||||
return compareRanks(irank, jrank)
|
return compareRanks(irank, jrank, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func compareRanks(irank Rank, jrank Rank) bool {
|
// ByRelevanceTac is for sorting Items
|
||||||
|
type ByRelevanceTac []*Item
|
||||||
|
|
||||||
|
func (a ByRelevanceTac) Len() int {
|
||||||
|
return len(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a ByRelevanceTac) Swap(i, j int) {
|
||||||
|
a[i], a[j] = a[j], a[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a ByRelevanceTac) Less(i, j int) bool {
|
||||||
|
irank := a[i].Rank(true)
|
||||||
|
jrank := a[j].Rank(true)
|
||||||
|
|
||||||
|
return compareRanks(irank, jrank, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareRanks(irank Rank, jrank Rank, tac bool) bool {
|
||||||
if irank.matchlen < jrank.matchlen {
|
if irank.matchlen < jrank.matchlen {
|
||||||
return true
|
return true
|
||||||
} else if irank.matchlen > jrank.matchlen {
|
} else if irank.matchlen > jrank.matchlen {
|
||||||
@@ -103,8 +205,5 @@ func compareRanks(irank Rank, jrank Rank) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if irank.index <= jrank.index {
|
return (irank.index <= jrank.index) != tac
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
@@ -3,6 +3,8 @@ package fzf
|
|||||||
import (
|
import (
|
||||||
"sort"
|
"sort"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/junegunn/fzf/src/curses"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestOffsetSort(t *testing.T) {
|
func TestOffsetSort(t *testing.T) {
|
||||||
@@ -20,12 +22,19 @@ func TestOffsetSort(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRankComparison(t *testing.T) {
|
func TestRankComparison(t *testing.T) {
|
||||||
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}) ||
|
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, false) ||
|
||||||
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}) ||
|
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||
|
||||||
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}) ||
|
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, false) ||
|
||||||
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}) {
|
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {
|
||||||
t.Error("Invalid order")
|
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) {
|
||||||
|
t.Error("Invalid order (tac)")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Match length, string length, index
|
// Match length, string length, index
|
||||||
@@ -65,3 +74,31 @@ func TestItemRank(t *testing.T) {
|
|||||||
t.Error(items)
|
t.Error(items)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestColorOffset(t *testing.T) {
|
||||||
|
// ------------ 20 ---- -- ----
|
||||||
|
// ++++++++ ++++++++++
|
||||||
|
// --++++++++-- --++++++++++---
|
||||||
|
item := Item{
|
||||||
|
offsets: []Offset{Offset{5, 15}, Offset{25, 35}},
|
||||||
|
colors: []ansiOffset{
|
||||||
|
ansiOffset{[2]int32{0, 20}, ansiState{1, 5, false}},
|
||||||
|
ansiOffset{[2]int32{22, 27}, ansiState{2, 6, true}},
|
||||||
|
ansiOffset{[2]int32{30, 32}, ansiState{3, 7, false}},
|
||||||
|
ansiOffset{[2]int32{33, 40}, ansiState{4, 8, true}}}}
|
||||||
|
// [{[0 5] 9 false} {[5 15] 99 false} {[15 20] 9 false} {[22 25] 10 true} {[25 35] 99 false} {[35 40] 11 true}]
|
||||||
|
|
||||||
|
offsets := item.colorOffsets(99, false, true)
|
||||||
|
assert := func(idx int, b int32, e int32, c int, bold bool) {
|
||||||
|
o := offsets[idx]
|
||||||
|
if o.offset[0] != b || o.offset[1] != e || o.color != c || o.bold != bold {
|
||||||
|
t.Error(o)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert(0, 0, 5, curses.ColUser, false)
|
||||||
|
assert(1, 5, 15, 99, false)
|
||||||
|
assert(2, 15, 20, curses.ColUser, false)
|
||||||
|
assert(3, 22, 25, curses.ColUser+1, true)
|
||||||
|
assert(4, 25, 35, 99, false)
|
||||||
|
assert(5, 35, 40, curses.ColUser+2, true)
|
||||||
|
}
|
||||||
|
@@ -15,12 +15,14 @@ type MatchRequest struct {
|
|||||||
chunks []*Chunk
|
chunks []*Chunk
|
||||||
pattern *Pattern
|
pattern *Pattern
|
||||||
final bool
|
final bool
|
||||||
|
sort bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matcher is responsible for performing search
|
// Matcher is responsible for performing search
|
||||||
type Matcher struct {
|
type Matcher struct {
|
||||||
patternBuilder func([]rune) *Pattern
|
patternBuilder func([]rune) *Pattern
|
||||||
sort bool
|
sort bool
|
||||||
|
tac bool
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
reqBox *util.EventBox
|
reqBox *util.EventBox
|
||||||
partitions int
|
partitions int
|
||||||
@@ -38,10 +40,11 @@ const (
|
|||||||
|
|
||||||
// NewMatcher returns a new Matcher
|
// NewMatcher returns a new Matcher
|
||||||
func NewMatcher(patternBuilder func([]rune) *Pattern,
|
func NewMatcher(patternBuilder func([]rune) *Pattern,
|
||||||
sort bool, eventBox *util.EventBox) *Matcher {
|
sort bool, tac bool, eventBox *util.EventBox) *Matcher {
|
||||||
return &Matcher{
|
return &Matcher{
|
||||||
patternBuilder: patternBuilder,
|
patternBuilder: patternBuilder,
|
||||||
sort: sort,
|
sort: sort,
|
||||||
|
tac: tac,
|
||||||
eventBox: eventBox,
|
eventBox: eventBox,
|
||||||
reqBox: util.NewEventBox(),
|
reqBox: util.NewEventBox(),
|
||||||
partitions: runtime.NumCPU(),
|
partitions: runtime.NumCPU(),
|
||||||
@@ -67,6 +70,12 @@ func (m *Matcher) Loop() {
|
|||||||
events.Clear()
|
events.Clear()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if request.sort != m.sort {
|
||||||
|
m.sort = request.sort
|
||||||
|
m.mergerCache = make(map[string]*Merger)
|
||||||
|
clearChunkCache()
|
||||||
|
}
|
||||||
|
|
||||||
// Restart search
|
// Restart search
|
||||||
patternString := request.pattern.AsString()
|
patternString := request.pattern.AsString()
|
||||||
var merger *Merger
|
var merger *Merger
|
||||||
@@ -131,7 +140,10 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
return EmptyMerger, false
|
return EmptyMerger, false
|
||||||
}
|
}
|
||||||
pattern := request.pattern
|
pattern := request.pattern
|
||||||
empty := pattern.IsEmpty()
|
if pattern.IsEmpty() {
|
||||||
|
return PassMerger(&request.chunks, m.tac), false
|
||||||
|
}
|
||||||
|
|
||||||
cancelled := util.NewAtomicBool(false)
|
cancelled := util.NewAtomicBool(false)
|
||||||
|
|
||||||
slices := m.sliceChunks(request.chunks)
|
slices := m.sliceChunks(request.chunks)
|
||||||
@@ -146,20 +158,19 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
defer func() { waitGroup.Done() }()
|
defer func() { waitGroup.Done() }()
|
||||||
sliceMatches := []*Item{}
|
sliceMatches := []*Item{}
|
||||||
for _, chunk := range chunks {
|
for _, chunk := range chunks {
|
||||||
var matches []*Item
|
matches := request.pattern.Match(chunk)
|
||||||
if empty {
|
|
||||||
matches = *chunk
|
|
||||||
} else {
|
|
||||||
matches = request.pattern.Match(chunk)
|
|
||||||
}
|
|
||||||
sliceMatches = append(sliceMatches, matches...)
|
sliceMatches = append(sliceMatches, matches...)
|
||||||
if cancelled.Get() {
|
if cancelled.Get() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
countChan <- len(matches)
|
countChan <- len(matches)
|
||||||
}
|
}
|
||||||
if !empty && m.sort {
|
if m.sort {
|
||||||
sort.Sort(ByRelevance(sliceMatches))
|
if m.tac {
|
||||||
|
sort.Sort(ByRelevanceTac(sliceMatches))
|
||||||
|
} else {
|
||||||
|
sort.Sort(ByRelevance(sliceMatches))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
resultChan <- partialResult{idx, sliceMatches}
|
resultChan <- partialResult{idx, sliceMatches}
|
||||||
}(idx, chunks)
|
}(idx, chunks)
|
||||||
@@ -181,7 +192,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if !empty && m.reqBox.Peek(reqReset) {
|
if m.reqBox.Peek(reqReset) {
|
||||||
return nil, wait()
|
return nil, wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,11 +206,11 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
partialResult := <-resultChan
|
partialResult := <-resultChan
|
||||||
partialResults[partialResult.index] = partialResult.matches
|
partialResults[partialResult.index] = partialResult.matches
|
||||||
}
|
}
|
||||||
return NewMerger(partialResults, !empty && m.sort), false
|
return NewMerger(partialResults, m.sort, m.tac), false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset is called to interrupt/signal the ongoing search
|
// Reset is called to interrupt/signal the ongoing search
|
||||||
func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool) {
|
func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool, sort bool) {
|
||||||
pattern := m.patternBuilder(patternRunes)
|
pattern := m.patternBuilder(patternRunes)
|
||||||
|
|
||||||
var event util.EventType
|
var event util.EventType
|
||||||
@@ -208,5 +219,5 @@ func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final
|
|||||||
} else {
|
} else {
|
||||||
event = reqRetry
|
event = reqRetry
|
||||||
}
|
}
|
||||||
m.reqBox.Set(event, MatchRequest{chunks, pattern, final})
|
m.reqBox.Set(event, MatchRequest{chunks, pattern, final, sort})
|
||||||
}
|
}
|
||||||
|
@@ -3,26 +3,44 @@ package fzf
|
|||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
// Merger with no data
|
// Merger with no data
|
||||||
var EmptyMerger = NewMerger([][]*Item{}, false)
|
var EmptyMerger = NewMerger([][]*Item{}, false, false)
|
||||||
|
|
||||||
// Merger holds a set of locally sorted lists of items and provides the view of
|
// Merger holds a set of locally sorted lists of items and provides the view of
|
||||||
// a single, globally-sorted list
|
// a single, globally-sorted list
|
||||||
type Merger struct {
|
type Merger struct {
|
||||||
lists [][]*Item
|
lists [][]*Item
|
||||||
merged []*Item
|
merged []*Item
|
||||||
|
chunks *[]*Chunk
|
||||||
cursors []int
|
cursors []int
|
||||||
sorted bool
|
sorted bool
|
||||||
|
tac bool
|
||||||
final bool
|
final bool
|
||||||
count int
|
count int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PassMerger returns a new Merger that simply returns the items in the
|
||||||
|
// original order
|
||||||
|
func PassMerger(chunks *[]*Chunk, tac bool) *Merger {
|
||||||
|
mg := Merger{
|
||||||
|
chunks: chunks,
|
||||||
|
tac: tac,
|
||||||
|
count: 0}
|
||||||
|
|
||||||
|
for _, chunk := range *mg.chunks {
|
||||||
|
mg.count += len(*chunk)
|
||||||
|
}
|
||||||
|
return &mg
|
||||||
|
}
|
||||||
|
|
||||||
// NewMerger returns a new Merger
|
// NewMerger returns a new Merger
|
||||||
func NewMerger(lists [][]*Item, sorted bool) *Merger {
|
func NewMerger(lists [][]*Item, sorted bool, tac bool) *Merger {
|
||||||
mg := Merger{
|
mg := Merger{
|
||||||
lists: lists,
|
lists: lists,
|
||||||
merged: []*Item{},
|
merged: []*Item{},
|
||||||
|
chunks: nil,
|
||||||
cursors: make([]int, len(lists)),
|
cursors: make([]int, len(lists)),
|
||||||
sorted: sorted,
|
sorted: sorted,
|
||||||
|
tac: tac,
|
||||||
final: false,
|
final: false,
|
||||||
count: 0}
|
count: 0}
|
||||||
|
|
||||||
@@ -39,19 +57,29 @@ func (mg *Merger) Length() int {
|
|||||||
|
|
||||||
// Get returns the pointer to the Item object indexed by the given integer
|
// Get returns the pointer to the Item object indexed by the given integer
|
||||||
func (mg *Merger) Get(idx int) *Item {
|
func (mg *Merger) Get(idx int) *Item {
|
||||||
if len(mg.lists) == 1 {
|
if mg.chunks != nil {
|
||||||
return mg.lists[0][idx]
|
if mg.tac {
|
||||||
} else if !mg.sorted {
|
idx = mg.count - idx - 1
|
||||||
for _, list := range mg.lists {
|
|
||||||
numItems := len(list)
|
|
||||||
if idx < numItems {
|
|
||||||
return list[idx]
|
|
||||||
}
|
|
||||||
idx -= numItems
|
|
||||||
}
|
}
|
||||||
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
chunk := (*mg.chunks)[idx/ChunkSize]
|
||||||
|
return (*chunk)[idx%ChunkSize]
|
||||||
}
|
}
|
||||||
return mg.mergedGet(idx)
|
|
||||||
|
if mg.sorted {
|
||||||
|
return mg.mergedGet(idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
if mg.tac {
|
||||||
|
idx = mg.count - idx - 1
|
||||||
|
}
|
||||||
|
for _, list := range mg.lists {
|
||||||
|
numItems := len(list)
|
||||||
|
if idx < numItems {
|
||||||
|
return list[idx]
|
||||||
|
}
|
||||||
|
idx -= numItems
|
||||||
|
}
|
||||||
|
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Merger) mergedGet(idx int) *Item {
|
func (mg *Merger) mergedGet(idx int) *Item {
|
||||||
@@ -66,7 +94,7 @@ func (mg *Merger) mergedGet(idx int) *Item {
|
|||||||
}
|
}
|
||||||
if cursor >= 0 {
|
if cursor >= 0 {
|
||||||
rank := list[cursor].Rank(false)
|
rank := list[cursor].Rank(false)
|
||||||
if minIdx < 0 || compareRanks(rank, minRank) {
|
if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {
|
||||||
minRank = rank
|
minRank = rank
|
||||||
minIdx = listIdx
|
minIdx = listIdx
|
||||||
}
|
}
|
||||||
|
@@ -62,7 +62,7 @@ func TestMergerUnsorted(t *testing.T) {
|
|||||||
cnt := len(items)
|
cnt := len(items)
|
||||||
|
|
||||||
// Not sorted: same order
|
// Not sorted: same order
|
||||||
mg := NewMerger(lists, false)
|
mg := NewMerger(lists, false, false)
|
||||||
assert(t, cnt == mg.Length(), "Invalid Length")
|
assert(t, cnt == mg.Length(), "Invalid Length")
|
||||||
for i := 0; i < cnt; i++ {
|
for i := 0; i < cnt; i++ {
|
||||||
assert(t, items[i] == mg.Get(i), "Invalid Get")
|
assert(t, items[i] == mg.Get(i), "Invalid Get")
|
||||||
@@ -74,7 +74,7 @@ func TestMergerSorted(t *testing.T) {
|
|||||||
cnt := len(items)
|
cnt := len(items)
|
||||||
|
|
||||||
// Sorted sorted order
|
// Sorted sorted order
|
||||||
mg := NewMerger(lists, true)
|
mg := NewMerger(lists, true, false)
|
||||||
assert(t, cnt == mg.Length(), "Invalid Length")
|
assert(t, cnt == mg.Length(), "Invalid Length")
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
for i := 0; i < cnt; i++ {
|
for i := 0; i < cnt; i++ {
|
||||||
@@ -84,7 +84,7 @@ func TestMergerSorted(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Inverse order
|
// Inverse order
|
||||||
mg2 := NewMerger(lists, true)
|
mg2 := NewMerger(lists, true, false)
|
||||||
for i := cnt - 1; i >= 0; i-- {
|
for i := cnt - 1; i >= 0; i-- {
|
||||||
if items[i] != mg2.Get(i) {
|
if items[i] != mg2.Get(i) {
|
||||||
t.Error("Not sorted", items[i], mg2.Get(i))
|
t.Error("Not sorted", items[i], mg2.Get(i))
|
||||||
|
@@ -5,13 +5,16 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/junegunn/fzf/src/curses"
|
||||||
|
|
||||||
"github.com/junegunn/go-shellwords"
|
"github.com/junegunn/go-shellwords"
|
||||||
)
|
)
|
||||||
|
|
||||||
const usage = `usage: fzf [options]
|
const usage = `usage: fzf [options]
|
||||||
|
|
||||||
Search
|
Search mode
|
||||||
-x, --extended Extended-search mode
|
-x, --extended Extended-search mode
|
||||||
-e, --extended-exact Extended-search mode (exact match)
|
-e, --extended-exact Extended-search mode (exact match)
|
||||||
-i Case-insensitive match (default: smart-case match)
|
-i Case-insensitive match (default: smart-case match)
|
||||||
@@ -23,11 +26,13 @@ const usage = `usage: fzf [options]
|
|||||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||||
|
|
||||||
Search result
|
Search result
|
||||||
-s, --sort Sort the result
|
+s, --no-sort Do not sort the result
|
||||||
+s, --no-sort Do not sort the result. Keep the sequence unchanged.
|
--tac Reverse the order of the input
|
||||||
|
(e.g. 'history | fzf --tac --no-sort')
|
||||||
|
|
||||||
Interface
|
Interface
|
||||||
-m, --multi Enable multi-select with tab/shift-tab
|
-m, --multi Enable multi-select with tab/shift-tab
|
||||||
|
--ansi Enable processing of ANSI color codes
|
||||||
--no-mouse Disable mouse
|
--no-mouse Disable mouse
|
||||||
+c, --no-color Disable colors
|
+c, --no-color Disable colors
|
||||||
+2, --no-256 Disable 256-color
|
+2, --no-256 Disable 256-color
|
||||||
@@ -41,6 +46,8 @@ const usage = `usage: fzf [options]
|
|||||||
-0, --exit-0 Exit immediately when there's no match
|
-0, --exit-0 Exit immediately when there's no match
|
||||||
-f, --filter=STR Filter mode. Do not start interactive finder.
|
-f, --filter=STR Filter mode. Do not start interactive finder.
|
||||||
--print-query Print query as the first line
|
--print-query Print query as the first line
|
||||||
|
--expect=KEYS Comma-separated list of keys to complete fzf
|
||||||
|
--toggle-sort=KEY Key to toggle sort
|
||||||
--sync Synchronous search for multi-staged filtering
|
--sync Synchronous search for multi-staged filtering
|
||||||
(e.g. 'fzf --multi | fzf --sync')
|
(e.g. 'fzf --multi | fzf --sync')
|
||||||
|
|
||||||
@@ -78,7 +85,9 @@ type Options struct {
|
|||||||
WithNth []Range
|
WithNth []Range
|
||||||
Delimiter *regexp.Regexp
|
Delimiter *regexp.Regexp
|
||||||
Sort int
|
Sort int
|
||||||
|
Tac bool
|
||||||
Multi bool
|
Multi bool
|
||||||
|
Ansi bool
|
||||||
Mouse bool
|
Mouse bool
|
||||||
Color bool
|
Color bool
|
||||||
Color256 bool
|
Color256 bool
|
||||||
@@ -89,6 +98,8 @@ type Options struct {
|
|||||||
Select1 bool
|
Select1 bool
|
||||||
Exit0 bool
|
Exit0 bool
|
||||||
Filter *string
|
Filter *string
|
||||||
|
ToggleSort int
|
||||||
|
Expect []int
|
||||||
PrintQuery bool
|
PrintQuery bool
|
||||||
Sync bool
|
Sync bool
|
||||||
Version bool
|
Version bool
|
||||||
@@ -102,7 +113,9 @@ func defaultOptions() *Options {
|
|||||||
WithNth: make([]Range, 0),
|
WithNth: make([]Range, 0),
|
||||||
Delimiter: nil,
|
Delimiter: nil,
|
||||||
Sort: 1000,
|
Sort: 1000,
|
||||||
|
Tac: false,
|
||||||
Multi: false,
|
Multi: false,
|
||||||
|
Ansi: false,
|
||||||
Mouse: true,
|
Mouse: true,
|
||||||
Color: true,
|
Color: true,
|
||||||
Color256: strings.Contains(os.Getenv("TERM"), "256"),
|
Color256: strings.Contains(os.Getenv("TERM"), "256"),
|
||||||
@@ -113,6 +126,8 @@ func defaultOptions() *Options {
|
|||||||
Select1: false,
|
Select1: false,
|
||||||
Exit0: false,
|
Exit0: false,
|
||||||
Filter: nil,
|
Filter: nil,
|
||||||
|
ToggleSort: 0,
|
||||||
|
Expect: []int{},
|
||||||
PrintQuery: false,
|
PrintQuery: false,
|
||||||
Sync: false,
|
Sync: false,
|
||||||
Version: false}
|
Version: false}
|
||||||
@@ -185,6 +200,49 @@ func delimiterRegexp(str string) *regexp.Regexp {
|
|||||||
return rx
|
return rx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isAlphabet(char uint8) bool {
|
||||||
|
return char >= 'a' && char <= 'z'
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseKeyChords(str string, message string) []int {
|
||||||
|
if len(str) == 0 {
|
||||||
|
errorExit(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens := strings.Split(str, ",")
|
||||||
|
if str == "," || strings.HasPrefix(str, ",,") || strings.HasSuffix(str, ",,") || strings.Index(str, ",,,") >= 0 {
|
||||||
|
tokens = append(tokens, ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
var chords []int
|
||||||
|
for _, key := range tokens {
|
||||||
|
if len(key) == 0 {
|
||||||
|
continue // ignore
|
||||||
|
}
|
||||||
|
lkey := strings.ToLower(key)
|
||||||
|
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||||
|
chords = append(chords, curses.CtrlA+int(lkey[5])-'a')
|
||||||
|
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||||
|
chords = append(chords, curses.AltA+int(lkey[4])-'a')
|
||||||
|
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
||||||
|
chords = append(chords, curses.F1+int(key[1])-'1')
|
||||||
|
} else if utf8.RuneCountInString(key) == 1 {
|
||||||
|
chords = append(chords, curses.AltZ+int([]rune(key)[0]))
|
||||||
|
} else {
|
||||||
|
errorExit("unsupported key: " + key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return chords
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkToggleSort(str string) int {
|
||||||
|
keys := parseKeyChords(str, "key name required")
|
||||||
|
if len(keys) != 1 {
|
||||||
|
errorExit("multiple keys specified")
|
||||||
|
}
|
||||||
|
return keys[0]
|
||||||
|
}
|
||||||
|
|
||||||
func parseOptions(opts *Options, allArgs []string) {
|
func parseOptions(opts *Options, allArgs []string) {
|
||||||
for i := 0; i < len(allArgs); i++ {
|
for i := 0; i < len(allArgs); i++ {
|
||||||
arg := allArgs[i]
|
arg := allArgs[i]
|
||||||
@@ -202,6 +260,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
case "-f", "--filter":
|
case "-f", "--filter":
|
||||||
filter := nextString(allArgs, &i, "query string required")
|
filter := nextString(allArgs, &i, "query string required")
|
||||||
opts.Filter = &filter
|
opts.Filter = &filter
|
||||||
|
case "--expect":
|
||||||
|
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
||||||
|
case "--toggle-sort":
|
||||||
|
opts.ToggleSort = checkToggleSort(nextString(allArgs, &i, "key name required"))
|
||||||
case "-d", "--delimiter":
|
case "-d", "--delimiter":
|
||||||
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
||||||
case "-n", "--nth":
|
case "-n", "--nth":
|
||||||
@@ -212,6 +274,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Sort = optionalNumeric(allArgs, &i)
|
opts.Sort = optionalNumeric(allArgs, &i)
|
||||||
case "+s", "--no-sort":
|
case "+s", "--no-sort":
|
||||||
opts.Sort = 0
|
opts.Sort = 0
|
||||||
|
case "--tac":
|
||||||
|
opts.Tac = true
|
||||||
|
case "--no-tac":
|
||||||
|
opts.Tac = false
|
||||||
case "-i":
|
case "-i":
|
||||||
opts.Case = CaseIgnore
|
opts.Case = CaseIgnore
|
||||||
case "+i":
|
case "+i":
|
||||||
@@ -220,6 +286,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Multi = true
|
opts.Multi = true
|
||||||
case "+m", "--no-multi":
|
case "+m", "--no-multi":
|
||||||
opts.Multi = false
|
opts.Multi = false
|
||||||
|
case "--ansi":
|
||||||
|
opts.Ansi = true
|
||||||
|
case "--no-ansi":
|
||||||
|
opts.Ansi = false
|
||||||
case "--no-mouse":
|
case "--no-mouse":
|
||||||
opts.Mouse = false
|
opts.Mouse = false
|
||||||
case "+c", "--no-color":
|
case "+c", "--no-color":
|
||||||
@@ -271,6 +341,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.WithNth = splitNth(value)
|
opts.WithNth = splitNth(value)
|
||||||
} else if match, _ := optString(arg, "-s|--sort="); match {
|
} else if match, _ := optString(arg, "-s|--sort="); match {
|
||||||
opts.Sort = 1 // Don't care
|
opts.Sort = 1 // Don't care
|
||||||
|
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||||
|
opts.ToggleSort = checkToggleSort(value)
|
||||||
|
} else if match, value := optString(arg, "--expect="); match {
|
||||||
|
opts.Expect = parseKeyChords(value, "key names required")
|
||||||
} else {
|
} else {
|
||||||
errorExit("unknown option: " + arg)
|
errorExit("unknown option: " + arg)
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,10 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/junegunn/fzf/src/curses"
|
||||||
|
)
|
||||||
|
|
||||||
func TestDelimiterRegex(t *testing.T) {
|
func TestDelimiterRegex(t *testing.T) {
|
||||||
rx := delimiterRegexp("*")
|
rx := delimiterRegexp("*")
|
||||||
@@ -65,3 +69,63 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseKeys(t *testing.T) {
|
||||||
|
keys := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
||||||
|
check := func(key int, expected int) {
|
||||||
|
if key != expected {
|
||||||
|
t.Errorf("%d != %d", key, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check(len(keys), 9)
|
||||||
|
check(keys[0], curses.CtrlZ)
|
||||||
|
check(keys[1], curses.AltZ)
|
||||||
|
check(keys[2], curses.F2)
|
||||||
|
check(keys[3], curses.AltZ+'@')
|
||||||
|
check(keys[4], curses.AltA)
|
||||||
|
check(keys[5], curses.AltZ+'!')
|
||||||
|
check(keys[6], curses.CtrlA+'g'-'a')
|
||||||
|
check(keys[7], curses.AltZ+'J')
|
||||||
|
check(keys[8], curses.AltZ+'g')
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseKeysWithComma(t *testing.T) {
|
||||||
|
check := func(key int, expected int) {
|
||||||
|
if key != expected {
|
||||||
|
t.Errorf("%d != %d", key, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
keys := parseKeyChords(",", "")
|
||||||
|
check(len(keys), 1)
|
||||||
|
check(keys[0], curses.AltZ+',')
|
||||||
|
|
||||||
|
keys = parseKeyChords(",,a,b", "")
|
||||||
|
check(len(keys), 3)
|
||||||
|
check(keys[0], curses.AltZ+'a')
|
||||||
|
check(keys[1], curses.AltZ+'b')
|
||||||
|
check(keys[2], curses.AltZ+',')
|
||||||
|
|
||||||
|
keys = parseKeyChords("a,b,,", "")
|
||||||
|
check(len(keys), 3)
|
||||||
|
check(keys[0], curses.AltZ+'a')
|
||||||
|
check(keys[1], curses.AltZ+'b')
|
||||||
|
check(keys[2], curses.AltZ+',')
|
||||||
|
|
||||||
|
keys = parseKeyChords("a,,,b", "")
|
||||||
|
check(len(keys), 3)
|
||||||
|
check(keys[0], curses.AltZ+'a')
|
||||||
|
check(keys[1], curses.AltZ+'b')
|
||||||
|
check(keys[2], curses.AltZ+',')
|
||||||
|
|
||||||
|
keys = parseKeyChords("a,,,b,c", "")
|
||||||
|
check(len(keys), 4)
|
||||||
|
check(keys[0], curses.AltZ+'a')
|
||||||
|
check(keys[1], curses.AltZ+'b')
|
||||||
|
check(keys[2], curses.AltZ+'c')
|
||||||
|
check(keys[3], curses.AltZ+',')
|
||||||
|
|
||||||
|
keys = parseKeyChords(",,,", "")
|
||||||
|
check(len(keys), 1)
|
||||||
|
check(keys[0], curses.AltZ+',')
|
||||||
|
}
|
||||||
|
@@ -54,17 +54,21 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
// We can uniquely identify the pattern for a given string since
|
|
||||||
// mode and caseMode do not change while the program is running
|
|
||||||
_patternCache = make(map[string]*Pattern)
|
|
||||||
_splitRegex = regexp.MustCompile("\\s+")
|
_splitRegex = regexp.MustCompile("\\s+")
|
||||||
_cache = NewChunkCache()
|
clearPatternCache()
|
||||||
|
clearChunkCache()
|
||||||
}
|
}
|
||||||
|
|
||||||
func clearPatternCache() {
|
func clearPatternCache() {
|
||||||
|
// We can uniquely identify the pattern for a given string since
|
||||||
|
// mode and caseMode do not change while the program is running
|
||||||
_patternCache = make(map[string]*Pattern)
|
_patternCache = make(map[string]*Pattern)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func clearChunkCache() {
|
||||||
|
_cache = NewChunkCache()
|
||||||
|
}
|
||||||
|
|
||||||
// BuildPattern builds Pattern object from the given arguments
|
// BuildPattern builds Pattern object from the given arguments
|
||||||
func BuildPattern(mode Mode, caseMode Case,
|
func BuildPattern(mode Mode, caseMode Case,
|
||||||
nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {
|
nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {
|
||||||
@@ -219,12 +223,7 @@ Loop:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var matches []*Item
|
matches := p.matchChunk(space)
|
||||||
if p.mode == ModeFuzzy {
|
|
||||||
matches = p.fuzzyMatch(space)
|
|
||||||
} else {
|
|
||||||
matches = p.extendedMatch(space)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !p.hasInvTerm {
|
if !p.hasInvTerm {
|
||||||
_cache.Add(chunk, cacheKey, matches)
|
_cache.Add(chunk, cacheKey, matches)
|
||||||
@@ -232,6 +231,35 @@ Loop:
|
|||||||
return matches
|
return matches
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||||
|
matches := []*Item{}
|
||||||
|
if p.mode == ModeFuzzy {
|
||||||
|
for _, item := range *chunk {
|
||||||
|
if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {
|
||||||
|
matches = append(matches,
|
||||||
|
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, item := range *chunk {
|
||||||
|
if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {
|
||||||
|
matches = append(matches, dupItem(item, offsets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchItem returns true if the Item is a match
|
||||||
|
func (p *Pattern) MatchItem(item *Item) bool {
|
||||||
|
if p.mode == ModeFuzzy {
|
||||||
|
sidx, _ := p.fuzzyMatch(item)
|
||||||
|
return sidx >= 0
|
||||||
|
}
|
||||||
|
offsets := p.extendedMatch(item)
|
||||||
|
return len(offsets) == len(p.terms)
|
||||||
|
}
|
||||||
|
|
||||||
func dupItem(item *Item, offsets []Offset) *Item {
|
func dupItem(item *Item, offsets []Offset) *Item {
|
||||||
sort.Sort(ByOrder(offsets))
|
sort.Sort(ByOrder(offsets))
|
||||||
return &Item{
|
return &Item{
|
||||||
@@ -240,42 +268,30 @@ func dupItem(item *Item, offsets []Offset) *Item {
|
|||||||
transformed: item.transformed,
|
transformed: item.transformed,
|
||||||
index: item.index,
|
index: item.index,
|
||||||
offsets: offsets,
|
offsets: offsets,
|
||||||
|
colors: item.colors,
|
||||||
rank: Rank{0, 0, item.index}}
|
rank: Rank{0, 0, item.index}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) fuzzyMatch(chunk *Chunk) []*Item {
|
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
||||||
matches := []*Item{}
|
input := p.prepareInput(item)
|
||||||
for _, item := range *chunk {
|
return p.iter(algo.FuzzyMatch, input, p.text)
|
||||||
input := p.prepareInput(item)
|
|
||||||
if sidx, eidx := p.iter(algo.FuzzyMatch, input, p.text); sidx >= 0 {
|
|
||||||
matches = append(matches,
|
|
||||||
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return matches
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) extendedMatch(chunk *Chunk) []*Item {
|
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
||||||
matches := []*Item{}
|
input := p.prepareInput(item)
|
||||||
for _, item := range *chunk {
|
offsets := []Offset{}
|
||||||
input := p.prepareInput(item)
|
for _, term := range p.terms {
|
||||||
offsets := []Offset{}
|
pfun := p.procFun[term.typ]
|
||||||
for _, term := range p.terms {
|
if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {
|
||||||
pfun := p.procFun[term.typ]
|
if term.inv {
|
||||||
if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {
|
break
|
||||||
if term.inv {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
|
|
||||||
} else if term.inv {
|
|
||||||
offsets = append(offsets, Offset{0, 0})
|
|
||||||
}
|
}
|
||||||
}
|
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
|
||||||
if len(offsets) == len(p.terms) {
|
} else if term.inv {
|
||||||
matches = append(matches, dupItem(item, offsets))
|
offsets = append(offsets, Offset{0, 0})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return matches
|
return offsets
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) prepareInput(item *Item) *Transformed {
|
func (p *Pattern) prepareInput(item *Item) *Transformed {
|
||||||
|
@@ -98,14 +98,15 @@ func TestOrigTextAndTransformed(t *testing.T) {
|
|||||||
tokens := Tokenize(strptr("junegunn"), nil)
|
tokens := Tokenize(strptr("junegunn"), nil)
|
||||||
trans := Transform(tokens, []Range{Range{1, 1}})
|
trans := Transform(tokens, []Range{Range{1, 1}})
|
||||||
|
|
||||||
for _, fun := range []func(*Chunk) []*Item{pattern.fuzzyMatch, pattern.extendedMatch} {
|
for _, mode := range []Mode{ModeFuzzy, ModeExtended} {
|
||||||
chunk := Chunk{
|
chunk := Chunk{
|
||||||
&Item{
|
&Item{
|
||||||
text: strptr("junegunn"),
|
text: strptr("junegunn"),
|
||||||
origText: strptr("junegunn.choi"),
|
origText: strptr("junegunn.choi"),
|
||||||
transformed: trans},
|
transformed: trans},
|
||||||
}
|
}
|
||||||
matches := fun(&chunk)
|
pattern.mode = mode
|
||||||
|
matches := pattern.matchChunk(&chunk)
|
||||||
if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||
|
if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||
|
||||||
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
||||||
matches[0].transformed != trans {
|
matches[0].transformed != trans {
|
||||||
|
104
src/terminal.go
104
src/terminal.go
@@ -22,13 +22,15 @@ import (
|
|||||||
type Terminal struct {
|
type Terminal struct {
|
||||||
prompt string
|
prompt string
|
||||||
reverse bool
|
reverse bool
|
||||||
tac bool
|
|
||||||
cx int
|
cx int
|
||||||
cy int
|
cy int
|
||||||
offset int
|
offset int
|
||||||
yanked []rune
|
yanked []rune
|
||||||
input []rune
|
input []rune
|
||||||
multi bool
|
multi bool
|
||||||
|
toggleSort int
|
||||||
|
expect []int
|
||||||
|
pressed int
|
||||||
printQuery bool
|
printQuery bool
|
||||||
count int
|
count int
|
||||||
progress int
|
progress int
|
||||||
@@ -48,17 +50,17 @@ type selectedItem struct {
|
|||||||
text *string
|
text *string
|
||||||
}
|
}
|
||||||
|
|
||||||
type ByTimeOrder []selectedItem
|
type byTimeOrder []selectedItem
|
||||||
|
|
||||||
func (a ByTimeOrder) Len() int {
|
func (a byTimeOrder) Len() int {
|
||||||
return len(a)
|
return len(a)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a ByTimeOrder) Swap(i, j int) {
|
func (a byTimeOrder) Swap(i, j int) {
|
||||||
a[i], a[j] = a[j], a[i]
|
a[i], a[j] = a[j], a[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a ByTimeOrder) Less(i, j int) bool {
|
func (a byTimeOrder) Less(i, j int) bool {
|
||||||
return a[i].at.Before(a[j].at)
|
return a[i].at.Before(a[j].at)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,7 +87,6 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
input := []rune(opts.Query)
|
input := []rune(opts.Query)
|
||||||
return &Terminal{
|
return &Terminal{
|
||||||
prompt: opts.Prompt,
|
prompt: opts.Prompt,
|
||||||
tac: opts.Sort == 0,
|
|
||||||
reverse: opts.Reverse,
|
reverse: opts.Reverse,
|
||||||
cx: len(input),
|
cx: len(input),
|
||||||
cy: 0,
|
cy: 0,
|
||||||
@@ -93,6 +94,9 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
yanked: []rune{},
|
yanked: []rune{},
|
||||||
input: input,
|
input: input,
|
||||||
multi: opts.Multi,
|
multi: opts.Multi,
|
||||||
|
toggleSort: opts.ToggleSort,
|
||||||
|
expect: opts.Expect,
|
||||||
|
pressed: 0,
|
||||||
printQuery: opts.PrintQuery,
|
printQuery: opts.PrintQuery,
|
||||||
merger: EmptyMerger,
|
merger: EmptyMerger,
|
||||||
selected: make(map[*string]selectedItem),
|
selected: make(map[*string]selectedItem),
|
||||||
@@ -148,28 +152,34 @@ func (t *Terminal) UpdateList(merger *Merger) {
|
|||||||
t.reqBox.Set(reqList, nil)
|
t.reqBox.Set(reqList, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) listIndex(y int) int {
|
|
||||||
if t.tac {
|
|
||||||
return t.merger.Length() - y - 1
|
|
||||||
}
|
|
||||||
return y
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Terminal) output() {
|
func (t *Terminal) output() {
|
||||||
if t.printQuery {
|
if t.printQuery {
|
||||||
fmt.Println(string(t.input))
|
fmt.Println(string(t.input))
|
||||||
}
|
}
|
||||||
|
if len(t.expect) > 0 {
|
||||||
|
if t.pressed == 0 {
|
||||||
|
fmt.Println()
|
||||||
|
} else if util.Between(t.pressed, C.AltA, C.AltZ) {
|
||||||
|
fmt.Printf("alt-%c\n", t.pressed+'a'-C.AltA)
|
||||||
|
} else if util.Between(t.pressed, C.F1, C.F4) {
|
||||||
|
fmt.Printf("f%c\n", t.pressed+'1'-C.F1)
|
||||||
|
} else if util.Between(t.pressed, C.CtrlA, C.CtrlZ) {
|
||||||
|
fmt.Printf("ctrl-%c\n", t.pressed+'a'-C.CtrlA)
|
||||||
|
} else {
|
||||||
|
fmt.Printf("%c\n", t.pressed-C.AltZ)
|
||||||
|
}
|
||||||
|
}
|
||||||
if len(t.selected) == 0 {
|
if len(t.selected) == 0 {
|
||||||
cnt := t.merger.Length()
|
cnt := t.merger.Length()
|
||||||
if cnt > 0 && cnt > t.cy {
|
if cnt > 0 && cnt > t.cy {
|
||||||
fmt.Println(t.merger.Get(t.listIndex(t.cy)).AsString())
|
fmt.Println(t.merger.Get(t.cy).AsString())
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
sels := make([]selectedItem, 0, len(t.selected))
|
sels := make([]selectedItem, 0, len(t.selected))
|
||||||
for _, sel := range t.selected {
|
for _, sel := range t.selected {
|
||||||
sels = append(sels, sel)
|
sels = append(sels, sel)
|
||||||
}
|
}
|
||||||
sort.Sort(ByTimeOrder(sels))
|
sort.Sort(byTimeOrder(sels))
|
||||||
for _, sel := range sels {
|
for _, sel := range sels {
|
||||||
fmt.Println(*sel.text)
|
fmt.Println(*sel.text)
|
||||||
}
|
}
|
||||||
@@ -246,7 +256,7 @@ func (t *Terminal) printList() {
|
|||||||
for i := 0; i < maxy; i++ {
|
for i := 0; i < maxy; i++ {
|
||||||
t.move(i+2, 0, true)
|
t.move(i+2, 0, true)
|
||||||
if i < count {
|
if i < count {
|
||||||
t.printItem(t.merger.Get(t.listIndex(i+t.offset)), i == t.cy-t.offset)
|
t.printItem(t.merger.Get(i+t.offset), i == t.cy-t.offset)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -260,7 +270,7 @@ func (t *Terminal) printItem(item *Item, current bool) {
|
|||||||
} else {
|
} else {
|
||||||
C.CPrint(C.ColCurrent, true, " ")
|
C.CPrint(C.ColCurrent, true, " ")
|
||||||
}
|
}
|
||||||
t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch)
|
t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch, true)
|
||||||
} else {
|
} else {
|
||||||
C.CPrint(C.ColCursor, true, " ")
|
C.CPrint(C.ColCursor, true, " ")
|
||||||
if selected {
|
if selected {
|
||||||
@@ -268,7 +278,7 @@ func (t *Terminal) printItem(item *Item, current bool) {
|
|||||||
} else {
|
} else {
|
||||||
C.Print(" ")
|
C.Print(" ")
|
||||||
}
|
}
|
||||||
t.printHighlighted(item, false, 0, C.ColMatch)
|
t.printHighlighted(item, false, 0, C.ColMatch, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +318,7 @@ func trimLeft(runes []rune, width int) ([]rune, int32) {
|
|||||||
return runes, trimmed
|
return runes, trimmed
|
||||||
}
|
}
|
||||||
|
|
||||||
func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int) {
|
func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, current bool) {
|
||||||
var maxe int32
|
var maxe int32
|
||||||
for _, offset := range item.offsets {
|
for _, offset := range item.offsets {
|
||||||
if offset[1] > maxe {
|
if offset[1] > maxe {
|
||||||
@@ -318,7 +328,7 @@ func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int) {
|
|||||||
|
|
||||||
// Overflow
|
// Overflow
|
||||||
text := []rune(*item.text)
|
text := []rune(*item.text)
|
||||||
offsets := item.offsets
|
offsets := item.colorOffsets(col2, bold, current)
|
||||||
maxWidth := C.MaxX() - 3
|
maxWidth := C.MaxX() - 3
|
||||||
fullWidth := displayWidth(text)
|
fullWidth := displayWidth(text)
|
||||||
if fullWidth > maxWidth {
|
if fullWidth > maxWidth {
|
||||||
@@ -337,37 +347,40 @@ func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int) {
|
|||||||
text, diff = trimLeft(text, maxWidth-2)
|
text, diff = trimLeft(text, maxWidth-2)
|
||||||
|
|
||||||
// Transform offsets
|
// Transform offsets
|
||||||
offsets = make([]Offset, len(item.offsets))
|
for idx, offset := range offsets {
|
||||||
for idx, offset := range item.offsets {
|
b, e := offset.offset[0], offset.offset[1]
|
||||||
b, e := offset[0], offset[1]
|
|
||||||
b += 2 - diff
|
b += 2 - diff
|
||||||
e += 2 - diff
|
e += 2 - diff
|
||||||
b = util.Max32(b, 2)
|
b = util.Max32(b, 2)
|
||||||
if b < e {
|
offsets[idx].offset[0] = b
|
||||||
offsets[idx] = Offset{b, e}
|
offsets[idx].offset[1] = util.Max32(b, e)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
text = append([]rune(".."), text...)
|
text = append([]rune(".."), text...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Sort(ByOrder(offsets))
|
|
||||||
var index int32
|
var index int32
|
||||||
var substr string
|
var substr string
|
||||||
var prefixWidth int
|
var prefixWidth int
|
||||||
|
maxOffset := int32(len(text))
|
||||||
for _, offset := range offsets {
|
for _, offset := range offsets {
|
||||||
b := util.Max32(index, offset[0])
|
b := util.Constrain32(offset.offset[0], index, maxOffset)
|
||||||
e := util.Max32(index, offset[1])
|
e := util.Constrain32(offset.offset[1], index, maxOffset)
|
||||||
|
|
||||||
substr, prefixWidth = processTabs(text[index:b], prefixWidth)
|
substr, prefixWidth = processTabs(text[index:b], prefixWidth)
|
||||||
C.CPrint(col1, bold, substr)
|
C.CPrint(col1, bold, substr)
|
||||||
|
|
||||||
substr, prefixWidth = processTabs(text[b:e], prefixWidth)
|
if b < e {
|
||||||
C.CPrint(col2, bold, substr)
|
substr, prefixWidth = processTabs(text[b:e], prefixWidth)
|
||||||
|
C.CPrint(offset.color, offset.bold, substr)
|
||||||
|
}
|
||||||
|
|
||||||
index = e
|
index = e
|
||||||
|
if index >= maxOffset {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if index < int32(len(text)) {
|
if index < maxOffset {
|
||||||
substr, _ = processTabs(text[index:], prefixWidth)
|
substr, _ = processTabs(text[index:], prefixWidth)
|
||||||
C.CPrint(col1, bold, substr)
|
C.CPrint(col1, bold, substr)
|
||||||
}
|
}
|
||||||
@@ -446,6 +459,10 @@ func (t *Terminal) rubout(pattern string) {
|
|||||||
t.input = append(t.input[:t.cx], after...)
|
t.input = append(t.input[:t.cx], after...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func keyMatch(key int, event C.Event) bool {
|
||||||
|
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
||||||
|
}
|
||||||
|
|
||||||
// Loop is called to start Terminal I/O
|
// Loop is called to start Terminal I/O
|
||||||
func (t *Terminal) Loop() {
|
func (t *Terminal) Loop() {
|
||||||
<-t.startChan
|
<-t.startChan
|
||||||
@@ -525,9 +542,8 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
toggle := func() {
|
toggle := func() {
|
||||||
idx := t.listIndex(t.cy)
|
if t.cy < t.merger.Length() {
|
||||||
if idx < t.merger.Length() {
|
item := t.merger.Get(t.cy)
|
||||||
item := t.merger.Get(idx)
|
|
||||||
if _, found := t.selected[item.text]; !found {
|
if _, found := t.selected[item.text]; !found {
|
||||||
var strptr *string
|
var strptr *string
|
||||||
if item.origText != nil {
|
if item.origText != nil {
|
||||||
@@ -542,6 +558,20 @@ func (t *Terminal) Loop() {
|
|||||||
req(reqInfo)
|
req(reqInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for _, key := range t.expect {
|
||||||
|
if keyMatch(key, event) {
|
||||||
|
t.pressed = key
|
||||||
|
req(reqClose)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if t.toggleSort > 0 {
|
||||||
|
if keyMatch(t.toggleSort, event) {
|
||||||
|
t.eventBox.Set(EvtSearchNew, true)
|
||||||
|
t.mutex.Unlock()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
switch event.Type {
|
switch event.Type {
|
||||||
case C.Invalid:
|
case C.Invalid:
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
@@ -650,7 +680,7 @@ func (t *Terminal) Loop() {
|
|||||||
} else if me.Double {
|
} else if me.Double {
|
||||||
// Double-click
|
// Double-click
|
||||||
if my >= 2 {
|
if my >= 2 {
|
||||||
if t.vset(my-2) && t.listIndex(t.cy) < t.merger.Length() {
|
if t.vset(my-2) && t.cy < t.merger.Length() {
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -671,7 +701,7 @@ func (t *Terminal) Loop() {
|
|||||||
t.mutex.Unlock() // Must be unlocked before touching reqBox
|
t.mutex.Unlock() // Must be unlocked before touching reqBox
|
||||||
|
|
||||||
if changed {
|
if changed {
|
||||||
t.eventBox.Set(EvtSearchNew, nil)
|
t.eventBox.Set(EvtSearchNew, false)
|
||||||
}
|
}
|
||||||
for _, event := range events {
|
for _, event := range events {
|
||||||
t.reqBox.Set(event, nil)
|
t.reqBox.Set(event, nil)
|
||||||
|
@@ -79,6 +79,7 @@ func (b *EventBox) Unwatch(events ...EventType) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WaitFor blocks the execution until the event is received
|
||||||
func (b *EventBox) WaitFor(event EventType) {
|
func (b *EventBox) WaitFor(event EventType) {
|
||||||
looping := true
|
looping := true
|
||||||
for looping {
|
for looping {
|
||||||
|
@@ -27,6 +27,17 @@ func Max32(first int32, second int32) int32 {
|
|||||||
return second
|
return second
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Constrain32 limits the given 32-bit integer with the upper and lower bounds
|
||||||
|
func Constrain32(val int32, min int32, max int32) int32 {
|
||||||
|
if val < min {
|
||||||
|
return min
|
||||||
|
}
|
||||||
|
if val > max {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
// Constrain limits the given integer with the upper and lower bounds
|
// Constrain limits the given integer with the upper and lower bounds
|
||||||
func Constrain(val int, min int, max int) int {
|
func Constrain(val int, min int, max int) int {
|
||||||
if val < min {
|
if val < min {
|
||||||
@@ -50,6 +61,10 @@ func DurWithin(
|
|||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func Between(val int, min int, max int) bool {
|
||||||
|
return val >= min && val <= max
|
||||||
|
}
|
||||||
|
|
||||||
// IsTty returns true is stdin is a terminal
|
// IsTty returns true is stdin is a terminal
|
||||||
func IsTty() bool {
|
func IsTty() bool {
|
||||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||||
|
342
test/test_go.rb
342
test/test_go.rb
@@ -2,11 +2,22 @@
|
|||||||
# encoding: utf-8
|
# encoding: utf-8
|
||||||
|
|
||||||
require 'minitest/autorun'
|
require 'minitest/autorun'
|
||||||
|
require 'fileutils'
|
||||||
|
|
||||||
|
Dir.chdir File.expand_path('../../', __FILE__)
|
||||||
|
|
||||||
class NilClass
|
class NilClass
|
||||||
def include? str
|
def include? str
|
||||||
false
|
false
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def start_with? str
|
||||||
|
false
|
||||||
|
end
|
||||||
|
|
||||||
|
def end_with? str
|
||||||
|
false
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
module Temp
|
module Temp
|
||||||
@@ -15,7 +26,7 @@ module Temp
|
|||||||
waited = 0
|
waited = 0
|
||||||
while waited < 5
|
while waited < 5
|
||||||
begin
|
begin
|
||||||
data = File.read(name)
|
data = `cat #{name}`
|
||||||
return data unless data.empty?
|
return data unless data.empty?
|
||||||
rescue
|
rescue
|
||||||
sleep 0.1
|
sleep 0.1
|
||||||
@@ -30,6 +41,20 @@ module Temp
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class Shell
|
||||||
|
class << self
|
||||||
|
def bash
|
||||||
|
'PS1= PROMPT_COMMAND= bash --rcfile ~/.fzf.bash'
|
||||||
|
end
|
||||||
|
|
||||||
|
def zsh
|
||||||
|
FileUtils.mkdir_p '/tmp/fzf-zsh'
|
||||||
|
FileUtils.cp File.expand_path('~/.fzf.zsh'), '/tmp/fzf-zsh/.zshrc'
|
||||||
|
'PS1= PROMPT_COMMAND= HISTSIZE=100 ZDOTDIR=/tmp/fzf-zsh zsh'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
class Tmux
|
class Tmux
|
||||||
include Temp
|
include Temp
|
||||||
|
|
||||||
@@ -37,18 +62,33 @@ class Tmux
|
|||||||
|
|
||||||
attr_reader :win
|
attr_reader :win
|
||||||
|
|
||||||
def initialize shell = 'bash'
|
def initialize shell = :bash
|
||||||
@win = go("new-window -d -P -F '#I' 'PS1= PROMPT_COMMAND= bash --rcfile ~/.fzf.#{shell}'").first
|
@win =
|
||||||
|
case shell
|
||||||
|
when :bash
|
||||||
|
go("new-window -d -P -F '#I' '#{Shell.bash}'").first
|
||||||
|
when :zsh
|
||||||
|
go("new-window -d -P -F '#I' '#{Shell.zsh}'").first
|
||||||
|
when :fish
|
||||||
|
go("new-window -d -P -F '#I' 'fish'").first
|
||||||
|
else
|
||||||
|
raise "Unknown shell: #{shell}"
|
||||||
|
end
|
||||||
@lines = `tput lines`.chomp.to_i
|
@lines = `tput lines`.chomp.to_i
|
||||||
|
|
||||||
|
if shell == :fish
|
||||||
|
send_keys('function fish_prompt; end; clear', :Enter)
|
||||||
|
self.until { |lines| lines.empty? }
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def closed?
|
def closed?
|
||||||
!go("list-window -F '#I'").include?(win)
|
!go("list-window -F '#I'").include?(win)
|
||||||
end
|
end
|
||||||
|
|
||||||
def close timeout = 1
|
def close
|
||||||
send_keys 'C-c', 'C-u', 'exit', :Enter
|
send_keys 'C-c', 'C-u', 'exit', :Enter
|
||||||
wait(timeout) { closed? }
|
wait { closed? }
|
||||||
end
|
end
|
||||||
|
|
||||||
def kill
|
def kill
|
||||||
@@ -56,35 +96,68 @@ class Tmux
|
|||||||
end
|
end
|
||||||
|
|
||||||
def send_keys *args
|
def send_keys *args
|
||||||
|
target =
|
||||||
|
if args.last.is_a?(Hash)
|
||||||
|
hash = args.pop
|
||||||
|
go("select-window -t #{win}")
|
||||||
|
"#{win}.#{hash[:pane]}"
|
||||||
|
else
|
||||||
|
win
|
||||||
|
end
|
||||||
args = args.map { |a| %{"#{a}"} }.join ' '
|
args = args.map { |a| %{"#{a}"} }.join ' '
|
||||||
go("send-keys -t #{win} #{args}")
|
go("send-keys -t #{target} #{args}")
|
||||||
end
|
end
|
||||||
|
|
||||||
def capture
|
def capture opts = {}
|
||||||
go("capture-pane -t #{win} \\; save-buffer #{TEMPNAME}")
|
timeout, pane = defaults(opts).values_at(:timeout, :pane)
|
||||||
raise "Window not found" if $?.exitstatus != 0
|
waited = 0
|
||||||
|
loop do
|
||||||
|
go("capture-pane -t #{win}.#{pane} \\; save-buffer #{TEMPNAME}")
|
||||||
|
break if $?.exitstatus == 0
|
||||||
|
|
||||||
|
if waited > timeout
|
||||||
|
raise "Window not found"
|
||||||
|
end
|
||||||
|
waited += 0.1
|
||||||
|
sleep 0.1
|
||||||
|
end
|
||||||
readonce.split($/)[0, @lines].reverse.drop_while(&:empty?).reverse
|
readonce.split($/)[0, @lines].reverse.drop_while(&:empty?).reverse
|
||||||
end
|
end
|
||||||
|
|
||||||
def until timeout = 1
|
def until opts = {}
|
||||||
wait(timeout) { yield capture }
|
lines = nil
|
||||||
|
wait(opts) do
|
||||||
|
yield lines = capture(opts)
|
||||||
|
end
|
||||||
|
lines
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def prepare
|
||||||
|
self.send_keys 'echo hello', :Enter
|
||||||
|
self.until { |lines| lines[-1].start_with?('hello') }
|
||||||
|
self.send_keys 'clear', :Enter
|
||||||
|
self.until { |lines| lines.empty? }
|
||||||
|
end
|
||||||
private
|
private
|
||||||
def wait timeout = 1
|
def defaults opts
|
||||||
|
{ timeout: 10, pane: 0 }.merge(opts)
|
||||||
|
end
|
||||||
|
|
||||||
|
def wait opts = {}
|
||||||
|
timeout, pane = defaults(opts).values_at(:timeout, :pane)
|
||||||
waited = 0
|
waited = 0
|
||||||
until yield
|
until yield
|
||||||
waited += 0.1
|
|
||||||
sleep 0.1
|
|
||||||
if waited > timeout
|
if waited > timeout
|
||||||
hl = '=' * 10
|
hl = '=' * 10
|
||||||
puts hl
|
puts hl
|
||||||
capture.each_with_index do |line, idx|
|
capture(opts).each_with_index do |line, idx|
|
||||||
puts [idx.to_s.rjust(2), line].join(': ')
|
puts [idx.to_s.rjust(2), line].join(': ')
|
||||||
end
|
end
|
||||||
puts hl
|
puts hl
|
||||||
raise "timeout"
|
raise "timeout"
|
||||||
end
|
end
|
||||||
|
waited += 0.1
|
||||||
|
sleep 0.1
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -93,7 +166,7 @@ private
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class TestGoFZF < MiniTest::Unit::TestCase
|
class TestBase < Minitest::Test
|
||||||
include Temp
|
include Temp
|
||||||
|
|
||||||
FIN = 'FIN'
|
FIN = 'FIN'
|
||||||
@@ -104,11 +177,6 @@ class TestGoFZF < MiniTest::Unit::TestCase
|
|||||||
def setup
|
def setup
|
||||||
ENV.delete 'FZF_DEFAULT_OPTS'
|
ENV.delete 'FZF_DEFAULT_OPTS'
|
||||||
ENV.delete 'FZF_DEFAULT_COMMAND'
|
ENV.delete 'FZF_DEFAULT_COMMAND'
|
||||||
@tmux = Tmux.new
|
|
||||||
end
|
|
||||||
|
|
||||||
def teardown
|
|
||||||
@tmux.kill
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def fzf(*opts)
|
def fzf(*opts)
|
||||||
@@ -129,10 +197,22 @@ class TestGoFZF < MiniTest::Unit::TestCase
|
|||||||
}.compact
|
}.compact
|
||||||
"fzf #{opts.join ' '}"
|
"fzf #{opts.join ' '}"
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class TestGoFZF < TestBase
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@tmux = Tmux.new
|
||||||
|
end
|
||||||
|
|
||||||
|
def teardown
|
||||||
|
@tmux.kill
|
||||||
|
end
|
||||||
|
|
||||||
def test_vanilla
|
def test_vanilla
|
||||||
tmux.send_keys "seq 1 100000 | #{fzf}", :Enter
|
tmux.send_keys "seq 1 100000 | #{fzf}", :Enter
|
||||||
tmux.until(10) { |lines| lines.last =~ /^>/ && lines[-2] =~ /^ 100000/ }
|
tmux.until(timeout: 20) { |lines|
|
||||||
|
lines.last =~ /^>/ && lines[-2] =~ /^ 100000/ }
|
||||||
lines = tmux.capture
|
lines = tmux.capture
|
||||||
assert_equal ' 2', lines[-4]
|
assert_equal ' 2', lines[-4]
|
||||||
assert_equal '> 1', lines[-3]
|
assert_equal '> 1', lines[-3]
|
||||||
@@ -322,5 +402,223 @@ class TestGoFZF < MiniTest::Unit::TestCase
|
|||||||
tmux.send_keys 'C-K', :Enter
|
tmux.send_keys 'C-K', :Enter
|
||||||
assert_equal ['1919'], readonce.split($/)
|
assert_equal ['1919'], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_tac
|
||||||
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
||||||
|
assert_equal %w[1000 999 998], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_tac_sort
|
||||||
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :multi}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
|
tmux.send_keys '99'
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
||||||
|
assert_equal %w[99 999 998], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_tac_nosort
|
||||||
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :no_sort, :multi}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
|
tmux.send_keys '00'
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
||||||
|
assert_equal %w[1000 900 800], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_expect
|
||||||
|
test = lambda do |key, feed, expected = key|
|
||||||
|
tmux.send_keys "seq 1 100 | #{fzf :expect, key}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys '55'
|
||||||
|
tmux.send_keys *feed
|
||||||
|
assert_equal [expected, '55'], readonce.split($/)
|
||||||
|
end
|
||||||
|
test.call 'ctrl-t', 'C-T'
|
||||||
|
test.call 'ctrl-t', 'Enter', ''
|
||||||
|
test.call 'alt-c', [:Escape, :c]
|
||||||
|
test.call 'f1', 'f1'
|
||||||
|
test.call 'f2', 'f2'
|
||||||
|
test.call 'f3', 'f3'
|
||||||
|
test.call 'f2,f4', 'f2', 'f2'
|
||||||
|
test.call 'f2,f4', 'f4', 'f4'
|
||||||
|
test.call '@', '@'
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_expect_print_query
|
||||||
|
tmux.send_keys "seq 1 100 | #{fzf '--expect=alt-z', :print_query}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys '55'
|
||||||
|
tmux.send_keys :Escape, :z
|
||||||
|
assert_equal ['55', 'alt-z', '55'], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_expect_print_query_select_1
|
||||||
|
tmux.send_keys "seq 1 100 | #{fzf '-q55 -1 --expect=alt-z --print-query'}", :Enter
|
||||||
|
assert_equal ['55', '', '55'], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_toggle_sort
|
||||||
|
tmux.send_keys "seq 1 111 | #{fzf '-m +s --tac --toggle-sort=ctrl-r -q11'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-3].include? '> 111' }
|
||||||
|
tmux.send_keys :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '4/111 (1)' }
|
||||||
|
tmux.send_keys 'C-R'
|
||||||
|
tmux.until { |lines| lines[-3].include? '> 11' }
|
||||||
|
tmux.send_keys :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '4/111 (2)' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal ['111', '11'], readonce.split($/)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
module TestShell
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
end
|
||||||
|
|
||||||
|
def teardown
|
||||||
|
@tmux.kill
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_ctrl_t
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys 'C-t', pane: 0
|
||||||
|
lines = tmux.until(pane: 1) { |lines| lines[-1].start_with? '>' }
|
||||||
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
|
tmux.send_keys :BTab, :BTab, :Enter, pane: 1
|
||||||
|
tmux.until(pane: 0) { |lines| lines[-1].include? expected }
|
||||||
|
tmux.send_keys 'C-c'
|
||||||
|
|
||||||
|
# FZF_TMUX=0
|
||||||
|
new_shell
|
||||||
|
tmux.send_keys 'C-t', pane: 0
|
||||||
|
lines = tmux.until(pane: 0) { |lines| lines[-1].start_with? '>' }
|
||||||
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
|
tmux.send_keys :BTab, :BTab, :Enter, pane: 0
|
||||||
|
tmux.until(pane: 0) { |lines| lines[-1].include? expected }
|
||||||
|
tmux.send_keys 'C-c', 'C-d'
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_alt_c
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys :Escape, :c
|
||||||
|
lines = tmux.until { |lines| lines[-1].start_with? '>' }
|
||||||
|
expected = lines[-3][2..-1]
|
||||||
|
p expected
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys :pwd, :Enter
|
||||||
|
tmux.until { |lines| p lines; lines[-1].end_with?(expected) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_ctrl_r
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys 'echo 1st', :Enter; tmux.prepare
|
||||||
|
tmux.send_keys 'echo 2nd', :Enter; tmux.prepare
|
||||||
|
tmux.send_keys 'echo 3d', :Enter; tmux.prepare
|
||||||
|
tmux.send_keys 'echo 3rd', :Enter; tmux.prepare
|
||||||
|
tmux.send_keys 'echo 4th', :Enter; tmux.prepare
|
||||||
|
tmux.send_keys 'C-r'
|
||||||
|
tmux.until { |lines| lines[-1].start_with? '>' }
|
||||||
|
tmux.send_keys '3d'
|
||||||
|
tmux.until { |lines| lines[-3].end_with? 'echo 3rd' } # --no-sort
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until { |lines| lines[-1] == 'echo 3rd' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until { |lines| lines[-1] == '3rd' }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class TestBash < TestBase
|
||||||
|
include TestShell
|
||||||
|
|
||||||
|
def new_shell
|
||||||
|
tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@tmux = Tmux.new :bash
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_file_completion
|
||||||
|
tmux.send_keys 'mkdir -p /tmp/fzf-test; touch /tmp/fzf-test/{1..100}', :Enter
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab
|
||||||
|
tmux.until { |lines| lines[-1].start_with? '>' }
|
||||||
|
tmux.send_keys :BTab, :BTab, :Enter
|
||||||
|
tmux.until { |lines|
|
||||||
|
lines[-1].include?('/tmp/fzf-test/10') &&
|
||||||
|
lines[-1].include?('/tmp/fzf-test/100')
|
||||||
|
}
|
||||||
|
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
|
||||||
|
tmux.send_keys 'cd /tmp/fzf-test/**', :Tab
|
||||||
|
tmux.until { |lines| lines[-1].start_with? '>' }
|
||||||
|
tmux.send_keys :BTab, :BTab # BTab does not work here
|
||||||
|
tmux.send_keys 55
|
||||||
|
tmux.until { |lines| lines[-2].start_with? ' 1/' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/' }
|
||||||
|
tmux.send_keys :xx
|
||||||
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
||||||
|
|
||||||
|
# Should not match regular files
|
||||||
|
tmux.send_keys :Tab
|
||||||
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
||||||
|
|
||||||
|
# Fail back to plusdirs
|
||||||
|
tmux.send_keys :BSpace, :BSpace, :BSpace
|
||||||
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55' }
|
||||||
|
tmux.send_keys :Tab
|
||||||
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/' }
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_process_completion
|
||||||
|
tmux.send_keys 'sleep 12345 &', :Enter
|
||||||
|
lines = tmux.until { |lines| lines[-1].start_with? '[1]' }
|
||||||
|
pid = lines[-1].split.last
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys 'kill ', :Tab
|
||||||
|
tmux.until { |lines| lines[-1].start_with? '>' }
|
||||||
|
tmux.send_keys 'sleep12345'
|
||||||
|
tmux.until { |lines| lines[-3].include? 'sleep 12345' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until { |lines| lines[-1] == "kill #{pid}" }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class TestZsh < TestBase
|
||||||
|
include TestShell
|
||||||
|
|
||||||
|
def new_shell
|
||||||
|
tmux.send_keys "FZF_TMUX=0 #{Shell.zsh}", :Enter
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@tmux = Tmux.new :zsh
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class TestFish < TestBase
|
||||||
|
include TestShell
|
||||||
|
|
||||||
|
def new_shell
|
||||||
|
tmux.send_keys 'env FZF_TMUX=0 fish', :Enter
|
||||||
|
tmux.send_keys 'function fish_prompt; end; clear', :Enter
|
||||||
|
tmux.until { |lines| lines.empty? }
|
||||||
|
end
|
||||||
|
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@tmux = Tmux.new :fish
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@@ -1,850 +0,0 @@
|
|||||||
#!/usr/bin/env ruby
|
|
||||||
# encoding: utf-8
|
|
||||||
|
|
||||||
require 'rubygems'
|
|
||||||
require 'curses'
|
|
||||||
require 'timeout'
|
|
||||||
require 'stringio'
|
|
||||||
require 'minitest/autorun'
|
|
||||||
require 'tempfile'
|
|
||||||
$LOAD_PATH.unshift File.expand_path('../..', __FILE__)
|
|
||||||
ENV['FZF_EXECUTABLE'] = '0'
|
|
||||||
load 'fzf'
|
|
||||||
|
|
||||||
class MockTTY
|
|
||||||
def initialize
|
|
||||||
@buffer = ''
|
|
||||||
@mutex = Mutex.new
|
|
||||||
@condv = ConditionVariable.new
|
|
||||||
end
|
|
||||||
|
|
||||||
def read_nonblock sz
|
|
||||||
@mutex.synchronize do
|
|
||||||
take sz
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def take sz
|
|
||||||
if @buffer.length >= sz
|
|
||||||
ret = @buffer[0, sz]
|
|
||||||
@buffer = @buffer[sz..-1]
|
|
||||||
ret
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def getc
|
|
||||||
sleep 0.1
|
|
||||||
while true
|
|
||||||
@mutex.synchronize do
|
|
||||||
if char = take(1)
|
|
||||||
return char
|
|
||||||
else
|
|
||||||
@condv.wait(@mutex)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def << str
|
|
||||||
@mutex.synchronize do
|
|
||||||
@buffer << str
|
|
||||||
@condv.broadcast
|
|
||||||
end
|
|
||||||
self
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
class TestRubyFZF < MiniTest::Unit::TestCase
|
|
||||||
def setup
|
|
||||||
ENV.delete 'FZF_DEFAULT_SORT'
|
|
||||||
ENV.delete 'FZF_DEFAULT_OPTS'
|
|
||||||
ENV.delete 'FZF_DEFAULT_COMMAND'
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_default_options
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal 1000, fzf.sort
|
|
||||||
assert_equal false, fzf.multi
|
|
||||||
assert_equal true, fzf.color
|
|
||||||
assert_equal nil, fzf.rxflag
|
|
||||||
assert_equal true, fzf.mouse
|
|
||||||
assert_equal nil, fzf.nth
|
|
||||||
assert_equal nil, fzf.with_nth
|
|
||||||
assert_equal true, fzf.color
|
|
||||||
assert_equal false, fzf.black
|
|
||||||
assert_equal true, fzf.ansi256
|
|
||||||
assert_equal '', fzf.query
|
|
||||||
assert_equal false, fzf.select1
|
|
||||||
assert_equal false, fzf.exit0
|
|
||||||
assert_equal nil, fzf.filter
|
|
||||||
assert_equal nil, fzf.extended
|
|
||||||
assert_equal false, fzf.reverse
|
|
||||||
assert_equal '> ', fzf.prompt
|
|
||||||
assert_equal false, fzf.print_query
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_environment_variables
|
|
||||||
# Deprecated
|
|
||||||
ENV['FZF_DEFAULT_SORT'] = '20000'
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal 20000, fzf.sort
|
|
||||||
assert_equal nil, fzf.nth
|
|
||||||
|
|
||||||
ENV['FZF_DEFAULT_OPTS'] =
|
|
||||||
'-x -m -s 10000 -q " hello world " +c +2 --select-1 -0 ' <<
|
|
||||||
'--no-mouse -f "goodbye world" --black --with-nth=3,-3..,2 --nth=3,-1,2 --reverse --print-query'
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal 10000, fzf.sort
|
|
||||||
assert_equal ' hello world ',
|
|
||||||
fzf.query
|
|
||||||
assert_equal 'goodbye world',
|
|
||||||
fzf.filter
|
|
||||||
assert_equal :fuzzy, fzf.extended
|
|
||||||
assert_equal true, fzf.multi
|
|
||||||
assert_equal false, fzf.color
|
|
||||||
assert_equal false, fzf.ansi256
|
|
||||||
assert_equal true, fzf.black
|
|
||||||
assert_equal false, fzf.mouse
|
|
||||||
assert_equal true, fzf.select1
|
|
||||||
assert_equal true, fzf.exit0
|
|
||||||
assert_equal true, fzf.reverse
|
|
||||||
assert_equal true, fzf.print_query
|
|
||||||
assert_equal [2..2, -1..-1, 1..1], fzf.nth
|
|
||||||
assert_equal [2..2, -3..-1, 1..1], fzf.with_nth
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_option_parser
|
|
||||||
# Long opts
|
|
||||||
fzf = FZF.new %w[--sort=2000 --no-color --multi +i --query hello --select-1
|
|
||||||
--exit-0 --filter=howdy --extended-exact
|
|
||||||
--no-mouse --no-256 --nth=1 --with-nth=.. --reverse --prompt (hi)
|
|
||||||
--print-query]
|
|
||||||
assert_equal 2000, fzf.sort
|
|
||||||
assert_equal true, fzf.multi
|
|
||||||
assert_equal false, fzf.color
|
|
||||||
assert_equal false, fzf.ansi256
|
|
||||||
assert_equal false, fzf.black
|
|
||||||
assert_equal false, fzf.mouse
|
|
||||||
assert_equal 0, fzf.rxflag
|
|
||||||
assert_equal 'hello', fzf.query
|
|
||||||
assert_equal true, fzf.select1
|
|
||||||
assert_equal true, fzf.exit0
|
|
||||||
assert_equal 'howdy', fzf.filter
|
|
||||||
assert_equal :exact, fzf.extended
|
|
||||||
assert_equal [0..0], fzf.nth
|
|
||||||
assert_equal nil, fzf.with_nth
|
|
||||||
assert_equal true, fzf.reverse
|
|
||||||
assert_equal '(hi)', fzf.prompt
|
|
||||||
assert_equal true, fzf.print_query
|
|
||||||
|
|
||||||
# Long opts (left-to-right)
|
|
||||||
fzf = FZF.new %w[--sort=2000 --no-color --multi +i --query=hello
|
|
||||||
--filter a --filter b --no-256 --black --nth -1 --nth -2
|
|
||||||
--select-1 --exit-0 --no-select-1 --no-exit-0
|
|
||||||
--no-sort -i --color --no-multi --256
|
|
||||||
--reverse --no-reverse --prompt (hi) --prompt=(HI)
|
|
||||||
--print-query --no-print-query]
|
|
||||||
assert_equal nil, fzf.sort
|
|
||||||
assert_equal false, fzf.multi
|
|
||||||
assert_equal true, fzf.color
|
|
||||||
assert_equal true, fzf.ansi256
|
|
||||||
assert_equal true, fzf.black
|
|
||||||
assert_equal true, fzf.mouse
|
|
||||||
assert_equal 1, fzf.rxflag
|
|
||||||
assert_equal 'b', fzf.filter
|
|
||||||
assert_equal 'hello', fzf.query
|
|
||||||
assert_equal false, fzf.select1
|
|
||||||
assert_equal false, fzf.exit0
|
|
||||||
assert_equal nil, fzf.extended
|
|
||||||
assert_equal [-2..-2], fzf.nth
|
|
||||||
assert_equal false, fzf.reverse
|
|
||||||
assert_equal '(HI)', fzf.prompt
|
|
||||||
assert_equal false, fzf.print_query
|
|
||||||
|
|
||||||
# Short opts
|
|
||||||
fzf = FZF.new %w[-s2000 +c -m +i -qhello -x -fhowdy +2 -n3 -1 -0]
|
|
||||||
assert_equal 2000, fzf.sort
|
|
||||||
assert_equal true, fzf.multi
|
|
||||||
assert_equal false, fzf.color
|
|
||||||
assert_equal false, fzf.ansi256
|
|
||||||
assert_equal 0, fzf.rxflag
|
|
||||||
assert_equal 'hello', fzf.query
|
|
||||||
assert_equal 'howdy', fzf.filter
|
|
||||||
assert_equal :fuzzy, fzf.extended
|
|
||||||
assert_equal [2..2], fzf.nth
|
|
||||||
assert_equal true, fzf.select1
|
|
||||||
assert_equal true, fzf.exit0
|
|
||||||
|
|
||||||
# Left-to-right
|
|
||||||
fzf = FZF.new %w[-s 2000 +c -m +i -qhello -x -fgoodbye +2 -n3 -n4,5
|
|
||||||
-s 3000 -c +m -i -q world +x -fworld -2 --black --no-black
|
|
||||||
-1 -0 +1 +0
|
|
||||||
]
|
|
||||||
assert_equal 3000, fzf.sort
|
|
||||||
assert_equal false, fzf.multi
|
|
||||||
assert_equal true, fzf.color
|
|
||||||
assert_equal true, fzf.ansi256
|
|
||||||
assert_equal false, fzf.black
|
|
||||||
assert_equal 1, fzf.rxflag
|
|
||||||
assert_equal 'world', fzf.query
|
|
||||||
assert_equal false, fzf.select1
|
|
||||||
assert_equal false, fzf.exit0
|
|
||||||
assert_equal 'world', fzf.filter
|
|
||||||
assert_equal nil, fzf.extended
|
|
||||||
assert_equal [3..3, 4..4], fzf.nth
|
|
||||||
rescue SystemExit => e
|
|
||||||
assert false, "Exited"
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_invalid_option
|
|
||||||
[
|
|
||||||
%w[--unknown],
|
|
||||||
%w[yo dawg],
|
|
||||||
%w[--nth=0],
|
|
||||||
%w[-n 0],
|
|
||||||
%w[-n 1..2..3],
|
|
||||||
%w[-n 1....],
|
|
||||||
%w[-n ....3],
|
|
||||||
%w[-n 1....3],
|
|
||||||
%w[-n 1..0],
|
|
||||||
%w[--nth ..0],
|
|
||||||
].each do |argv|
|
|
||||||
assert_raises(SystemExit) do
|
|
||||||
fzf = FZF.new argv
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_width
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal 5, fzf.width('abcde')
|
|
||||||
assert_equal 4, fzf.width('한글')
|
|
||||||
assert_equal 5, fzf.width('한글.')
|
|
||||||
end if RUBY_VERSION >= '1.9'
|
|
||||||
|
|
||||||
def test_trim
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal ['사.', 6], fzf.trim('가나다라마바사.', 4, true)
|
|
||||||
assert_equal ['바사.', 5], fzf.trim('가나다라마바사.', 5, true)
|
|
||||||
assert_equal ['바사.', 5], fzf.trim('가나다라마바사.', 6, true)
|
|
||||||
assert_equal ['마바사.', 4], fzf.trim('가나다라마바사.', 7, true)
|
|
||||||
assert_equal ['가나', 6], fzf.trim('가나다라마바사.', 4, false)
|
|
||||||
assert_equal ['가나', 6], fzf.trim('가나다라마바사.', 5, false)
|
|
||||||
assert_equal ['가나a', 6], fzf.trim('가나ab라마바사.', 5, false)
|
|
||||||
assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 6, false)
|
|
||||||
assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 7, false)
|
|
||||||
end if RUBY_VERSION >= '1.9'
|
|
||||||
|
|
||||||
def test_format
|
|
||||||
fzf = FZF.new []
|
|
||||||
assert_equal [['01234..', false]], fzf.format('0123456789', 7, [])
|
|
||||||
assert_equal [['012', false], ['34', true], ['..', false]],
|
|
||||||
fzf.format('0123456789', 7, [[3, 5]])
|
|
||||||
assert_equal [['..56', false], ['789', true]],
|
|
||||||
fzf.format('0123456789', 7, [[7, 10]])
|
|
||||||
assert_equal [['..56', false], ['78', true], ['9', false]],
|
|
||||||
fzf.format('0123456789', 7, [[7, 9]])
|
|
||||||
|
|
||||||
(3..5).each do |i|
|
|
||||||
assert_equal [['..', false], ['567', true], ['89', false]],
|
|
||||||
fzf.format('0123456789', 7, [[i, 8]])
|
|
||||||
end
|
|
||||||
|
|
||||||
assert_equal [['..', false], ['345', true], ['..', false]],
|
|
||||||
fzf.format('0123456789', 7, [[3, 6]])
|
|
||||||
assert_equal [['012', false], ['34', true], ['..', false]],
|
|
||||||
fzf.format('0123456789', 7, [[3, 5]])
|
|
||||||
|
|
||||||
# Multi-region
|
|
||||||
assert_equal [["0", true], ["1", false], ["2", true], ["34..", false]],
|
|
||||||
fzf.format('0123456789', 7, [[0, 1], [2, 3]])
|
|
||||||
|
|
||||||
assert_equal [["..", false], ["5", true], ["6", false], ["78", true], ["9", false]],
|
|
||||||
fzf.format('0123456789', 7, [[3, 6], [7, 9]])
|
|
||||||
|
|
||||||
assert_equal [["..", false], ["3", true], ["4", false], ["5", true], ["..", false]],
|
|
||||||
fzf.format('0123456789', 7, [[3, 4], [5, 6]])
|
|
||||||
|
|
||||||
# Multi-region Overlap
|
|
||||||
assert_equal [["..", false], ["345", true], ["..", false]],
|
|
||||||
fzf.format('0123456789', 7, [[4, 5], [3, 6]])
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_fuzzy_matcher
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
list = %w[
|
|
||||||
juice
|
|
||||||
juiceful
|
|
||||||
juiceless
|
|
||||||
juicily
|
|
||||||
juiciness
|
|
||||||
juicy]
|
|
||||||
assert matcher.caches.empty?
|
|
||||||
assert_equal(
|
|
||||||
[["juice", [[0, 1]]],
|
|
||||||
["juiceful", [[0, 1]]],
|
|
||||||
["juiceless", [[0, 1]]],
|
|
||||||
["juicily", [[0, 1]]],
|
|
||||||
["juiciness", [[0, 1]]],
|
|
||||||
["juicy", [[0, 1]]]], matcher.match(list, 'j', '', '').sort)
|
|
||||||
assert !matcher.caches.empty?
|
|
||||||
assert_equal [list.object_id], matcher.caches.keys
|
|
||||||
assert_equal 1, matcher.caches[list.object_id].length
|
|
||||||
assert_equal 6, matcher.caches[list.object_id]['j'].length
|
|
||||||
|
|
||||||
assert_equal(
|
|
||||||
[["juicily", [[0, 5]]],
|
|
||||||
["juiciness", [[0, 5]]]], matcher.match(list, 'jii', '', '').sort)
|
|
||||||
|
|
||||||
assert_equal(
|
|
||||||
[["juicily", [[2, 5]]],
|
|
||||||
["juiciness", [[2, 5]]]], matcher.match(list, 'ii', '', '').sort)
|
|
||||||
|
|
||||||
assert_equal 3, matcher.caches[list.object_id].length
|
|
||||||
assert_equal 2, matcher.caches[list.object_id]['ii'].length
|
|
||||||
|
|
||||||
# TODO : partial_cache
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_fuzzy_matcher_rxflag
|
|
||||||
assert_equal nil, FZF::FuzzyMatcher.new(nil).rxflag
|
|
||||||
assert_equal 0, FZF::FuzzyMatcher.new(0).rxflag
|
|
||||||
assert_equal 1, FZF::FuzzyMatcher.new(1).rxflag
|
|
||||||
|
|
||||||
assert_equal 1, FZF::FuzzyMatcher.new(nil).rxflag_for('abc')
|
|
||||||
assert_equal 0, FZF::FuzzyMatcher.new(nil).rxflag_for('Abc')
|
|
||||||
assert_equal 0, FZF::FuzzyMatcher.new(0).rxflag_for('abc')
|
|
||||||
assert_equal 0, FZF::FuzzyMatcher.new(0).rxflag_for('Abc')
|
|
||||||
assert_equal 1, FZF::FuzzyMatcher.new(1).rxflag_for('abc')
|
|
||||||
assert_equal 1, FZF::FuzzyMatcher.new(1).rxflag_for('Abc')
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_fuzzy_matcher_case_sensitive
|
|
||||||
# Smart-case match (Uppercase found)
|
|
||||||
assert_equal [['Fruit', [[0, 5]]]],
|
|
||||||
FZF::FuzzyMatcher.new(nil).match(%w[Fruit Grapefruit], 'Fruit', '', '').sort
|
|
||||||
|
|
||||||
# Smart-case match (Uppercase not-found)
|
|
||||||
assert_equal [["Fruit", [[0, 5]]], ["Grapefruit", [[5, 10]]]],
|
|
||||||
FZF::FuzzyMatcher.new(nil).match(%w[Fruit Grapefruit], 'fruit', '', '').sort
|
|
||||||
|
|
||||||
# Case-sensitive match (-i)
|
|
||||||
assert_equal [['Fruit', [[0, 5]]]],
|
|
||||||
FZF::FuzzyMatcher.new(0).match(%w[Fruit Grapefruit], 'Fruit', '', '').sort
|
|
||||||
|
|
||||||
# Case-insensitive match (+i)
|
|
||||||
assert_equal [["Fruit", [[0, 5]]], ["Grapefruit", [[5, 10]]]],
|
|
||||||
FZF::FuzzyMatcher.new(Regexp::IGNORECASE).
|
|
||||||
match(%w[Fruit Grapefruit], 'Fruit', '', '').sort
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_extended_fuzzy_matcher_case_sensitive
|
|
||||||
%w['Fruit Fruit$].each do |q|
|
|
||||||
# Smart-case match (Uppercase found)
|
|
||||||
assert_equal [['Fruit', [[0, 5]]]],
|
|
||||||
FZF::ExtendedFuzzyMatcher.new(nil).match(%w[Fruit Grapefruit], q, '', '').sort
|
|
||||||
|
|
||||||
# Smart-case match (Uppercase not-found)
|
|
||||||
assert_equal [["Fruit", [[0, 5]]], ["Grapefruit", [[5, 10]]]],
|
|
||||||
FZF::ExtendedFuzzyMatcher.new(nil).match(%w[Fruit Grapefruit], q.downcase, '', '').sort
|
|
||||||
|
|
||||||
# Case-sensitive match (-i)
|
|
||||||
assert_equal [['Fruit', [[0, 5]]]],
|
|
||||||
FZF::ExtendedFuzzyMatcher.new(0).match(%w[Fruit Grapefruit], q, '', '').sort
|
|
||||||
|
|
||||||
# Case-insensitive match (+i)
|
|
||||||
assert_equal [["Fruit", [[0, 5]]], ["Grapefruit", [[5, 10]]]],
|
|
||||||
FZF::ExtendedFuzzyMatcher.new(Regexp::IGNORECASE).
|
|
||||||
match(%w[Fruit Grapefruit], q, '', '').sort
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_extended_fuzzy_matcher
|
|
||||||
matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
list = %w[
|
|
||||||
juice
|
|
||||||
juiceful
|
|
||||||
juiceless
|
|
||||||
juicily
|
|
||||||
juiciness
|
|
||||||
juicy
|
|
||||||
_juice]
|
|
||||||
match = proc { |q, prefix|
|
|
||||||
matcher.match(list, q, prefix, '').sort.map { |p| [p.first, p.last.sort] }
|
|
||||||
}
|
|
||||||
|
|
||||||
assert matcher.caches.empty?
|
|
||||||
3.times do
|
|
||||||
['y j', 'j y'].each do |pat|
|
|
||||||
(0..pat.length - 1).each do |prefix_length|
|
|
||||||
prefix = pat[0, prefix_length]
|
|
||||||
assert_equal(
|
|
||||||
[["juicily", [[0, 1], [6, 7]]],
|
|
||||||
["juicy", [[0, 1], [4, 5]]]],
|
|
||||||
match.call(pat, prefix))
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# $
|
|
||||||
assert_equal [["juiceful", [[7, 8]]]], match.call('l$', '')
|
|
||||||
assert_equal [["juiceful", [[7, 8]]],
|
|
||||||
["juiceless", [[5, 6]]],
|
|
||||||
["juicily", [[5, 6]]]], match.call('l', '')
|
|
||||||
|
|
||||||
# ^
|
|
||||||
assert_equal list.length, match.call('j', '').length
|
|
||||||
assert_equal list.length - 1, match.call('^j', '').length
|
|
||||||
|
|
||||||
# ^ + $
|
|
||||||
assert_equal 0, match.call('^juici$', '').length
|
|
||||||
assert_equal 1, match.call('^juice$', '').length
|
|
||||||
assert_equal 0, match.call('^.*$', '').length
|
|
||||||
|
|
||||||
# !
|
|
||||||
assert_equal 0, match.call('!j', '').length
|
|
||||||
|
|
||||||
# ! + ^
|
|
||||||
assert_equal [["_juice", []]], match.call('!^j', '')
|
|
||||||
|
|
||||||
# ! + $
|
|
||||||
assert_equal list.length - 1, match.call('!l$', '').length
|
|
||||||
|
|
||||||
# ! + f
|
|
||||||
assert_equal [["juicy", [[4, 5]]]], match.call('y !l', '')
|
|
||||||
|
|
||||||
# '
|
|
||||||
assert_equal %w[juiceful juiceless juicily],
|
|
||||||
match.call('il', '').map { |e| e.first }
|
|
||||||
assert_equal %w[juicily],
|
|
||||||
match.call("'il", '').map { |e| e.first }
|
|
||||||
assert_equal (list - %w[juicily]).sort,
|
|
||||||
match.call("!'il", '').map { |e| e.first }.sort
|
|
||||||
end
|
|
||||||
assert !matcher.caches.empty?
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_xfuzzy_matcher_prefix_cache
|
|
||||||
matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
list = %w[
|
|
||||||
a.java
|
|
||||||
b.java
|
|
||||||
java.jive
|
|
||||||
c.java$
|
|
||||||
d.java
|
|
||||||
]
|
|
||||||
2.times do
|
|
||||||
assert_equal 5, matcher.match(list, 'java', 'java', '').length
|
|
||||||
assert_equal 3, matcher.match(list, 'java$', 'java$', '').length
|
|
||||||
assert_equal 1, matcher.match(list, 'java$$', 'java$$', '').length
|
|
||||||
|
|
||||||
assert_equal 0, matcher.match(list, '!java', '!java', '').length
|
|
||||||
assert_equal 4, matcher.match(list, '!^jav', '!^jav', '').length
|
|
||||||
assert_equal 4, matcher.match(list, '!^java', '!^java', '').length
|
|
||||||
assert_equal 2, matcher.match(list, '!^java !b !c', '!^java', '').length
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_sort_by_rank
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
xmatcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
list = %w[
|
|
||||||
0____1
|
|
||||||
0_____1
|
|
||||||
01
|
|
||||||
____0_1
|
|
||||||
01_
|
|
||||||
_01_
|
|
||||||
0______1
|
|
||||||
___01___
|
|
||||||
]
|
|
||||||
assert_equal(
|
|
||||||
[["01", [[0, 2]]],
|
|
||||||
["01_", [[0, 2]]],
|
|
||||||
["_01_", [[1, 3]]],
|
|
||||||
["___01___", [[3, 5]]],
|
|
||||||
["____0_1", [[4, 7]]],
|
|
||||||
["0____1", [[0, 6]]],
|
|
||||||
["0_____1", [[0, 7]]],
|
|
||||||
["0______1", [[0, 8]]]],
|
|
||||||
FZF.sort(matcher.match(list, '01', '', '')))
|
|
||||||
|
|
||||||
assert_equal(
|
|
||||||
[["01", [[0, 1], [1, 2]]],
|
|
||||||
["01_", [[0, 1], [1, 2]]],
|
|
||||||
["_01_", [[1, 2], [2, 3]]],
|
|
||||||
["0____1", [[0, 1], [5, 6]]],
|
|
||||||
["0_____1", [[0, 1], [6, 7]]],
|
|
||||||
["____0_1", [[4, 5], [6, 7]]],
|
|
||||||
["0______1", [[0, 1], [7, 8]]],
|
|
||||||
["___01___", [[3, 4], [4, 5]]]],
|
|
||||||
FZF.sort(xmatcher.match(list, '0 1', '', '')))
|
|
||||||
|
|
||||||
assert_equal(
|
|
||||||
[["_01_", [[1, 3], [0, 4]], [4, 4, "_01_"]],
|
|
||||||
["___01___", [[3, 5], [0, 2]], [4, 8, "___01___"]],
|
|
||||||
["____0_1", [[4, 7], [0, 2]], [5, 7, "____0_1"]],
|
|
||||||
["0____1", [[0, 6], [1, 3]], [6, 6, "0____1"]],
|
|
||||||
["0_____1", [[0, 7], [1, 3]], [7, 7, "0_____1"]],
|
|
||||||
["0______1", [[0, 8], [1, 3]], [8, 8, "0______1"]]],
|
|
||||||
FZF.sort(xmatcher.match(list, '01 __', '', '')).map { |tuple|
|
|
||||||
tuple << FZF.rank(tuple)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_extended_exact_mode
|
|
||||||
exact = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :exact
|
|
||||||
fuzzy = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy
|
|
||||||
list = %w[
|
|
||||||
extended-exact-mode-not-fuzzy
|
|
||||||
extended'-fuzzy-mode
|
|
||||||
]
|
|
||||||
assert_equal 2, fuzzy.match(list, 'extended', '', '').length
|
|
||||||
assert_equal 2, fuzzy.match(list, 'mode extended', '', '').length
|
|
||||||
assert_equal 2, fuzzy.match(list, 'xtndd', '', '').length
|
|
||||||
assert_equal 2, fuzzy.match(list, "'-fuzzy", '', '').length
|
|
||||||
|
|
||||||
assert_equal 2, exact.match(list, 'extended', '', '').length
|
|
||||||
assert_equal 2, exact.match(list, 'mode extended', '', '').length
|
|
||||||
assert_equal 0, exact.match(list, 'xtndd', '', '').length
|
|
||||||
assert_equal 1, exact.match(list, "'-fuzzy", '', '').length
|
|
||||||
assert_equal 2, exact.match(list, "-fuzzy", '', '').length
|
|
||||||
end
|
|
||||||
|
|
||||||
# ^$ -> matches empty item
|
|
||||||
def test_format_empty_item
|
|
||||||
fzf = FZF.new []
|
|
||||||
item = ['', [[0, 0]]]
|
|
||||||
line, offsets = item
|
|
||||||
tokens = fzf.format line, 80, offsets
|
|
||||||
assert_equal [], tokens
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_mouse_event
|
|
||||||
interval = FZF::MouseEvent::DOUBLE_CLICK_INTERVAL
|
|
||||||
me = FZF::MouseEvent.new nil
|
|
||||||
me.v = 10
|
|
||||||
assert_equal false, me.double?(10)
|
|
||||||
assert_equal false, me.double?(20)
|
|
||||||
me.v = 20
|
|
||||||
assert_equal false, me.double?(10)
|
|
||||||
assert_equal false, me.double?(20)
|
|
||||||
me.v = 20
|
|
||||||
assert_equal false, me.double?(10)
|
|
||||||
assert_equal true, me.double?(20)
|
|
||||||
sleep interval
|
|
||||||
assert_equal false, me.double?(20)
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_nth_match
|
|
||||||
list = [
|
|
||||||
' first second third',
|
|
||||||
'fourth fifth sixth',
|
|
||||||
]
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE
|
|
||||||
assert_equal list, matcher.match(list, 'f', '', '').map(&:first)
|
|
||||||
assert_equal [
|
|
||||||
[list[0], [[2, 5]]],
|
|
||||||
[list[1], [[9, 17]]]], matcher.match(list, 'is', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [1..1]
|
|
||||||
assert_equal [[list[1], [[8, 9]]]], matcher.match(list, 'f', '', '')
|
|
||||||
assert_equal [[list[0], [[8, 9]]]], matcher.match(list, 's', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [2..2]
|
|
||||||
assert_equal [[list[0], [[19, 20]]]], matcher.match(list, 'r', '', '')
|
|
||||||
|
|
||||||
# Comma-separated
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [2..2, 0..0]
|
|
||||||
assert_equal [[list[0], [[19, 20]]], [list[1], [[3, 4]]]], matcher.match(list, 'r', '', '')
|
|
||||||
|
|
||||||
# Ordered
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [0..0, 2..2]
|
|
||||||
assert_equal [[list[0], [[3, 4]]], [list[1], [[3, 4]]]], matcher.match(list, 'r', '', '')
|
|
||||||
|
|
||||||
regex = FZF.build_delim_regex "\t"
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [0..0], regex
|
|
||||||
assert_equal [[list[0], [[3, 10]]]], matcher.match(list, 're', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [1..1], regex
|
|
||||||
assert_equal [], matcher.match(list, 'r', '', '')
|
|
||||||
assert_equal [[list[1], [[9, 17]]]], matcher.match(list, 'is', '', '')
|
|
||||||
|
|
||||||
# Negative indexing
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [-1..-1], regex
|
|
||||||
assert_equal [[list[0], [[3, 6]]]], matcher.match(list, 'rt', '', '')
|
|
||||||
assert_equal [[list[0], [[2, 5]]], [list[1], [[9, 17]]]], matcher.match(list, 'is', '', '')
|
|
||||||
|
|
||||||
# Regex delimiter
|
|
||||||
regex = FZF.build_delim_regex "[ \t]+"
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [0..0], regex
|
|
||||||
assert_equal [list[1]], matcher.match(list, 'f', '', '').map(&:first)
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [1..1], regex
|
|
||||||
assert_equal [[list[0], [[1, 2]]], [list[1], [[8, 9]]]], matcher.match(list, 'f', '', '')
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_nth_match_range
|
|
||||||
list = [
|
|
||||||
' first second third',
|
|
||||||
'fourth fifth sixth',
|
|
||||||
]
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [1..2]
|
|
||||||
assert_equal [[list[0], [[8, 20]]]], matcher.match(list, 'sr', '', '')
|
|
||||||
assert_equal [], matcher.match(list, 'fo', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE, [1..-1, 0..0]
|
|
||||||
assert_equal [[list[0], [[8, 20]]]], matcher.match(list, 'sr', '', '')
|
|
||||||
assert_equal [[list[1], [[0, 2]]]], matcher.match(list, 'fo', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy, [0..0, 1..2]
|
|
||||||
assert_equal [], matcher.match(list, '^t', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy, [0..1, 2..2]
|
|
||||||
assert_equal [[list[0], [[16, 17]]]], matcher.match(list, '^t', '', '')
|
|
||||||
|
|
||||||
matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy, [1..-1]
|
|
||||||
assert_equal [[list[0], [[8, 9]]]], matcher.match(list, '^s', '', '')
|
|
||||||
end
|
|
||||||
|
|
||||||
def stream_for str, delay = 0
|
|
||||||
StringIO.new(str).tap do |sio|
|
|
||||||
sio.instance_eval do
|
|
||||||
alias org_gets gets
|
|
||||||
|
|
||||||
def gets
|
|
||||||
org_gets.tap { |e| sleep(@delay) unless e.nil? }
|
|
||||||
end
|
|
||||||
|
|
||||||
def reopen _
|
|
||||||
end
|
|
||||||
end
|
|
||||||
sio.instance_variable_set :@delay, delay
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def assert_fzf_output opts, given, expected
|
|
||||||
stream = stream_for given
|
|
||||||
output = stream_for ''
|
|
||||||
|
|
||||||
def sorted_lines line
|
|
||||||
line.split($/).sort
|
|
||||||
end
|
|
||||||
|
|
||||||
begin
|
|
||||||
tty = MockTTY.new
|
|
||||||
$stdout = output
|
|
||||||
fzf = FZF.new(opts, stream)
|
|
||||||
fzf.instance_variable_set :@tty, tty
|
|
||||||
thr = block_given? && Thread.new { yield tty }
|
|
||||||
fzf.start
|
|
||||||
thr && thr.join
|
|
||||||
rescue SystemExit => e
|
|
||||||
assert_equal 0, e.status
|
|
||||||
assert_equal sorted_lines(expected), sorted_lines(output.string)
|
|
||||||
ensure
|
|
||||||
$stdout = STDOUT
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_filter
|
|
||||||
{
|
|
||||||
%w[--filter=ol] => 'World',
|
|
||||||
%w[--filter=ol --print-query] => "ol\nWorld",
|
|
||||||
}.each do |opts, expected|
|
|
||||||
assert_fzf_output opts, "Hello\nWorld", expected
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_select_1
|
|
||||||
{
|
|
||||||
%w[--query=ol --select-1] => 'World',
|
|
||||||
%w[--query=ol --select-1 --print-query] => "ol\nWorld",
|
|
||||||
}.each do |opts, expected|
|
|
||||||
assert_fzf_output opts, "Hello\nWorld", expected
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_select_1_without_query
|
|
||||||
assert_fzf_output %w[--select-1], 'Hello World', 'Hello World'
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_select_1_ambiguity
|
|
||||||
begin
|
|
||||||
Timeout::timeout(0.5) do
|
|
||||||
assert_fzf_output %w[--query=o --select-1], "hello\nworld", "should not match"
|
|
||||||
end
|
|
||||||
rescue Timeout::Error
|
|
||||||
Curses.close_screen
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_exit_0
|
|
||||||
{
|
|
||||||
%w[--query=zz --exit-0] => '',
|
|
||||||
%w[--query=zz --exit-0 --print-query] => 'zz',
|
|
||||||
}.each do |opts, expected|
|
|
||||||
assert_fzf_output opts, "Hello\nWorld", expected
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_exit_0_without_query
|
|
||||||
assert_fzf_output %w[--exit-0], '', ''
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_with_nth
|
|
||||||
source = "hello world\nbatman"
|
|
||||||
assert_fzf_output %w[-0 -1 --with-nth=2,1 -x -q ^worl],
|
|
||||||
source, 'hello world'
|
|
||||||
assert_fzf_output %w[-0 -1 --with-nth=2,1 -x -q llo$],
|
|
||||||
source, 'hello world'
|
|
||||||
assert_fzf_output %w[-0 -1 --with-nth=.. -x -q llo$],
|
|
||||||
source, ''
|
|
||||||
assert_fzf_output %w[-0 -1 --with-nth=2,2,2,..,1 -x -q worlworlworlhellworlhell],
|
|
||||||
source, 'hello world'
|
|
||||||
assert_fzf_output %w[-0 -1 --with-nth=1,1,-1,1 -x -q batbatbatbat],
|
|
||||||
source, 'batman'
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_with_nth_transform
|
|
||||||
fzf = FZF.new %w[--with-nth 2..,1]
|
|
||||||
assert_equal 'my world hello', fzf.transform('hello my world')
|
|
||||||
assert_equal 'my world hello', fzf.transform('hello my world')
|
|
||||||
assert_equal 'my world hello', fzf.transform('hello my world ')
|
|
||||||
|
|
||||||
fzf = FZF.new %w[--with-nth 2,-1,2]
|
|
||||||
assert_equal 'my world my', fzf.transform('hello my world')
|
|
||||||
assert_equal 'world world world', fzf.transform('hello world')
|
|
||||||
assert_equal 'world world world', fzf.transform('hello world ')
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_ranking_overlap_match_regions
|
|
||||||
list = [
|
|
||||||
'1 3 4 2',
|
|
||||||
'1 2 3 4'
|
|
||||||
]
|
|
||||||
assert_equal [
|
|
||||||
['1 2 3 4', [[0, 13], [16, 22]]],
|
|
||||||
['1 3 4 2', [[0, 24], [12, 17]]],
|
|
||||||
], FZF.sort(FZF::ExtendedFuzzyMatcher.new(nil).match(list, '12 34', '', ''))
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_constrain
|
|
||||||
fzf = FZF.new []
|
|
||||||
|
|
||||||
# [#**** ]
|
|
||||||
assert_equal [false, 0, 0], fzf.constrain(0, 0, 5, 100)
|
|
||||||
|
|
||||||
# *****[**#** ... ] => [**#******* ... ]
|
|
||||||
assert_equal [true, 0, 2], fzf.constrain(5, 7, 10, 100)
|
|
||||||
|
|
||||||
# [**********]**#** => ***[*********#]**
|
|
||||||
assert_equal [true, 3, 12], fzf.constrain(0, 12, 15, 10)
|
|
||||||
|
|
||||||
# *****[**#** ] => ***[**#****]
|
|
||||||
assert_equal [true, 3, 5], fzf.constrain(5, 7, 10, 7)
|
|
||||||
|
|
||||||
# *****[**#** ] => ****[**#***]
|
|
||||||
assert_equal [true, 4, 6], fzf.constrain(5, 7, 10, 6)
|
|
||||||
|
|
||||||
# ***** [#] => ****[#]
|
|
||||||
assert_equal [true, 4, 4], fzf.constrain(10, 10, 5, 1)
|
|
||||||
|
|
||||||
# [ ] #**** => [#]****
|
|
||||||
assert_equal [true, 0, 0], fzf.constrain(-5, 0, 5, 1)
|
|
||||||
|
|
||||||
# [ ] **#** => **[#]**
|
|
||||||
assert_equal [true, 2, 2], fzf.constrain(-5, 2, 5, 1)
|
|
||||||
|
|
||||||
# [***** #] => [****# ]
|
|
||||||
assert_equal [true, 0, 4], fzf.constrain(0, 7, 5, 10)
|
|
||||||
|
|
||||||
# **[***** #] => [******# ]
|
|
||||||
assert_equal [true, 0, 6], fzf.constrain(2, 10, 7, 10)
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_invalid_utf8
|
|
||||||
tmp = Tempfile.new('fzf')
|
|
||||||
tmp << 'hello ' << [0xff].pack('C*') << ' world' << $/ << [0xff].pack('C*')
|
|
||||||
tmp.close
|
|
||||||
begin
|
|
||||||
Timeout::timeout(0.5) do
|
|
||||||
FZF.new(%w[-n..,1,2.. -q^ -x], File.open(tmp.path)).start
|
|
||||||
end
|
|
||||||
rescue Timeout::Error
|
|
||||||
Curses.close_screen
|
|
||||||
end
|
|
||||||
ensure
|
|
||||||
tmp.unlink
|
|
||||||
end
|
|
||||||
|
|
||||||
def test_with_nth_mock_tty
|
|
||||||
# Manual selection with input
|
|
||||||
assert_fzf_output ["--with-nth=2,1"], "hello world", "hello world" do |tty|
|
|
||||||
tty << "world"
|
|
||||||
tty << "hell"
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# Manual selection without input
|
|
||||||
assert_fzf_output ["--with-nth=2,1"], "hello world", "hello world" do |tty|
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# Manual selection with input and --multi
|
|
||||||
lines = "hello world\ngoodbye world"
|
|
||||||
assert_fzf_output %w[-m --with-nth=2,1], lines, lines do |tty|
|
|
||||||
tty << "o"
|
|
||||||
tty << "\e[Z\e[Z"
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# Manual selection without input and --multi
|
|
||||||
assert_fzf_output %w[-m --with-nth=2,1], lines, lines do |tty|
|
|
||||||
tty << "\e[Z\e[Z"
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# ALT-D
|
|
||||||
assert_fzf_output %w[--print-query], "", "hello baby = world" do |tty|
|
|
||||||
tty << "hello world baby"
|
|
||||||
tty << alt(:b) << alt(:b) << alt(:d)
|
|
||||||
tty << ctrl(:e) << " = " << ctrl(:y)
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# ALT-BACKSPACE
|
|
||||||
assert_fzf_output %w[--print-query], "", "hello baby = world " do |tty|
|
|
||||||
tty << "hello world baby"
|
|
||||||
tty << alt(:b) << alt(127.chr)
|
|
||||||
tty << ctrl(:e) << " = " << ctrl(:y)
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
|
|
||||||
# Word-movements
|
|
||||||
assert_fzf_output %w[--print-query], "", "ello!_orld!~ foo=?" do |tty|
|
|
||||||
tty << "hello_world==baby?"
|
|
||||||
tty << alt(:b) << ctrl(:d)
|
|
||||||
tty << alt(:b) << ctrl(:d)
|
|
||||||
tty << alt(:b) << ctrl(:d)
|
|
||||||
tty << alt(:f) << '!'
|
|
||||||
tty << alt(:f) << '!'
|
|
||||||
tty << alt(:d) << '~'
|
|
||||||
tty << " foo=bar foo=bar"
|
|
||||||
tty << ctrl(:w)
|
|
||||||
tty << alt(127.chr)
|
|
||||||
tty << "\r"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def alt chr
|
|
||||||
"\e#{chr}"
|
|
||||||
end
|
|
||||||
|
|
||||||
def ctrl char
|
|
||||||
char.to_s.ord - 'a'.ord + 1
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
@@ -68,6 +68,7 @@ fi
|
|||||||
|
|
||||||
if [ -d ~/.config/fish/functions ]; then
|
if [ -d ~/.config/fish/functions ]; then
|
||||||
remove ~/.config/fish/functions/fzf.fish
|
remove ~/.config/fish/functions/fzf.fish
|
||||||
|
remove ~/.config/fish/functions/fzf_key_bindings.fish
|
||||||
|
|
||||||
if [ "$(ls -A ~/.config/fish/functions)" ]; then
|
if [ "$(ls -A ~/.config/fish/functions)" ]; then
|
||||||
echo "Can't delete non-empty directory: \"~/.config/fish/functions\""
|
echo "Can't delete non-empty directory: \"~/.config/fish/functions\""
|
||||||
|
Reference in New Issue
Block a user