mirror of
https://github.com/junegunn/fzf.git
synced 2025-08-03 21:52:00 -07:00
Compare commits
165 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
355d004895 | ||
|
a336494f5d | ||
|
8270f7f0ca | ||
|
638a956a9e | ||
|
d395ebd28f | ||
|
c0d3faa84f | ||
|
3492c8b780 | ||
|
a8b2c257cd | ||
|
5e8d8dab82 | ||
|
b504c6eb39 | ||
|
d261c36cde | ||
|
fe4e452d68 | ||
|
d54a4fa223 | ||
|
45bd323cab | ||
|
8677dbded1 | ||
|
794ad5785d | ||
|
fa5b58968e | ||
|
e720f56ea8 | ||
|
7db53e6459 | ||
|
e287bd7f04 | ||
|
022435a90a | ||
|
6c99cc1700 | ||
|
fe5b190a7d | ||
|
77bab51696 | ||
|
77048f3e3b | ||
|
8b618f7439 | ||
|
8973207bb4 | ||
|
6ad1736832 | ||
|
9fca611c4a | ||
|
8e7164553f | ||
|
3b52811796 | ||
|
2e84b1db64 | ||
|
9f33068ab3 | ||
|
eaa3c67a5e | ||
|
1b9b1d15bc | ||
|
97f433a274 | ||
|
45a3655eaf | ||
|
81ffde92fb | ||
|
0be4cead20 | ||
|
f6dd32046e | ||
|
443a80f254 | ||
|
8017635a71 | ||
|
98f62b191a | ||
|
52771a6226 | ||
|
b00bcf506e | ||
|
fdbfe36c0b | ||
|
446e822723 | ||
|
b68e59a24b | ||
|
4e0e492427 | ||
|
8f99f8fcc6 | ||
|
3cdf71801e | ||
|
801cf9ac62 | ||
|
34946b72a5 | ||
|
1592bedbe8 | ||
|
15099eb13b | ||
|
c511b45ff6 | ||
|
40761b11b1 | ||
|
cca543d0cd | ||
|
34e5e2dd82 | ||
|
2b7c3df66b | ||
|
f766531e74 | ||
|
7f59b42b05 | ||
|
f41de932d6 | ||
|
b4a05ff27e | ||
|
3b91467941 | ||
|
26d2af5ee8 | ||
|
2b61dc6557 | ||
|
0b770cd48a | ||
|
c14aa99ef6 | ||
|
8f371ee81c | ||
|
3b63b39810 | ||
|
0cd238700c | ||
|
14fbe06d9e | ||
|
64949bf467 | ||
|
732f133940 | ||
|
5dc4df9570 | ||
|
7dde8dbbd9 | ||
|
01405ad92e | ||
|
683abb86ef | ||
|
207aa07891 | ||
|
26a141c6a6 | ||
|
dc64568c83 | ||
|
f4a595eedd | ||
|
5a17a6323a | ||
|
2b8e445321 | ||
|
315499b1d4 | ||
|
65a2bdb01d | ||
|
ed8202efc6 | ||
|
0937bd6c16 | ||
|
3d26b5336c | ||
|
c8f208b96b | ||
|
2e339e49b8 | ||
|
5d9107fd15 | ||
|
4b7c571575 | ||
|
5502b68a1d | ||
|
5794fd42df | ||
|
9c6e46ab15 | ||
|
09d0ac0347 | ||
|
22ae7adac8 | ||
|
36924d0b1c | ||
|
6ed9de9051 | ||
|
857619995e | ||
|
9310ae28ab | ||
|
27e26bd1ea | ||
|
305ec3b3ce | ||
|
f4fe93338b | ||
|
3b84c80d56 | ||
|
5e120e7ab5 | ||
|
a4cf5510e3 | ||
|
edb5ab5622 | ||
|
06b4f75680 | ||
|
318edc8c35 | ||
|
651a8f8cc2 | ||
|
9f64a00549 | ||
|
a88bf87e2a | ||
|
e82eb27787 | ||
|
3f0e6a5806 | ||
|
917b1759b0 | ||
|
16ca9c688b | ||
|
7b6a27cb5e | ||
|
869a234938 | ||
|
537d07c1e5 | ||
|
d091a2c4bb | ||
|
d2f95d69fb | ||
|
1169cc8653 | ||
|
f66d94c6b0 | ||
|
2fe1e28220 | ||
|
288131ac5a | ||
|
3610acec5a | ||
|
cc67d2e1cf | ||
|
f77ed0fb07 | ||
|
a30908c66a | ||
|
f9225f98e7 | ||
|
2db2feea37 | ||
|
d1d59272a2 | ||
|
d08542ce5d | ||
|
b8904a8c3e | ||
|
48ab87294b | ||
|
3e1e75fe08 | ||
|
120cc0aadd | ||
|
853012ceef | ||
|
2add45fe2f | ||
|
b882de87ab | ||
|
2d68cb8639 | ||
|
3a9d1df026 | ||
|
5c25984ea0 | ||
|
319d6ced80 | ||
|
51a19a2804 | ||
|
a7cb1a78df | ||
|
d4daece76b | ||
|
3ec83babac | ||
|
91fc6c984b | ||
|
a4f3d09704 | ||
|
40180c18ac | ||
|
82bea6758a | ||
|
348731fc3b | ||
|
797f42ecc6 | ||
|
8385a55bda | ||
|
8406cedf2d | ||
|
f22b83db6c | ||
|
1481304d3b | ||
|
2cec5c0f30 | ||
|
4760bb7743 | ||
|
c1adf0cd3d | ||
|
622e69ff54 |
10
.travis.yml
10
.travis.yml
@@ -12,17 +12,13 @@ install:
|
|||||||
- sudo apt-get install -y zsh fish
|
- sudo apt-get install -y zsh fish
|
||||||
|
|
||||||
script: |
|
script: |
|
||||||
export GOROOT=~/go1.4
|
|
||||||
export GOPATH=~/go
|
export GOPATH=~/go
|
||||||
export FZF_BASE=~/go/src/github.com/junegunn/fzf
|
export FZF_BASE=$GOPATH/src/github.com/junegunn/fzf
|
||||||
|
|
||||||
mkdir -p ~/go/src/github.com/junegunn
|
mkdir -p $GOPATH/src/github.com/junegunn
|
||||||
ln -s $(pwd) $FZF_BASE
|
ln -s $(pwd) $FZF_BASE
|
||||||
|
|
||||||
curl https://storage.googleapis.com/golang/go1.4.1.linux-amd64.tar.gz | tar -xz
|
|
||||||
mv go $GOROOT
|
|
||||||
|
|
||||||
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 && rm -f fzf &&
|
||||||
tmux new "ruby test/test_go.rb > out && touch ok" && cat out && [ -e ok ]
|
tmux new "ruby test/test_go.rb > out && touch ok" && cat out && [ -e ok ]
|
||||||
|
118
CHANGELOG.md
118
CHANGELOG.md
@@ -1,6 +1,124 @@
|
|||||||
CHANGELOG
|
CHANGELOG
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
0.10.0
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- More actions for `--bind`
|
||||||
|
- `select-all`
|
||||||
|
- `deselect-all`
|
||||||
|
- `toggle-all`
|
||||||
|
- `ignore`
|
||||||
|
- `execute(...)` action for running arbitrary command without leaving fzf
|
||||||
|
- `fzf --bind "ctrl-m:execute(less {})"`
|
||||||
|
- `fzf --bind "ctrl-t:execute(tmux new-window -d 'vim {}')"`
|
||||||
|
- If the command contains parentheses, use any of the follows alternative
|
||||||
|
notations to avoid parse errors
|
||||||
|
- `execute[...]`
|
||||||
|
- `execute~...~`
|
||||||
|
- `execute!...!`
|
||||||
|
- `execute@...@`
|
||||||
|
- `execute#...#`
|
||||||
|
- `execute$...$`
|
||||||
|
- `execute%...%`
|
||||||
|
- `execute^...^`
|
||||||
|
- `execute&...&`
|
||||||
|
- `execute*...*`
|
||||||
|
- `execute;...;`
|
||||||
|
- `execute/.../`
|
||||||
|
- `execute|...|`
|
||||||
|
- `execute:...`
|
||||||
|
- This is the special form that frees you from parse errors as it
|
||||||
|
does not expect the closing character
|
||||||
|
- The catch is that it should be the last one in the
|
||||||
|
comma-separated list
|
||||||
|
- Added support for optional search history
|
||||||
|
- `--history HISTORY_FILE`
|
||||||
|
- When used, `CTRL-N` and `CTRL-P` are automatically remapped to
|
||||||
|
`next-history` and `previous-history`
|
||||||
|
- `--history-size MAX_ENTRIES` (default: 1000)
|
||||||
|
- Cyclic scrolling can be enabled with `--cycle`
|
||||||
|
- Fixed the bug where the spinner was not spinning on idle input stream
|
||||||
|
- e.g. `sleep 100 | fzf`
|
||||||
|
|
||||||
|
### Minor improvements/fixes
|
||||||
|
|
||||||
|
- Added synonyms for key names that can be specified for `--bind`,
|
||||||
|
`--toggle-sort`, and `--expect`
|
||||||
|
- Fixed the color of multi-select marker on the current line
|
||||||
|
- Fixed to allow `^pattern$` in extended-search mode
|
||||||
|
|
||||||
|
|
||||||
|
0.9.13
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Color customization with the extended `--color` option
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed premature termination of Reader in the presence of a long line which
|
||||||
|
is longer than 64KB
|
||||||
|
|
||||||
|
0.9.12
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--bind` option for custom key bindings
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed to update "inline-info" immediately after terminal resize
|
||||||
|
- Fixed ANSI code offset calculation
|
||||||
|
|
||||||
|
0.9.11
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--inline-info` option for saving screen estate (#202)
|
||||||
|
- Useful inside Neovim
|
||||||
|
- e.g. `let $FZF_DEFAULT_OPTS = $FZF_DEFAULT_OPTS.' --inline-info'`
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Invalid mutation of input on case conversion (#209)
|
||||||
|
- Smart-case for each term in extended-search mode (#208)
|
||||||
|
- Fixed double-click result when scroll offset is positive
|
||||||
|
|
||||||
|
0.9.10
|
||||||
|
------
|
||||||
|
|
||||||
|
### Improvements
|
||||||
|
|
||||||
|
- Performance optimization
|
||||||
|
- Less aggressive memoization to limit memory usage
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added color scheme for light background: `--color=light`
|
||||||
|
|
||||||
|
0.9.9
|
||||||
|
-----
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--tiebreak` option (#191)
|
||||||
|
- Added `--no-hscroll` option (#193)
|
||||||
|
- Visual indication of `--toggle-sort` (#194)
|
||||||
|
|
||||||
|
0.9.8
|
||||||
|
-----
|
||||||
|
|
||||||
|
### Bug fixes
|
||||||
|
|
||||||
|
- Fixed Unicode case handling (#186)
|
||||||
|
- Fixed to terminate on RuneError (#185)
|
||||||
|
|
||||||
0.9.7
|
0.9.7
|
||||||
-----
|
-----
|
||||||
|
|
||||||
|
147
README.md
147
README.md
@@ -1,4 +1,4 @@
|
|||||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf)
|
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf) <a href="http://flattr.com/thing/3115381/junegunnfzf-on-GitHub" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a>
|
||||||
===
|
===
|
||||||
|
|
||||||
fzf is a general-purpose command-line fuzzy finder.
|
fzf is a general-purpose command-line fuzzy finder.
|
||||||
@@ -8,7 +8,7 @@ fzf is a general-purpose command-line fuzzy finder.
|
|||||||
Pros
|
Pros
|
||||||
----
|
----
|
||||||
|
|
||||||
- No dependency
|
- No dependencies
|
||||||
- Blazingly fast
|
- Blazingly fast
|
||||||
- e.g. `locate / | fzf`
|
- e.g. `locate / | fzf`
|
||||||
- Flexible layout
|
- Flexible layout
|
||||||
@@ -16,7 +16,7 @@ Pros
|
|||||||
- The most comprehensive feature set
|
- The most comprehensive feature set
|
||||||
- Try `fzf --help` and be surprised
|
- Try `fzf --help` and be surprised
|
||||||
- Batteries included
|
- Batteries included
|
||||||
- Vim plugin, key bindings and fuzzy auto-completion
|
- Vim/Neovim plugin, key bindings and fuzzy auto-completion
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
@@ -27,7 +27,8 @@ fzf project consists of the followings:
|
|||||||
- `fzf-tmux` script for launching fzf in a tmux pane
|
- `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 only)
|
- Fuzzy auto-completion (bash, zsh)
|
||||||
|
- Vim/Neovim plugin
|
||||||
|
|
||||||
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.
|
||||||
@@ -44,17 +45,6 @@ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
|
|||||||
~/.fzf/install
|
~/.fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Using curl
|
|
||||||
|
|
||||||
In case you don't have git installed:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
mkdir -p ~/.fzf
|
|
||||||
curl -L https://github.com/junegunn/fzf/archive/master.tar.gz |
|
|
||||||
tar xz --strip-components 1 -C ~/.fzf
|
|
||||||
~/.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.
|
||||||
@@ -88,7 +78,7 @@ while. Please follow the instruction below depending on the installation
|
|||||||
method.
|
method.
|
||||||
|
|
||||||
- git: `cd ~/.fzf && git pull && ./install`
|
- git: `cd ~/.fzf && git pull && ./install`
|
||||||
- brew: `brew update && brew upgrade fzf && $(brew info fzf | grep /install)`
|
- brew: `brew reinstall --HEAD fzf`
|
||||||
- vim-plug: `:PlugUpdate fzf`
|
- vim-plug: `:PlugUpdate fzf`
|
||||||
|
|
||||||
Usage
|
Usage
|
||||||
@@ -152,21 +142,18 @@ 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.
|
- Sort is disabled by default to respect chronological ordering
|
||||||
|
- 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, fzf will start in a split pane. You may disable
|
||||||
may disable this tmux integration by setting `FZF_TMUX` to 0, or change the
|
this tmux integration by setting `FZF_TMUX` to 0, or change the height of the
|
||||||
height of the window with `FZF_TMUX_HEIGHT` (e.g. `20`, `50%`).
|
pane with `FZF_TMUX_HEIGHT` (e.g. `20`, `50%`).
|
||||||
|
|
||||||
If you use vi mode on bash, you need to add `set -o vi` *before* `source
|
If you use vi mode on bash, you need to add `set -o vi` *before* `source
|
||||||
~/.fzf.bash` in your .bashrc, so that it correctly sets up key bindings for vi
|
~/.fzf.bash` in your .bashrc, so that it correctly sets up key bindings for vi
|
||||||
mode.
|
mode.
|
||||||
|
|
||||||
If you want to customize the key bindings, consider editing the
|
|
||||||
installer-generated source code: `~/.fzf.bash`, `~/.fzf.zsh`, and
|
|
||||||
`~/.config/fish/functions/fzf_key_bindings.fish`.
|
|
||||||
|
|
||||||
`fzf-tmux` script
|
`fzf-tmux` script
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
@@ -186,8 +173,8 @@ 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]`
|
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.
|
options, so you can invariably use `fzf-tmux` in your scripts.
|
||||||
|
|
||||||
Fuzzy completion for bash
|
Fuzzy completion for bash and zsh
|
||||||
-------------------------
|
---------------------------------
|
||||||
|
|
||||||
#### Files and directories
|
#### Files and directories
|
||||||
|
|
||||||
@@ -274,35 +261,20 @@ If you have set up fzf for Vim, `:FZF` command will be added.
|
|||||||
|
|
||||||
" With options
|
" With options
|
||||||
:FZF --no-sort -m /tmp
|
:FZF --no-sort -m /tmp
|
||||||
|
|
||||||
|
" Bang version starts in fullscreen instead of using tmux pane or Neovim split
|
||||||
|
:FZF!
|
||||||
```
|
```
|
||||||
|
|
||||||
Similarly to [ctrlp.vim](https://github.com/kien/ctrlp.vim), use enter key,
|
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,
|
`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.
|
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
|
||||||
also apply here.
|
`FZF_DEFAULT_OPTS` also apply here. Refer to [the wiki page][fzf-config] for
|
||||||
|
customization.
|
||||||
|
|
||||||
If you're on a tmux session, `:FZF` will launch fzf in a new split-window whose
|
[fzf-config]: https://github.com/junegunn/fzf/wiki/Configuring-FZF-command-(vim)
|
||||||
height can be adjusted with `g:fzf_tmux_height` (default: '40%'). However, the
|
|
||||||
bang version (`:FZF!`) will always start in fullscreen.
|
|
||||||
|
|
||||||
In GVim, you need an external terminal emulator to start fzf with. `xterm`
|
|
||||||
command is used by default, but you can customize it with `g:fzf_launcher`.
|
|
||||||
|
|
||||||
```vim
|
|
||||||
" This is the default. %s is replaced with fzf command
|
|
||||||
let g:fzf_launcher = 'xterm -e bash -ic %s'
|
|
||||||
|
|
||||||
" Use urxvt instead
|
|
||||||
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.
|
|
||||||
Refer to the [this wiki
|
|
||||||
page](https://github.com/junegunn/fzf/wiki/On-MacVim-with-iTerm2) to see
|
|
||||||
|
|
||||||
how to set up.
|
|
||||||
|
|
||||||
#### `fzf#run([options])`
|
#### `fzf#run([options])`
|
||||||
|
|
||||||
@@ -317,10 +289,16 @@ of the selected items.
|
|||||||
| `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 |
|
||||||
|
| `sink*` | funcref | Similar to `sink`, but takes the list of output lines at once |
|
||||||
| `options` | string | Options to fzf |
|
| `options` | string | Options to fzf |
|
||||||
| `dir` | string | Working directory |
|
| `dir` | string | Working directory |
|
||||||
| `up`/`down`/`left`/`right` | number/string | Use tmux pane with the given size (e.g. `20`, `50%`) |
|
| `up`/`down`/`left`/`right` | number/string | Use tmux pane with the given size (e.g. `20`, `50%`) |
|
||||||
| `launcher` | string | External terminal emulator to start fzf with (Only used in GVim) |
|
| `window` (*Neovim only*) | string | Command to open fzf window (e.g. `vertical aboveleft 30new`) |
|
||||||
|
| `launcher` | string | External terminal emulator to start fzf with (GVim only) |
|
||||||
|
| `launcher` | funcref | Function for generating `launcher` string (GVim only) |
|
||||||
|
|
||||||
|
_However on Neovim `fzf#run` is asynchronous and does not return values so you
|
||||||
|
should use `sink` or `sink*` to process the output from fzf._
|
||||||
|
|
||||||
##### Examples
|
##### Examples
|
||||||
|
|
||||||
@@ -358,32 +336,28 @@ handy mapping that selects an open buffer.
|
|||||||
|
|
||||||
```vim
|
```vim
|
||||||
" List of buffers
|
" List of buffers
|
||||||
function! BufList()
|
function! s:buflist()
|
||||||
redir => ls
|
redir => ls
|
||||||
silent ls
|
silent ls
|
||||||
redir END
|
redir END
|
||||||
return split(ls, '\n')
|
return split(ls, '\n')
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! BufOpen(e)
|
function! s:bufopen(e)
|
||||||
execute 'buffer '. matchstr(a:e, '^[ 0-9]*')
|
execute 'buffer' matchstr(a:e, '^[ 0-9]*')
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
||||||
\ 'source': reverse(BufList()),
|
\ 'source': reverse(<sid>buflist()),
|
||||||
\ 'sink': function('BufOpen'),
|
\ 'sink': function('<sid>bufopen'),
|
||||||
\ 'options': '+m',
|
\ 'options': '+m',
|
||||||
\ 'down': '40%'
|
\ 'down': len(<sid>buflist()) + 2
|
||||||
\ })<CR>
|
\ })<CR>
|
||||||
```
|
```
|
||||||
|
|
||||||
More examples can be found on [the wiki
|
More examples can be found on [the wiki
|
||||||
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
||||||
|
|
||||||
#### Articles
|
|
||||||
|
|
||||||
- [fzf+vim+tmux](http://junegunn.kr/2014/04/fzf+vim+tmux)
|
|
||||||
|
|
||||||
Tips
|
Tips
|
||||||
----
|
----
|
||||||
|
|
||||||
@@ -396,9 +370,9 @@ If you have any rendering issues, check the followings:
|
|||||||
2. If you're on screen or tmux, `$TERM` should be either `screen` or
|
2. If you're on screen or tmux, `$TERM` should be either `screen` or
|
||||||
`screen-256color`
|
`screen-256color`
|
||||||
3. Some terminal emulators (e.g. mintty) have problem displaying default
|
3. Some terminal emulators (e.g. mintty) have problem displaying default
|
||||||
background color and make some text unable to read. In that case, try `--black`
|
background color and make some text unable to read. In that case, try
|
||||||
option. And if it solves your problem, I recommend including it in
|
`--black` option. And if it solves your problem, I recommend including it
|
||||||
`FZF_DEFAULT_OPTS` for further convenience.
|
in `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`
|
||||||
@@ -429,41 +403,6 @@ export FZF_DEFAULT_COMMAND='
|
|||||||
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Using fzf with tmux panes
|
|
||||||
|
|
||||||
The supplied [fzf-tmux](bin/fzf-tmux) script should suffice in most of the
|
|
||||||
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
|
|
||||||
# This is a helper function that splits the current pane to start the given
|
|
||||||
# command ($1) and sends its output back to the original pane with any number of
|
|
||||||
# optional keys (shift; $*).
|
|
||||||
fzf_tmux_helper() {
|
|
||||||
[ -n "$TMUX_PANE" ] || return
|
|
||||||
local cmd=$1
|
|
||||||
shift
|
|
||||||
tmux split-window -p 40 \
|
|
||||||
"bash -c \"\$(tmux send-keys -t $TMUX_PANE \"\$(source ~/.fzf.bash; $cmd)\" $*)\""
|
|
||||||
}
|
|
||||||
|
|
||||||
# This is the function we are going to run in the split pane.
|
|
||||||
# - "find" to list the directories
|
|
||||||
# - "sed" will escape spaces in the paths.
|
|
||||||
# - "paste" will join the selected paths into a single line
|
|
||||||
fzf_tmux_dir() {
|
|
||||||
fzf_tmux_helper \
|
|
||||||
'find * -path "*/\.*" -prune -o -type d -print 2> /dev/null |
|
|
||||||
fzf --multi |
|
|
||||||
sed "s/ /\\\\ /g" |
|
|
||||||
paste -sd" " -' Space
|
|
||||||
}
|
|
||||||
|
|
||||||
# Bind CTRL-X-CTRL-D to fzf_tmux_dir
|
|
||||||
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)
|
||||||
@@ -472,19 +411,7 @@ simple `vim (fzf)` won't work as expected. The workaround is to store the result
|
|||||||
of fzf to a temporary file.
|
of fzf to a temporary file.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
function vimf
|
fzf > $TMPDIR/fzf.result; and vim (cat $TMPDIR/fzf.result)
|
||||||
if fzf > $TMPDIR/fzf.result
|
|
||||||
vim (cat $TMPDIR/fzf.result)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
function fe
|
|
||||||
set tmp $TMPDIR/fzf.result
|
|
||||||
fzf --query="$argv[1]" --select-1 --exit-0 > $tmp
|
|
||||||
if [ (cat $tmp | wc -l) -gt 0 ]
|
|
||||||
vim (cat $tmp)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Handling UTF-8 NFD paths on OSX
|
#### Handling UTF-8 NFD paths on OSX
|
||||||
|
25
bin/fzf-tmux
25
bin/fzf-tmux
@@ -89,16 +89,14 @@ fi
|
|||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
# Build arguments to fzf
|
|
||||||
[ ${#args[@]} -gt 0 ] && fzf_args=$(printf '\\"%s\\" ' "${args[@]}"; echo '')
|
|
||||||
|
|
||||||
# Clean up named pipes on exit
|
# Clean up named pipes on exit
|
||||||
id=$RANDOM
|
id=$RANDOM
|
||||||
|
argsf=/tmp/fzf-args-$id
|
||||||
fifo1=/tmp/fzf-fifo1-$id
|
fifo1=/tmp/fzf-fifo1-$id
|
||||||
fifo2=/tmp/fzf-fifo2-$id
|
fifo2=/tmp/fzf-fifo2-$id
|
||||||
fifo3=/tmp/fzf-fifo3-$id
|
fifo3=/tmp/fzf-fifo3-$id
|
||||||
cleanup() {
|
cleanup() {
|
||||||
rm -f $fifo1 $fifo2 $fifo3
|
rm -f $argsf $fifo1 $fifo2 $fifo3
|
||||||
}
|
}
|
||||||
trap cleanup EXIT SIGINT SIGTERM
|
trap cleanup EXIT SIGINT SIGTERM
|
||||||
|
|
||||||
@@ -106,20 +104,31 @@ fail() {
|
|||||||
>&2 echo "$1"
|
>&2 echo "$1"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
fzf=$(which fzf 2> /dev/null) || fail "fzf executable not found"
|
fzf="$(which fzf 2> /dev/null)" || fzf="$(dirname "$0")/fzf"
|
||||||
envs=""
|
[ -x "$fzf" ] || fail "fzf executable not found"
|
||||||
|
|
||||||
|
envs="env "
|
||||||
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
||||||
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
||||||
|
|
||||||
mkfifo $fifo2
|
mkfifo $fifo2
|
||||||
mkfifo $fifo3
|
mkfifo $fifo3
|
||||||
|
|
||||||
|
# Build arguments to fzf
|
||||||
|
opts=""
|
||||||
|
for arg in "${args[@]}"; do
|
||||||
|
opts="$opts \"${arg//\"/\\\"}\""
|
||||||
|
done
|
||||||
|
|
||||||
if [ -n "$term" -o -t 0 ]; then
|
if [ -n "$term" -o -t 0 ]; then
|
||||||
|
cat <<< "$fzf $opts > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||||
tmux set-window-option -q synchronize-panes off \;\
|
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
|
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap
|
||||||
else
|
else
|
||||||
mkfifo $fifo1
|
mkfifo $fifo1
|
||||||
|
cat <<< "$fzf $opts < $fifo1 > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||||
tmux set-window-option -q synchronize-panes off \;\
|
tmux set-window-option -q synchronize-panes off \;\
|
||||||
split-window $opt "$envs"' sh -c "'$fzf' '"$fzf_args"' < '$fifo1' > '$fifo2'; echo \$? > '$fifo3' '"$close"'"' $swap
|
split-window $opt "$envs bash $argsf" $swap
|
||||||
cat <&0 > $fifo1 &
|
cat <&0 > $fifo1 &
|
||||||
fi
|
fi
|
||||||
cat $fifo2
|
cat $fifo2
|
||||||
|
6
fzf
6
fzf
@@ -206,9 +206,11 @@ class FZF
|
|||||||
@expect = true
|
@expect = true
|
||||||
when /^--expect=(.*)$/
|
when /^--expect=(.*)$/
|
||||||
@expect = true
|
@expect = true
|
||||||
when '--toggle-sort'
|
when '--toggle-sort', '--tiebreak', '--color', '--bind', '--history', '--history-size'
|
||||||
argv.shift
|
argv.shift
|
||||||
when '--tac', '--sync', '--toggle-sort', /^--toggle-sort=(.*)$/
|
when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',
|
||||||
|
'--inline-info', '--no-inline-info', '--read0', '--cycle', /^--bind=(.*)$/,
|
||||||
|
/^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/, /^--history(-max)?=(.*)$/
|
||||||
# XXX
|
# XXX
|
||||||
else
|
else
|
||||||
usage 1, "illegal option: #{o}"
|
usage 1, "illegal option: #{o}"
|
||||||
|
17
install
17
install
@@ -1,12 +1,19 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
version=0.9.7
|
version=0.10.0
|
||||||
|
|
||||||
cd $(dirname $BASH_SOURCE)
|
cd $(dirname $BASH_SOURCE)
|
||||||
fzf_base=$(pwd)
|
fzf_base=$(pwd)
|
||||||
|
|
||||||
|
# If stdin is a tty, we are "interactive".
|
||||||
|
[ -t 0 ] && interactive=yes
|
||||||
|
|
||||||
ask() {
|
ask() {
|
||||||
read -p "$1 ([y]/n) " -n 1 -r
|
# non-interactive shell: wait for a linefeed
|
||||||
|
# interactive shell: continue after a single keypress
|
||||||
|
[ -n "$interactive" ] && read_n='-n 1' || read_n=
|
||||||
|
|
||||||
|
read -p "$1 ([y]/n) " $read_n -r
|
||||||
echo
|
echo
|
||||||
[[ ! $REPLY =~ ^[Nn]$ ]]
|
[[ ! $REPLY =~ ^[Nn]$ ]]
|
||||||
}
|
}
|
||||||
@@ -154,6 +161,8 @@ if [ -n "$binary_error" ]; then
|
|||||||
echo "OK"
|
echo "OK"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
[[ "$*" =~ "--bin" ]] && exit 0
|
||||||
|
|
||||||
# Auto-completion
|
# Auto-completion
|
||||||
ask "Do you want to add auto-completion support?"
|
ask "Do you want to add auto-completion support?"
|
||||||
auto_completion=$?
|
auto_completion=$?
|
||||||
@@ -167,8 +176,8 @@ 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/shell/completion.${shell}\""
|
fzf_completion="[[ \$- =~ i ]] && source \"$fzf_base/shell/completion.${shell}\" 2> /dev/null"
|
||||||
if [ $shell != bash -o $auto_completion -ne 0 ]; then
|
if [ $auto_completion -ne 0 ]; then
|
||||||
fzf_completion="# $fzf_completion"
|
fzf_completion="# $fzf_completion"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
200
man/man1/fzf.1
200
man/man1/fzf.1
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
..
|
..
|
||||||
.TH fzf 1 "March 2015" "fzf 0.9.6" "fzf - a command-line fuzzy finder"
|
.TH fzf 1 "June 2015" "fzf 0.10.0" "fzf - a command-line fuzzy finder"
|
||||||
|
|
||||||
.SH NAME
|
.SH NAME
|
||||||
fzf - a command-line fuzzy finder
|
fzf - a command-line fuzzy finder
|
||||||
@@ -52,10 +52,10 @@ Comma-separated list of field index expressions for limiting search scope.
|
|||||||
See \fBFIELD INDEX EXPRESSION\fR for details.
|
See \fBFIELD INDEX EXPRESSION\fR for details.
|
||||||
.TP
|
.TP
|
||||||
.BI "--with-nth=" "N[,..]"
|
.BI "--with-nth=" "N[,..]"
|
||||||
Transform the item using the list of index expressions for search
|
Transform each item using index expressions within finder
|
||||||
.TP
|
.TP
|
||||||
.BI "-d, --delimiter=" "STR"
|
.BI "-d, --delimiter=" "STR"
|
||||||
Field delimiter regex for \fI--nth\fR and \fI--with-nth\fR (default: AWK-style)
|
Field delimiter regex for \fB--nth\fR and \fB--with-nth\fR (default: AWK-style)
|
||||||
.SS Search result
|
.SS Search result
|
||||||
.TP
|
.TP
|
||||||
.B "+s, --no-sort"
|
.B "+s, --no-sort"
|
||||||
@@ -66,6 +66,20 @@ Reverse the order of the input
|
|||||||
.RS
|
.RS
|
||||||
e.g. \fBhistory | fzf --tac --no-sort\fR
|
e.g. \fBhistory | fzf --tac --no-sort\fR
|
||||||
.RE
|
.RE
|
||||||
|
.TP
|
||||||
|
.BI "--tiebreak=" "CRI"
|
||||||
|
Sort criterion to use when the scores are tied
|
||||||
|
.br
|
||||||
|
.R ""
|
||||||
|
.br
|
||||||
|
.BR length " Prefers item with shorter length"
|
||||||
|
.br
|
||||||
|
.BR begin " Prefers item with matched substring closer to the beginning"
|
||||||
|
.br
|
||||||
|
.BR end " Prefers item with matched substring closer to the end"
|
||||||
|
.br
|
||||||
|
.BR index " Prefers item that appeared earlier in the input stream"
|
||||||
|
.br
|
||||||
.SS Interface
|
.SS Interface
|
||||||
.TP
|
.TP
|
||||||
.B "-m, --multi"
|
.B "-m, --multi"
|
||||||
@@ -77,11 +91,38 @@ Enable processing of ANSI color codes
|
|||||||
.B "--no-mouse"
|
.B "--no-mouse"
|
||||||
Disable mouse
|
Disable mouse
|
||||||
.TP
|
.TP
|
||||||
.B "+c, --no-color"
|
.BI "--color=" "[BASE_SCHEME][,COLOR:ANSI]"
|
||||||
Disable colors
|
Color configuration. The name of the base color scheme is followed by custom
|
||||||
.TP
|
color mappings. Ansi color code of -1 denotes terminal default
|
||||||
.B "+2, --no-256"
|
foreground/background color.
|
||||||
Disable 256-color
|
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --color=bg+:24\fR
|
||||||
|
\fBfzf --color=light,fg:232,bg:255,bg+:116,info:27\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
.B BASE SCHEME:
|
||||||
|
(default: dark on 256-color terminal, otherwise 16)
|
||||||
|
|
||||||
|
\fBdark \fRColor scheme for dark 256-color terminal
|
||||||
|
\fBlight \fRColor scheme for light 256-color terminal
|
||||||
|
\fB16 \fRColor scheme for 16-color terminal
|
||||||
|
\fBbw \fRNo colors
|
||||||
|
|
||||||
|
.B COLOR:
|
||||||
|
\fBfg \fRText
|
||||||
|
\fBbg \fRBackground
|
||||||
|
\fBhl \fRHighlighted substrings
|
||||||
|
\fBfg+ \fRText (current line)
|
||||||
|
\fBbg+ \fRBackground (current line)
|
||||||
|
\fBhl+ \fRHighlighted substrings (current line)
|
||||||
|
\fBinfo \fRInfo
|
||||||
|
\fBprompt \fRPrompt
|
||||||
|
\fBpointer \fRPointer to the current line
|
||||||
|
\fBmarker \fRMulti-select marker
|
||||||
|
\fBspinner \fRStreaming input indicator
|
||||||
|
.RE
|
||||||
.TP
|
.TP
|
||||||
.B "--black"
|
.B "--black"
|
||||||
Use black background
|
Use black background
|
||||||
@@ -89,8 +130,132 @@ Use black background
|
|||||||
.B "--reverse"
|
.B "--reverse"
|
||||||
Reverse orientation
|
Reverse orientation
|
||||||
.TP
|
.TP
|
||||||
|
.B "--cycle"
|
||||||
|
Enable cyclic scroll
|
||||||
|
.TP
|
||||||
|
.B "--no-hscroll"
|
||||||
|
Disable horizontal scroll
|
||||||
|
.TP
|
||||||
|
.B "--inline-info"
|
||||||
|
Display finder info inline with the query
|
||||||
|
.TP
|
||||||
.BI "--prompt=" "STR"
|
.BI "--prompt=" "STR"
|
||||||
Input prompt (default: '> ')
|
Input prompt (default: '> ')
|
||||||
|
.TP
|
||||||
|
.BI "--toggle-sort=" "KEY"
|
||||||
|
Key to toggle sort. For the list of the allowed key names, see \fB--bind\fR.
|
||||||
|
.TP
|
||||||
|
.BI "--bind=" "KEYBINDS"
|
||||||
|
Comma-separated list of custom key bindings. Each key binding expression
|
||||||
|
follows the following format: \fBKEY:ACTION\fR
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
.B AVAILABLE KEYS:
|
||||||
|
\fIctrl-[a-z]\fR
|
||||||
|
\fIalt-[a-z]\fR
|
||||||
|
\fIf[1-4]\fR
|
||||||
|
\fIenter\fR (\fIreturn\fR)
|
||||||
|
\fIspace\fR
|
||||||
|
\fIbspace\fR (\fIbs\fR)
|
||||||
|
\fIalt-bspace\fR (\fIalt-bs\fR)
|
||||||
|
\fItab\fR
|
||||||
|
\fIbtab\fR (\fIshift-tab\fR)
|
||||||
|
\fIesc\fR
|
||||||
|
\fIdel\fR
|
||||||
|
\fIup\fR
|
||||||
|
\fIdown\fR
|
||||||
|
\fIleft\fR
|
||||||
|
\fIright\fR
|
||||||
|
\fIhome\fR
|
||||||
|
\fIend\fR
|
||||||
|
\fIpgup\fR (\fIpage-up\fR)
|
||||||
|
\fIpgdn\fR (\fIpage-down\fR)
|
||||||
|
\fIshift-left\fR
|
||||||
|
\fIshift-right\fR
|
||||||
|
or any single character
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
\fBACTION: DEFAULT BINDINGS:
|
||||||
|
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
||||||
|
\fBaccept\fR \fIctrl-m (enter)\fR
|
||||||
|
\fBbackward-char\fR \fIctrl-b left\fR
|
||||||
|
\fBbackward-delete-char\fR \fIctrl-h bspace\fR
|
||||||
|
\fBbackward-kill-word\fR \fIalt-bs\fR
|
||||||
|
\fBbackward-word\fR \fIalt-b shift-left\fR
|
||||||
|
\fBbeginning-of-line\fR \fIctrl-a home\fR
|
||||||
|
\fBclear-screen\fR \fIctrl-l\fR
|
||||||
|
\fBdelete-char\fR \fIctrl-d del\fR
|
||||||
|
\fBdeselect-all\fR
|
||||||
|
\fBdown\fR \fIctrl-j ctrl-n down\fR
|
||||||
|
\fBend-of-line\fR \fIctrl-e end\fR
|
||||||
|
\fBexecute(...)\fR (see below for the details)
|
||||||
|
\fBforward-char\fR \fIctrl-f right\fR
|
||||||
|
\fBforward-word\fR \fIalt-f shift-right\fR
|
||||||
|
\fBignore\fR
|
||||||
|
\fBkill-line\fR
|
||||||
|
\fBkill-word\fR \fIalt-d\fR
|
||||||
|
\fBnext-history\fR (\fIctrl-n\fR on \fB--history\fR)
|
||||||
|
\fBpage-down\fR \fIpgdn\fR
|
||||||
|
\fBpage-up\fR \fIpgup\fR
|
||||||
|
\fBprevious-history\fR (\fIctrl-p\fR on \fB--history\fR)
|
||||||
|
\fBselect-all\fR
|
||||||
|
\fBtoggle\fR
|
||||||
|
\fBtoggle-all\fR
|
||||||
|
\fBtoggle-down\fR \fIctrl-i (tab)\fR
|
||||||
|
\fBtoggle-sort\fR (equivalent to \fB--toggle-sort\fR)
|
||||||
|
\fBtoggle-up\fR \fIbtab (shift-tab)\fR
|
||||||
|
\fBunix-line-discard\fR \fIctrl-u\fR
|
||||||
|
\fBunix-word-rubout\fR \fIctrl-w\fR
|
||||||
|
\fBup\fR \fIctrl-k ctrl-p up\fR
|
||||||
|
\fByank\fR \fIctrl-y\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
With \fBexecute(...)\fR action, you can execute arbitrary commands without
|
||||||
|
leaving fzf. For example, you can turn fzf into a simple file browser by
|
||||||
|
binding \fBenter\fR key to \fBless\fR command like follows.
|
||||||
|
|
||||||
|
.RS
|
||||||
|
\fBfzf --bind "enter:execute(less {})"\fR
|
||||||
|
.RE
|
||||||
|
|
||||||
|
\fB{}\fR is the placeholder for the double-quoted string of the current line.
|
||||||
|
If the command contains parentheses, you can use any of the following
|
||||||
|
alternative notations to avoid parse errors.
|
||||||
|
|
||||||
|
\fBexecute[...]\fR
|
||||||
|
\fBexecute~...~\fR
|
||||||
|
\fBexecute!...!\fR
|
||||||
|
\fBexecute@...@\fR
|
||||||
|
\fBexecute#...#\fR
|
||||||
|
\fBexecute$...$\fR
|
||||||
|
\fBexecute%...%\fR
|
||||||
|
\fBexecute^...^\fR
|
||||||
|
\fBexecute&...&\fR
|
||||||
|
\fBexecute*...*\fR
|
||||||
|
\fBexecute;...;\fR
|
||||||
|
\fBexecute/.../\fR
|
||||||
|
\fBexecute|...|\fR
|
||||||
|
\fBexecute:...\fR
|
||||||
|
.RS
|
||||||
|
This is the special form that frees you from parse errors as it does not expect
|
||||||
|
the closing character. The catch is that it should be the last one in the
|
||||||
|
comma-separated list.
|
||||||
|
.RE
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.BI "--history=" "HISTORY_FILE"
|
||||||
|
Load search history from the specified file and update the file on completion.
|
||||||
|
When enabled, \fBCTRL-N\fR and \fBCTRL-P\fR are automatically remapped to
|
||||||
|
\fBnext-history\fR and \fBprevious-history\fR.
|
||||||
|
.TP
|
||||||
|
.BI "--history-size=" "N"
|
||||||
|
Maximum number of entries in the history file (default: 1000). The file is
|
||||||
|
automatically truncated when the number of the lines exceeds the value.
|
||||||
.SS Scripting
|
.SS Scripting
|
||||||
.TP
|
.TP
|
||||||
.BI "-q, --query=" "STR"
|
.BI "-q, --query=" "STR"
|
||||||
@@ -110,20 +275,15 @@ fzf becomes a fuzzy-version of grep.
|
|||||||
Print query as the first line
|
Print query as the first line
|
||||||
.TP
|
.TP
|
||||||
.BI "--expect=" "KEY[,..]"
|
.BI "--expect=" "KEY[,..]"
|
||||||
Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
Comma-separated list of keys that can be used to complete fzf in addition to
|
||||||
or any single character) that can be used to complete fzf in addition to the
|
the default enter key. When this option is set, fzf will print the name of the
|
||||||
default enter key. When this option is set, fzf will print the name of the key
|
key pressed as the first line of its output (or as the second line if
|
||||||
pressed as the first line of its output (or as the second line if
|
|
||||||
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
||||||
with the default enter key.
|
with the default enter key.
|
||||||
.RS
|
.RS
|
||||||
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR
|
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR
|
||||||
.RE
|
.RE
|
||||||
.TP
|
.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"
|
.B "--sync"
|
||||||
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
||||||
ncurses finder only after the input stream is complete.
|
ncurses finder only after the input stream is complete.
|
||||||
@@ -147,7 +307,7 @@ Default options. e.g. \fB--extended --ansi\fR
|
|||||||
.SH FIELD INDEX EXPRESSION
|
.SH FIELD INDEX EXPRESSION
|
||||||
|
|
||||||
A field index expression can be a non-zero integer or a range expression
|
A field index expression can be a non-zero integer or a range expression
|
||||||
([BEGIN]..[END]). \fI--nth\fR and \fI--with-nth\fR take a comma-separated list
|
([BEGIN]..[END]). \fB--nth\fR and \fB--with-nth\fR take a comma-separated list
|
||||||
of field index expressions.
|
of field index expressions.
|
||||||
|
|
||||||
.SS Examples
|
.SS Examples
|
||||||
@@ -170,7 +330,7 @@ of field index expressions.
|
|||||||
|
|
||||||
.SH EXTENDED SEARCH MODE
|
.SH EXTENDED SEARCH MODE
|
||||||
|
|
||||||
With \fI-x\fR or \fI--extended\fR option, fzf will start in "extended-search
|
With \fB-x\fR or \fB--extended\fR option, fzf will start in "extended-search
|
||||||
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
||||||
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
||||||
|
|
||||||
@@ -190,8 +350,8 @@ from the result.
|
|||||||
|
|
||||||
.SS Extended-exact mode
|
.SS Extended-exact mode
|
||||||
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
||||||
with ') every word, start fzf with \fI-e\fR or \fI--extended-exact\fR option
|
with ') every word, start fzf with \fB-e\fR or \fB--extended-exact\fR option
|
||||||
(instead of \fI-x\fR or \fI--extended\fR).
|
(instead of \fB-x\fR or \fB--extended\fR).
|
||||||
|
|
||||||
.SH AUTHOR
|
.SH AUTHOR
|
||||||
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||||
|
228
plugin/fzf.vim
228
plugin/fzf.vim
@@ -21,12 +21,11 @@
|
|||||||
" 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:default_tmux_height = '40%'
|
let s:default_height = '40%'
|
||||||
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:install = expand('<sfile>:h:h').'/install'
|
||||||
|
let s:installed = 0
|
||||||
let s:fzf_tmux = expand('<sfile>:h:h').'/bin/fzf-tmux'
|
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
|
||||||
@@ -35,26 +34,24 @@ function! s:fzf_exec()
|
|||||||
if !exists('s:exec')
|
if !exists('s:exec')
|
||||||
if executable(s:fzf_go)
|
if executable(s:fzf_go)
|
||||||
let s:exec = s:fzf_go
|
let s:exec = s:fzf_go
|
||||||
else
|
elseif executable('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'
|
let s:exec = 'fzf'
|
||||||
endif
|
elseif !s:installed && executable(s:install) &&
|
||||||
endif
|
\ input('fzf executable not found. Download binary? (y/n) ') =~? '^y'
|
||||||
endif
|
redraw
|
||||||
return s:exec
|
echo
|
||||||
|
echohl WarningMsg
|
||||||
|
echo 'Downloading fzf binary. Please wait ...'
|
||||||
|
echohl None
|
||||||
|
let s:installed = 1
|
||||||
|
call system(s:install.' --bin')
|
||||||
|
return s:fzf_exec()
|
||||||
else
|
else
|
||||||
return s:exec
|
redraw
|
||||||
|
throw 'fzf executable not found'
|
||||||
endif
|
endif
|
||||||
|
endif
|
||||||
|
return s:exec
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_enabled()
|
function! s:tmux_enabled()
|
||||||
@@ -79,7 +76,7 @@ function! s:shellesc(arg)
|
|||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:escape(path)
|
function! s:escape(path)
|
||||||
return substitute(a:path, ' ', '\\ ', 'g')
|
return escape(a:path, ' %#\')
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
" Upgrade legacy options
|
" Upgrade legacy options
|
||||||
@@ -98,6 +95,15 @@ function! s:upgrade(dict)
|
|||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! fzf#run(...) abort
|
function! fzf#run(...) abort
|
||||||
|
try
|
||||||
|
let oshell = &shell
|
||||||
|
set shell=sh
|
||||||
|
if has('nvim') && bufexists('term://*:FZF')
|
||||||
|
echohl WarningMsg
|
||||||
|
echomsg 'FZF is already running!'
|
||||||
|
echohl None
|
||||||
|
return []
|
||||||
|
endif
|
||||||
let dict = exists('a:1') ? s:upgrade(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', '')
|
||||||
@@ -122,18 +128,23 @@ function! fzf#run(...) abort
|
|||||||
else
|
else
|
||||||
let prefix = ''
|
let prefix = ''
|
||||||
endif
|
endif
|
||||||
let split = s:tmux_enabled() && s:tmux_splittable(dict)
|
let tmux = !has('nvim') && s:tmux_enabled() && s:splittable(dict)
|
||||||
let command = prefix.(split ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result
|
let command = prefix.(tmux ? s:fzf_tmux(dict) : fzf_exec).' '.optstr.' > '.temps.result
|
||||||
|
|
||||||
try
|
try
|
||||||
if split
|
if tmux
|
||||||
return s:execute_tmux(dict, command, temps)
|
return s:execute_tmux(dict, command, temps)
|
||||||
|
elseif has('nvim')
|
||||||
|
return s:execute_term(dict, command, temps)
|
||||||
else
|
else
|
||||||
return s:execute(dict, command, temps)
|
return s:execute(dict, command, temps)
|
||||||
endif
|
endif
|
||||||
finally
|
finally
|
||||||
call s:popd(dict)
|
call s:popd(dict)
|
||||||
endtry
|
endtry
|
||||||
|
finally
|
||||||
|
let &shell = oshell
|
||||||
|
endtry
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:present(dict, ...)
|
function! s:present(dict, ...)
|
||||||
@@ -150,19 +161,24 @@ function! s:fzf_tmux(dict)
|
|||||||
for o in ['up', 'down', 'left', 'right']
|
for o in ['up', 'down', 'left', 'right']
|
||||||
if s:present(a:dict, o)
|
if s:present(a:dict, o)
|
||||||
let size = '-'.o[0].(a:dict[o] == 1 ? '' : a:dict[o])
|
let size = '-'.o[0].(a:dict[o] == 1 ? '' : a:dict[o])
|
||||||
|
break
|
||||||
endif
|
endif
|
||||||
endfor
|
endfor
|
||||||
return printf('LINES=%d COLUMNS=%d %s %s %s --',
|
return printf('LINES=%d COLUMNS=%d %s %s %s --',
|
||||||
\ &lines, &columns, s:fzf_tmux, size, (has_key(a:dict, 'source') ? '' : '-'))
|
\ &lines, &columns, s:fzf_tmux, size, (has_key(a:dict, 'source') ? '' : '-'))
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_splittable(dict)
|
function! s:splittable(dict)
|
||||||
return s:present(a:dict, 'up', 'down', 'left', 'right')
|
return s:present(a:dict, 'up', 'down', 'left', 'right')
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:pushd(dict)
|
function! s:pushd(dict)
|
||||||
if s:present(a:dict, 'dir')
|
if s:present(a:dict, 'dir')
|
||||||
let a:dict.prev_dir = getcwd()
|
let cwd = getcwd()
|
||||||
|
if get(a:dict, 'prev_dir', '') ==# cwd
|
||||||
|
return 1
|
||||||
|
endif
|
||||||
|
let a:dict.prev_dir = cwd
|
||||||
execute 'chdir '.s:escape(a:dict.dir)
|
execute 'chdir '.s:escape(a:dict.dir)
|
||||||
let a:dict.dir = getcwd()
|
let a:dict.dir = getcwd()
|
||||||
return 1
|
return 1
|
||||||
@@ -176,12 +192,25 @@ function! s:popd(dict)
|
|||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:xterm_launcher()
|
||||||
|
let fmt = 'xterm -T "[fzf]" -bg "\%s" -fg "\%s" -geometry %dx%d+%d+%d -e bash -ic %%s'
|
||||||
|
if has('gui_macvim')
|
||||||
|
let fmt .= '; osascript -e "tell application \"MacVim\" to activate"'
|
||||||
|
endif
|
||||||
|
return printf(fmt,
|
||||||
|
\ synIDattr(hlID("Normal"), "bg"), synIDattr(hlID("Normal"), "fg"),
|
||||||
|
\ &columns, &lines/2, getwinposx(), getwinposy())
|
||||||
|
endfunction
|
||||||
|
unlet! s:launcher
|
||||||
|
let s:launcher = function('s:xterm_launcher')
|
||||||
|
|
||||||
function! s:execute(dict, command, temps)
|
function! s:execute(dict, command, temps)
|
||||||
call s:pushd(a:dict)
|
call s:pushd(a:dict)
|
||||||
silent! !clear 2> /dev/null
|
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', get(g:, 'fzf_launcher', s:launcher)))
|
||||||
let command = printf(launcher, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher
|
||||||
|
let command = printf(fmt, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
||||||
else
|
else
|
||||||
let command = a:command
|
let command = a:command
|
||||||
endif
|
endif
|
||||||
@@ -207,10 +236,92 @@ function! s:execute_tmux(dict, command, temps)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
call system(command)
|
call system(command)
|
||||||
|
redraw!
|
||||||
return s:callback(a:dict, a:temps)
|
return s:callback(a:dict, a:temps)
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:calc_size(max, val)
|
||||||
|
if a:val =~ '%$'
|
||||||
|
return a:max * str2nr(a:val[:-2]) / 100
|
||||||
|
else
|
||||||
|
return min([a:max, a:val])
|
||||||
|
endif
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:getpos()
|
||||||
|
return {'tab': tabpagenr(), 'win': winnr()}
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:split(dict)
|
||||||
|
let directions = {
|
||||||
|
\ 'up': ['topleft', 'resize', &lines],
|
||||||
|
\ 'down': ['botright', 'resize', &lines],
|
||||||
|
\ 'left': ['vertical topleft', 'vertical resize', &columns],
|
||||||
|
\ 'right': ['vertical botright', 'vertical resize', &columns] }
|
||||||
|
let s:ppos = s:getpos()
|
||||||
|
try
|
||||||
|
for [dir, triple] in items(directions)
|
||||||
|
let val = get(a:dict, dir, '')
|
||||||
|
if !empty(val)
|
||||||
|
let [cmd, resz, max] = triple
|
||||||
|
let sz = s:calc_size(max, val)
|
||||||
|
execute cmd sz.'new'
|
||||||
|
execute resz sz
|
||||||
|
return
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
if s:present(a:dict, 'window')
|
||||||
|
execute a:dict.window
|
||||||
|
else
|
||||||
|
tabnew
|
||||||
|
endif
|
||||||
|
finally
|
||||||
|
setlocal winfixwidth winfixheight buftype=nofile bufhidden=wipe nobuflisted
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:execute_term(dict, command, temps)
|
||||||
|
call s:split(a:dict)
|
||||||
|
call s:pushd(a:dict)
|
||||||
|
|
||||||
|
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps, 'name': 'FZF' }
|
||||||
|
function! fzf.on_exit(id, code)
|
||||||
|
let pos = s:getpos()
|
||||||
|
let inplace = pos == s:ppos " {'window': 'enew'}
|
||||||
|
if !inplace
|
||||||
|
if bufnr('') == self.buf
|
||||||
|
" We use close instead of bd! since Vim does not close the split when
|
||||||
|
" there's no other listed buffer (nvim +'set nobuflisted')
|
||||||
|
close
|
||||||
|
endif
|
||||||
|
if pos.tab == s:ppos.tab
|
||||||
|
wincmd p
|
||||||
|
endif
|
||||||
|
endif
|
||||||
|
call s:pushd(self.dict)
|
||||||
|
try
|
||||||
|
redraw!
|
||||||
|
call s:callback(self.dict, self.temps)
|
||||||
|
|
||||||
|
if inplace && bufnr('') == self.buf
|
||||||
|
execute "normal! \<c-^>"
|
||||||
|
" No other listed buffer
|
||||||
|
if bufnr('') == self.buf
|
||||||
|
bd!
|
||||||
|
endif
|
||||||
|
endif
|
||||||
|
finally
|
||||||
|
call s:popd(self.dict)
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
call termopen(a:command, fzf)
|
||||||
|
startinsert
|
||||||
|
return []
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! s:callback(dict, temps)
|
function! s:callback(dict, temps)
|
||||||
|
try
|
||||||
if !filereadable(a:temps.result)
|
if !filereadable(a:temps.result)
|
||||||
let lines = []
|
let lines = []
|
||||||
else
|
else
|
||||||
@@ -224,6 +335,9 @@ function! s:callback(dict, temps)
|
|||||||
endif
|
endif
|
||||||
endfor
|
endfor
|
||||||
endif
|
endif
|
||||||
|
if has_key(a:dict, 'sink*')
|
||||||
|
call a:dict['sink*'](lines)
|
||||||
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
for tf in values(a:temps)
|
for tf in values(a:temps)
|
||||||
@@ -231,46 +345,44 @@ function! s:callback(dict, temps)
|
|||||||
endfor
|
endfor
|
||||||
|
|
||||||
return lines
|
return lines
|
||||||
|
catch
|
||||||
|
if stridx(v:exception, ':E325:') < 0
|
||||||
|
echoerr v:exception
|
||||||
|
endif
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
let s:default_action = {
|
||||||
|
\ 'ctrl-m': 'e',
|
||||||
|
\ 'ctrl-t': 'tabedit',
|
||||||
|
\ 'ctrl-x': 'split',
|
||||||
|
\ 'ctrl-v': 'vsplit' }
|
||||||
|
|
||||||
|
function! s:cmd_callback(lines) abort
|
||||||
|
if empty(a:lines)
|
||||||
|
return
|
||||||
|
endif
|
||||||
|
let key = remove(a:lines, 0)
|
||||||
|
let cmd = get(s:action, key, 'e')
|
||||||
|
for item in a:lines
|
||||||
|
execute cmd s:escape(item)
|
||||||
|
endfor
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:cmd(bang, ...) abort
|
function! s:cmd(bang, ...) abort
|
||||||
let args = copy(a:000)
|
let s:action = get(g:, 'fzf_action', s:default_action)
|
||||||
if !s:legacy
|
let args = extend(['--expect='.join(keys(s:action), ',')], a:000)
|
||||||
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.down = get(g:, 'fzf_tmux_height', s:default_tmux_height)
|
let opts.down = get(g:, 'fzf_height', get(g:, 'fzf_tmux_height', s:default_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({'options': join(args), 'sink*': function('<sid>cmd_callback')}, 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>0, <f-args>)
|
||||||
|
|
||||||
let &cpo = s:cpo_save
|
let &cpo = s:cpo_save
|
||||||
unlet s:cpo_save
|
unlet s:cpo_save
|
||||||
|
@@ -5,6 +5,8 @@
|
|||||||
# / __/ / /_/ __/
|
# / __/ / /_/ __/
|
||||||
# /_/ /___/_/-completion.bash
|
# /_/ /___/_/-completion.bash
|
||||||
#
|
#
|
||||||
|
# - $FZF_TMUX (default: 1)
|
||||||
|
# - $FZF_TMUX_HEIGHT (default: '40%')
|
||||||
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||||
# - $FZF_COMPLETION_OPTS (default: empty)
|
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||||
|
|
||||||
@@ -14,9 +16,10 @@ _fzf_orig_completion_filter() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_opts_completion() {
|
_fzf_opts_completion() {
|
||||||
local cur opts
|
local cur prev 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
|
||||||
@@ -25,19 +28,42 @@ _fzf_opts_completion() {
|
|||||||
-d --delimiter
|
-d --delimiter
|
||||||
+s --no-sort
|
+s --no-sort
|
||||||
--tac
|
--tac
|
||||||
|
--tiebreak
|
||||||
|
--bind
|
||||||
-m --multi
|
-m --multi
|
||||||
--no-mouse
|
--no-mouse
|
||||||
+c --no-color
|
--color
|
||||||
+2 --no-256
|
|
||||||
--black
|
--black
|
||||||
--reverse
|
--reverse
|
||||||
|
--no-hscroll
|
||||||
|
--inline-info
|
||||||
--prompt
|
--prompt
|
||||||
-q --query
|
-q --query
|
||||||
-1 --select-1
|
-1 --select-1
|
||||||
-0 --exit-0
|
-0 --exit-0
|
||||||
-f --filter
|
-f --filter
|
||||||
--print-query
|
--print-query
|
||||||
--sync"
|
--expect
|
||||||
|
--toggle-sort
|
||||||
|
--sync
|
||||||
|
--cycle
|
||||||
|
--history
|
||||||
|
--history-size"
|
||||||
|
|
||||||
|
case "${prev}" in
|
||||||
|
--tiebreak)
|
||||||
|
COMPREPLY=( $(compgen -W "length begin end index" -- ${cur}) )
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
--color)
|
||||||
|
COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
--history)
|
||||||
|
COMPREPLY=()
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
if [[ ${cur} =~ ^-|\+ ]]; then
|
||||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||||
@@ -65,10 +91,11 @@ _fzf_handle_dynamic_completion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_path_completion() {
|
_fzf_path_completion() {
|
||||||
local cur base dir leftover matches trigger cmd
|
local cur base dir leftover matches trigger cmd fzf
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||||
COMPREPLY=()
|
COMPREPLY=()
|
||||||
trigger=${FZF_COMPLETION_TRIGGER:-**}
|
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||||
if [[ ${cur} == *"$trigger" ]]; then
|
if [[ ${cur} == *"$trigger" ]]; then
|
||||||
base=${cur:0:${#cur}-${#trigger}}
|
base=${cur:0:${#cur}-${#trigger}}
|
||||||
@@ -81,7 +108,7 @@ _fzf_path_completion() {
|
|||||||
leftover=${leftover/#\/}
|
leftover=${leftover/#\/}
|
||||||
[ "$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$3 " "$item"
|
printf "%q$3 " "$item"
|
||||||
done)
|
done)
|
||||||
matches=${matches% }
|
matches=${matches% }
|
||||||
@@ -105,16 +132,17 @@ _fzf_path_completion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_list_completion() {
|
_fzf_list_completion() {
|
||||||
local cur selected trigger cmd src
|
local cur selected trigger cmd src fzf
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
read -r src
|
read -r src
|
||||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||||
trigger=${FZF_COMPLETION_TRIGGER:-**}
|
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||||
if [[ ${cur} == *"$trigger" ]]; then
|
if [[ ${cur} == *"$trigger" ]]; then
|
||||||
cur=${cur:0:${#cur}-${#trigger}}
|
cur=${cur:0:${#cur}-${#trigger}}
|
||||||
|
|
||||||
tput sc
|
tput sc
|
||||||
selected=$(eval "$src | fzf $FZF_COMPLETION_OPTS $1 -q '$cur'" | tr '\n' ' ')
|
selected=$(eval "$src | $fzf $FZF_COMPLETION_OPTS $1 -q '$cur'" | tr '\n' ' ')
|
||||||
selected=${selected% }
|
selected=${selected% }
|
||||||
tput rc
|
tput rc
|
||||||
|
|
||||||
@@ -149,9 +177,10 @@ _fzf_dir_completion() {
|
|||||||
_fzf_kill_completion() {
|
_fzf_kill_completion() {
|
||||||
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
||||||
|
|
||||||
local selected
|
local selected fzf
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
tput sc
|
tput sc
|
||||||
selected=$(ps -ef | sed 1d | fzf -m $FZF_COMPLETION_OPTS | awk '{print $2}' | tr '\n' ' ')
|
selected=$(ps -ef | sed 1d | $fzf -m $FZF_COMPLETION_OPTS | awk '{print $2}' | tr '\n' ' ')
|
||||||
tput rc
|
tput rc
|
||||||
|
|
||||||
if [ -n "$selected" ]; then
|
if [ -n "$selected" ]; then
|
||||||
@@ -162,13 +191,13 @@ _fzf_kill_completion() {
|
|||||||
|
|
||||||
_fzf_telnet_completion() {
|
_fzf_telnet_completion() {
|
||||||
_fzf_list_completion '+m' "$@" << "EOF"
|
_fzf_list_completion '+m' "$@" << "EOF"
|
||||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_ssh_completion() {
|
_fzf_ssh_completion() {
|
||||||
_fzf_list_completion '+m' "$@" << "EOF"
|
_fzf_list_completion '+m' "$@" << "EOF"
|
||||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i ^host | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts) | awk '{print $2}' | sort -u
|
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +214,7 @@ EOF
|
|||||||
}
|
}
|
||||||
|
|
||||||
# fzf options
|
# fzf options
|
||||||
complete -F _fzf_opts_completion fzf
|
complete -o default -F _fzf_opts_completion fzf
|
||||||
|
|
||||||
d_cmds="cd pushd rmdir"
|
d_cmds="cd pushd rmdir"
|
||||||
f_cmds="
|
f_cmds="
|
||||||
@@ -201,11 +230,11 @@ a_cmds="
|
|||||||
x_cmds="kill ssh telnet unset unalias export"
|
x_cmds="kill ssh telnet unset unalias export"
|
||||||
|
|
||||||
# Preserve existing completion
|
# Preserve existing completion
|
||||||
if [ "$_fzf_completion_loaded" != '0.8.6-1' ]; then
|
if [ "$_fzf_completion_loaded" != '0.9.12' ]; then
|
||||||
# Really wish I could use associative array but OSX comes with bash 3.2 :(
|
# Really wish I could use associative array but OSX comes with bash 3.2 :(
|
||||||
eval $(complete | \grep '\-F' | \grep -v _fzf_ |
|
eval $(complete | \grep '\-F' | \grep -v _fzf_ |
|
||||||
\grep -E " ($(echo $d_cmds $f_cmds $a_cmds $x_cmds | sed 's/ /|/g' | sed 's/+/\\+/g'))$" | _fzf_orig_completion_filter)
|
\grep -E " ($(echo $d_cmds $f_cmds $a_cmds $x_cmds | sed 's/ /|/g' | sed 's/+/\\+/g'))$" | _fzf_orig_completion_filter)
|
||||||
export _fzf_completion_loaded=0.8.6-1
|
export _fzf_completion_loaded=0.9.12
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if type _completion_loader > /dev/null 2>&1; then
|
if type _completion_loader > /dev/null 2>&1; then
|
||||||
|
158
shell/completion.zsh
Normal file
158
shell/completion.zsh
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
#!/bin/zsh
|
||||||
|
# ____ ____
|
||||||
|
# / __/___ / __/
|
||||||
|
# / /_/_ / / /_
|
||||||
|
# / __/ / /_/ __/
|
||||||
|
# /_/ /___/_/-completion.zsh
|
||||||
|
#
|
||||||
|
# - $FZF_TMUX (default: 1)
|
||||||
|
# - $FZF_TMUX_HEIGHT (default: '40%')
|
||||||
|
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||||
|
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||||
|
|
||||||
|
_fzf_path_completion() {
|
||||||
|
local base lbuf find_opts fzf_opts suffix tail fzf dir leftover matches nnm
|
||||||
|
base=${(Q)1}
|
||||||
|
lbuf=$2
|
||||||
|
find_opts=$3
|
||||||
|
fzf_opts=$4
|
||||||
|
suffix=$5
|
||||||
|
tail=$6
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
|
||||||
|
if ! setopt | grep nonomatch > /dev/null; then
|
||||||
|
nnm=1
|
||||||
|
setopt nonomatch
|
||||||
|
fi
|
||||||
|
dir="$base"
|
||||||
|
while [ 1 ]; do
|
||||||
|
if [ -z "$dir" -o -d ${~dir} ]; then
|
||||||
|
leftover=${base/#"$dir"}
|
||||||
|
leftover=${leftover/#\/}
|
||||||
|
[ "$dir" = './' ] && dir=''
|
||||||
|
dir=${~dir}
|
||||||
|
matches=$(\find -L $dir* ${=find_opts} 2> /dev/null | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$leftover" | while read item; do
|
||||||
|
printf "%q$suffix " "$item"
|
||||||
|
done)
|
||||||
|
matches=${matches% }
|
||||||
|
if [ -n "$matches" ]; then
|
||||||
|
LBUFFER="$lbuf$matches$tail"
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
dir=$(dirname "$dir")
|
||||||
|
dir=${dir%/}/
|
||||||
|
done
|
||||||
|
[ -n "$nnm" ] && unsetopt nonomatch
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_all_completion() {
|
||||||
|
_fzf_path_completion "$1" "$2" \
|
||||||
|
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||||
|
"-m" "" " "
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_dir_completion() {
|
||||||
|
_fzf_path_completion "$1" "$2" \
|
||||||
|
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||||
|
"" "/" ""
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_list_completion() {
|
||||||
|
local prefix lbuf fzf_opts src fzf matches
|
||||||
|
prefix=$1
|
||||||
|
lbuf=$2
|
||||||
|
fzf_opts=$3
|
||||||
|
read -r src
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
|
||||||
|
matches=$(eval "$src" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$prefix")
|
||||||
|
if [ -n "$matches" ]; then
|
||||||
|
LBUFFER="$lbuf$matches "
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_telnet_completion() {
|
||||||
|
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||||
|
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_ssh_completion() {
|
||||||
|
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||||
|
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_env_var_completion() {
|
||||||
|
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||||
|
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_alias_completion() {
|
||||||
|
_fzf_list_completion "$1" "$2" '+m' << "EOF"
|
||||||
|
alias | sed 's/=.*//'
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
fzf-completion() {
|
||||||
|
local tokens cmd prefix trigger tail fzf matches lbuf d_cmds
|
||||||
|
|
||||||
|
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
||||||
|
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
||||||
|
tokens=(${(z)LBUFFER})
|
||||||
|
if [ ${#tokens} -lt 1 ]; then
|
||||||
|
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
cmd=${tokens[1]}
|
||||||
|
|
||||||
|
# Explicitly allow for empty trigger.
|
||||||
|
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||||
|
[ -z "$trigger" -a ${LBUFFER[-1]} = ' ' ] && tokens+=("")
|
||||||
|
|
||||||
|
tail=${LBUFFER:$(( ${#LBUFFER} - ${#trigger} ))}
|
||||||
|
# Kill completion (do not require trigger sequence)
|
||||||
|
if [ $cmd = kill -a ${LBUFFER[-1]} = ' ' ]; then
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
matches=$(ps -ef | sed 1d | ${=fzf} ${=FZF_COMPLETION_OPTS} -m | awk '{print $2}' | tr '\n' ' ')
|
||||||
|
if [ -n "$matches" ]; then
|
||||||
|
LBUFFER="$LBUFFER$matches"
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
# Trigger sequence given
|
||||||
|
elif [ ${#tokens} -gt 1 -a "$tail" = "$trigger" ]; then
|
||||||
|
d_cmds=(cd pushd rmdir)
|
||||||
|
|
||||||
|
[ -z "$trigger" ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}
|
||||||
|
[ -z "${tokens[-1]}" ] && lbuf=$LBUFFER || lbuf=${LBUFFER:0:-${#tokens[-1]}}
|
||||||
|
|
||||||
|
if [ ${d_cmds[(i)$cmd]} -le ${#d_cmds} ]; then
|
||||||
|
_fzf_dir_completion "$prefix" $lbuf
|
||||||
|
elif [ $cmd = telnet ]; then
|
||||||
|
_fzf_telnet_completion "$prefix" $lbuf
|
||||||
|
elif [ $cmd = ssh ]; then
|
||||||
|
_fzf_ssh_completion "$prefix" $lbuf
|
||||||
|
elif [ $cmd = unset -o $cmd = export ]; then
|
||||||
|
_fzf_env_var_completion "$prefix" $lbuf
|
||||||
|
elif [ $cmd = unalias ]; then
|
||||||
|
_fzf_alias_completion "$prefix" $lbuf
|
||||||
|
else
|
||||||
|
_fzf_all_completion "$prefix" $lbuf
|
||||||
|
fi
|
||||||
|
# Fall back to default completion
|
||||||
|
else
|
||||||
|
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
[ -z "$fzf_default_completion" ] &&
|
||||||
|
fzf_default_completion=$(bindkey '^I' | grep -v undefined-key | awk '{print $2}')
|
||||||
|
|
||||||
|
zle -N fzf-completion
|
||||||
|
bindkey '^I' fzf-completion
|
||||||
|
|
@@ -1,6 +1,6 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
__fsel() {
|
__fzf_select__() {
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
@@ -12,7 +12,11 @@ __fsel() {
|
|||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
__fsel_tmux() {
|
__fzfcmd() {
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||||
|
}
|
||||||
|
|
||||||
|
__fzf_select_tmux__() {
|
||||||
local height
|
local height
|
||||||
height=${FZF_TMUX_HEIGHT:-40%}
|
height=${FZF_TMUX_HEIGHT:-40%}
|
||||||
if [[ $height =~ %$ ]]; then
|
if [[ $height =~ %$ ]]; then
|
||||||
@@ -20,13 +24,21 @@ __fsel_tmux() {
|
|||||||
else
|
else
|
||||||
height="-l $height"
|
height="-l $height"
|
||||||
fi
|
fi
|
||||||
tmux split-window $height "cd $(printf %q "$PWD");bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
tmux split-window $height "cd $(printf %q "$PWD");bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||||
}
|
}
|
||||||
|
|
||||||
__fcd() {
|
__fzf_cd__() {
|
||||||
local dir
|
local dir
|
||||||
dir=$(command find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
dir=$(command find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m) && printf 'cd %q' "$dir"
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
__fzf_history__() {
|
||||||
|
local line
|
||||||
|
line=$(
|
||||||
|
HISTTIMEFORMAT= history |
|
||||||
|
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r |
|
||||||
|
\grep '^ *[0-9]') && sed 's/ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||||
}
|
}
|
||||||
|
|
||||||
__use_tmux=0
|
__use_tmux=0
|
||||||
@@ -35,38 +47,40 @@ __use_tmux=0
|
|||||||
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||||
# Required to refresh the prompt after fzf
|
# Required to refresh the prompt after fzf
|
||||||
bind '"\er": redraw-current-line'
|
bind '"\er": redraw-current-line'
|
||||||
|
bind '"\e^": history-expand-line'
|
||||||
|
|
||||||
# CTRL-T - Paste the selected file path into the command line
|
# CTRL-T - Paste the selected file path into the command line
|
||||||
if [ $__use_tmux -eq 1 ]; then
|
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"'
|
bind '"\C-t": " \C-u \C-a\C-k$(__fzf_select_tmux__)\e\C-e\C-y\C-a\C-d\C-y\ey\C-h"'
|
||||||
else
|
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"'
|
bind '"\C-t": " \C-u \C-a\C-k$(__fzf_select__)\e\C-e\C-y\C-a\C-y\ey\C-h\C-e\er \C-h"'
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# CTRL-R - Paste the selected command from history into the command line
|
# 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"'
|
bind '"\C-r": " \C-e\C-u$(__fzf_history__)\e\C-e\e^\er"'
|
||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
# ALT-C - cd into the selected directory
|
||||||
bind '"\ec": " \C-e\C-u$(__fcd)\e\C-e\er\C-m"'
|
bind '"\ec": " \C-e\C-u$(__fzf_cd__)\e\C-e\er\C-m"'
|
||||||
else
|
else
|
||||||
bind '"\C-x\C-e": shell-expand-line'
|
bind '"\C-x\C-e": shell-expand-line'
|
||||||
bind '"\C-x\C-r": redraw-current-line'
|
bind '"\C-x\C-r": redraw-current-line'
|
||||||
|
bind '"\C-x^": history-expand-line'
|
||||||
|
|
||||||
# CTRL-T - Paste the selected file path into the command line
|
# CTRL-T - Paste the selected file path into the command line
|
||||||
# - FIXME: Selected items are attached to the end regardless of cursor position
|
# - FIXME: Selected items are attached to the end regardless of cursor position
|
||||||
if [ $__use_tmux -eq 1 ]; then
|
if [ $__use_tmux -eq 1 ]; then
|
||||||
bind '"\C-t": "\e$a \eddi$(__fsel_tmux)\C-x\C-e\e0P$xa"'
|
bind '"\C-t": "\e$a \eddi$(__fzf_select_tmux__)\C-x\C-e\e0P$xa"'
|
||||||
else
|
else
|
||||||
bind '"\C-t": "\e$a \eddi$(__fsel)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
bind '"\C-t": "\e$a \eddi$(__fzf_select__)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
||||||
fi
|
fi
|
||||||
bind -m vi-command '"\C-t": "i\C-t"'
|
bind -m vi-command '"\C-t": "i\C-t"'
|
||||||
|
|
||||||
# CTRL-R - Paste the selected command from history into the command line
|
# 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 '"\C-r": "\eddi$(__fzf_history__)\C-x\C-e\C-x^\e$a\C-x\C-r"'
|
||||||
bind -m vi-command '"\C-r": "i\C-r"'
|
bind -m vi-command '"\C-r": "i\C-r"'
|
||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
# ALT-C - cd into the selected directory
|
||||||
bind '"\ec": "\eddi$(__fcd)\C-x\C-e\C-x\C-r\C-m"'
|
bind '"\ec": "\eddi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||||
bind -m vi-command '"\ec": "i\ec"'
|
bind -m vi-command '"\ec": "i\ec"'
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
@@ -7,18 +7,6 @@ function fzf_key_bindings
|
|||||||
set -g TMPDIR /tmp
|
set -g TMPDIR /tmp
|
||||||
end
|
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
|
function __fzf_escape
|
||||||
while read item
|
while read item
|
||||||
echo -n (echo -n "$item" | sed -E 's/([ "$~'\''([{<>})])/\\\\\\1/g')' '
|
echo -n (echo -n "$item" | sed -E 's/([ "$~'\''([{<>})])/\\\\\\1/g')' '
|
||||||
@@ -26,25 +14,17 @@ function fzf_key_bindings
|
|||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_ctrl_t
|
function __fzf_ctrl_t
|
||||||
if [ -n "$TMUX_PANE" -a "$FZF_TMUX" != "0" ]
|
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
# FIXME need to handle directory with double-quotes
|
-o -type f -print \
|
||||||
tmux split-window (__fzf_tmux_height) "cd \"$PWD\";fish -c 'fzf_key_bindings; __fzf_ctrl_t_tmux \\$TMUX_PANE'"
|
-o -type d -print \
|
||||||
else
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) -m > $TMPDIR/fzf.result
|
||||||
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
|
||||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
rm -f $TMPDIR/fzf.result
|
rm -f $TMPDIR/fzf.result
|
||||||
end
|
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
|
function __fzf_ctrl_r
|
||||||
history | fzf +s +m --toggle-sort=ctrl-r > $TMPDIR/fzf.result
|
history | eval (__fzfcmd) +s +m --tiebreak=index --toggle-sort=ctrl-r > $TMPDIR/fzf.result
|
||||||
and commandline (cat $TMPDIR/fzf.result)
|
and commandline (cat $TMPDIR/fzf.result)
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
rm -f $TMPDIR/fzf.result
|
rm -f $TMPDIR/fzf.result
|
||||||
@@ -52,29 +32,36 @@ function fzf_key_bindings
|
|||||||
|
|
||||||
function __fzf_alt_c
|
function __fzf_alt_c
|
||||||
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
||||||
__fzf_list_dir | fzf +m > $TMPDIR/fzf.result
|
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) \
|
||||||
|
-prune -o -type d -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) +m > $TMPDIR/fzf.result
|
||||||
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
||||||
and cd (cat $TMPDIR/fzf.result)
|
and cd (cat $TMPDIR/fzf.result)
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
rm -f $TMPDIR/fzf.result
|
rm -f $TMPDIR/fzf.result
|
||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_tmux_height
|
function __fzfcmd
|
||||||
|
set -q FZF_TMUX; or set FZF_TMUX 1
|
||||||
|
|
||||||
|
if [ $FZF_TMUX -eq 1 ]
|
||||||
if set -q FZF_TMUX_HEIGHT
|
if set -q FZF_TMUX_HEIGHT
|
||||||
set height $FZF_TMUX_HEIGHT
|
echo "fzf-tmux -d$FZF_TMUX_HEIGHT"
|
||||||
else
|
else
|
||||||
set height 40%
|
echo "fzf-tmux -d40%"
|
||||||
end
|
end
|
||||||
if echo $height | \grep -q -E '%$'
|
|
||||||
echo "-p "(echo $height | sed 's/%$//')
|
|
||||||
else
|
else
|
||||||
echo "-l $height"
|
echo "fzf"
|
||||||
end
|
end
|
||||||
set -e height
|
|
||||||
end
|
end
|
||||||
|
|
||||||
bind \ct '__fzf_ctrl_t'
|
bind \ct '__fzf_ctrl_t'
|
||||||
bind \cr '__fzf_ctrl_r'
|
bind \cr '__fzf_ctrl_r'
|
||||||
bind \ec '__fzf_alt_c'
|
bind \ec '__fzf_alt_c'
|
||||||
|
|
||||||
|
if bind -M insert > /dev/null 2>&1
|
||||||
|
bind -M insert \ct '__fzf_ctrl_t'
|
||||||
|
bind -M insert \cr '__fzf_ctrl_r'
|
||||||
|
bind -M insert \ec '__fzf_alt_c'
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@@ -5,38 +5,29 @@ __fsel() {
|
|||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | fzf -m | while read item; do
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) -m | while read item; do
|
||||||
printf '%q ' "$item"
|
printf '%q ' "$item"
|
||||||
done
|
done
|
||||||
echo
|
echo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
__fzfcmd() {
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||||
|
}
|
||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
if [ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ]; then
|
fzf-file-widget() {
|
||||||
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)"
|
LBUFFER="${LBUFFER}$(__fsel)"
|
||||||
zle redisplay
|
zle redisplay
|
||||||
}
|
}
|
||||||
fi
|
|
||||||
zle -N fzf-file-widget
|
zle -N fzf-file-widget
|
||||||
bindkey '^T' fzf-file-widget
|
bindkey '^T' fzf-file-widget
|
||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
# ALT-C - cd into the selected directory
|
||||||
fzf-cd-widget() {
|
fzf-cd-widget() {
|
||||||
cd "${$(command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
cd "${$(command \find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m):-.}"
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m):-.}"
|
||||||
zle reset-prompt
|
zle reset-prompt
|
||||||
}
|
}
|
||||||
zle -N fzf-cd-widget
|
zle -N fzf-cd-widget
|
||||||
@@ -44,11 +35,12 @@ bindkey '\ec' fzf-cd-widget
|
|||||||
|
|
||||||
# CTRL-R - Paste the selected command from history into the command line
|
# CTRL-R - Paste the selected command from history into the command line
|
||||||
fzf-history-widget() {
|
fzf-history-widget() {
|
||||||
local selected
|
local selected restore_no_bang_hist
|
||||||
if selected=$(fc -l 1 | fzf +s --tac +m -n2..,.. --toggle-sort=ctrl-r -q "$LBUFFER"); then
|
if selected=( $(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r -q "$LBUFFER") ); then
|
||||||
num=$(echo "$selected" | head -1 | awk '{print $1}' | sed 's/[^0-9]//g')
|
num=$selected[1]
|
||||||
LBUFFER=!$num
|
if [ -n "$num" ]; then
|
||||||
zle expand-history
|
zle vi-fetch-history -n $num
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
zle redisplay
|
zle redisplay
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,11 @@
|
|||||||
package algo
|
package algo
|
||||||
|
|
||||||
import "strings"
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"github.com/junegunn/fzf/src/util"
|
||||||
|
)
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* String matching algorithms here do not use strings.ToLower to avoid
|
* String matching algorithms here do not use strings.ToLower to avoid
|
||||||
@@ -11,13 +16,11 @@ import "strings"
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// FuzzyMatch performs fuzzy-match
|
// FuzzyMatch performs fuzzy-match
|
||||||
func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
|
||||||
|
|
||||||
// 0. (FIXME) How to find the shortest match?
|
// 0. (FIXME) How to find the shortest match?
|
||||||
// a_____b__c__abc
|
// a_____b__c__abc
|
||||||
// ^^^^^^^^^^ ^^^
|
// ^^^^^^^^^^ ^^^
|
||||||
@@ -31,11 +34,18 @@ func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
sidx := -1
|
sidx := -1
|
||||||
eidx := -1
|
eidx := -1
|
||||||
|
|
||||||
for index, char := range runes {
|
for index, char := range *runes {
|
||||||
// This is considerably faster than blindly applying strings.ToLower to the
|
// This is considerably faster than blindly applying strings.ToLower to the
|
||||||
// whole string
|
// whole string
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
|
// Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable
|
||||||
|
// difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go
|
||||||
|
// compiler as of now does not inline non-leaf functions.)
|
||||||
|
if char >= 'A' && char <= 'Z' {
|
||||||
char += 32
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if char == pattern[pidx] {
|
if char == pattern[pidx] {
|
||||||
if sidx < 0 {
|
if sidx < 0 {
|
||||||
@@ -51,9 +61,13 @@ func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
if sidx >= 0 && eidx >= 0 {
|
if sidx >= 0 && eidx >= 0 {
|
||||||
pidx--
|
pidx--
|
||||||
for index := eidx - 1; index >= sidx; index-- {
|
for index := eidx - 1; index >= sidx; index-- {
|
||||||
char := runes[index]
|
char := (*runes)[index]
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
|
if char >= 'A' && char <= 'Z' {
|
||||||
char += 32
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if char == pattern[pidx] {
|
if char == pattern[pidx] {
|
||||||
if pidx--; pidx < 0 {
|
if pidx--; pidx < 0 {
|
||||||
@@ -67,27 +81,6 @@ func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
return -1, -1
|
return -1, -1
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExactMatchStrings performs exact-match using strings package.
|
|
||||||
// Currently not used.
|
|
||||||
func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|
||||||
if len(pattern) == 0 {
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
var str string
|
|
||||||
if caseSensitive {
|
|
||||||
str = *input
|
|
||||||
} else {
|
|
||||||
str = strings.ToLower(*input)
|
|
||||||
}
|
|
||||||
|
|
||||||
if idx := strings.Index(str, string(pattern)); idx >= 0 {
|
|
||||||
prefixRuneLen := len([]rune((*input)[:idx]))
|
|
||||||
return prefixRuneLen, prefixRuneLen + len(pattern)
|
|
||||||
}
|
|
||||||
return -1, -1
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExactMatchNaive is a basic string searching algorithm that handles case
|
// ExactMatchNaive is a basic string searching algorithm that handles case
|
||||||
// sensitivity. Although naive, it still performs better than the combination
|
// sensitivity. Although naive, it still performs better than the combination
|
||||||
// of strings.ToLower + strings.Index for typical fzf use cases where input
|
// of strings.ToLower + strings.Index for typical fzf use cases where input
|
||||||
@@ -95,13 +88,12 @@ 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, runes *[]rune, pattern []rune) (int, int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
numRunes := len(*runes)
|
||||||
numRunes := len(runes)
|
|
||||||
plen := len(pattern)
|
plen := len(pattern)
|
||||||
if numRunes < plen {
|
if numRunes < plen {
|
||||||
return -1, -1
|
return -1, -1
|
||||||
@@ -109,9 +101,13 @@ func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, in
|
|||||||
|
|
||||||
pidx := 0
|
pidx := 0
|
||||||
for index := 0; index < numRunes; index++ {
|
for index := 0; index < numRunes; index++ {
|
||||||
char := runes[index]
|
char := (*runes)[index]
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
|
if char >= 'A' && char <= 'Z' {
|
||||||
char += 32
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if pattern[pidx] == char {
|
if pattern[pidx] == char {
|
||||||
pidx++
|
pidx++
|
||||||
@@ -127,16 +123,15 @@ func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, in
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PrefixMatch performs prefix-match
|
// PrefixMatch performs prefix-match
|
||||||
func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||||
runes := []rune(*input)
|
if len(*runes) < len(pattern) {
|
||||||
if len(runes) < len(pattern) {
|
|
||||||
return -1, -1
|
return -1, -1
|
||||||
}
|
}
|
||||||
|
|
||||||
for index, r := range pattern {
|
for index, r := range pattern {
|
||||||
char := runes[index]
|
char := (*runes)[index]
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
char += 32
|
char = unicode.ToLower(char)
|
||||||
}
|
}
|
||||||
if char != r {
|
if char != r {
|
||||||
return -1, -1
|
return -1, -1
|
||||||
@@ -146,8 +141,8 @@ func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SuffixMatch performs suffix-match
|
// SuffixMatch performs suffix-match
|
||||||
func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {
|
||||||
runes := []rune(strings.TrimRight(*input, " "))
|
runes := util.TrimRight(input)
|
||||||
trimmedLen := len(runes)
|
trimmedLen := len(runes)
|
||||||
diff := trimmedLen - len(pattern)
|
diff := trimmedLen - len(pattern)
|
||||||
if diff < 0 {
|
if diff < 0 {
|
||||||
@@ -156,8 +151,8 @@ func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
|
|
||||||
for index, r := range pattern {
|
for index, r := range pattern {
|
||||||
char := runes[index+diff]
|
char := runes[index+diff]
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
char += 32
|
char = unicode.ToLower(char)
|
||||||
}
|
}
|
||||||
if char != r {
|
if char != r {
|
||||||
return -1, -1
|
return -1, -1
|
||||||
@@ -165,3 +160,17 @@ func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
}
|
}
|
||||||
return trimmedLen - len(pattern), trimmedLen
|
return trimmedLen - len(pattern), trimmedLen
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func EqualMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||||
|
if len(*runes) != len(pattern) {
|
||||||
|
return -1, -1
|
||||||
|
}
|
||||||
|
runesStr := string(*runes)
|
||||||
|
if !caseSensitive {
|
||||||
|
runesStr = strings.ToLower(runesStr)
|
||||||
|
}
|
||||||
|
if runesStr == string(pattern) {
|
||||||
|
return 0, len(pattern)
|
||||||
|
}
|
||||||
|
return -1, -1
|
||||||
|
}
|
||||||
|
@@ -5,11 +5,12 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func assertMatch(t *testing.T, fun func(bool, *string, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {
|
func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
pattern = strings.ToLower(pattern)
|
pattern = strings.ToLower(pattern)
|
||||||
}
|
}
|
||||||
s, e := fun(caseSensitive, &input, []rune(pattern))
|
runes := []rune(input)
|
||||||
|
s, e := fun(caseSensitive, &runes, []rune(pattern))
|
||||||
if s != sidx {
|
if s != sidx {
|
||||||
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
||||||
}
|
}
|
||||||
@@ -45,7 +46,6 @@ func TestSuffixMatch(t *testing.T) {
|
|||||||
|
|
||||||
func TestEmptyPattern(t *testing.T) {
|
func TestEmptyPattern(t *testing.T) {
|
||||||
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
||||||
assertMatch(t, ExactMatchStrings, true, "foobar", "", 0, 0)
|
|
||||||
assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)
|
assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)
|
||||||
assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)
|
assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)
|
||||||
assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)
|
assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)
|
||||||
|
@@ -50,7 +50,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
|||||||
if !newState.equals(state) {
|
if !newState.equals(state) {
|
||||||
if state != nil {
|
if state != nil {
|
||||||
// Update last offset
|
// Update last offset
|
||||||
(&offsets[len(offsets)-1]).offset[1] = int32(output.Len())
|
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||||
}
|
}
|
||||||
|
|
||||||
if newState.colored() {
|
if newState.colored() {
|
||||||
|
12
src/cache.go
12
src/cache.go
@@ -2,23 +2,23 @@ package fzf
|
|||||||
|
|
||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
// QueryCache associates strings to lists of items
|
// queryCache associates strings to lists of items
|
||||||
type QueryCache map[string][]*Item
|
type queryCache map[string][]*Item
|
||||||
|
|
||||||
// ChunkCache associates Chunk and query string to lists of items
|
// ChunkCache associates Chunk and query string to lists of items
|
||||||
type ChunkCache struct {
|
type ChunkCache struct {
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
cache map[*Chunk]*QueryCache
|
cache map[*Chunk]*queryCache
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewChunkCache returns a new ChunkCache
|
// NewChunkCache returns a new ChunkCache
|
||||||
func NewChunkCache() ChunkCache {
|
func NewChunkCache() ChunkCache {
|
||||||
return ChunkCache{sync.Mutex{}, make(map[*Chunk]*QueryCache)}
|
return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add adds the list to the cache
|
// Add adds the list to the cache
|
||||||
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {
|
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {
|
||||||
if len(key) == 0 || !chunk.IsFull() {
|
if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {
|
|||||||
|
|
||||||
qc, ok := cc.cache[chunk]
|
qc, ok := cc.cache[chunk]
|
||||||
if !ok {
|
if !ok {
|
||||||
cc.cache[chunk] = &QueryCache{}
|
cc.cache[chunk] = &queryCache{}
|
||||||
qc = cc.cache[chunk]
|
qc = cc.cache[chunk]
|
||||||
}
|
}
|
||||||
(*qc)[key] = list
|
(*qc)[key] = list
|
||||||
|
@@ -4,7 +4,7 @@ import "testing"
|
|||||||
|
|
||||||
func TestChunkCache(t *testing.T) {
|
func TestChunkCache(t *testing.T) {
|
||||||
cache := NewChunkCache()
|
cache := NewChunkCache()
|
||||||
chunk2 := make(Chunk, ChunkSize)
|
chunk2 := make(Chunk, chunkSize)
|
||||||
chunk1p := &Chunk{}
|
chunk1p := &Chunk{}
|
||||||
chunk2p := &chunk2
|
chunk2p := &chunk2
|
||||||
items1 := []*Item{&Item{}}
|
items1 := []*Item{&Item{}}
|
||||||
|
@@ -2,10 +2,7 @@ package fzf
|
|||||||
|
|
||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
// Capacity of each chunk
|
// Chunk is a list of Item pointers whose size has the upper limit of chunkSize
|
||||||
const ChunkSize int = 100
|
|
||||||
|
|
||||||
// Chunk is a list of Item pointers whose size has the upper limit of ChunkSize
|
|
||||||
type Chunk []*Item // >>> []Item
|
type Chunk []*Item // >>> []Item
|
||||||
|
|
||||||
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
||||||
@@ -35,7 +32,7 @@ func (c *Chunk) push(trans ItemBuilder, data *string, index int) {
|
|||||||
|
|
||||||
// IsFull returns true if the Chunk is full
|
// IsFull returns true if the Chunk is full
|
||||||
func (c *Chunk) IsFull() bool {
|
func (c *Chunk) IsFull() bool {
|
||||||
return len(*c) == ChunkSize
|
return len(*c) == chunkSize
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cl *ChunkList) lastChunk() *Chunk {
|
func (cl *ChunkList) lastChunk() *Chunk {
|
||||||
@@ -47,7 +44,7 @@ func CountItems(cs []*Chunk) int {
|
|||||||
if len(cs) == 0 {
|
if len(cs) == 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
return ChunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))
|
return chunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push adds the item to the list
|
// Push adds the item to the list
|
||||||
@@ -56,7 +53,7 @@ func (cl *ChunkList) Push(data string) {
|
|||||||
defer cl.mutex.Unlock()
|
defer cl.mutex.Unlock()
|
||||||
|
|
||||||
if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {
|
if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {
|
||||||
newChunk := Chunk(make([]*Item, 0, ChunkSize))
|
newChunk := Chunk(make([]*Item, 0, chunkSize))
|
||||||
cl.chunks = append(cl.chunks, &newChunk)
|
cl.chunks = append(cl.chunks, &newChunk)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -45,7 +45,7 @@ func TestChunkList(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add more data
|
// Add more data
|
||||||
for i := 0; i < ChunkSize*2; i++ {
|
for i := 0; i < chunkSize*2; i++ {
|
||||||
cl.Push(fmt.Sprintf("item %d", i))
|
cl.Push(fmt.Sprintf("item %d", i))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ func TestChunkList(t *testing.T) {
|
|||||||
// New snapshot
|
// New snapshot
|
||||||
snapshot, count = cl.Snapshot()
|
snapshot, count = cl.Snapshot()
|
||||||
if len(snapshot) != 3 || !snapshot[0].IsFull() ||
|
if len(snapshot) != 3 || !snapshot[0].IsFull() ||
|
||||||
!snapshot[1].IsFull() || snapshot[2].IsFull() || count != ChunkSize*2+2 {
|
!snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {
|
||||||
t.Error("Expected two full chunks and one more chunk")
|
t.Error("Expected two full chunks and one more chunk")
|
||||||
}
|
}
|
||||||
if len(*snapshot[2]) != 2 {
|
if len(*snapshot[2]) != 2 {
|
||||||
|
@@ -1,11 +1,41 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Current version
|
const (
|
||||||
const Version = "0.9.7"
|
// Current version
|
||||||
|
Version = "0.10.0"
|
||||||
|
|
||||||
|
// Core
|
||||||
|
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
||||||
|
coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
||||||
|
|
||||||
|
// Reader
|
||||||
|
defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`
|
||||||
|
|
||||||
|
// Terminal
|
||||||
|
initialDelay = 100 * time.Millisecond
|
||||||
|
spinnerDuration = 200 * time.Millisecond
|
||||||
|
|
||||||
|
// Matcher
|
||||||
|
progressMinDuration = 200 * time.Millisecond
|
||||||
|
|
||||||
|
// Capacity of each chunk
|
||||||
|
chunkSize int = 100
|
||||||
|
|
||||||
|
// Do not cache results of low selectivity queries
|
||||||
|
queryCacheMax int = chunkSize / 5
|
||||||
|
|
||||||
|
// Not to cache mergers with large lists
|
||||||
|
mergerCacheMax int = 100000
|
||||||
|
|
||||||
|
// History
|
||||||
|
defaultHistoryMax int = 1000
|
||||||
|
)
|
||||||
|
|
||||||
// fzf events
|
// fzf events
|
||||||
const (
|
const (
|
||||||
|
21
src/core.go
21
src/core.go
@@ -34,9 +34,6 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
const coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
|
||||||
const coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
|
||||||
|
|
||||||
func initProcs() {
|
func initProcs() {
|
||||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||||
}
|
}
|
||||||
@@ -50,11 +47,11 @@ Matcher -> EvtSearchFin -> Terminal (update list)
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Run starts fzf
|
// Run starts fzf
|
||||||
func Run(options *Options) {
|
func Run(opts *Options) {
|
||||||
initProcs()
|
initProcs()
|
||||||
|
|
||||||
opts := ParseOptions()
|
|
||||||
sort := opts.Sort > 0
|
sort := opts.Sort > 0
|
||||||
|
rankTiebreak = opts.Tiebreak
|
||||||
|
|
||||||
if opts.Version {
|
if opts.Version {
|
||||||
fmt.Println(Version)
|
fmt.Println(Version)
|
||||||
@@ -70,7 +67,7 @@ func Run(options *Options) {
|
|||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
if opts.Ansi {
|
if opts.Ansi {
|
||||||
if opts.Color {
|
if opts.Theme != nil {
|
||||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
||||||
return extractColor(data)
|
return extractColor(data)
|
||||||
}
|
}
|
||||||
@@ -98,8 +95,9 @@ func Run(options *Options) {
|
|||||||
} else {
|
} else {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data *string, index int) *Item {
|
||||||
tokens := Tokenize(data, opts.Delimiter)
|
tokens := Tokenize(data, opts.Delimiter)
|
||||||
|
trans := Transform(tokens, opts.WithNth)
|
||||||
item := Item{
|
item := Item{
|
||||||
text: Transform(tokens, opts.WithNth).whole,
|
text: joinTokens(trans),
|
||||||
origText: data,
|
origText: data,
|
||||||
index: uint32(index),
|
index: uint32(index),
|
||||||
colors: nil,
|
colors: nil,
|
||||||
@@ -115,7 +113,7 @@ func Run(options *Options) {
|
|||||||
// Reader
|
// Reader
|
||||||
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
||||||
if !streamingFilter {
|
if !streamingFilter {
|
||||||
reader := Reader{func(str string) { chunkList.Push(str) }, eventBox}
|
reader := Reader{func(str string) { chunkList.Push(str) }, eventBox, opts.ReadZero}
|
||||||
go reader.ReadSource()
|
go reader.ReadSource()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +139,7 @@ func Run(options *Options) {
|
|||||||
if pattern.MatchItem(item) {
|
if pattern.MatchItem(item) {
|
||||||
fmt.Println(*item.text)
|
fmt.Println(*item.text)
|
||||||
}
|
}
|
||||||
}, eventBox}
|
}, eventBox, opts.ReadZero}
|
||||||
reader.ReadSource()
|
reader.ReadSource()
|
||||||
} else {
|
} else {
|
||||||
eventBox.Unwatch(EvtReadNew)
|
eventBox.Unwatch(EvtReadNew)
|
||||||
@@ -194,8 +192,9 @@ func Run(options *Options) {
|
|||||||
matcher.Reset(snapshot, terminal.Input(), false, !reading, sort)
|
matcher.Reset(snapshot, terminal.Input(), false, !reading, sort)
|
||||||
|
|
||||||
case EvtSearchNew:
|
case EvtSearchNew:
|
||||||
if value.(bool) {
|
switch val := value.(type) {
|
||||||
sort = !sort
|
case bool:
|
||||||
|
sort = val
|
||||||
}
|
}
|
||||||
snapshot, _ := chunkList.Snapshot()
|
snapshot, _ := chunkList.Snapshot()
|
||||||
matcher.Reset(snapshot, terminal.Input(), true, !reading, sort)
|
matcher.Reset(snapshot, terminal.Input(), true, !reading, sort)
|
||||||
|
@@ -4,11 +4,6 @@ package curses
|
|||||||
#include <ncurses.h>
|
#include <ncurses.h>
|
||||||
#include <locale.h>
|
#include <locale.h>
|
||||||
#cgo LDFLAGS: -lncurses
|
#cgo LDFLAGS: -lncurses
|
||||||
void swapOutput() {
|
|
||||||
FILE* temp = stdout;
|
|
||||||
stdout = stderr;
|
|
||||||
stderr = temp;
|
|
||||||
}
|
|
||||||
*/
|
*/
|
||||||
import "C"
|
import "C"
|
||||||
|
|
||||||
@@ -56,11 +51,22 @@ const (
|
|||||||
Mouse
|
Mouse
|
||||||
|
|
||||||
BTab
|
BTab
|
||||||
|
BSpace
|
||||||
|
|
||||||
Del
|
Del
|
||||||
PgUp
|
PgUp
|
||||||
PgDn
|
PgDn
|
||||||
|
|
||||||
|
Up
|
||||||
|
Down
|
||||||
|
Left
|
||||||
|
Right
|
||||||
|
Home
|
||||||
|
End
|
||||||
|
|
||||||
|
SLeft
|
||||||
|
SRight
|
||||||
|
|
||||||
F1
|
F1
|
||||||
F2
|
F2
|
||||||
F3
|
F3
|
||||||
@@ -95,6 +101,21 @@ const (
|
|||||||
doubleClickDuration = 500 * time.Millisecond
|
doubleClickDuration = 500 * time.Millisecond
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type ColorTheme struct {
|
||||||
|
UseDefault bool
|
||||||
|
Fg int16
|
||||||
|
Bg int16
|
||||||
|
DarkBg int16
|
||||||
|
Prompt int16
|
||||||
|
Match int16
|
||||||
|
Current int16
|
||||||
|
CurrentMatch int16
|
||||||
|
Spinner int16
|
||||||
|
Info int16
|
||||||
|
Cursor int16
|
||||||
|
Selected int16
|
||||||
|
}
|
||||||
|
|
||||||
type Event struct {
|
type Event struct {
|
||||||
Type int
|
Type int
|
||||||
Char rune
|
Char rune
|
||||||
@@ -116,15 +137,60 @@ var (
|
|||||||
_color func(int, bool) C.int
|
_color func(int, bool) C.int
|
||||||
_colorMap map[int]int
|
_colorMap map[int]int
|
||||||
_prevDownTime time.Time
|
_prevDownTime time.Time
|
||||||
_prevDownY int
|
|
||||||
_clickY []int
|
_clickY []int
|
||||||
DarkBG C.short
|
_screen *C.SCREEN
|
||||||
|
Default16 *ColorTheme
|
||||||
|
Dark256 *ColorTheme
|
||||||
|
Light256 *ColorTheme
|
||||||
|
FG int
|
||||||
|
CurrentFG int
|
||||||
|
BG int
|
||||||
|
DarkBG int
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
_prevDownTime = time.Unix(0, 0)
|
_prevDownTime = time.Unix(0, 0)
|
||||||
_clickY = []int{}
|
_clickY = []int{}
|
||||||
_colorMap = make(map[int]int)
|
_colorMap = make(map[int]int)
|
||||||
|
Default16 = &ColorTheme{
|
||||||
|
UseDefault: true,
|
||||||
|
Fg: 15,
|
||||||
|
Bg: 0,
|
||||||
|
DarkBg: C.COLOR_BLACK,
|
||||||
|
Prompt: C.COLOR_BLUE,
|
||||||
|
Match: C.COLOR_GREEN,
|
||||||
|
Current: C.COLOR_YELLOW,
|
||||||
|
CurrentMatch: C.COLOR_GREEN,
|
||||||
|
Spinner: C.COLOR_GREEN,
|
||||||
|
Info: C.COLOR_WHITE,
|
||||||
|
Cursor: C.COLOR_RED,
|
||||||
|
Selected: C.COLOR_MAGENTA}
|
||||||
|
Dark256 = &ColorTheme{
|
||||||
|
UseDefault: true,
|
||||||
|
Fg: 15,
|
||||||
|
Bg: 0,
|
||||||
|
DarkBg: 236,
|
||||||
|
Prompt: 110,
|
||||||
|
Match: 108,
|
||||||
|
Current: 254,
|
||||||
|
CurrentMatch: 151,
|
||||||
|
Spinner: 148,
|
||||||
|
Info: 144,
|
||||||
|
Cursor: 161,
|
||||||
|
Selected: 168}
|
||||||
|
Light256 = &ColorTheme{
|
||||||
|
UseDefault: true,
|
||||||
|
Fg: 15,
|
||||||
|
Bg: 0,
|
||||||
|
DarkBg: 251,
|
||||||
|
Prompt: 25,
|
||||||
|
Match: 66,
|
||||||
|
Current: 237,
|
||||||
|
CurrentMatch: 23,
|
||||||
|
Spinner: 65,
|
||||||
|
Info: 101,
|
||||||
|
Cursor: 161,
|
||||||
|
Selected: 168}
|
||||||
}
|
}
|
||||||
|
|
||||||
func attrColored(pair int, bold bool) C.int {
|
func attrColored(pair int, bold bool) C.int {
|
||||||
@@ -174,7 +240,7 @@ func getch(nonblock bool) int {
|
|||||||
return int(b[0])
|
return int(b[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
func Init(color bool, color256 bool, black bool, mouse bool) {
|
func Init(theme *ColorTheme, black bool, mouse bool) {
|
||||||
{
|
{
|
||||||
in, err := os.OpenFile("/dev/tty", syscall.O_RDONLY, 0)
|
in, err := os.OpenFile("/dev/tty", syscall.O_RDONLY, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -185,10 +251,9 @@ func Init(color bool, color256 bool, black bool, mouse bool) {
|
|||||||
// syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))
|
// syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))
|
||||||
}
|
}
|
||||||
|
|
||||||
C.swapOutput()
|
|
||||||
|
|
||||||
C.setlocale(C.LC_ALL, C.CString(""))
|
C.setlocale(C.LC_ALL, C.CString(""))
|
||||||
C.initscr()
|
_screen = C.newterm(nil, C.stderr, C.stdin)
|
||||||
|
C.set_term(_screen)
|
||||||
if mouse {
|
if mouse {
|
||||||
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
||||||
}
|
}
|
||||||
@@ -204,45 +269,50 @@ func Init(color bool, color256 bool, black bool, mouse bool) {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
if color {
|
if theme != nil {
|
||||||
C.start_color()
|
C.start_color()
|
||||||
var bg C.short
|
initPairs(theme, black)
|
||||||
if black {
|
|
||||||
bg = C.COLOR_BLACK
|
|
||||||
} else {
|
|
||||||
C.use_default_colors()
|
|
||||||
bg = -1
|
|
||||||
}
|
|
||||||
if color256 {
|
|
||||||
DarkBG = 236
|
|
||||||
C.init_pair(ColPrompt, 110, bg)
|
|
||||||
C.init_pair(ColMatch, 108, bg)
|
|
||||||
C.init_pair(ColCurrent, 254, DarkBG)
|
|
||||||
C.init_pair(ColCurrentMatch, 151, DarkBG)
|
|
||||||
C.init_pair(ColSpinner, 148, bg)
|
|
||||||
C.init_pair(ColInfo, 144, bg)
|
|
||||||
C.init_pair(ColCursor, 161, DarkBG)
|
|
||||||
C.init_pair(ColSelected, 168, DarkBG)
|
|
||||||
} else {
|
|
||||||
DarkBG = C.COLOR_BLACK
|
|
||||||
C.init_pair(ColPrompt, C.COLOR_BLUE, bg)
|
|
||||||
C.init_pair(ColMatch, C.COLOR_GREEN, bg)
|
|
||||||
C.init_pair(ColCurrent, C.COLOR_YELLOW, DarkBG)
|
|
||||||
C.init_pair(ColCurrentMatch, C.COLOR_GREEN, DarkBG)
|
|
||||||
C.init_pair(ColSpinner, C.COLOR_GREEN, bg)
|
|
||||||
C.init_pair(ColInfo, C.COLOR_WHITE, bg)
|
|
||||||
C.init_pair(ColCursor, C.COLOR_RED, DarkBG)
|
|
||||||
C.init_pair(ColSelected, C.COLOR_MAGENTA, DarkBG)
|
|
||||||
}
|
|
||||||
_color = attrColored
|
_color = attrColored
|
||||||
} else {
|
} else {
|
||||||
_color = attrMono
|
_color = attrMono
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func initPairs(theme *ColorTheme, black bool) {
|
||||||
|
fg := C.short(theme.Fg)
|
||||||
|
bg := C.short(theme.Bg)
|
||||||
|
if black {
|
||||||
|
bg = C.COLOR_BLACK
|
||||||
|
} else if theme.UseDefault {
|
||||||
|
fg = -1
|
||||||
|
bg = -1
|
||||||
|
C.use_default_colors()
|
||||||
|
}
|
||||||
|
if theme.UseDefault {
|
||||||
|
FG = -1
|
||||||
|
BG = -1
|
||||||
|
} else {
|
||||||
|
FG = int(fg)
|
||||||
|
BG = int(bg)
|
||||||
|
C.assume_default_colors(C.int(theme.Fg), C.int(bg))
|
||||||
|
}
|
||||||
|
|
||||||
|
CurrentFG = int(theme.Current)
|
||||||
|
DarkBG = int(theme.DarkBg)
|
||||||
|
darkBG := C.short(DarkBG)
|
||||||
|
C.init_pair(ColPrompt, C.short(theme.Prompt), bg)
|
||||||
|
C.init_pair(ColMatch, C.short(theme.Match), bg)
|
||||||
|
C.init_pair(ColCurrent, C.short(theme.Current), darkBG)
|
||||||
|
C.init_pair(ColCurrentMatch, C.short(theme.CurrentMatch), darkBG)
|
||||||
|
C.init_pair(ColSpinner, C.short(theme.Spinner), bg)
|
||||||
|
C.init_pair(ColInfo, C.short(theme.Info), bg)
|
||||||
|
C.init_pair(ColCursor, C.short(theme.Cursor), darkBG)
|
||||||
|
C.init_pair(ColSelected, C.short(theme.Selected), darkBG)
|
||||||
|
}
|
||||||
|
|
||||||
func Close() {
|
func Close() {
|
||||||
C.endwin()
|
C.endwin()
|
||||||
C.swapOutput()
|
C.delscreen(_screen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetBytes() []byte {
|
func GetBytes() []byte {
|
||||||
@@ -319,19 +389,19 @@ func escSequence(sz *int) Event {
|
|||||||
*sz = 3
|
*sz = 3
|
||||||
switch _buf[2] {
|
switch _buf[2] {
|
||||||
case 68:
|
case 68:
|
||||||
return Event{CtrlB, 0, nil}
|
return Event{Left, 0, nil}
|
||||||
case 67:
|
case 67:
|
||||||
return Event{CtrlF, 0, nil}
|
return Event{Right, 0, nil}
|
||||||
case 66:
|
case 66:
|
||||||
return Event{CtrlJ, 0, nil}
|
return Event{Down, 0, nil}
|
||||||
case 65:
|
case 65:
|
||||||
return Event{CtrlK, 0, nil}
|
return Event{Up, 0, nil}
|
||||||
case 90:
|
case 90:
|
||||||
return Event{BTab, 0, nil}
|
return Event{BTab, 0, nil}
|
||||||
case 72:
|
case 72:
|
||||||
return Event{CtrlA, 0, nil}
|
return Event{Home, 0, nil}
|
||||||
case 70:
|
case 70:
|
||||||
return Event{CtrlE, 0, nil}
|
return Event{End, 0, nil}
|
||||||
case 77:
|
case 77:
|
||||||
return mouseSequence(sz)
|
return mouseSequence(sz)
|
||||||
case 80:
|
case 80:
|
||||||
@@ -353,7 +423,7 @@ func escSequence(sz *int) Event {
|
|||||||
case 51:
|
case 51:
|
||||||
return Event{Del, 0, nil}
|
return Event{Del, 0, nil}
|
||||||
case 52:
|
case 52:
|
||||||
return Event{CtrlE, 0, nil}
|
return Event{End, 0, nil}
|
||||||
case 53:
|
case 53:
|
||||||
return Event{PgUp, 0, nil}
|
return Event{PgUp, 0, nil}
|
||||||
case 54:
|
case 54:
|
||||||
@@ -361,7 +431,7 @@ func escSequence(sz *int) Event {
|
|||||||
case 49:
|
case 49:
|
||||||
switch _buf[3] {
|
switch _buf[3] {
|
||||||
case 126:
|
case 126:
|
||||||
return Event{CtrlA, 0, nil}
|
return Event{Home, 0, nil}
|
||||||
case 59:
|
case 59:
|
||||||
if len(_buf) != 6 {
|
if len(_buf) != 6 {
|
||||||
return Event{Invalid, 0, nil}
|
return Event{Invalid, 0, nil}
|
||||||
@@ -371,16 +441,16 @@ func escSequence(sz *int) Event {
|
|||||||
case 50:
|
case 50:
|
||||||
switch _buf[5] {
|
switch _buf[5] {
|
||||||
case 68:
|
case 68:
|
||||||
return Event{CtrlA, 0, nil}
|
return Event{Home, 0, nil}
|
||||||
case 67:
|
case 67:
|
||||||
return Event{CtrlE, 0, nil}
|
return Event{End, 0, nil}
|
||||||
}
|
}
|
||||||
case 53:
|
case 53:
|
||||||
switch _buf[5] {
|
switch _buf[5] {
|
||||||
case 68:
|
case 68:
|
||||||
return Event{AltB, 0, nil}
|
return Event{SLeft, 0, nil}
|
||||||
case 67:
|
case 67:
|
||||||
return Event{AltF, 0, nil}
|
return Event{SRight, 0, nil}
|
||||||
}
|
}
|
||||||
} // _buf[4]
|
} // _buf[4]
|
||||||
} // _buf[3]
|
} // _buf[3]
|
||||||
@@ -407,10 +477,14 @@ func GetChar() Event {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
switch _buf[0] {
|
switch _buf[0] {
|
||||||
case CtrlC, CtrlG, CtrlQ:
|
case CtrlC:
|
||||||
return Event{CtrlC, 0, nil}
|
return Event{CtrlC, 0, nil}
|
||||||
|
case CtrlG:
|
||||||
|
return Event{CtrlG, 0, nil}
|
||||||
|
case CtrlQ:
|
||||||
|
return Event{CtrlQ, 0, nil}
|
||||||
case 127:
|
case 127:
|
||||||
return Event{CtrlH, 0, nil}
|
return Event{BSpace, 0, nil}
|
||||||
case ESC:
|
case ESC:
|
||||||
return escSequence(&sz)
|
return escSequence(&sz)
|
||||||
}
|
}
|
||||||
@@ -420,6 +494,9 @@ func GetChar() Event {
|
|||||||
return Event{int(_buf[0]), 0, nil}
|
return Event{int(_buf[0]), 0, nil}
|
||||||
}
|
}
|
||||||
r, rsz := utf8.DecodeRune(_buf)
|
r, rsz := utf8.DecodeRune(_buf)
|
||||||
|
if r == utf8.RuneError {
|
||||||
|
return Event{ESC, 0, nil}
|
||||||
|
}
|
||||||
sz = rsz
|
sz = rsz
|
||||||
return Event{Rune, r, nil}
|
return Event{Rune, r, nil}
|
||||||
}
|
}
|
||||||
|
94
src/history.go
Normal file
94
src/history.go
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type History struct {
|
||||||
|
path string
|
||||||
|
lines []string
|
||||||
|
modified map[int]string
|
||||||
|
maxSize int
|
||||||
|
cursor int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHistory(path string, maxSize int) (*History, error) {
|
||||||
|
fmtError := func(e error) error {
|
||||||
|
if os.IsPermission(e) {
|
||||||
|
return errors.New("permission denied: " + path)
|
||||||
|
}
|
||||||
|
return errors.New("invalid history file: " + e.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read history file
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
// If it doesn't exist, check if we can create a file with the name
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
data = []byte{}
|
||||||
|
if err := ioutil.WriteFile(path, data, 0600); err != nil {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Split lines and limit the maximum number of lines
|
||||||
|
lines := strings.Split(strings.Trim(string(data), "\n"), "\n")
|
||||||
|
if len(lines[len(lines)-1]) > 0 {
|
||||||
|
lines = append(lines, "")
|
||||||
|
}
|
||||||
|
return &History{
|
||||||
|
path: path,
|
||||||
|
maxSize: maxSize,
|
||||||
|
lines: lines,
|
||||||
|
modified: make(map[int]string),
|
||||||
|
cursor: len(lines) - 1}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) append(line string) error {
|
||||||
|
// We don't append empty lines
|
||||||
|
if len(line) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := append(h.lines[:len(h.lines)-1], line)
|
||||||
|
if len(lines) > h.maxSize {
|
||||||
|
lines = lines[len(lines)-h.maxSize : len(lines)]
|
||||||
|
}
|
||||||
|
h.lines = append(lines, "")
|
||||||
|
return ioutil.WriteFile(h.path, []byte(strings.Join(h.lines, "\n")), 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) override(str string) {
|
||||||
|
// You can update the history but they're not written to the file
|
||||||
|
if h.cursor == len(h.lines)-1 {
|
||||||
|
h.lines[h.cursor] = str
|
||||||
|
} else if h.cursor < len(h.lines)-1 {
|
||||||
|
h.modified[h.cursor] = str
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) current() string {
|
||||||
|
if str, prs := h.modified[h.cursor]; prs {
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
return h.lines[h.cursor]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) previous() string {
|
||||||
|
if h.cursor > 0 {
|
||||||
|
h.cursor--
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) next() string {
|
||||||
|
if h.cursor < len(h.lines)-1 {
|
||||||
|
h.cursor++
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
59
src/history_test.go
Normal file
59
src/history_test.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/user"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHistory(t *testing.T) {
|
||||||
|
maxHistory := 50
|
||||||
|
|
||||||
|
// Invalid arguments
|
||||||
|
user, _ := user.Current()
|
||||||
|
paths := []string{"/etc", "/proc"}
|
||||||
|
if user.Name != "root" {
|
||||||
|
paths = append(paths, "/etc/sudoers")
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
if _, e := NewHistory(path, maxHistory); e == nil {
|
||||||
|
t.Error("Error expected for: " + path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
for i := 0; i < maxHistory+10; i++ {
|
||||||
|
h.append("foobar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Read lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
for i := 0; i < maxHistory; i++ {
|
||||||
|
if h.lines[i] != "foobar" {
|
||||||
|
t.Error("Expected: foobar, actual: " + h.lines[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
h.append("barfoo")
|
||||||
|
h.append("")
|
||||||
|
h.append("foobarbaz")
|
||||||
|
}
|
||||||
|
{ // Read lines again
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
compare := func(idx int, exp string) {
|
||||||
|
if h.lines[idx] != exp {
|
||||||
|
t.Errorf("Expected: %s, actual: %s\n", exp, h.lines[idx])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compare(maxHistory-3, "foobar")
|
||||||
|
compare(maxHistory-2, "barfoo")
|
||||||
|
compare(maxHistory-1, "foobarbaz")
|
||||||
|
}
|
||||||
|
}
|
65
src/item.go
65
src/item.go
@@ -1,6 +1,8 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/curses"
|
"github.com/junegunn/fzf/src/curses"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,7 +19,7 @@ type colorOffset struct {
|
|||||||
type Item struct {
|
type Item struct {
|
||||||
text *string
|
text *string
|
||||||
origText *string
|
origText *string
|
||||||
transformed *Transformed
|
transformed *[]Token
|
||||||
index uint32
|
index uint32
|
||||||
offsets []Offset
|
offsets []Offset
|
||||||
colors []ansiOffset
|
colors []ansiOffset
|
||||||
@@ -27,17 +29,21 @@ type Item struct {
|
|||||||
// Rank is used to sort the search result
|
// Rank is used to sort the search result
|
||||||
type Rank struct {
|
type Rank struct {
|
||||||
matchlen uint16
|
matchlen uint16
|
||||||
strlen uint16
|
tiebreak uint16
|
||||||
index uint32
|
index uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tiebreak criterion to use. Never changes once fzf is started.
|
||||||
|
var rankTiebreak tiebreak
|
||||||
|
|
||||||
// Rank calculates rank of the Item
|
// Rank calculates rank of the Item
|
||||||
func (i *Item) Rank(cache bool) Rank {
|
func (i *Item) Rank(cache bool) Rank {
|
||||||
if cache && (i.rank.matchlen > 0 || i.rank.strlen > 0) {
|
if cache && (i.rank.matchlen > 0 || i.rank.tiebreak > 0) {
|
||||||
return i.rank
|
return i.rank
|
||||||
}
|
}
|
||||||
matchlen := 0
|
matchlen := 0
|
||||||
prevEnd := 0
|
prevEnd := 0
|
||||||
|
minBegin := math.MaxUint16
|
||||||
for _, offset := range i.offsets {
|
for _, offset := range i.offsets {
|
||||||
begin := int(offset[0])
|
begin := int(offset[0])
|
||||||
end := int(offset[1])
|
end := int(offset[1])
|
||||||
@@ -48,10 +54,30 @@ func (i *Item) Rank(cache bool) Rank {
|
|||||||
prevEnd = end
|
prevEnd = end
|
||||||
}
|
}
|
||||||
if end > begin {
|
if end > begin {
|
||||||
|
if begin < minBegin {
|
||||||
|
minBegin = begin
|
||||||
|
}
|
||||||
matchlen += end - begin
|
matchlen += end - begin
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rank := Rank{uint16(matchlen), uint16(len(*i.text)), i.index}
|
var tiebreak uint16
|
||||||
|
switch rankTiebreak {
|
||||||
|
case byLength:
|
||||||
|
tiebreak = uint16(len(*i.text))
|
||||||
|
case byBegin:
|
||||||
|
// We can't just look at i.offsets[0][0] because it can be an inverse term
|
||||||
|
tiebreak = uint16(minBegin)
|
||||||
|
case byEnd:
|
||||||
|
if prevEnd > 0 {
|
||||||
|
tiebreak = uint16(1 + len(*i.text) - prevEnd)
|
||||||
|
} else {
|
||||||
|
// Empty offsets due to inverse terms.
|
||||||
|
tiebreak = 1
|
||||||
|
}
|
||||||
|
case byIndex:
|
||||||
|
tiebreak = 1
|
||||||
|
}
|
||||||
|
rank := Rank{uint16(matchlen), tiebreak, i.index}
|
||||||
if cache {
|
if cache {
|
||||||
i.rank = rank
|
i.rank = rank
|
||||||
}
|
}
|
||||||
@@ -60,10 +86,15 @@ func (i *Item) Rank(cache bool) Rank {
|
|||||||
|
|
||||||
// AsString returns the original string
|
// AsString returns the original string
|
||||||
func (i *Item) AsString() string {
|
func (i *Item) AsString() string {
|
||||||
|
return *i.StringPtr()
|
||||||
|
}
|
||||||
|
|
||||||
|
// StringPtr returns the pointer to the original string
|
||||||
|
func (i *Item) StringPtr() *string {
|
||||||
if i.origText != nil {
|
if i.origText != nil {
|
||||||
return *i.origText
|
return i.origText
|
||||||
}
|
}
|
||||||
return *i.text
|
return i.text
|
||||||
}
|
}
|
||||||
|
|
||||||
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
||||||
@@ -117,13 +148,25 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
|||||||
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
||||||
} else {
|
} else {
|
||||||
ansi := item.colors[curr-1]
|
ansi := item.colors[curr-1]
|
||||||
|
fg := ansi.color.fg
|
||||||
|
if fg == -1 {
|
||||||
|
if current {
|
||||||
|
fg = curses.CurrentFG
|
||||||
|
} else {
|
||||||
|
fg = curses.FG
|
||||||
|
}
|
||||||
|
}
|
||||||
bg := ansi.color.bg
|
bg := ansi.color.bg
|
||||||
if current && bg == -1 {
|
if bg == -1 {
|
||||||
bg = int(curses.DarkBG)
|
if current {
|
||||||
|
bg = curses.DarkBG
|
||||||
|
} else {
|
||||||
|
bg = curses.BG
|
||||||
|
}
|
||||||
}
|
}
|
||||||
offsets = append(offsets, colorOffset{
|
offsets = append(offsets, colorOffset{
|
||||||
offset: Offset{int32(start), int32(idx)},
|
offset: Offset{int32(start), int32(idx)},
|
||||||
color: curses.PairFor(ansi.color.fg, bg),
|
color: curses.PairFor(fg, bg),
|
||||||
bold: ansi.color.bold || bold})
|
bold: ansi.color.bold || bold})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,9 +242,9 @@ func compareRanks(irank Rank, jrank Rank, tac bool) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if irank.strlen < jrank.strlen {
|
if irank.tiebreak < jrank.tiebreak {
|
||||||
return true
|
return true
|
||||||
} else if irank.strlen > jrank.strlen {
|
} else if irank.tiebreak > jrank.tiebreak {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -42,7 +42,7 @@ func TestItemRank(t *testing.T) {
|
|||||||
strs := []string{"foo", "foobar", "bar", "baz"}
|
strs := []string{"foo", "foobar", "bar", "baz"}
|
||||||
item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}
|
item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}
|
||||||
rank1 := item1.Rank(true)
|
rank1 := item1.Rank(true)
|
||||||
if rank1.matchlen != 0 || rank1.strlen != 3 || rank1.index != 1 {
|
if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {
|
||||||
t.Error(item1.Rank(true))
|
t.Error(item1.Rank(true))
|
||||||
}
|
}
|
||||||
// Only differ in index
|
// Only differ in index
|
||||||
|
@@ -34,10 +34,6 @@ const (
|
|||||||
reqReset
|
reqReset
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
progressMinDuration = 200 * time.Millisecond
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewMatcher returns a new Matcher
|
// NewMatcher returns a new Matcher
|
||||||
func NewMatcher(patternBuilder func([]rune) *Pattern,
|
func NewMatcher(patternBuilder func([]rune) *Pattern,
|
||||||
sort bool, tac bool, eventBox *util.EventBox) *Matcher {
|
sort bool, tac bool, eventBox *util.EventBox) *Matcher {
|
||||||
@@ -100,7 +96,9 @@ func (m *Matcher) Loop() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !cancelled {
|
if !cancelled {
|
||||||
|
if merger.Cacheable() {
|
||||||
m.mergerCache[patternString] = merger
|
m.mergerCache[patternString] = merger
|
||||||
|
}
|
||||||
merger.final = request.final
|
merger.final = request.final
|
||||||
m.eventBox.Set(EvtSearchFin, merger)
|
m.eventBox.Set(EvtSearchFin, merger)
|
||||||
}
|
}
|
||||||
|
@@ -61,8 +61,8 @@ func (mg *Merger) Get(idx int) *Item {
|
|||||||
if mg.tac {
|
if mg.tac {
|
||||||
idx = mg.count - idx - 1
|
idx = mg.count - idx - 1
|
||||||
}
|
}
|
||||||
chunk := (*mg.chunks)[idx/ChunkSize]
|
chunk := (*mg.chunks)[idx/chunkSize]
|
||||||
return (*chunk)[idx%ChunkSize]
|
return (*chunk)[idx%chunkSize]
|
||||||
}
|
}
|
||||||
|
|
||||||
if mg.sorted {
|
if mg.sorted {
|
||||||
@@ -82,6 +82,10 @@ func (mg *Merger) Get(idx int) *Item {
|
|||||||
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (mg *Merger) Cacheable() bool {
|
||||||
|
return mg.count < mergerCacheMax
|
||||||
|
}
|
||||||
|
|
||||||
func (mg *Merger) mergedGet(idx int) *Item {
|
func (mg *Merger) mergedGet(idx int) *Item {
|
||||||
for i := len(mg.merged); i <= idx; i++ {
|
for i := len(mg.merged); i <= idx; i++ {
|
||||||
minRank := Rank{0, 0, 0}
|
minRank := Rank{0, 0, 0}
|
||||||
|
481
src/options.go
481
src/options.go
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ import (
|
|||||||
|
|
||||||
const usage = `usage: fzf [options]
|
const usage = `usage: fzf [options]
|
||||||
|
|
||||||
Search mode
|
Search
|
||||||
-x, --extended Extended-search mode
|
-x, --extended Extended-search mode
|
||||||
-e, --extended-exact Extended-search mode (exact match)
|
-e, --extended-exact Extended-search mode (exact match)
|
||||||
-i Case-insensitive match (default: smart-case match)
|
-i Case-insensitive match (default: smart-case match)
|
||||||
@@ -22,23 +23,27 @@ const usage = `usage: fzf [options]
|
|||||||
-n, --nth=N[,..] Comma-separated list of field index expressions
|
-n, --nth=N[,..] Comma-separated list of field index expressions
|
||||||
for limiting search scope. Each can be a non-zero
|
for limiting search scope. Each can be a non-zero
|
||||||
integer or a range expression ([BEGIN]..[END])
|
integer or a range expression ([BEGIN]..[END])
|
||||||
--with-nth=N[,..] Transform the item using index expressions for search
|
--with-nth=N[,..] Transform item using index expressions within finder
|
||||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||||
|
|
||||||
Search result
|
|
||||||
+s, --no-sort Do not sort the result
|
+s, --no-sort Do not sort the result
|
||||||
--tac Reverse the order of the input
|
--tac Reverse the order of the input
|
||||||
(e.g. 'history | fzf --tac --no-sort')
|
--tiebreak=CRI Sort criterion when the scores are tied;
|
||||||
|
[length|begin|end|index] (default: length)
|
||||||
|
|
||||||
Interface
|
Interface
|
||||||
-m, --multi Enable multi-select with tab/shift-tab
|
-m, --multi Enable multi-select with tab/shift-tab
|
||||||
--ansi Enable processing of ANSI color codes
|
--ansi Enable processing of ANSI color codes
|
||||||
--no-mouse Disable mouse
|
--no-mouse Disable mouse
|
||||||
+c, --no-color Disable colors
|
--color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors
|
||||||
+2, --no-256 Disable 256-color
|
|
||||||
--black Use black background
|
--black Use black background
|
||||||
--reverse Reverse orientation
|
--reverse Reverse orientation
|
||||||
|
--cycle Enable cyclic scroll
|
||||||
|
--no-hscroll Disable horizontal scroll
|
||||||
|
--inline-info Display finder info inline with the query
|
||||||
--prompt=STR Input prompt (default: '> ')
|
--prompt=STR Input prompt (default: '> ')
|
||||||
|
--bind=KEYBINDS Custom key bindings. Refer to the man page.
|
||||||
|
--history=FILE History file
|
||||||
|
--history-size=N Maximum number of history entries (default: 1000)
|
||||||
|
|
||||||
Scripting
|
Scripting
|
||||||
-q, --query=STR Start the finder with the given query
|
-q, --query=STR Start the finder with the given query
|
||||||
@@ -47,9 +52,7 @@ const usage = `usage: fzf [options]
|
|||||||
-f, --filter=STR Filter mode. Do not start interactive finder.
|
-f, --filter=STR Filter mode. Do not start interactive finder.
|
||||||
--print-query Print query as the first line
|
--print-query Print query as the first line
|
||||||
--expect=KEYS Comma-separated list of keys to complete fzf
|
--expect=KEYS Comma-separated list of keys to complete fzf
|
||||||
--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')
|
|
||||||
|
|
||||||
Environment variables
|
Environment variables
|
||||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||||
@@ -77,6 +80,16 @@ const (
|
|||||||
CaseRespect
|
CaseRespect
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Sort criteria
|
||||||
|
type tiebreak int
|
||||||
|
|
||||||
|
const (
|
||||||
|
byLength tiebreak = iota
|
||||||
|
byBegin
|
||||||
|
byEnd
|
||||||
|
byIndex
|
||||||
|
)
|
||||||
|
|
||||||
// Options stores the values of command-line options
|
// Options stores the values of command-line options
|
||||||
type Options struct {
|
type Options struct {
|
||||||
Mode Mode
|
Mode Mode
|
||||||
@@ -86,25 +99,39 @@ type Options struct {
|
|||||||
Delimiter *regexp.Regexp
|
Delimiter *regexp.Regexp
|
||||||
Sort int
|
Sort int
|
||||||
Tac bool
|
Tac bool
|
||||||
|
Tiebreak tiebreak
|
||||||
Multi bool
|
Multi bool
|
||||||
Ansi bool
|
Ansi bool
|
||||||
Mouse bool
|
Mouse bool
|
||||||
Color bool
|
Theme *curses.ColorTheme
|
||||||
Color256 bool
|
|
||||||
Black bool
|
Black bool
|
||||||
Reverse bool
|
Reverse bool
|
||||||
|
Cycle bool
|
||||||
|
Hscroll bool
|
||||||
|
InlineInfo bool
|
||||||
Prompt string
|
Prompt string
|
||||||
Query string
|
Query string
|
||||||
Select1 bool
|
Select1 bool
|
||||||
Exit0 bool
|
Exit0 bool
|
||||||
Filter *string
|
Filter *string
|
||||||
ToggleSort int
|
ToggleSort bool
|
||||||
Expect []int
|
Expect map[int]string
|
||||||
|
Keymap map[int]actionType
|
||||||
|
Execmap map[int]string
|
||||||
PrintQuery bool
|
PrintQuery bool
|
||||||
|
ReadZero bool
|
||||||
Sync bool
|
Sync bool
|
||||||
|
History *History
|
||||||
Version bool
|
Version bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func defaultTheme() *curses.ColorTheme {
|
||||||
|
if strings.Contains(os.Getenv("TERM"), "256") {
|
||||||
|
return curses.Dark256
|
||||||
|
}
|
||||||
|
return curses.Default16
|
||||||
|
}
|
||||||
|
|
||||||
func defaultOptions() *Options {
|
func defaultOptions() *Options {
|
||||||
return &Options{
|
return &Options{
|
||||||
Mode: ModeFuzzy,
|
Mode: ModeFuzzy,
|
||||||
@@ -114,22 +141,29 @@ func defaultOptions() *Options {
|
|||||||
Delimiter: nil,
|
Delimiter: nil,
|
||||||
Sort: 1000,
|
Sort: 1000,
|
||||||
Tac: false,
|
Tac: false,
|
||||||
|
Tiebreak: byLength,
|
||||||
Multi: false,
|
Multi: false,
|
||||||
Ansi: false,
|
Ansi: false,
|
||||||
Mouse: true,
|
Mouse: true,
|
||||||
Color: true,
|
Theme: defaultTheme(),
|
||||||
Color256: strings.Contains(os.Getenv("TERM"), "256"),
|
|
||||||
Black: false,
|
Black: false,
|
||||||
Reverse: false,
|
Reverse: false,
|
||||||
|
Cycle: false,
|
||||||
|
Hscroll: true,
|
||||||
|
InlineInfo: false,
|
||||||
Prompt: "> ",
|
Prompt: "> ",
|
||||||
Query: "",
|
Query: "",
|
||||||
Select1: false,
|
Select1: false,
|
||||||
Exit0: false,
|
Exit0: false,
|
||||||
Filter: nil,
|
Filter: nil,
|
||||||
ToggleSort: 0,
|
ToggleSort: false,
|
||||||
Expect: []int{},
|
Expect: make(map[int]string),
|
||||||
|
Keymap: defaultKeymap(),
|
||||||
|
Execmap: make(map[int]string),
|
||||||
PrintQuery: false,
|
PrintQuery: false,
|
||||||
|
ReadZero: false,
|
||||||
Sync: false,
|
Sync: false,
|
||||||
|
History: nil,
|
||||||
Version: false}
|
Version: false}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,11 +177,11 @@ func errorExit(msg string) {
|
|||||||
help(1)
|
help(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func optString(arg string, prefix string) (bool, string) {
|
func optString(arg string, prefixes ...string) (bool, string) {
|
||||||
rx, _ := regexp.Compile(fmt.Sprintf("^(?:%s)(.*)$", prefix))
|
for _, prefix := range prefixes {
|
||||||
matches := rx.FindStringSubmatch(arg)
|
if strings.HasPrefix(arg, prefix) {
|
||||||
if len(matches) > 1 {
|
return true, arg[len(prefix):]
|
||||||
return true, matches[1]
|
}
|
||||||
}
|
}
|
||||||
return false, ""
|
return false, ""
|
||||||
}
|
}
|
||||||
@@ -161,6 +195,31 @@ func nextString(args []string, i *int, message string) string {
|
|||||||
return args[*i]
|
return args[*i]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func optionalNextString(args []string, i *int) string {
|
||||||
|
if len(args) > *i+1 {
|
||||||
|
*i++
|
||||||
|
return args[*i]
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func atoi(str string) int {
|
||||||
|
num, err := strconv.Atoi(str)
|
||||||
|
if err != nil {
|
||||||
|
errorExit("not a valid integer: " + str)
|
||||||
|
}
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextInt(args []string, i *int, message string) int {
|
||||||
|
if len(args) > *i+1 {
|
||||||
|
*i++
|
||||||
|
} else {
|
||||||
|
errorExit(message)
|
||||||
|
}
|
||||||
|
return atoi(args[*i])
|
||||||
|
}
|
||||||
|
|
||||||
func optionalNumeric(args []string, i *int) int {
|
func optionalNumeric(args []string, i *int) int {
|
||||||
if len(args) > *i+1 {
|
if len(args) > *i+1 {
|
||||||
if strings.IndexAny(args[*i+1], "0123456789") == 0 {
|
if strings.IndexAny(args[*i+1], "0123456789") == 0 {
|
||||||
@@ -204,7 +263,7 @@ func isAlphabet(char uint8) bool {
|
|||||||
return char >= 'a' && char <= 'z'
|
return char >= 'a' && char <= 'z'
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseKeyChords(str string, message string) []int {
|
func parseKeyChords(str string, message string) map[int]string {
|
||||||
if len(str) == 0 {
|
if len(str) == 0 {
|
||||||
errorExit(message)
|
errorExit(message)
|
||||||
}
|
}
|
||||||
@@ -214,36 +273,318 @@ func parseKeyChords(str string, message string) []int {
|
|||||||
tokens = append(tokens, ",")
|
tokens = append(tokens, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
var chords []int
|
chords := make(map[int]string)
|
||||||
for _, key := range tokens {
|
for _, key := range tokens {
|
||||||
if len(key) == 0 {
|
if len(key) == 0 {
|
||||||
continue // ignore
|
continue // ignore
|
||||||
}
|
}
|
||||||
lkey := strings.ToLower(key)
|
lkey := strings.ToLower(key)
|
||||||
|
chord := 0
|
||||||
|
switch lkey {
|
||||||
|
case "up":
|
||||||
|
chord = curses.Up
|
||||||
|
case "down":
|
||||||
|
chord = curses.Down
|
||||||
|
case "left":
|
||||||
|
chord = curses.Left
|
||||||
|
case "right":
|
||||||
|
chord = curses.Right
|
||||||
|
case "enter", "return":
|
||||||
|
chord = curses.CtrlM
|
||||||
|
case "space":
|
||||||
|
chord = curses.AltZ + int(' ')
|
||||||
|
case "bspace", "bs":
|
||||||
|
chord = curses.BSpace
|
||||||
|
case "alt-bs", "alt-bspace":
|
||||||
|
chord = curses.AltBS
|
||||||
|
case "tab":
|
||||||
|
chord = curses.Tab
|
||||||
|
case "btab", "shift-tab":
|
||||||
|
chord = curses.BTab
|
||||||
|
case "esc":
|
||||||
|
chord = curses.ESC
|
||||||
|
case "del":
|
||||||
|
chord = curses.Del
|
||||||
|
case "home":
|
||||||
|
chord = curses.Home
|
||||||
|
case "end":
|
||||||
|
chord = curses.End
|
||||||
|
case "pgup", "page-up":
|
||||||
|
chord = curses.PgUp
|
||||||
|
case "pgdn", "page-down":
|
||||||
|
chord = curses.PgDn
|
||||||
|
case "shift-left":
|
||||||
|
chord = curses.SLeft
|
||||||
|
case "shift-right":
|
||||||
|
chord = curses.SRight
|
||||||
|
default:
|
||||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||||
chords = append(chords, curses.CtrlA+int(lkey[5])-'a')
|
chord = curses.CtrlA + int(lkey[5]) - 'a'
|
||||||
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||||
chords = append(chords, curses.AltA+int(lkey[4])-'a')
|
chord = curses.AltA + int(lkey[4]) - 'a'
|
||||||
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
||||||
chords = append(chords, curses.F1+int(key[1])-'1')
|
chord = curses.F1 + int(key[1]) - '1'
|
||||||
} else if utf8.RuneCountInString(key) == 1 {
|
} else if utf8.RuneCountInString(key) == 1 {
|
||||||
chords = append(chords, curses.AltZ+int([]rune(key)[0]))
|
chord = curses.AltZ + int([]rune(key)[0])
|
||||||
} else {
|
} else {
|
||||||
errorExit("unsupported key: " + key)
|
errorExit("unsupported key: " + key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if chord > 0 {
|
||||||
|
chords[chord] = key
|
||||||
|
}
|
||||||
|
}
|
||||||
return chords
|
return chords
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkToggleSort(str string) int {
|
func parseTiebreak(str string) tiebreak {
|
||||||
|
switch strings.ToLower(str) {
|
||||||
|
case "length":
|
||||||
|
return byLength
|
||||||
|
case "index":
|
||||||
|
return byIndex
|
||||||
|
case "begin":
|
||||||
|
return byBegin
|
||||||
|
case "end":
|
||||||
|
return byEnd
|
||||||
|
default:
|
||||||
|
errorExit("invalid sort criterion: " + str)
|
||||||
|
}
|
||||||
|
return byLength
|
||||||
|
}
|
||||||
|
|
||||||
|
func dupeTheme(theme *curses.ColorTheme) *curses.ColorTheme {
|
||||||
|
dupe := *theme
|
||||||
|
return &dupe
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme {
|
||||||
|
theme := dupeTheme(defaultTheme)
|
||||||
|
for _, str := range strings.Split(strings.ToLower(str), ",") {
|
||||||
|
switch str {
|
||||||
|
case "dark":
|
||||||
|
theme = dupeTheme(curses.Dark256)
|
||||||
|
case "light":
|
||||||
|
theme = dupeTheme(curses.Light256)
|
||||||
|
case "16":
|
||||||
|
theme = dupeTheme(curses.Default16)
|
||||||
|
case "bw", "no":
|
||||||
|
theme = nil
|
||||||
|
default:
|
||||||
|
fail := func() {
|
||||||
|
errorExit("invalid color specification: " + str)
|
||||||
|
}
|
||||||
|
// Color is disabled
|
||||||
|
if theme == nil {
|
||||||
|
errorExit("colors disabled; cannot customize colors")
|
||||||
|
}
|
||||||
|
|
||||||
|
pair := strings.Split(str, ":")
|
||||||
|
if len(pair) != 2 {
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
ansi32, err := strconv.Atoi(pair[1])
|
||||||
|
if err != nil || ansi32 < -1 || ansi32 > 255 {
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
ansi := int16(ansi32)
|
||||||
|
switch pair[0] {
|
||||||
|
case "fg":
|
||||||
|
theme.Fg = ansi
|
||||||
|
theme.UseDefault = theme.UseDefault && ansi < 0
|
||||||
|
case "bg":
|
||||||
|
theme.Bg = ansi
|
||||||
|
theme.UseDefault = theme.UseDefault && ansi < 0
|
||||||
|
case "fg+":
|
||||||
|
theme.Current = ansi
|
||||||
|
case "bg+":
|
||||||
|
theme.DarkBg = ansi
|
||||||
|
case "hl":
|
||||||
|
theme.Match = ansi
|
||||||
|
case "hl+":
|
||||||
|
theme.CurrentMatch = ansi
|
||||||
|
case "prompt":
|
||||||
|
theme.Prompt = ansi
|
||||||
|
case "spinner":
|
||||||
|
theme.Spinner = ansi
|
||||||
|
case "info":
|
||||||
|
theme.Info = ansi
|
||||||
|
case "pointer":
|
||||||
|
theme.Cursor = ansi
|
||||||
|
case "marker":
|
||||||
|
theme.Selected = ansi
|
||||||
|
default:
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return theme
|
||||||
|
}
|
||||||
|
|
||||||
|
var executeRegexp *regexp.Regexp
|
||||||
|
|
||||||
|
func firstKey(keymap map[int]string) int {
|
||||||
|
for k := range keymap {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {
|
||||||
|
if executeRegexp == nil {
|
||||||
|
// Backreferences are not supported.
|
||||||
|
// "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')
|
||||||
|
executeRegexp = regexp.MustCompile(
|
||||||
|
"(?s):execute:.*|:execute(\\([^)]*\\)|\\[[^\\]]*\\]|~[^~]*~|![^!]*!|@[^@]*@|\\#[^\\#]*\\#|\\$[^\\$]*\\$|%[^%]*%|\\^[^\\^]*\\^|&[^&]*&|\\*[^\\*]*\\*|;[^;]*;|/[^/]*/|\\|[^\\|]*\\|)")
|
||||||
|
}
|
||||||
|
masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {
|
||||||
|
return ":execute(" + strings.Repeat(" ", len(src)-10) + ")"
|
||||||
|
})
|
||||||
|
|
||||||
|
idx := 0
|
||||||
|
for _, pairStr := range strings.Split(masked, ",") {
|
||||||
|
pairStr = str[idx : idx+len(pairStr)]
|
||||||
|
idx += len(pairStr) + 1
|
||||||
|
|
||||||
|
fail := func() {
|
||||||
|
errorExit("invalid key binding: " + pairStr)
|
||||||
|
}
|
||||||
|
pair := strings.SplitN(pairStr, ":", 2)
|
||||||
|
if len(pair) != 2 {
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
keys := parseKeyChords(pair[0], "key name required")
|
||||||
|
if len(keys) != 1 {
|
||||||
|
fail()
|
||||||
|
}
|
||||||
|
key := firstKey(keys)
|
||||||
|
act := strings.ToLower(pair[1])
|
||||||
|
switch act {
|
||||||
|
case "ignore":
|
||||||
|
keymap[key] = actIgnore
|
||||||
|
case "beginning-of-line":
|
||||||
|
keymap[key] = actBeginningOfLine
|
||||||
|
case "abort":
|
||||||
|
keymap[key] = actAbort
|
||||||
|
case "accept":
|
||||||
|
keymap[key] = actAccept
|
||||||
|
case "backward-char":
|
||||||
|
keymap[key] = actBackwardChar
|
||||||
|
case "backward-delete-char":
|
||||||
|
keymap[key] = actBackwardDeleteChar
|
||||||
|
case "backward-word":
|
||||||
|
keymap[key] = actBackwardWord
|
||||||
|
case "clear-screen":
|
||||||
|
keymap[key] = actClearScreen
|
||||||
|
case "delete-char":
|
||||||
|
keymap[key] = actDeleteChar
|
||||||
|
case "end-of-line":
|
||||||
|
keymap[key] = actEndOfLine
|
||||||
|
case "forward-char":
|
||||||
|
keymap[key] = actForwardChar
|
||||||
|
case "forward-word":
|
||||||
|
keymap[key] = actForwardWord
|
||||||
|
case "kill-line":
|
||||||
|
keymap[key] = actKillLine
|
||||||
|
case "kill-word":
|
||||||
|
keymap[key] = actKillWord
|
||||||
|
case "unix-line-discard", "line-discard":
|
||||||
|
keymap[key] = actUnixLineDiscard
|
||||||
|
case "unix-word-rubout", "word-rubout":
|
||||||
|
keymap[key] = actUnixWordRubout
|
||||||
|
case "yank":
|
||||||
|
keymap[key] = actYank
|
||||||
|
case "backward-kill-word":
|
||||||
|
keymap[key] = actBackwardKillWord
|
||||||
|
case "toggle-down":
|
||||||
|
keymap[key] = actToggleDown
|
||||||
|
case "toggle-up":
|
||||||
|
keymap[key] = actToggleUp
|
||||||
|
case "toggle-all":
|
||||||
|
keymap[key] = actToggleAll
|
||||||
|
case "select-all":
|
||||||
|
keymap[key] = actSelectAll
|
||||||
|
case "deselect-all":
|
||||||
|
keymap[key] = actDeselectAll
|
||||||
|
case "toggle":
|
||||||
|
keymap[key] = actToggle
|
||||||
|
case "down":
|
||||||
|
keymap[key] = actDown
|
||||||
|
case "up":
|
||||||
|
keymap[key] = actUp
|
||||||
|
case "page-up":
|
||||||
|
keymap[key] = actPageUp
|
||||||
|
case "page-down":
|
||||||
|
keymap[key] = actPageDown
|
||||||
|
case "previous-history":
|
||||||
|
keymap[key] = actPreviousHistory
|
||||||
|
case "next-history":
|
||||||
|
keymap[key] = actNextHistory
|
||||||
|
case "toggle-sort":
|
||||||
|
keymap[key] = actToggleSort
|
||||||
|
toggleSort = true
|
||||||
|
default:
|
||||||
|
if isExecuteAction(act) {
|
||||||
|
keymap[key] = actExecute
|
||||||
|
if pair[1][7] == ':' {
|
||||||
|
execmap[key] = pair[1][8:]
|
||||||
|
} else {
|
||||||
|
execmap[key] = pair[1][8 : len(act)-1]
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
errorExit("unknown action: " + act)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keymap, execmap, toggleSort
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExecuteAction(str string) bool {
|
||||||
|
if !strings.HasPrefix(str, "execute") || len(str) < 9 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b := str[7]
|
||||||
|
e := str[len(str)-1]
|
||||||
|
if b == ':' || b == '(' && e == ')' || b == '[' && e == ']' ||
|
||||||
|
b == e && strings.ContainsAny(string(b), "~!@#$%^&*;/|") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
||||||
keys := parseKeyChords(str, "key name required")
|
keys := parseKeyChords(str, "key name required")
|
||||||
if len(keys) != 1 {
|
if len(keys) != 1 {
|
||||||
errorExit("multiple keys specified")
|
errorExit("multiple keys specified")
|
||||||
}
|
}
|
||||||
return keys[0]
|
keymap[firstKey(keys)] = actToggleSort
|
||||||
|
return keymap
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOptions(opts *Options, allArgs []string) {
|
func parseOptions(opts *Options, allArgs []string) {
|
||||||
|
keymap := make(map[int]actionType)
|
||||||
|
var historyMax int
|
||||||
|
if opts.History == nil {
|
||||||
|
historyMax = defaultHistoryMax
|
||||||
|
} else {
|
||||||
|
historyMax = opts.History.maxSize
|
||||||
|
}
|
||||||
|
setHistory := func(path string) {
|
||||||
|
h, e := NewHistory(path, historyMax)
|
||||||
|
if e != nil {
|
||||||
|
errorExit(e.Error())
|
||||||
|
}
|
||||||
|
opts.History = h
|
||||||
|
}
|
||||||
|
setHistoryMax := func(max int) {
|
||||||
|
historyMax = max
|
||||||
|
if historyMax < 1 {
|
||||||
|
errorExit("history max must be a positive integer")
|
||||||
|
}
|
||||||
|
if opts.History != nil {
|
||||||
|
opts.History.maxSize = historyMax
|
||||||
|
}
|
||||||
|
}
|
||||||
for i := 0; i < len(allArgs); i++ {
|
for i := 0; i < len(allArgs); i++ {
|
||||||
arg := allArgs[i]
|
arg := allArgs[i]
|
||||||
switch arg {
|
switch arg {
|
||||||
@@ -262,8 +603,21 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Filter = &filter
|
opts.Filter = &filter
|
||||||
case "--expect":
|
case "--expect":
|
||||||
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
||||||
|
case "--tiebreak":
|
||||||
|
opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||||
|
case "--bind":
|
||||||
|
keymap, opts.Execmap, opts.ToggleSort =
|
||||||
|
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))
|
||||||
|
case "--color":
|
||||||
|
spec := optionalNextString(allArgs, &i)
|
||||||
|
if len(spec) == 0 {
|
||||||
|
opts.Theme = defaultTheme()
|
||||||
|
} else {
|
||||||
|
opts.Theme = parseTheme(opts.Theme, spec)
|
||||||
|
}
|
||||||
case "--toggle-sort":
|
case "--toggle-sort":
|
||||||
opts.ToggleSort = checkToggleSort(nextString(allArgs, &i, "key name required"))
|
keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))
|
||||||
|
opts.ToggleSort = true
|
||||||
case "-d", "--delimiter":
|
case "-d", "--delimiter":
|
||||||
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
||||||
case "-n", "--nth":
|
case "-n", "--nth":
|
||||||
@@ -293,9 +647,9 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
case "--no-mouse":
|
case "--no-mouse":
|
||||||
opts.Mouse = false
|
opts.Mouse = false
|
||||||
case "+c", "--no-color":
|
case "+c", "--no-color":
|
||||||
opts.Color = false
|
opts.Theme = nil
|
||||||
case "+2", "--no-256":
|
case "+2", "--no-256":
|
||||||
opts.Color256 = false
|
opts.Theme = curses.Default16
|
||||||
case "--black":
|
case "--black":
|
||||||
opts.Black = true
|
opts.Black = true
|
||||||
case "--no-black":
|
case "--no-black":
|
||||||
@@ -304,6 +658,18 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Reverse = true
|
opts.Reverse = true
|
||||||
case "--no-reverse":
|
case "--no-reverse":
|
||||||
opts.Reverse = false
|
opts.Reverse = false
|
||||||
|
case "--cycle":
|
||||||
|
opts.Cycle = true
|
||||||
|
case "--no-cycle":
|
||||||
|
opts.Cycle = false
|
||||||
|
case "--hscroll":
|
||||||
|
opts.Hscroll = true
|
||||||
|
case "--no-hscroll":
|
||||||
|
opts.Hscroll = false
|
||||||
|
case "--inline-info":
|
||||||
|
opts.InlineInfo = true
|
||||||
|
case "--no-inline-info":
|
||||||
|
opts.InlineInfo = false
|
||||||
case "-1", "--select-1":
|
case "-1", "--select-1":
|
||||||
opts.Select1 = true
|
opts.Select1 = true
|
||||||
case "+1", "--no-select-1":
|
case "+1", "--no-select-1":
|
||||||
@@ -312,6 +678,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Exit0 = true
|
opts.Exit0 = true
|
||||||
case "+0", "--no-exit-0":
|
case "+0", "--no-exit-0":
|
||||||
opts.Exit0 = false
|
opts.Exit0 = false
|
||||||
|
case "--read0":
|
||||||
|
opts.ReadZero = true
|
||||||
|
case "--no-read0":
|
||||||
|
opts.ReadZero = false
|
||||||
case "--print-query":
|
case "--print-query":
|
||||||
opts.PrintQuery = true
|
opts.PrintQuery = true
|
||||||
case "--no-print-query":
|
case "--no-print-query":
|
||||||
@@ -324,33 +694,66 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
opts.Sync = false
|
opts.Sync = false
|
||||||
case "--async":
|
case "--async":
|
||||||
opts.Sync = false
|
opts.Sync = false
|
||||||
|
case "--no-history":
|
||||||
|
opts.History = nil
|
||||||
|
case "--history":
|
||||||
|
setHistory(nextString(allArgs, &i, "history file path required"))
|
||||||
|
case "--history-size":
|
||||||
|
setHistoryMax(nextInt(allArgs, &i, "history max size required"))
|
||||||
case "--version":
|
case "--version":
|
||||||
opts.Version = true
|
opts.Version = true
|
||||||
default:
|
default:
|
||||||
if match, value := optString(arg, "-q|--query="); match {
|
if match, value := optString(arg, "-q", "--query="); match {
|
||||||
opts.Query = value
|
opts.Query = value
|
||||||
} else if match, value := optString(arg, "-f|--filter="); match {
|
} else if match, value := optString(arg, "-f", "--filter="); match {
|
||||||
opts.Filter = &value
|
opts.Filter = &value
|
||||||
} else if match, value := optString(arg, "-d|--delimiter="); match {
|
} else if match, value := optString(arg, "-d", "--delimiter="); match {
|
||||||
opts.Delimiter = delimiterRegexp(value)
|
opts.Delimiter = delimiterRegexp(value)
|
||||||
} else if match, value := optString(arg, "--prompt="); match {
|
} else if match, value := optString(arg, "--prompt="); match {
|
||||||
opts.Prompt = value
|
opts.Prompt = value
|
||||||
} else if match, value := optString(arg, "-n|--nth="); match {
|
} else if match, value := optString(arg, "-n", "--nth="); match {
|
||||||
opts.Nth = splitNth(value)
|
opts.Nth = splitNth(value)
|
||||||
} else if match, value := optString(arg, "--with-nth="); match {
|
} else if match, value := optString(arg, "--with-nth="); match {
|
||||||
opts.WithNth = splitNth(value)
|
opts.WithNth = splitNth(value)
|
||||||
} else if match, _ := optString(arg, "-s|--sort="); match {
|
} else if match, _ := optString(arg, "-s", "--sort="); match {
|
||||||
opts.Sort = 1 // Don't care
|
opts.Sort = 1 // Don't care
|
||||||
} else if match, value := optString(arg, "--toggle-sort="); match {
|
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||||
opts.ToggleSort = checkToggleSort(value)
|
keymap = checkToggleSort(keymap, value)
|
||||||
|
opts.ToggleSort = true
|
||||||
} else if match, value := optString(arg, "--expect="); match {
|
} else if match, value := optString(arg, "--expect="); match {
|
||||||
opts.Expect = parseKeyChords(value, "key names required")
|
opts.Expect = parseKeyChords(value, "key names required")
|
||||||
|
} else if match, value := optString(arg, "--tiebreak="); match {
|
||||||
|
opts.Tiebreak = parseTiebreak(value)
|
||||||
|
} else if match, value := optString(arg, "--color="); match {
|
||||||
|
opts.Theme = parseTheme(opts.Theme, value)
|
||||||
|
} else if match, value := optString(arg, "--bind="); match {
|
||||||
|
keymap, opts.Execmap, opts.ToggleSort =
|
||||||
|
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)
|
||||||
|
} else if match, value := optString(arg, "--history="); match {
|
||||||
|
setHistory(value)
|
||||||
|
} else if match, value := optString(arg, "--history-size="); match {
|
||||||
|
setHistoryMax(atoi(value))
|
||||||
} else {
|
} else {
|
||||||
errorExit("unknown option: " + arg)
|
errorExit("unknown option: " + arg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Change default actions for CTRL-N / CTRL-P when --history is used
|
||||||
|
if opts.History != nil {
|
||||||
|
if _, prs := keymap[curses.CtrlP]; !prs {
|
||||||
|
keymap[curses.CtrlP] = actPreviousHistory
|
||||||
|
}
|
||||||
|
if _, prs := keymap[curses.CtrlN]; !prs {
|
||||||
|
keymap[curses.CtrlN] = actNextHistory
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override default key bindings
|
||||||
|
for key, act := range keymap {
|
||||||
|
opts.Keymap[key] = act
|
||||||
|
}
|
||||||
|
|
||||||
// If we're not using extended search mode, --nth option becomes irrelevant
|
// If we're not using extended search mode, --nth option becomes irrelevant
|
||||||
// if it contains the whole range
|
// if it contains the whole range
|
||||||
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/curses"
|
"github.com/junegunn/fzf/src/curses"
|
||||||
@@ -71,61 +72,197 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseKeys(t *testing.T) {
|
func TestParseKeys(t *testing.T) {
|
||||||
keys := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
||||||
check := func(key int, expected int) {
|
check := func(i int, s string) {
|
||||||
if key != expected {
|
if pairs[i] != s {
|
||||||
t.Errorf("%d != %d", key, expected)
|
t.Errorf("%s != %s", pairs[i], s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
check(len(keys), 9)
|
if len(pairs) != 9 {
|
||||||
check(keys[0], curses.CtrlZ)
|
t.Error(9)
|
||||||
check(keys[1], curses.AltZ)
|
}
|
||||||
check(keys[2], curses.F2)
|
check(curses.CtrlZ, "ctrl-z")
|
||||||
check(keys[3], curses.AltZ+'@')
|
check(curses.AltZ, "alt-z")
|
||||||
check(keys[4], curses.AltA)
|
check(curses.F2, "f2")
|
||||||
check(keys[5], curses.AltZ+'!')
|
check(curses.AltZ+'@', "@")
|
||||||
check(keys[6], curses.CtrlA+'g'-'a')
|
check(curses.AltA, "Alt-a")
|
||||||
check(keys[7], curses.AltZ+'J')
|
check(curses.AltZ+'!', "!")
|
||||||
check(keys[8], curses.AltZ+'g')
|
check(curses.CtrlA+'g'-'a', "ctrl-G")
|
||||||
|
check(curses.AltZ+'J', "J")
|
||||||
|
check(curses.AltZ+'g', "g")
|
||||||
|
|
||||||
|
// Synonyms
|
||||||
|
pairs = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")
|
||||||
|
if len(pairs) != 9 {
|
||||||
|
t.Error(9)
|
||||||
|
}
|
||||||
|
check(curses.CtrlM, "Return")
|
||||||
|
check(curses.AltZ+' ', "space")
|
||||||
|
check(curses.Tab, "tab")
|
||||||
|
check(curses.BTab, "btab")
|
||||||
|
check(curses.ESC, "esc")
|
||||||
|
check(curses.Up, "up")
|
||||||
|
check(curses.Down, "down")
|
||||||
|
check(curses.Left, "left")
|
||||||
|
check(curses.Right, "right")
|
||||||
|
|
||||||
|
pairs = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")
|
||||||
|
if len(pairs) != 11 {
|
||||||
|
t.Error(11)
|
||||||
|
}
|
||||||
|
check(curses.Tab, "Ctrl-I")
|
||||||
|
check(curses.PgUp, "page-up")
|
||||||
|
check(curses.PgDn, "Page-Down")
|
||||||
|
check(curses.Home, "Home")
|
||||||
|
check(curses.End, "End")
|
||||||
|
check(curses.AltBS, "Alt-BSpace")
|
||||||
|
check(curses.SLeft, "shift-left")
|
||||||
|
check(curses.SRight, "shift-right")
|
||||||
|
check(curses.BTab, "shift-tab")
|
||||||
|
check(curses.CtrlM, "Enter")
|
||||||
|
check(curses.BSpace, "bspace")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseKeysWithComma(t *testing.T) {
|
func TestParseKeysWithComma(t *testing.T) {
|
||||||
check := func(key int, expected int) {
|
checkN := func(a int, b int) {
|
||||||
if key != expected {
|
if a != b {
|
||||||
t.Errorf("%d != %d", key, expected)
|
t.Errorf("%d != %d", a, b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check := func(pairs map[int]string, i int, s string) {
|
||||||
|
if pairs[i] != s {
|
||||||
|
t.Errorf("%s != %s", pairs[i], s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
keys := parseKeyChords(",", "")
|
pairs := parseKeyChords(",", "")
|
||||||
check(len(keys), 1)
|
checkN(len(pairs), 1)
|
||||||
check(keys[0], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords(",,a,b", "")
|
pairs = parseKeyChords(",,a,b", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,b,,", "")
|
pairs = parseKeyChords("a,b,,", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,,,b", "")
|
pairs = parseKeyChords("a,,,b", "")
|
||||||
check(len(keys), 3)
|
checkN(len(pairs), 3)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords("a,,,b,c", "")
|
pairs = parseKeyChords("a,,,b,c", "")
|
||||||
check(len(keys), 4)
|
checkN(len(pairs), 4)
|
||||||
check(keys[0], curses.AltZ+'a')
|
check(pairs, curses.AltZ+'a', "a")
|
||||||
check(keys[1], curses.AltZ+'b')
|
check(pairs, curses.AltZ+'b', "b")
|
||||||
check(keys[2], curses.AltZ+'c')
|
check(pairs, curses.AltZ+'c', "c")
|
||||||
check(keys[3], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
|
||||||
keys = parseKeyChords(",,,", "")
|
pairs = parseKeyChords(",,,", "")
|
||||||
check(len(keys), 1)
|
checkN(len(pairs), 1)
|
||||||
check(keys[0], curses.AltZ+',')
|
check(pairs, curses.AltZ+',', ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBind(t *testing.T) {
|
||||||
|
check := func(action actionType, expected actionType) {
|
||||||
|
if action != expected {
|
||||||
|
t.Errorf("%d != %d", action, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkString := func(action string, expected string) {
|
||||||
|
if action != expected {
|
||||||
|
t.Errorf("%d != %d", action, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keymap := defaultKeymap()
|
||||||
|
execmap := make(map[int]string)
|
||||||
|
check(actBeginningOfLine, keymap[curses.CtrlA])
|
||||||
|
keymap, execmap, toggleSort :=
|
||||||
|
parseKeymap(keymap, execmap, false,
|
||||||
|
"ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+
|
||||||
|
"f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+
|
||||||
|
"alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+
|
||||||
|
",X:execute:\nfoobar,Y:execute(baz)")
|
||||||
|
if !toggleSort {
|
||||||
|
t.Errorf("toggleSort not set")
|
||||||
|
}
|
||||||
|
check(actKillLine, keymap[curses.CtrlA])
|
||||||
|
check(actToggleSort, keymap[curses.CtrlB])
|
||||||
|
check(actPageUp, keymap[curses.AltZ+'c'])
|
||||||
|
check(actPageDown, keymap[curses.AltZ])
|
||||||
|
check(actExecute, keymap[curses.F1])
|
||||||
|
check(actExecute, keymap[curses.F2])
|
||||||
|
check(actExecute, keymap[curses.F3])
|
||||||
|
check(actExecute, keymap[curses.F4])
|
||||||
|
checkString("ls {}", execmap[curses.F1])
|
||||||
|
checkString("echo {}, {}, {}", execmap[curses.F2])
|
||||||
|
checkString("echo '({})'", execmap[curses.F3])
|
||||||
|
checkString("less {}", execmap[curses.F4])
|
||||||
|
checkString("echo (,),[,],/,:,;,%,{}", execmap[curses.AltA])
|
||||||
|
checkString("echo (,),[,],/,:,@,%,{}", execmap[curses.AltB])
|
||||||
|
checkString("\nfoobar,Y:execute(baz)", execmap[curses.AltZ+'X'])
|
||||||
|
|
||||||
|
for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {
|
||||||
|
keymap, execmap, toggleSort =
|
||||||
|
parseKeymap(keymap, execmap, false, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))
|
||||||
|
checkString("foobar", execmap[curses.AltZ+int([]rune(fmt.Sprintf("%d", idx%10))[0])])
|
||||||
|
}
|
||||||
|
|
||||||
|
keymap, execmap, toggleSort = parseKeymap(keymap, execmap, false, "f1:abort")
|
||||||
|
if toggleSort {
|
||||||
|
t.Errorf("toggleSort set")
|
||||||
|
}
|
||||||
|
check(actAbort, keymap[curses.F1])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestColorSpec(t *testing.T) {
|
||||||
|
theme := curses.Dark256
|
||||||
|
dark := parseTheme(theme, "dark")
|
||||||
|
if *dark != *theme {
|
||||||
|
t.Errorf("colors should be equivalent")
|
||||||
|
}
|
||||||
|
if dark == theme {
|
||||||
|
t.Errorf("point should not be equivalent")
|
||||||
|
}
|
||||||
|
|
||||||
|
light := parseTheme(theme, "dark,light")
|
||||||
|
if *light == *theme {
|
||||||
|
t.Errorf("should not be equivalent")
|
||||||
|
}
|
||||||
|
if *light != *curses.Light256 {
|
||||||
|
t.Errorf("colors should be equivalent")
|
||||||
|
}
|
||||||
|
if light == theme {
|
||||||
|
t.Errorf("point should not be equivalent")
|
||||||
|
}
|
||||||
|
|
||||||
|
customized := parseTheme(theme, "fg:231,bg:232")
|
||||||
|
if customized.Fg != 231 || customized.Bg != 232 {
|
||||||
|
t.Errorf("color not customized")
|
||||||
|
}
|
||||||
|
if *curses.Dark256 == *customized {
|
||||||
|
t.Errorf("colors should not be equivalent")
|
||||||
|
}
|
||||||
|
customized.Fg = curses.Dark256.Fg
|
||||||
|
customized.Bg = curses.Dark256.Bg
|
||||||
|
if *curses.Dark256 == *customized {
|
||||||
|
t.Errorf("colors should now be equivalent")
|
||||||
|
}
|
||||||
|
|
||||||
|
customized = parseTheme(theme, "fg:231,dark,bg:232")
|
||||||
|
if customized.Fg != curses.Dark256.Fg || customized.Bg == curses.Dark256.Bg {
|
||||||
|
t.Errorf("color not customized")
|
||||||
|
}
|
||||||
|
if customized.UseDefault {
|
||||||
|
t.Errorf("not using default colors")
|
||||||
|
}
|
||||||
|
if !curses.Dark256.UseDefault {
|
||||||
|
t.Errorf("using default colors")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@@ -8,8 +8,6 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/algo"
|
"github.com/junegunn/fzf/src/algo"
|
||||||
)
|
)
|
||||||
|
|
||||||
const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
||||||
|
|
||||||
// fuzzy
|
// fuzzy
|
||||||
// 'exact
|
// 'exact
|
||||||
// ^exact-prefix
|
// ^exact-prefix
|
||||||
@@ -26,12 +24,14 @@ const (
|
|||||||
termExact
|
termExact
|
||||||
termPrefix
|
termPrefix
|
||||||
termSuffix
|
termSuffix
|
||||||
|
termEqual
|
||||||
)
|
)
|
||||||
|
|
||||||
type term struct {
|
type term struct {
|
||||||
typ termType
|
typ termType
|
||||||
inv bool
|
inv bool
|
||||||
text []rune
|
text []rune
|
||||||
|
caseSensitive bool
|
||||||
origText []rune
|
origText []rune
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ type Pattern struct {
|
|||||||
hasInvTerm bool
|
hasInvTerm bool
|
||||||
delimiter *regexp.Regexp
|
delimiter *regexp.Regexp
|
||||||
nth []Range
|
nth []Range
|
||||||
procFun map[termType]func(bool, *string, []rune) (int, int)
|
procFun map[termType]func(bool, *[]rune, []rune) (int, int)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -89,36 +89,35 @@ func BuildPattern(mode Mode, caseMode Case,
|
|||||||
caseSensitive, hasInvTerm := true, false
|
caseSensitive, hasInvTerm := true, false
|
||||||
terms := []term{}
|
terms := []term{}
|
||||||
|
|
||||||
switch caseMode {
|
|
||||||
case CaseSmart:
|
|
||||||
if !strings.ContainsAny(asString, uppercaseLetters) {
|
|
||||||
runes, caseSensitive = []rune(strings.ToLower(asString)), false
|
|
||||||
}
|
|
||||||
case CaseIgnore:
|
|
||||||
runes, caseSensitive = []rune(strings.ToLower(asString)), false
|
|
||||||
}
|
|
||||||
|
|
||||||
switch mode {
|
switch mode {
|
||||||
case ModeExtended, ModeExtendedExact:
|
case ModeExtended, ModeExtendedExact:
|
||||||
terms = parseTerms(mode, string(runes))
|
terms = parseTerms(mode, caseMode, asString)
|
||||||
for _, term := range terms {
|
for _, term := range terms {
|
||||||
if term.inv {
|
if term.inv {
|
||||||
hasInvTerm = true
|
hasInvTerm = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
lowerString := strings.ToLower(asString)
|
||||||
|
caseSensitive = caseMode == CaseRespect ||
|
||||||
|
caseMode == CaseSmart && lowerString != asString
|
||||||
|
if !caseSensitive {
|
||||||
|
asString = lowerString
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ptr := &Pattern{
|
ptr := &Pattern{
|
||||||
mode: mode,
|
mode: mode,
|
||||||
caseSensitive: caseSensitive,
|
caseSensitive: caseSensitive,
|
||||||
text: runes,
|
text: []rune(asString),
|
||||||
terms: terms,
|
terms: terms,
|
||||||
hasInvTerm: hasInvTerm,
|
hasInvTerm: hasInvTerm,
|
||||||
nth: nth,
|
nth: nth,
|
||||||
delimiter: delimiter,
|
delimiter: delimiter,
|
||||||
procFun: make(map[termType]func(bool, *string, []rune) (int, int))}
|
procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}
|
||||||
|
|
||||||
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
||||||
|
ptr.procFun[termEqual] = algo.EqualMatch
|
||||||
ptr.procFun[termExact] = algo.ExactMatchNaive
|
ptr.procFun[termExact] = algo.ExactMatchNaive
|
||||||
ptr.procFun[termPrefix] = algo.PrefixMatch
|
ptr.procFun[termPrefix] = algo.PrefixMatch
|
||||||
ptr.procFun[termSuffix] = algo.SuffixMatch
|
ptr.procFun[termSuffix] = algo.SuffixMatch
|
||||||
@@ -127,11 +126,17 @@ func BuildPattern(mode Mode, caseMode Case,
|
|||||||
return ptr
|
return ptr
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTerms(mode Mode, str string) []term {
|
func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||||
tokens := _splitRegex.Split(str, -1)
|
tokens := _splitRegex.Split(str, -1)
|
||||||
terms := []term{}
|
terms := []term{}
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
typ, inv, text := termFuzzy, false, token
|
typ, inv, text := termFuzzy, false, token
|
||||||
|
lowerText := strings.ToLower(text)
|
||||||
|
caseSensitive := caseMode == CaseRespect ||
|
||||||
|
caseMode == CaseSmart && text != lowerText
|
||||||
|
if !caseSensitive {
|
||||||
|
text = lowerText
|
||||||
|
}
|
||||||
origText := []rune(text)
|
origText := []rune(text)
|
||||||
if mode == ModeExtendedExact {
|
if mode == ModeExtendedExact {
|
||||||
typ = termExact
|
typ = termExact
|
||||||
@@ -148,8 +153,13 @@ func parseTerms(mode Mode, str string) []term {
|
|||||||
text = text[1:]
|
text = text[1:]
|
||||||
}
|
}
|
||||||
} else if strings.HasPrefix(text, "^") {
|
} else if strings.HasPrefix(text, "^") {
|
||||||
|
if strings.HasSuffix(text, "$") {
|
||||||
|
typ = termEqual
|
||||||
|
text = text[1 : len(text)-1]
|
||||||
|
} else {
|
||||||
typ = termPrefix
|
typ = termPrefix
|
||||||
text = text[1:]
|
text = text[1:]
|
||||||
|
}
|
||||||
} else if strings.HasSuffix(text, "$") {
|
} else if strings.HasSuffix(text, "$") {
|
||||||
typ = termSuffix
|
typ = termSuffix
|
||||||
text = text[:len(text)-1]
|
text = text[:len(text)-1]
|
||||||
@@ -160,6 +170,7 @@ func parseTerms(mode Mode, str string) []term {
|
|||||||
typ: typ,
|
typ: typ,
|
||||||
inv: inv,
|
inv: inv,
|
||||||
text: []rune(text),
|
text: []rune(text),
|
||||||
|
caseSensitive: caseSensitive,
|
||||||
origText: origText})
|
origText: origText})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,7 +285,7 @@ func dupItem(item *Item, offsets []Offset) *Item {
|
|||||||
|
|
||||||
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
||||||
input := p.prepareInput(item)
|
input := p.prepareInput(item)
|
||||||
return p.iter(algo.FuzzyMatch, input, p.text)
|
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
||||||
@@ -282,7 +293,7 @@ func (p *Pattern) extendedMatch(item *Item) []Offset {
|
|||||||
offsets := []Offset{}
|
offsets := []Offset{}
|
||||||
for _, term := range p.terms {
|
for _, term := range p.terms {
|
||||||
pfun := p.procFun[term.typ]
|
pfun := p.procFun[term.typ]
|
||||||
if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {
|
if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {
|
||||||
if term.inv {
|
if term.inv {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -294,30 +305,29 @@ func (p *Pattern) extendedMatch(item *Item) []Offset {
|
|||||||
return offsets
|
return offsets
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) prepareInput(item *Item) *Transformed {
|
func (p *Pattern) prepareInput(item *Item) *[]Token {
|
||||||
if item.transformed != nil {
|
if item.transformed != nil {
|
||||||
return item.transformed
|
return item.transformed
|
||||||
}
|
}
|
||||||
|
|
||||||
var ret *Transformed
|
var ret *[]Token
|
||||||
if len(p.nth) > 0 {
|
if len(p.nth) > 0 {
|
||||||
tokens := Tokenize(item.text, p.delimiter)
|
tokens := Tokenize(item.text, p.delimiter)
|
||||||
ret = Transform(tokens, p.nth)
|
ret = Transform(tokens, p.nth)
|
||||||
} else {
|
} else {
|
||||||
trans := Transformed{
|
runes := []rune(*item.text)
|
||||||
whole: item.text,
|
trans := []Token{Token{text: &runes, prefixLength: 0}}
|
||||||
parts: []Token{Token{text: item.text, prefixLength: 0}}}
|
|
||||||
ret = &trans
|
ret = &trans
|
||||||
}
|
}
|
||||||
item.transformed = ret
|
item.transformed = ret
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) iter(pfun func(bool, *string, []rune) (int, int),
|
func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),
|
||||||
inputs *Transformed, pattern []rune) (int, int) {
|
tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {
|
||||||
for _, part := range inputs.parts {
|
for _, part := range *tokens {
|
||||||
prefixLength := part.prefixLength
|
prefixLength := part.prefixLength
|
||||||
if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {
|
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
|
||||||
return sidx + prefixLength, eidx + prefixLength
|
return sidx + prefixLength, eidx + prefixLength
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,9 +7,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestParseTermsExtended(t *testing.T) {
|
func TestParseTermsExtended(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtended,
|
terms := parseTerms(ModeExtended, CaseSmart,
|
||||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ ^iii$")
|
||||||
if len(terms) != 8 ||
|
if len(terms) != 9 ||
|
||||||
terms[0].typ != termFuzzy || terms[0].inv ||
|
terms[0].typ != termFuzzy || terms[0].inv ||
|
||||||
terms[1].typ != termExact || terms[1].inv ||
|
terms[1].typ != termExact || terms[1].inv ||
|
||||||
terms[2].typ != termPrefix || terms[2].inv ||
|
terms[2].typ != termPrefix || terms[2].inv ||
|
||||||
@@ -17,7 +17,8 @@ func TestParseTermsExtended(t *testing.T) {
|
|||||||
terms[4].typ != termFuzzy || !terms[4].inv ||
|
terms[4].typ != termFuzzy || !terms[4].inv ||
|
||||||
terms[5].typ != termExact || !terms[5].inv ||
|
terms[5].typ != termExact || !terms[5].inv ||
|
||||||
terms[6].typ != termPrefix || !terms[6].inv ||
|
terms[6].typ != termPrefix || !terms[6].inv ||
|
||||||
terms[7].typ != termSuffix || !terms[7].inv {
|
terms[7].typ != termSuffix || !terms[7].inv ||
|
||||||
|
terms[8].typ != termEqual || terms[8].inv {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
for idx, term := range terms {
|
for idx, term := range terms {
|
||||||
@@ -31,7 +32,7 @@ func TestParseTermsExtended(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTermsExtendedExact(t *testing.T) {
|
func TestParseTermsExtendedExact(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtendedExact,
|
terms := parseTerms(ModeExtendedExact, CaseSmart,
|
||||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
||||||
if len(terms) != 8 ||
|
if len(terms) != 8 ||
|
||||||
terms[0].typ != termExact || terms[0].inv || len(terms[0].text) != 3 ||
|
terms[0].typ != termExact || terms[0].inv || len(terms[0].text) != 3 ||
|
||||||
@@ -47,7 +48,7 @@ func TestParseTermsExtendedExact(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTermsEmpty(t *testing.T) {
|
func TestParseTermsEmpty(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtended, "' $ ^ !' !^ !$")
|
terms := parseTerms(ModeExtended, CaseSmart, "' $ ^ !' !^ !$")
|
||||||
if len(terms) != 0 {
|
if len(terms) != 0 {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
@@ -58,13 +59,29 @@ func TestExact(t *testing.T) {
|
|||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pattern := BuildPattern(ModeExtended, CaseSmart,
|
pattern := BuildPattern(ModeExtended, CaseSmart,
|
||||||
[]Range{}, nil, []rune("'abc"))
|
[]Range{}, nil, []rune("'abc"))
|
||||||
str := "aabbcc abc"
|
runes := []rune("aabbcc abc")
|
||||||
sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &str, pattern.terms[0].text)
|
sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)
|
||||||
if sidx != 7 || eidx != 10 {
|
if sidx != 7 || eidx != 10 {
|
||||||
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEqual(t *testing.T) {
|
||||||
|
defer clearPatternCache()
|
||||||
|
clearPatternCache()
|
||||||
|
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("^AbC$"))
|
||||||
|
|
||||||
|
match := func(str string, sidxExpected int, eidxExpected int) {
|
||||||
|
runes := []rune(str)
|
||||||
|
sidx, eidx := algo.EqualMatch(pattern.caseSensitive, &runes, pattern.terms[0].text)
|
||||||
|
if sidx != sidxExpected || eidx != eidxExpected {
|
||||||
|
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match("ABC", -1, -1)
|
||||||
|
match("AbC", 0, 3)
|
||||||
|
}
|
||||||
|
|
||||||
func TestCaseSensitivity(t *testing.T) {
|
func TestCaseSensitivity(t *testing.T) {
|
||||||
defer clearPatternCache()
|
defer clearPatternCache()
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
|
@@ -9,12 +9,11 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`
|
|
||||||
|
|
||||||
// Reader reads from command or standard input
|
// Reader reads from command or standard input
|
||||||
type Reader struct {
|
type Reader struct {
|
||||||
pusher func(string)
|
pusher func(string)
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
|
delimNil bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadSource reads data from the default command or from standard input
|
// ReadSource reads data from the default command or from standard input
|
||||||
@@ -32,11 +31,24 @@ func (r *Reader) ReadSource() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) feed(src io.Reader) {
|
func (r *Reader) feed(src io.Reader) {
|
||||||
if scanner := bufio.NewScanner(src); scanner != nil {
|
delim := byte('\n')
|
||||||
for scanner.Scan() {
|
if r.delimNil {
|
||||||
r.pusher(scanner.Text())
|
delim = '\000'
|
||||||
|
}
|
||||||
|
reader := bufio.NewReader(src)
|
||||||
|
for {
|
||||||
|
line, err := reader.ReadString(delim)
|
||||||
|
if line != "" {
|
||||||
|
// "ReadString returns err != nil if and only if the returned data does not end in delim."
|
||||||
|
if err == nil {
|
||||||
|
line = line[:len(line)-1]
|
||||||
|
}
|
||||||
|
r.pusher(line)
|
||||||
r.eventBox.Set(EvtReadNew, nil)
|
r.eventBox.Set(EvtReadNew, nil)
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
410
src/terminal.go
410
src/terminal.go
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -20,23 +21,30 @@ import (
|
|||||||
|
|
||||||
// Terminal represents terminal input/output
|
// Terminal represents terminal input/output
|
||||||
type Terminal struct {
|
type Terminal struct {
|
||||||
|
inlineInfo bool
|
||||||
prompt string
|
prompt string
|
||||||
reverse bool
|
reverse bool
|
||||||
|
hscroll 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
|
sort bool
|
||||||
expect []int
|
toggleSort bool
|
||||||
pressed int
|
expect map[int]string
|
||||||
|
keymap map[int]actionType
|
||||||
|
execmap map[int]string
|
||||||
|
pressed string
|
||||||
printQuery bool
|
printQuery bool
|
||||||
|
history *History
|
||||||
|
cycle bool
|
||||||
count int
|
count int
|
||||||
progress int
|
progress int
|
||||||
reading bool
|
reading bool
|
||||||
merger *Merger
|
merger *Merger
|
||||||
selected map[*string]selectedItem
|
selected map[uint32]selectedItem
|
||||||
reqBox *util.EventBox
|
reqBox *util.EventBox
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
@@ -77,36 +85,128 @@ const (
|
|||||||
reqQuit
|
reqQuit
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type actionType int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
initialDelay = 100 * time.Millisecond
|
actIgnore actionType = iota
|
||||||
spinnerDuration = 200 * time.Millisecond
|
actInvalid
|
||||||
|
actRune
|
||||||
|
actMouse
|
||||||
|
actBeginningOfLine
|
||||||
|
actAbort
|
||||||
|
actAccept
|
||||||
|
actBackwardChar
|
||||||
|
actBackwardDeleteChar
|
||||||
|
actBackwardWord
|
||||||
|
actClearScreen
|
||||||
|
actDeleteChar
|
||||||
|
actEndOfLine
|
||||||
|
actForwardChar
|
||||||
|
actForwardWord
|
||||||
|
actKillLine
|
||||||
|
actKillWord
|
||||||
|
actUnixLineDiscard
|
||||||
|
actUnixWordRubout
|
||||||
|
actYank
|
||||||
|
actBackwardKillWord
|
||||||
|
actSelectAll
|
||||||
|
actDeselectAll
|
||||||
|
actToggle
|
||||||
|
actToggleAll
|
||||||
|
actToggleDown
|
||||||
|
actToggleUp
|
||||||
|
actDown
|
||||||
|
actUp
|
||||||
|
actPageUp
|
||||||
|
actPageDown
|
||||||
|
actToggleSort
|
||||||
|
actPreviousHistory
|
||||||
|
actNextHistory
|
||||||
|
actExecute
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func defaultKeymap() map[int]actionType {
|
||||||
|
keymap := make(map[int]actionType)
|
||||||
|
keymap[C.Invalid] = actInvalid
|
||||||
|
keymap[C.CtrlA] = actBeginningOfLine
|
||||||
|
keymap[C.CtrlB] = actBackwardChar
|
||||||
|
keymap[C.CtrlC] = actAbort
|
||||||
|
keymap[C.CtrlG] = actAbort
|
||||||
|
keymap[C.CtrlQ] = actAbort
|
||||||
|
keymap[C.ESC] = actAbort
|
||||||
|
keymap[C.CtrlD] = actDeleteChar
|
||||||
|
keymap[C.CtrlE] = actEndOfLine
|
||||||
|
keymap[C.CtrlF] = actForwardChar
|
||||||
|
keymap[C.CtrlH] = actBackwardDeleteChar
|
||||||
|
keymap[C.BSpace] = actBackwardDeleteChar
|
||||||
|
keymap[C.Tab] = actToggleDown
|
||||||
|
keymap[C.BTab] = actToggleUp
|
||||||
|
keymap[C.CtrlJ] = actDown
|
||||||
|
keymap[C.CtrlK] = actUp
|
||||||
|
keymap[C.CtrlL] = actClearScreen
|
||||||
|
keymap[C.CtrlM] = actAccept
|
||||||
|
keymap[C.CtrlN] = actDown
|
||||||
|
keymap[C.CtrlP] = actUp
|
||||||
|
keymap[C.CtrlU] = actUnixLineDiscard
|
||||||
|
keymap[C.CtrlW] = actUnixWordRubout
|
||||||
|
keymap[C.CtrlY] = actYank
|
||||||
|
|
||||||
|
keymap[C.AltB] = actBackwardWord
|
||||||
|
keymap[C.SLeft] = actBackwardWord
|
||||||
|
keymap[C.AltF] = actForwardWord
|
||||||
|
keymap[C.SRight] = actForwardWord
|
||||||
|
keymap[C.AltD] = actKillWord
|
||||||
|
keymap[C.AltBS] = actBackwardKillWord
|
||||||
|
|
||||||
|
keymap[C.Up] = actUp
|
||||||
|
keymap[C.Down] = actDown
|
||||||
|
keymap[C.Left] = actBackwardChar
|
||||||
|
keymap[C.Right] = actForwardChar
|
||||||
|
|
||||||
|
keymap[C.Home] = actBeginningOfLine
|
||||||
|
keymap[C.End] = actEndOfLine
|
||||||
|
keymap[C.Del] = actDeleteChar // FIXME Del vs. CTRL-D
|
||||||
|
keymap[C.PgUp] = actPageUp
|
||||||
|
keymap[C.PgDn] = actPageDown
|
||||||
|
|
||||||
|
keymap[C.Rune] = actRune
|
||||||
|
keymap[C.Mouse] = actMouse
|
||||||
|
return keymap
|
||||||
|
}
|
||||||
|
|
||||||
// NewTerminal returns new Terminal object
|
// NewTerminal returns new Terminal object
|
||||||
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||||
input := []rune(opts.Query)
|
input := []rune(opts.Query)
|
||||||
return &Terminal{
|
return &Terminal{
|
||||||
|
inlineInfo: opts.InlineInfo,
|
||||||
prompt: opts.Prompt,
|
prompt: opts.Prompt,
|
||||||
reverse: opts.Reverse,
|
reverse: opts.Reverse,
|
||||||
|
hscroll: opts.Hscroll,
|
||||||
cx: len(input),
|
cx: len(input),
|
||||||
cy: 0,
|
cy: 0,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
yanked: []rune{},
|
yanked: []rune{},
|
||||||
input: input,
|
input: input,
|
||||||
multi: opts.Multi,
|
multi: opts.Multi,
|
||||||
|
sort: opts.Sort > 0,
|
||||||
toggleSort: opts.ToggleSort,
|
toggleSort: opts.ToggleSort,
|
||||||
expect: opts.Expect,
|
expect: opts.Expect,
|
||||||
pressed: 0,
|
keymap: opts.Keymap,
|
||||||
|
execmap: opts.Execmap,
|
||||||
|
pressed: "",
|
||||||
printQuery: opts.PrintQuery,
|
printQuery: opts.PrintQuery,
|
||||||
|
history: opts.History,
|
||||||
|
cycle: opts.Cycle,
|
||||||
|
reading: true,
|
||||||
merger: EmptyMerger,
|
merger: EmptyMerger,
|
||||||
selected: make(map[*string]selectedItem),
|
selected: make(map[uint32]selectedItem),
|
||||||
reqBox: util.NewEventBox(),
|
reqBox: util.NewEventBox(),
|
||||||
eventBox: eventBox,
|
eventBox: eventBox,
|
||||||
mutex: sync.Mutex{},
|
mutex: sync.Mutex{},
|
||||||
suppress: true,
|
suppress: true,
|
||||||
startChan: make(chan bool, 1),
|
startChan: make(chan bool, 1),
|
||||||
initFunc: func() {
|
initFunc: func() {
|
||||||
C.Init(opts.Color, opts.Color256, opts.Black, opts.Mouse)
|
C.Init(opts.Theme, opts.Black, opts.Mouse)
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,17 +257,7 @@ func (t *Terminal) output() {
|
|||||||
fmt.Println(string(t.input))
|
fmt.Println(string(t.input))
|
||||||
}
|
}
|
||||||
if len(t.expect) > 0 {
|
if len(t.expect) > 0 {
|
||||||
if t.pressed == 0 {
|
fmt.Println(t.pressed)
|
||||||
fmt.Println()
|
|
||||||
} else if util.Between(t.pressed, C.AltA, C.AltZ) {
|
|
||||||
fmt.Printf("alt-%c\n", t.pressed+'a'-C.AltA)
|
|
||||||
} else if util.Between(t.pressed, C.F1, C.F4) {
|
|
||||||
fmt.Printf("f%c\n", t.pressed+'1'-C.F1)
|
|
||||||
} else if util.Between(t.pressed, C.CtrlA, C.CtrlZ) {
|
|
||||||
fmt.Printf("ctrl-%c\n", t.pressed+'a'-C.CtrlA)
|
|
||||||
} else {
|
|
||||||
fmt.Printf("%c\n", t.pressed-C.AltZ)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(t.selected) == 0 {
|
if len(t.selected) == 0 {
|
||||||
cnt := t.merger.Length()
|
cnt := t.merger.Length()
|
||||||
@@ -230,15 +320,31 @@ func (t *Terminal) printPrompt() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printInfo() {
|
func (t *Terminal) printInfo() {
|
||||||
|
if t.inlineInfo {
|
||||||
|
t.move(0, len(t.prompt)+displayWidth(t.input)+1, true)
|
||||||
|
if t.reading {
|
||||||
|
C.CPrint(C.ColSpinner, true, " < ")
|
||||||
|
} else {
|
||||||
|
C.CPrint(C.ColPrompt, true, " < ")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
t.move(1, 0, true)
|
t.move(1, 0, true)
|
||||||
if t.reading {
|
if t.reading {
|
||||||
duration := int64(spinnerDuration)
|
duration := int64(spinnerDuration)
|
||||||
idx := (time.Now().UnixNano() % (duration * int64(len(_spinner)))) / duration
|
idx := (time.Now().UnixNano() % (duration * int64(len(_spinner)))) / duration
|
||||||
C.CPrint(C.ColSpinner, true, _spinner[idx])
|
C.CPrint(C.ColSpinner, true, _spinner[idx])
|
||||||
}
|
}
|
||||||
|
|
||||||
t.move(1, 2, false)
|
t.move(1, 2, false)
|
||||||
|
}
|
||||||
|
|
||||||
output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)
|
output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)
|
||||||
|
if t.toggleSort {
|
||||||
|
if t.sort {
|
||||||
|
output += "/S"
|
||||||
|
} else {
|
||||||
|
output += " "
|
||||||
|
}
|
||||||
|
}
|
||||||
if t.multi && len(t.selected) > 0 {
|
if t.multi && len(t.selected) > 0 {
|
||||||
output += fmt.Sprintf(" (%d)", len(t.selected))
|
output += fmt.Sprintf(" (%d)", len(t.selected))
|
||||||
}
|
}
|
||||||
@@ -251,10 +357,16 @@ func (t *Terminal) printInfo() {
|
|||||||
func (t *Terminal) printList() {
|
func (t *Terminal) printList() {
|
||||||
t.constrain()
|
t.constrain()
|
||||||
|
|
||||||
maxy := maxItems()
|
maxy := t.maxItems()
|
||||||
count := t.merger.Length() - t.offset
|
count := t.merger.Length() - t.offset
|
||||||
for i := 0; i < maxy; i++ {
|
for i := 0; i < maxy; i++ {
|
||||||
t.move(i+2, 0, true)
|
var line int
|
||||||
|
if t.inlineInfo {
|
||||||
|
line = i + 1
|
||||||
|
} else {
|
||||||
|
line = i + 2
|
||||||
|
}
|
||||||
|
t.move(line, 0, true)
|
||||||
if i < count {
|
if i < count {
|
||||||
t.printItem(t.merger.Get(i+t.offset), i == t.cy-t.offset)
|
t.printItem(t.merger.Get(i+t.offset), i == t.cy-t.offset)
|
||||||
}
|
}
|
||||||
@@ -262,11 +374,11 @@ func (t *Terminal) printList() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printItem(item *Item, current bool) {
|
func (t *Terminal) printItem(item *Item, current bool) {
|
||||||
_, selected := t.selected[item.text]
|
_, selected := t.selected[item.index]
|
||||||
if current {
|
if current {
|
||||||
C.CPrint(C.ColCursor, true, ">")
|
C.CPrint(C.ColCursor, true, ">")
|
||||||
if selected {
|
if selected {
|
||||||
C.CPrint(C.ColCurrent, true, ">")
|
C.CPrint(C.ColSelected, true, ">")
|
||||||
} else {
|
} else {
|
||||||
C.CPrint(C.ColCurrent, true, " ")
|
C.CPrint(C.ColCurrent, true, " ")
|
||||||
}
|
}
|
||||||
@@ -318,7 +430,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, current bool) {
|
func (t *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 {
|
||||||
@@ -332,6 +444,7 @@ func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, cur
|
|||||||
maxWidth := C.MaxX() - 3
|
maxWidth := C.MaxX() - 3
|
||||||
fullWidth := displayWidth(text)
|
fullWidth := displayWidth(text)
|
||||||
if fullWidth > maxWidth {
|
if fullWidth > maxWidth {
|
||||||
|
if t.hscroll {
|
||||||
// Stri..
|
// Stri..
|
||||||
matchEndWidth := displayWidth(text[:maxe])
|
matchEndWidth := displayWidth(text[:maxe])
|
||||||
if matchEndWidth <= maxWidth-2 {
|
if matchEndWidth <= maxWidth-2 {
|
||||||
@@ -357,6 +470,15 @@ func (*Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, cur
|
|||||||
}
|
}
|
||||||
text = append([]rune(".."), text...)
|
text = append([]rune(".."), text...)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
text, _ = trimRight(text, maxWidth-2)
|
||||||
|
text = append(text, []rune("..")...)
|
||||||
|
|
||||||
|
for idx, offset := range offsets {
|
||||||
|
offsets[idx].offset[0] = util.Min32(offset.offset[0], int32(maxWidth-2))
|
||||||
|
offsets[idx].offset[1] = util.Min32(offset.offset[1], int32(maxWidth))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var index int32
|
var index int32
|
||||||
@@ -403,8 +525,8 @@ func processTabs(runes []rune, prefixWidth int) (string, int) {
|
|||||||
|
|
||||||
func (t *Terminal) printAll() {
|
func (t *Terminal) printAll() {
|
||||||
t.printList()
|
t.printList()
|
||||||
t.printInfo()
|
|
||||||
t.printPrompt()
|
t.printPrompt()
|
||||||
|
t.printInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) refresh() {
|
func (t *Terminal) refresh() {
|
||||||
@@ -463,6 +585,17 @@ func keyMatch(key int, event C.Event) bool {
|
|||||||
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func executeCommand(template string, current string) {
|
||||||
|
command := strings.Replace(template, "{}", fmt.Sprintf("%q", current), -1)
|
||||||
|
cmd := exec.Command("sh", "-c", command)
|
||||||
|
cmd.Stdin = os.Stdin
|
||||||
|
cmd.Stdout = os.Stdout
|
||||||
|
cmd.Stderr = os.Stderr
|
||||||
|
C.Endwin()
|
||||||
|
cmd.Run()
|
||||||
|
C.Refresh()
|
||||||
|
}
|
||||||
|
|
||||||
// Loop is called to start Terminal I/O
|
// Loop is called to start Terminal I/O
|
||||||
func (t *Terminal) Loop() {
|
func (t *Terminal) Loop() {
|
||||||
<-t.startChan
|
<-t.startChan
|
||||||
@@ -488,6 +621,27 @@ func (t *Terminal) Loop() {
|
|||||||
t.reqBox.Set(reqRedraw, nil)
|
t.reqBox.Set(reqRedraw, nil)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// Keep the spinner spinning
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
t.mutex.Lock()
|
||||||
|
reading := t.reading
|
||||||
|
t.mutex.Unlock()
|
||||||
|
if !reading {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(spinnerDuration)
|
||||||
|
t.reqBox.Set(reqInfo, nil)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
exit := func(code int) {
|
||||||
|
if code == 0 && t.history != nil {
|
||||||
|
t.history.append(string(t.input))
|
||||||
|
}
|
||||||
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -499,6 +653,9 @@ func (t *Terminal) Loop() {
|
|||||||
switch req {
|
switch req {
|
||||||
case reqPrompt:
|
case reqPrompt:
|
||||||
t.printPrompt()
|
t.printPrompt()
|
||||||
|
if t.inlineInfo {
|
||||||
|
t.printInfo()
|
||||||
|
}
|
||||||
case reqInfo:
|
case reqInfo:
|
||||||
t.printInfo()
|
t.printInfo()
|
||||||
case reqList:
|
case reqList:
|
||||||
@@ -513,10 +670,10 @@ func (t *Terminal) Loop() {
|
|||||||
case reqClose:
|
case reqClose:
|
||||||
C.Close()
|
C.Close()
|
||||||
t.output()
|
t.output()
|
||||||
os.Exit(0)
|
exit(0)
|
||||||
case reqQuit:
|
case reqQuit:
|
||||||
C.Close()
|
C.Close()
|
||||||
os.Exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.placeCursor()
|
t.placeCursor()
|
||||||
@@ -541,133 +698,195 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
selectItem := func(item *Item) bool {
|
||||||
|
if _, found := t.selected[item.index]; !found {
|
||||||
|
t.selected[item.index] = selectedItem{time.Now(), item.StringPtr()}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
toggleY := func(y int) {
|
||||||
|
item := t.merger.Get(y)
|
||||||
|
if !selectItem(item) {
|
||||||
|
delete(t.selected, item.index)
|
||||||
|
}
|
||||||
|
}
|
||||||
toggle := func() {
|
toggle := func() {
|
||||||
if t.cy < t.merger.Length() {
|
if t.cy < t.merger.Length() {
|
||||||
item := t.merger.Get(t.cy)
|
toggleY(t.cy)
|
||||||
if _, found := t.selected[item.text]; !found {
|
|
||||||
var strptr *string
|
|
||||||
if item.origText != nil {
|
|
||||||
strptr = item.origText
|
|
||||||
} else {
|
|
||||||
strptr = item.text
|
|
||||||
}
|
|
||||||
t.selected[item.text] = selectedItem{time.Now(), strptr}
|
|
||||||
} else {
|
|
||||||
delete(t.selected, item.text)
|
|
||||||
}
|
|
||||||
req(reqInfo)
|
req(reqInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, key := range t.expect {
|
for key, ret := range t.expect {
|
||||||
if keyMatch(key, event) {
|
if keyMatch(key, event) {
|
||||||
t.pressed = key
|
t.pressed = ret
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if t.toggleSort > 0 {
|
|
||||||
if keyMatch(t.toggleSort, event) {
|
action := t.keymap[event.Type]
|
||||||
t.eventBox.Set(EvtSearchNew, true)
|
mapkey := event.Type
|
||||||
t.mutex.Unlock()
|
if event.Type == C.Rune {
|
||||||
continue
|
mapkey = int(event.Char) + int(C.AltZ)
|
||||||
|
if act, prs := t.keymap[mapkey]; prs {
|
||||||
|
action = act
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
switch event.Type {
|
switch action {
|
||||||
case C.Invalid:
|
case actIgnore:
|
||||||
|
case actExecute:
|
||||||
|
if t.cy >= 0 && t.cy < t.merger.Length() {
|
||||||
|
item := t.merger.Get(t.cy)
|
||||||
|
executeCommand(t.execmap[mapkey], item.AsString())
|
||||||
|
}
|
||||||
|
case actInvalid:
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
continue
|
continue
|
||||||
case C.CtrlA:
|
case actToggleSort:
|
||||||
|
t.sort = !t.sort
|
||||||
|
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||||
|
t.mutex.Unlock()
|
||||||
|
continue
|
||||||
|
case actBeginningOfLine:
|
||||||
t.cx = 0
|
t.cx = 0
|
||||||
case C.CtrlB:
|
case actBackwardChar:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.cx--
|
t.cx--
|
||||||
}
|
}
|
||||||
case C.CtrlC, C.CtrlG, C.CtrlQ, C.ESC:
|
case actAbort:
|
||||||
req(reqQuit)
|
req(reqQuit)
|
||||||
case C.CtrlD:
|
case actDeleteChar:
|
||||||
if !t.delChar() && t.cx == 0 {
|
if !t.delChar() && t.cx == 0 {
|
||||||
req(reqQuit)
|
req(reqQuit)
|
||||||
}
|
}
|
||||||
case C.CtrlE:
|
case actEndOfLine:
|
||||||
t.cx = len(t.input)
|
t.cx = len(t.input)
|
||||||
case C.CtrlF:
|
case actForwardChar:
|
||||||
if t.cx < len(t.input) {
|
if t.cx < len(t.input) {
|
||||||
t.cx++
|
t.cx++
|
||||||
}
|
}
|
||||||
case C.CtrlH:
|
case actBackwardDeleteChar:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
||||||
t.cx--
|
t.cx--
|
||||||
}
|
}
|
||||||
case C.Tab:
|
case actSelectAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
item := t.merger.Get(i)
|
||||||
|
selectItem(item)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
|
case actDeselectAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
item := t.merger.Get(i)
|
||||||
|
delete(t.selected, item.index)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
|
case actToggle:
|
||||||
|
if t.multi && t.merger.Length() > 0 {
|
||||||
|
toggle()
|
||||||
|
req(reqList)
|
||||||
|
}
|
||||||
|
case actToggleAll:
|
||||||
|
if t.multi {
|
||||||
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
|
toggleY(i)
|
||||||
|
}
|
||||||
|
req(reqList, reqInfo)
|
||||||
|
}
|
||||||
|
case actToggleDown:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
t.vmove(-1)
|
t.vmove(-1)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
case C.BTab:
|
case actToggleUp:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
t.vmove(1)
|
t.vmove(1)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
case C.CtrlJ, C.CtrlN:
|
case actDown:
|
||||||
t.vmove(-1)
|
t.vmove(-1)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case C.CtrlK, C.CtrlP:
|
case actUp:
|
||||||
t.vmove(1)
|
t.vmove(1)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case C.CtrlM:
|
case actAccept:
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
case C.CtrlL:
|
case actClearScreen:
|
||||||
req(reqRedraw)
|
req(reqRedraw)
|
||||||
case C.CtrlU:
|
case actUnixLineDiscard:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.yanked = copySlice(t.input[:t.cx])
|
t.yanked = copySlice(t.input[:t.cx])
|
||||||
t.input = t.input[t.cx:]
|
t.input = t.input[t.cx:]
|
||||||
t.cx = 0
|
t.cx = 0
|
||||||
}
|
}
|
||||||
case C.CtrlW:
|
case actUnixWordRubout:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.rubout("\\s\\S")
|
t.rubout("\\s\\S")
|
||||||
}
|
}
|
||||||
case C.AltBS:
|
case actBackwardKillWord:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.rubout("[^[:alnum:]][[:alnum:]]")
|
t.rubout("[^[:alnum:]][[:alnum:]]")
|
||||||
}
|
}
|
||||||
case C.CtrlY:
|
case actYank:
|
||||||
suffix := copySlice(t.input[t.cx:])
|
suffix := copySlice(t.input[t.cx:])
|
||||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||||
t.cx += len(t.yanked)
|
t.cx += len(t.yanked)
|
||||||
case C.Del:
|
case actPageUp:
|
||||||
t.delChar()
|
t.vmove(t.maxItems() - 1)
|
||||||
case C.PgUp:
|
|
||||||
t.vmove(maxItems() - 1)
|
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case C.PgDn:
|
case actPageDown:
|
||||||
t.vmove(-(maxItems() - 1))
|
t.vmove(-(t.maxItems() - 1))
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case C.AltB:
|
case actBackwardWord:
|
||||||
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
||||||
case C.AltF:
|
case actForwardWord:
|
||||||
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||||
case C.AltD:
|
case actKillWord:
|
||||||
ncx := t.cx +
|
ncx := t.cx +
|
||||||
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||||
if ncx > t.cx {
|
if ncx > t.cx {
|
||||||
t.yanked = copySlice(t.input[t.cx:ncx])
|
t.yanked = copySlice(t.input[t.cx:ncx])
|
||||||
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
||||||
}
|
}
|
||||||
case C.Rune:
|
case actKillLine:
|
||||||
|
if t.cx < len(t.input) {
|
||||||
|
t.yanked = copySlice(t.input[t.cx:])
|
||||||
|
t.input = t.input[:t.cx]
|
||||||
|
}
|
||||||
|
case actRune:
|
||||||
prefix := copySlice(t.input[:t.cx])
|
prefix := copySlice(t.input[:t.cx])
|
||||||
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
||||||
t.cx++
|
t.cx++
|
||||||
case C.Mouse:
|
case actPreviousHistory:
|
||||||
|
if t.history != nil {
|
||||||
|
t.history.override(string(t.input))
|
||||||
|
t.input = []rune(t.history.previous())
|
||||||
|
t.cx = len(t.input)
|
||||||
|
}
|
||||||
|
case actNextHistory:
|
||||||
|
if t.history != nil {
|
||||||
|
t.history.override(string(t.input))
|
||||||
|
t.input = []rune(t.history.next())
|
||||||
|
t.cx = len(t.input)
|
||||||
|
}
|
||||||
|
case actMouse:
|
||||||
me := event.MouseEvent
|
me := event.MouseEvent
|
||||||
mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y
|
mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y
|
||||||
if !t.reverse {
|
if !t.reverse {
|
||||||
my = C.MaxY() - my - 1
|
my = C.MaxY() - my - 1
|
||||||
}
|
}
|
||||||
|
min := 2
|
||||||
|
if t.inlineInfo {
|
||||||
|
min = 1
|
||||||
|
}
|
||||||
if me.S != 0 {
|
if me.S != 0 {
|
||||||
// Scroll
|
// Scroll
|
||||||
if t.merger.Length() > 0 {
|
if t.merger.Length() > 0 {
|
||||||
@@ -679,8 +898,8 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
} else if me.Double {
|
} else if me.Double {
|
||||||
// Double-click
|
// Double-click
|
||||||
if my >= 2 {
|
if my >= min {
|
||||||
if t.vset(my-2) && t.cy < t.merger.Length() {
|
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -688,9 +907,9 @@ func (t *Terminal) Loop() {
|
|||||||
if my == 0 && mx >= 0 {
|
if my == 0 && mx >= 0 {
|
||||||
// Prompt
|
// Prompt
|
||||||
t.cx = mx
|
t.cx = mx
|
||||||
} else if my >= 2 {
|
} else if my >= min {
|
||||||
// List
|
// List
|
||||||
if t.vset(t.offset+my-2) && t.multi && me.Mod {
|
if t.vset(t.offset+my-min) && t.multi && me.Mod {
|
||||||
toggle()
|
toggle()
|
||||||
}
|
}
|
||||||
req(reqList)
|
req(reqList)
|
||||||
@@ -701,7 +920,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, false)
|
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||||
}
|
}
|
||||||
for _, event := range events {
|
for _, event := range events {
|
||||||
t.reqBox.Set(event, nil)
|
t.reqBox.Set(event, nil)
|
||||||
@@ -711,7 +930,7 @@ func (t *Terminal) Loop() {
|
|||||||
|
|
||||||
func (t *Terminal) constrain() {
|
func (t *Terminal) constrain() {
|
||||||
count := t.merger.Length()
|
count := t.merger.Length()
|
||||||
height := C.MaxY() - 2
|
height := t.maxItems()
|
||||||
diffpos := t.cy - t.offset
|
diffpos := t.cy - t.offset
|
||||||
|
|
||||||
t.cy = util.Constrain(t.cy, 0, count-1)
|
t.cy = util.Constrain(t.cy, 0, count-1)
|
||||||
@@ -733,10 +952,22 @@ func (t *Terminal) constrain() {
|
|||||||
|
|
||||||
func (t *Terminal) vmove(o int) {
|
func (t *Terminal) vmove(o int) {
|
||||||
if t.reverse {
|
if t.reverse {
|
||||||
t.vset(t.cy - o)
|
o *= -1
|
||||||
} else {
|
|
||||||
t.vset(t.cy + o)
|
|
||||||
}
|
}
|
||||||
|
dest := t.cy + o
|
||||||
|
if t.cycle {
|
||||||
|
max := t.merger.Length() - 1
|
||||||
|
if dest > max {
|
||||||
|
if t.cy == max {
|
||||||
|
dest = 0
|
||||||
|
}
|
||||||
|
} else if dest < 0 {
|
||||||
|
if t.cy == 0 {
|
||||||
|
dest = max
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.vset(dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) vset(o int) bool {
|
func (t *Terminal) vset(o int) bool {
|
||||||
@@ -744,6 +975,9 @@ func (t *Terminal) vset(o int) bool {
|
|||||||
return t.cy == o
|
return t.cy == o
|
||||||
}
|
}
|
||||||
|
|
||||||
func maxItems() int {
|
func (t *Terminal) maxItems() int {
|
||||||
|
if t.inlineInfo {
|
||||||
|
return C.MaxY() - 1
|
||||||
|
}
|
||||||
return C.MaxY() - 2
|
return C.MaxY() - 2
|
||||||
}
|
}
|
||||||
|
@@ -16,15 +16,9 @@ type Range struct {
|
|||||||
end int
|
end int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transformed holds the result of tokenization and transformation
|
|
||||||
type Transformed struct {
|
|
||||||
whole *string
|
|
||||||
parts []Token
|
|
||||||
}
|
|
||||||
|
|
||||||
// Token contains the tokenized part of the strings and its prefix length
|
// Token contains the tokenized part of the strings and its prefix length
|
||||||
type Token struct {
|
type Token struct {
|
||||||
text *string
|
text *[]rune
|
||||||
prefixLength int
|
prefixLength int
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,8 +75,8 @@ func withPrefixLengths(tokens []string, begin int) []Token {
|
|||||||
for idx, token := range tokens {
|
for idx, token := range tokens {
|
||||||
// Need to define a new local variable instead of the reused token to take
|
// Need to define a new local variable instead of the reused token to take
|
||||||
// the pointer to it
|
// the pointer to it
|
||||||
str := token
|
runes := []rune(token)
|
||||||
ret[idx] = Token{text: &str, prefixLength: prefixLength}
|
ret[idx] = Token{text: &runes, prefixLength: prefixLength}
|
||||||
prefixLength += len([]rune(token))
|
prefixLength += len([]rune(token))
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
@@ -142,33 +136,40 @@ func Tokenize(str *string, delimiter *regexp.Regexp) []Token {
|
|||||||
return withPrefixLengths(tokens, 0)
|
return withPrefixLengths(tokens, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinTokens(tokens []Token) string {
|
func joinTokens(tokens *[]Token) *string {
|
||||||
ret := ""
|
ret := ""
|
||||||
for _, token := range tokens {
|
for _, token := range *tokens {
|
||||||
ret += *token.text
|
ret += string(*token.text)
|
||||||
}
|
}
|
||||||
return ret
|
return &ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinTokensAsRunes(tokens *[]Token) *[]rune {
|
||||||
|
ret := []rune{}
|
||||||
|
for _, token := range *tokens {
|
||||||
|
ret = append(ret, *token.text...)
|
||||||
|
}
|
||||||
|
return &ret
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform is used to transform the input when --with-nth option is given
|
// Transform is used to transform the input when --with-nth option is given
|
||||||
func Transform(tokens []Token, withNth []Range) *Transformed {
|
func Transform(tokens []Token, withNth []Range) *[]Token {
|
||||||
transTokens := make([]Token, len(withNth))
|
transTokens := make([]Token, len(withNth))
|
||||||
numTokens := len(tokens)
|
numTokens := len(tokens)
|
||||||
whole := ""
|
|
||||||
for idx, r := range withNth {
|
for idx, r := range withNth {
|
||||||
part := ""
|
part := []rune{}
|
||||||
minIdx := 0
|
minIdx := 0
|
||||||
if r.begin == r.end {
|
if r.begin == r.end {
|
||||||
idx := r.begin
|
idx := r.begin
|
||||||
if idx == rangeEllipsis {
|
if idx == rangeEllipsis {
|
||||||
part += joinTokens(tokens)
|
part = append(part, *joinTokensAsRunes(&tokens)...)
|
||||||
} else {
|
} else {
|
||||||
if idx < 0 {
|
if idx < 0 {
|
||||||
idx += numTokens + 1
|
idx += numTokens + 1
|
||||||
}
|
}
|
||||||
if idx >= 1 && idx <= numTokens {
|
if idx >= 1 && idx <= numTokens {
|
||||||
minIdx = idx - 1
|
minIdx = idx - 1
|
||||||
part += *tokens[idx-1].text
|
part = append(part, *tokens[idx-1].text...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -195,11 +196,10 @@ func Transform(tokens []Token, withNth []Range) *Transformed {
|
|||||||
minIdx = util.Max(0, begin-1)
|
minIdx = util.Max(0, begin-1)
|
||||||
for idx := begin; idx <= end; idx++ {
|
for idx := begin; idx <= end; idx++ {
|
||||||
if idx >= 1 && idx <= numTokens {
|
if idx >= 1 && idx <= numTokens {
|
||||||
part += *tokens[idx-1].text
|
part = append(part, *tokens[idx-1].text...)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
whole += part
|
|
||||||
var prefixLength int
|
var prefixLength int
|
||||||
if minIdx < numTokens {
|
if minIdx < numTokens {
|
||||||
prefixLength = tokens[minIdx].prefixLength
|
prefixLength = tokens[minIdx].prefixLength
|
||||||
@@ -208,7 +208,5 @@ func Transform(tokens []Token, withNth []Range) *Transformed {
|
|||||||
}
|
}
|
||||||
transTokens[idx] = Token{&part, prefixLength}
|
transTokens[idx] = Token{&part, prefixLength}
|
||||||
}
|
}
|
||||||
return &Transformed{
|
return &transTokens
|
||||||
whole: &whole,
|
|
||||||
parts: transTokens}
|
|
||||||
}
|
}
|
||||||
|
@@ -44,13 +44,13 @@ func TestTokenize(t *testing.T) {
|
|||||||
// AWK-style
|
// AWK-style
|
||||||
input := " abc: def: ghi "
|
input := " abc: def: ghi "
|
||||||
tokens := Tokenize(&input, nil)
|
tokens := Tokenize(&input, nil)
|
||||||
if *tokens[0].text != "abc: " || tokens[0].prefixLength != 2 {
|
if string(*tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With delimiter
|
// With delimiter
|
||||||
tokens = Tokenize(&input, delimiterRegexp(":"))
|
tokens = Tokenize(&input, delimiterRegexp(":"))
|
||||||
if *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {
|
if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,19 +62,19 @@ func TestTransform(t *testing.T) {
|
|||||||
{
|
{
|
||||||
ranges := splitNth("1,2,3")
|
ranges := splitNth("1,2,3")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *tx.whole != "abc: def: ghi: " {
|
if *joinTokens(tx) != "abc: def: ghi: " {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", *tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *tx.whole != "abc: def: ghi: def: ghi: jklabc: " ||
|
if *joinTokens(tx) != "abc: def: ghi: def: ghi: jklabc: " ||
|
||||||
len(tx.parts) != 4 ||
|
len(*tx) != 4 ||
|
||||||
*tx.parts[0].text != "abc: def: " || tx.parts[0].prefixLength != 2 ||
|
string(*(*tx)[0].text) != "abc: def: " || (*tx)[0].prefixLength != 2 ||
|
||||||
*tx.parts[1].text != "ghi: " || tx.parts[1].prefixLength != 14 ||
|
string(*(*tx)[1].text) != "ghi: " || (*tx)[1].prefixLength != 14 ||
|
||||||
*tx.parts[2].text != "def: ghi: jkl" || tx.parts[2].prefixLength != 8 ||
|
string(*(*tx)[2].text) != "def: ghi: jkl" || (*tx)[2].prefixLength != 8 ||
|
||||||
*tx.parts[3].text != "abc: " || tx.parts[3].prefixLength != 2 {
|
string(*(*tx)[3].text) != "abc: " || (*tx)[3].prefixLength != 2 {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", *tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,12 +84,12 @@ func TestTransform(t *testing.T) {
|
|||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *tx.whole != " abc: def: ghi: def: ghi: jkl abc:" ||
|
if *joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||
|
||||||
len(tx.parts) != 4 ||
|
len(*tx) != 4 ||
|
||||||
*tx.parts[0].text != " abc: def:" || tx.parts[0].prefixLength != 0 ||
|
string(*(*tx)[0].text) != " abc: def:" || (*tx)[0].prefixLength != 0 ||
|
||||||
*tx.parts[1].text != " ghi:" || tx.parts[1].prefixLength != 12 ||
|
string(*(*tx)[1].text) != " ghi:" || (*tx)[1].prefixLength != 12 ||
|
||||||
*tx.parts[2].text != " def: ghi: jkl" || tx.parts[2].prefixLength != 6 ||
|
string(*(*tx)[2].text) != " def: ghi: jkl" || (*tx)[2].prefixLength != 6 ||
|
||||||
*tx.parts[3].text != " abc:" || tx.parts[3].prefixLength != 0 {
|
string(*(*tx)[3].text) != " abc:" || (*tx)[3].prefixLength != 0 {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", *tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -19,6 +19,14 @@ func Max(first int, items ...int) int {
|
|||||||
return max
|
return max
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Max32 returns the smallest 32-bit integer
|
||||||
|
func Min32(first int32, second int32) int32 {
|
||||||
|
if first <= second {
|
||||||
|
return first
|
||||||
|
}
|
||||||
|
return second
|
||||||
|
}
|
||||||
|
|
||||||
// Max32 returns the largest 32-bit integer
|
// Max32 returns the largest 32-bit integer
|
||||||
func Max32(first int32, second int32) int32 {
|
func Max32(first int32, second int32) int32 {
|
||||||
if first > second {
|
if first > second {
|
||||||
@@ -69,3 +77,14 @@ func Between(val int, min int, max int) bool {
|
|||||||
func IsTty() bool {
|
func IsTty() bool {
|
||||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TrimRight(runes *[]rune) []rune {
|
||||||
|
var i int
|
||||||
|
for i = len(*runes) - 1; i >= 0; i-- {
|
||||||
|
char := (*runes)[i]
|
||||||
|
if char != ' ' && char != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (*runes)[0 : i+1]
|
||||||
|
}
|
||||||
|
498
test/test_go.rb
498
test/test_go.rb
@@ -4,7 +4,11 @@
|
|||||||
require 'minitest/autorun'
|
require 'minitest/autorun'
|
||||||
require 'fileutils'
|
require 'fileutils'
|
||||||
|
|
||||||
Dir.chdir File.expand_path('../../', __FILE__)
|
DEFAULT_TIMEOUT = 20
|
||||||
|
|
||||||
|
base = File.expand_path('../../', __FILE__)
|
||||||
|
Dir.chdir base
|
||||||
|
FZF = "#{base}/bin/fzf"
|
||||||
|
|
||||||
class NilClass
|
class NilClass
|
||||||
def include? str
|
def include? str
|
||||||
@@ -20,25 +24,13 @@ class NilClass
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
module Temp
|
def wait
|
||||||
def readonce
|
since = Time.now
|
||||||
name = self.class::TEMPNAME
|
while Time.now - since < DEFAULT_TIMEOUT
|
||||||
waited = 0
|
return if yield
|
||||||
while waited < 5
|
sleep 0.05
|
||||||
begin
|
|
||||||
data = `cat #{name}`
|
|
||||||
return data unless data.empty?
|
|
||||||
rescue
|
|
||||||
sleep 0.1
|
|
||||||
waited += 0.1
|
|
||||||
end
|
|
||||||
end
|
|
||||||
raise "failed to read tempfile"
|
|
||||||
ensure
|
|
||||||
while File.exists? name
|
|
||||||
File.unlink name rescue nil
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
throw 'timeout'
|
||||||
end
|
end
|
||||||
|
|
||||||
class Shell
|
class Shell
|
||||||
@@ -56,8 +48,6 @@ class Shell
|
|||||||
end
|
end
|
||||||
|
|
||||||
class Tmux
|
class Tmux
|
||||||
include Temp
|
|
||||||
|
|
||||||
TEMPNAME = '/tmp/fzf-test.txt'
|
TEMPNAME = '/tmp/fzf-test.txt'
|
||||||
|
|
||||||
attr_reader :win
|
attr_reader :win
|
||||||
@@ -82,15 +72,6 @@ class Tmux
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def closed?
|
|
||||||
!go("list-window -F '#I'").include?(win)
|
|
||||||
end
|
|
||||||
|
|
||||||
def close
|
|
||||||
send_keys 'C-c', 'C-u', 'exit', :Enter
|
|
||||||
wait { closed? }
|
|
||||||
end
|
|
||||||
|
|
||||||
def kill
|
def kill
|
||||||
go("kill-window -t #{win} 2> /dev/null")
|
go("kill-window -t #{win} 2> /dev/null")
|
||||||
end
|
end
|
||||||
@@ -108,79 +89,78 @@ class Tmux
|
|||||||
go("send-keys -t #{target} #{args}")
|
go("send-keys -t #{target} #{args}")
|
||||||
end
|
end
|
||||||
|
|
||||||
def capture opts = {}
|
def capture pane = 0
|
||||||
timeout, pane = defaults(opts).values_at(:timeout, :pane)
|
File.unlink TEMPNAME while File.exists? TEMPNAME
|
||||||
waited = 0
|
wait do
|
||||||
loop do
|
go("capture-pane -t #{win}.#{pane} \\; save-buffer #{TEMPNAME} 2> /dev/null")
|
||||||
go("capture-pane -t #{win}.#{pane} \\; save-buffer #{TEMPNAME}")
|
$?.exitstatus == 0
|
||||||
break if $?.exitstatus == 0
|
|
||||||
|
|
||||||
if waited > timeout
|
|
||||||
raise "Window not found"
|
|
||||||
end
|
end
|
||||||
waited += 0.1
|
File.read(TEMPNAME).split($/)[0, @lines].reverse.drop_while(&:empty?).reverse
|
||||||
sleep 0.1
|
|
||||||
end
|
|
||||||
readonce.split($/)[0, @lines].reverse.drop_while(&:empty?).reverse
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def until opts = {}
|
def until pane = 0
|
||||||
lines = nil
|
lines = nil
|
||||||
wait(opts) do
|
begin
|
||||||
yield lines = capture(opts)
|
wait do
|
||||||
|
lines = capture(pane)
|
||||||
|
class << lines
|
||||||
|
def item_count
|
||||||
|
self[-2] ? self[-2].strip.split('/').last.to_i : 0
|
||||||
|
end
|
||||||
|
end
|
||||||
|
yield lines
|
||||||
|
end
|
||||||
|
rescue Exception
|
||||||
|
puts $!.backtrace
|
||||||
|
puts '>' * 80
|
||||||
|
puts lines
|
||||||
|
puts '<' * 80
|
||||||
|
raise
|
||||||
end
|
end
|
||||||
lines
|
lines
|
||||||
end
|
end
|
||||||
|
|
||||||
def prepare
|
def prepare
|
||||||
self.send_keys 'echo hello', :Enter
|
tries = 0
|
||||||
self.until { |lines| lines[-1].start_with?('hello') }
|
begin
|
||||||
self.send_keys 'clear', :Enter
|
self.send_keys 'C-u', 'hello', 'Right'
|
||||||
self.until { |lines| lines.empty? }
|
self.until { |lines| lines[-1].end_with?('hello') }
|
||||||
|
rescue Exception
|
||||||
|
(tries += 1) < 5 ? retry : raise
|
||||||
|
end
|
||||||
|
self.send_keys 'C-u'
|
||||||
end
|
end
|
||||||
private
|
private
|
||||||
def defaults opts
|
|
||||||
{ timeout: 10, pane: 0 }.merge(opts)
|
|
||||||
end
|
|
||||||
|
|
||||||
def wait opts = {}
|
|
||||||
timeout, pane = defaults(opts).values_at(:timeout, :pane)
|
|
||||||
waited = 0
|
|
||||||
until yield
|
|
||||||
if waited > timeout
|
|
||||||
hl = '=' * 10
|
|
||||||
puts hl
|
|
||||||
capture(opts).each_with_index do |line, idx|
|
|
||||||
puts [idx.to_s.rjust(2), line].join(': ')
|
|
||||||
end
|
|
||||||
puts hl
|
|
||||||
raise "timeout"
|
|
||||||
end
|
|
||||||
waited += 0.1
|
|
||||||
sleep 0.1
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def go *args
|
def go *args
|
||||||
%x[tmux #{args.join ' '}].split($/)
|
%x[tmux #{args.join ' '}].split($/)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class TestBase < Minitest::Test
|
class TestBase < Minitest::Test
|
||||||
include Temp
|
|
||||||
|
|
||||||
FIN = 'FIN'
|
|
||||||
TEMPNAME = '/tmp/output'
|
TEMPNAME = '/tmp/output'
|
||||||
|
|
||||||
attr_reader :tmux
|
attr_reader :tmux
|
||||||
|
|
||||||
|
def tempname
|
||||||
|
[TEMPNAME,
|
||||||
|
caller_locations.map(&:label).find { |l| l =~ /^test_/ }].join '-'
|
||||||
|
end
|
||||||
|
|
||||||
def setup
|
def setup
|
||||||
ENV.delete 'FZF_DEFAULT_OPTS'
|
ENV.delete 'FZF_DEFAULT_OPTS'
|
||||||
ENV.delete 'FZF_DEFAULT_COMMAND'
|
ENV.delete 'FZF_DEFAULT_COMMAND'
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def readonce
|
||||||
|
wait { File.exists?(tempname) }
|
||||||
|
File.read(tempname)
|
||||||
|
ensure
|
||||||
|
File.unlink tempname while File.exists?(tempname)
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
def fzf(*opts)
|
def fzf(*opts)
|
||||||
fzf!(*opts) + " > #{TEMPNAME} && echo #{FIN}"
|
fzf!(*opts) + " > #{tempname}.tmp; mv #{tempname}.tmp #{tempname}"
|
||||||
end
|
end
|
||||||
|
|
||||||
def fzf!(*opts)
|
def fzf!(*opts)
|
||||||
@@ -195,7 +175,7 @@ class TestBase < Minitest::Test
|
|||||||
nil
|
nil
|
||||||
end
|
end
|
||||||
}.compact
|
}.compact
|
||||||
"fzf #{opts.join ' '}"
|
"#{FZF} #{opts.join ' '}"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -211,8 +191,7 @@ class TestGoFZF < TestBase
|
|||||||
|
|
||||||
def test_vanilla
|
def test_vanilla
|
||||||
tmux.send_keys "seq 1 100000 | #{fzf}", :Enter
|
tmux.send_keys "seq 1 100000 | #{fzf}", :Enter
|
||||||
tmux.until(timeout: 20) { |lines|
|
tmux.until { |lines| lines.last =~ /^>/ && lines[-2] =~ /^ 100000/ }
|
||||||
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]
|
||||||
@@ -229,7 +208,6 @@ class TestGoFZF < TestBase
|
|||||||
assert_equal '> 391', lines[-1]
|
assert_equal '> 391', lines[-1]
|
||||||
|
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.close
|
|
||||||
assert_equal '1391', readonce.chomp
|
assert_equal '1391', readonce.chomp
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -238,12 +216,11 @@ class TestGoFZF < TestBase
|
|||||||
tmux.until { |lines| lines.last =~ /^>/ }
|
tmux.until { |lines| lines.last =~ /^>/ }
|
||||||
|
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.close
|
|
||||||
assert_equal 'hello', readonce.chomp
|
assert_equal 'hello', readonce.chomp
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_key_bindings
|
def test_key_bindings
|
||||||
tmux.send_keys "fzf -q 'foo bar foo-bar'", :Enter
|
tmux.send_keys "#{FZF} -q 'foo bar foo-bar'", :Enter
|
||||||
tmux.until { |lines| lines.last =~ /^>/ }
|
tmux.until { |lines| lines.last =~ /^>/ }
|
||||||
|
|
||||||
# CTRL-A
|
# CTRL-A
|
||||||
@@ -305,7 +282,6 @@ class TestGoFZF < TestBase
|
|||||||
# CTRL-M
|
# CTRL-M
|
||||||
tmux.send_keys "C-M"
|
tmux.send_keys "C-M"
|
||||||
tmux.until { |lines| lines.last !~ /^>/ }
|
tmux.until { |lines| lines.last !~ /^>/ }
|
||||||
tmux.close
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_multi_order
|
def test_multi_order
|
||||||
@@ -317,9 +293,7 @@ class TestGoFZF < TestBase
|
|||||||
:PgUp, 'C-J', :Down, :Tab, :Tab # 8, 7
|
:PgUp, 'C-J', :Down, :Tab, :Tab # 8, 7
|
||||||
tmux.until { |lines| lines[-2].include? '(6)' }
|
tmux.until { |lines| lines[-2].include? '(6)' }
|
||||||
tmux.send_keys "C-M"
|
tmux.send_keys "C-M"
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal %w[3 2 5 6 8 7], readonce.split($/)
|
assert_equal %w[3 2 5 6 8 7], readonce.split($/)
|
||||||
tmux.close
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_with_nth
|
def test_with_nth
|
||||||
@@ -338,13 +312,11 @@ class TestGoFZF < TestBase
|
|||||||
# However, the output must not be transformed
|
# However, the output must not be transformed
|
||||||
if multi
|
if multi
|
||||||
tmux.send_keys :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal [' 1st 2nd 3rd/', ' first second third/'], readonce.split($/)
|
assert_equal [' 1st 2nd 3rd/', ' first second third/'], readonce.split($/)
|
||||||
else
|
else
|
||||||
tmux.send_keys '^', '3'
|
tmux.send_keys '^', '3'
|
||||||
tmux.until { |lines| lines[-2].include?('1/2') }
|
tmux.until { |lines| lines[-2].include?('1/2') }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal [' 1st 2nd 3rd/'], readonce.split($/)
|
assert_equal [' 1st 2nd 3rd/'], readonce.split($/)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -357,20 +329,17 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys *110.times.map { rev ? :Down : :Up }
|
tmux.send_keys *110.times.map { rev ? :Down : :Up }
|
||||||
tmux.until { |lines| lines.include? '> 100' }
|
tmux.until { |lines| lines.include? '> 100' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal '100', readonce.chomp
|
assert_equal '100', readonce.chomp
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_select_1
|
def test_select_1
|
||||||
tmux.send_keys "seq 1 100 | #{fzf :with_nth, '..,..', :print_query, :q, 5555, :'1'}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf :with_nth, '..,..', :print_query, :q, 5555, :'1'}", :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal ['5555', '55'], readonce.split($/)
|
assert_equal ['5555', '55'], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_exit_0
|
def test_exit_0
|
||||||
tmux.send_keys "seq 1 100 | #{fzf :with_nth, '..,..', :print_query, :q, 555555, :'0'}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf :with_nth, '..,..', :print_query, :q, 555555, :'0'}", :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal ['555555'], readonce.split($/)
|
assert_equal ['555555'], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -379,16 +348,14 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys "seq 1 100 | #{fzf :print_query, :multi, :q, 5, *opt}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf :print_query, :multi, :q, 5, *opt}", :Enter
|
||||||
tmux.until { |lines| lines.last =~ /^> 5/ }
|
tmux.until { |lines| lines.last =~ /^> 5/ }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal ['5', '5', '15', '25'], readonce.split($/)
|
assert_equal ['5', '5', '15', '25'], readonce.split($/)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_query_unicode
|
def test_query_unicode
|
||||||
tmux.send_keys "(echo abc; echo 가나다) | #{fzf :query, '가다'}", :Enter
|
tmux.send_keys "(echo abc; echo 가나다) | #{fzf :query, '가다'}", :Enter
|
||||||
tmux.until { |lines| lines.last.start_with? '>' }
|
tmux.until { |lines| lines[-2].include? '1/2' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1].include?(FIN) }
|
|
||||||
assert_equal ['가나다'], readonce.split($/)
|
assert_equal ['가나다'], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -422,6 +389,7 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys "seq 1 1000 | #{fzf :tac, :no_sort, :multi}", :Enter
|
tmux.send_keys "seq 1 1000 | #{fzf :tac, :no_sort, :multi}", :Enter
|
||||||
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
tmux.until { |lines| lines[-2].include? '1000/1000' }
|
||||||
tmux.send_keys '00'
|
tmux.send_keys '00'
|
||||||
|
tmux.until { |lines| lines[-2].include? '10/1000' }
|
||||||
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :BTab, :Enter
|
||||||
assert_equal %w[1000 900 800], readonce.split($/)
|
assert_equal %w[1000 900 800], readonce.split($/)
|
||||||
end
|
end
|
||||||
@@ -431,6 +399,7 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys "seq 1 100 | #{fzf :expect, key}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf :expect, key}", :Enter
|
||||||
tmux.until { |lines| lines[-2].include? '100/100' }
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
tmux.send_keys '55'
|
tmux.send_keys '55'
|
||||||
|
tmux.until { |lines| lines[-2].include? '1/100' }
|
||||||
tmux.send_keys *feed
|
tmux.send_keys *feed
|
||||||
assert_equal [expected, '55'], readonce.split($/)
|
assert_equal [expected, '55'], readonce.split($/)
|
||||||
end
|
end
|
||||||
@@ -449,6 +418,7 @@ class TestGoFZF < TestBase
|
|||||||
tmux.send_keys "seq 1 100 | #{fzf '--expect=alt-z', :print_query}", :Enter
|
tmux.send_keys "seq 1 100 | #{fzf '--expect=alt-z', :print_query}", :Enter
|
||||||
tmux.until { |lines| lines[-2].include? '100/100' }
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
tmux.send_keys '55'
|
tmux.send_keys '55'
|
||||||
|
tmux.until { |lines| lines[-2].include? '1/100' }
|
||||||
tmux.send_keys :Escape, :z
|
tmux.send_keys :Escape, :z
|
||||||
assert_equal ['55', 'alt-z', '55'], readonce.split($/)
|
assert_equal ['55', 'alt-z', '55'], readonce.split($/)
|
||||||
end
|
end
|
||||||
@@ -459,17 +429,217 @@ class TestGoFZF < TestBase
|
|||||||
end
|
end
|
||||||
|
|
||||||
def test_toggle_sort
|
def test_toggle_sort
|
||||||
tmux.send_keys "seq 1 111 | #{fzf '-m +s --tac --toggle-sort=ctrl-r -q11'}", :Enter
|
['--toggle-sort=ctrl-r', '--bind=ctrl-r:toggle-sort'].each do |opt|
|
||||||
|
tmux.send_keys "seq 1 111 | #{fzf "-m +s --tac #{opt} -q11"}", :Enter
|
||||||
tmux.until { |lines| lines[-3].include? '> 111' }
|
tmux.until { |lines| lines[-3].include? '> 111' }
|
||||||
tmux.send_keys :Tab
|
tmux.send_keys :Tab
|
||||||
tmux.until { |lines| lines[-2].include? '4/111 (1)' }
|
tmux.until { |lines| lines[-2].include? '4/111 (1)' }
|
||||||
tmux.send_keys 'C-R'
|
tmux.send_keys 'C-R'
|
||||||
tmux.until { |lines| lines[-3].include? '> 11' }
|
tmux.until { |lines| lines[-3].include? '> 11' }
|
||||||
tmux.send_keys :Tab
|
tmux.send_keys :Tab
|
||||||
tmux.until { |lines| lines[-2].include? '4/111 (2)' }
|
tmux.until { |lines| lines[-2].include? '4/111/S (2)' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
assert_equal ['111', '11'], readonce.split($/)
|
assert_equal ['111', '11'], readonce.split($/)
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_unicode_case
|
||||||
|
writelines tempname, %w[строКА1 СТРОКА2 строка3 Строка4]
|
||||||
|
assert_equal %w[СТРОКА2 Строка4], `cat #{tempname} | #{FZF} -fС`.split($/)
|
||||||
|
assert_equal %w[строКА1 СТРОКА2 строка3 Строка4], `cat #{tempname} | #{FZF} -fс`.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_tiebreak
|
||||||
|
input = %w[
|
||||||
|
--foobar--------
|
||||||
|
-----foobar---
|
||||||
|
----foobar--
|
||||||
|
-------foobar-
|
||||||
|
]
|
||||||
|
writelines tempname, input
|
||||||
|
|
||||||
|
assert_equal input, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=index`.split($/)
|
||||||
|
|
||||||
|
by_length = %w[
|
||||||
|
----foobar--
|
||||||
|
-----foobar---
|
||||||
|
-------foobar-
|
||||||
|
--foobar--------
|
||||||
|
]
|
||||||
|
assert_equal by_length, `cat #{tempname} | #{FZF} -ffoobar`.split($/)
|
||||||
|
assert_equal by_length, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=length`.split($/)
|
||||||
|
|
||||||
|
by_begin = %w[
|
||||||
|
--foobar--------
|
||||||
|
----foobar--
|
||||||
|
-----foobar---
|
||||||
|
-------foobar-
|
||||||
|
]
|
||||||
|
assert_equal by_begin, `cat #{tempname} | #{FZF} -ffoobar --tiebreak=begin`.split($/)
|
||||||
|
assert_equal by_begin, `cat #{tempname} | #{FZF} -f"!z foobar" -x --tiebreak begin`.split($/)
|
||||||
|
|
||||||
|
assert_equal %w[
|
||||||
|
-------foobar-
|
||||||
|
----foobar--
|
||||||
|
-----foobar---
|
||||||
|
--foobar--------
|
||||||
|
], `cat #{tempname} | #{FZF} -ffoobar --tiebreak end`.split($/)
|
||||||
|
|
||||||
|
assert_equal input, `cat #{tempname} | #{FZF} -f"!z" -x --tiebreak end`.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_invalid_cache
|
||||||
|
tmux.send_keys "(echo d; echo D; echo x) | #{fzf '-q d'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '2/3' }
|
||||||
|
tmux.send_keys :BSpace
|
||||||
|
tmux.until { |lines| lines[-2].include? '3/3' }
|
||||||
|
tmux.send_keys :D
|
||||||
|
tmux.until { |lines| lines[-2].include? '1/3' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_smart_case_for_each_term
|
||||||
|
assert_equal 1, `echo Foo bar | #{FZF} -x -f "foo Fbar" | wc -l`.to_i
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_bind
|
||||||
|
tmux.send_keys "seq 1 1000 | #{
|
||||||
|
fzf '-m --bind=ctrl-j:accept,u:up,T:toggle-up,t:toggle'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].end_with? '/1000' }
|
||||||
|
tmux.send_keys 'uuu', 'TTT', 'tt', 'uu', 'ttt', 'C-j'
|
||||||
|
assert_equal %w[4 5 6 9], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_long_line
|
||||||
|
data = '.' * 256 * 1024
|
||||||
|
File.open(tempname, 'w') do |f|
|
||||||
|
f << data
|
||||||
|
end
|
||||||
|
assert_equal data, `cat #{tempname} | #{FZF} -f .`.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_read0
|
||||||
|
lines = `find .`.split($/)
|
||||||
|
assert_equal lines.last, `find . | #{FZF} -e -f "^#{lines.last}$"`.chomp
|
||||||
|
assert_equal lines.last, `find . -print0 | #{FZF} --read0 -e -f "^#{lines.last}$"`.chomp
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_select_all_deselect_all_toggle_all
|
||||||
|
tmux.send_keys "seq 100 | #{fzf '--bind ctrl-a:select-all,ctrl-d:deselect-all,ctrl-t:toggle-all --multi'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys :BTab, :BTab, :BTab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(3)' }
|
||||||
|
tmux.send_keys 'C-t'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(97)' }
|
||||||
|
tmux.send_keys 'C-a'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(100)' }
|
||||||
|
tmux.send_keys :Tab, :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(98)' }
|
||||||
|
tmux.send_keys 'C-d'
|
||||||
|
tmux.until { |lines| !lines[-2].include? '(' }
|
||||||
|
tmux.send_keys :Tab, :Tab
|
||||||
|
tmux.until { |lines| lines[-2].include? '(2)' }
|
||||||
|
tmux.send_keys 0
|
||||||
|
tmux.until { |lines| lines[-2].include? '10/100' }
|
||||||
|
tmux.send_keys 'C-a'
|
||||||
|
tmux.until { |lines| lines[-2].include? '(12)' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
assert_equal %w[2 1 10 20 30 40 50 60 70 80 90 100], readonce.split($/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_history
|
||||||
|
history_file = '/tmp/fzf-test-history'
|
||||||
|
|
||||||
|
# History with limited number of entries
|
||||||
|
File.unlink history_file rescue nil
|
||||||
|
opts = "--history=#{history_file} --history-size=4"
|
||||||
|
input = %w[00 11 22 33 44].map { |e| e + $/ }
|
||||||
|
input.each do |keys|
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys keys
|
||||||
|
tmux.until { |lines| lines[-2].include? '1/100' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
end
|
||||||
|
assert_equal input[1..-1], File.readlines(history_file)
|
||||||
|
|
||||||
|
# Update history entries (not changed on disk)
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 44' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 33' }
|
||||||
|
tmux.send_keys :BSpace
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 3' }
|
||||||
|
tmux.send_keys 1
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 31' }
|
||||||
|
tmux.send_keys 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 22' }
|
||||||
|
tmux.send_keys 'C-n'
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 31' }
|
||||||
|
tmux.send_keys 0
|
||||||
|
tmux.until { |lines| lines[-1].end_with? '> 310' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
assert_equal %w[22 33 44 310].map { |e| e + $/ }, File.readlines(history_file)
|
||||||
|
|
||||||
|
# Respect --bind option
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts + ' --bind ctrl-p:next-history,ctrl-n:previous-history'}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys 'C-n', 'C-n', 'C-n', 'C-n', 'C-p'
|
||||||
|
tmux.until { |lines| lines[-1].end_with?('33') }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
ensure
|
||||||
|
File.unlink history_file
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_execute
|
||||||
|
output = '/tmp/fzf-test-execute'
|
||||||
|
opts = %[--bind \\"alt-a:execute(echo '[{}]' >> #{output}),alt-b:execute[echo '({}), ({})' >> #{output}],C:execute:echo '({}), [{}], @{}@' >> #{output}\\"]
|
||||||
|
tmux.send_keys "seq 100 | #{fzf opts}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '100/100' }
|
||||||
|
tmux.send_keys :Escape, :a, :Escape, :a
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.send_keys :Escape, :b, :Escape, :b
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.send_keys :C
|
||||||
|
tmux.send_keys 'foobar'
|
||||||
|
tmux.until { |lines| lines[-2].include? '0/100' }
|
||||||
|
tmux.send_keys :Escape, :a, :Escape, :b, :Escape, :c
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
readonce
|
||||||
|
assert_equal ['["1"]', '["1"]', '("2"), ("2")', '("2"), ("2")', '("3"), ["3"], @"3"@'],
|
||||||
|
File.readlines(output).map(&:chomp)
|
||||||
|
ensure
|
||||||
|
File.unlink output rescue nil
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_cycle
|
||||||
|
tmux.send_keys "seq 8 | #{fzf :cycle}", :Enter
|
||||||
|
tmux.until { |lines| lines[-2].include? '8/8' }
|
||||||
|
tmux.send_keys :Down
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
tmux.send_keys :Down
|
||||||
|
tmux.until { |lines| lines[-9].start_with? '>' }
|
||||||
|
tmux.send_keys :PgUp
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
tmux.send_keys :PgUp
|
||||||
|
tmux.until { |lines| lines[-3].start_with? '>' }
|
||||||
|
tmux.send_keys :Up
|
||||||
|
tmux.until { |lines| lines[-4].start_with? '>' }
|
||||||
|
tmux.send_keys :PgDn
|
||||||
|
tmux.until { |lines| lines[-3].start_with? '>' }
|
||||||
|
tmux.send_keys :PgDn
|
||||||
|
tmux.until { |lines| lines[-10].start_with? '>' }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
def writelines path, lines
|
||||||
|
File.unlink path while File.exists? path
|
||||||
|
File.open(path, 'w') { |f| f << lines.join($/) }
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
module TestShell
|
module TestShell
|
||||||
@@ -484,32 +654,31 @@ module TestShell
|
|||||||
def test_ctrl_t
|
def test_ctrl_t
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'C-t', pane: 0
|
tmux.send_keys 'C-t', pane: 0
|
||||||
lines = tmux.until(pane: 1) { |lines| lines[-1].start_with? '>' }
|
lines = tmux.until(1) { |lines| lines.item_count > 1 }
|
||||||
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
tmux.send_keys :BTab, :BTab, :Enter, pane: 1
|
tmux.send_keys :BTab, :BTab, :Enter, pane: 1
|
||||||
tmux.until(pane: 0) { |lines| lines[-1].include? expected }
|
tmux.until(0) { |lines| lines[-1].include? expected }
|
||||||
tmux.send_keys 'C-c'
|
tmux.send_keys 'C-c'
|
||||||
|
|
||||||
# FZF_TMUX=0
|
# FZF_TMUX=0
|
||||||
new_shell
|
new_shell
|
||||||
tmux.send_keys 'C-t', pane: 0
|
tmux.send_keys 'C-t', pane: 0
|
||||||
lines = tmux.until(pane: 0) { |lines| lines[-1].start_with? '>' }
|
lines = tmux.until(0) { |lines| lines.item_count > 1 }
|
||||||
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
expected = lines.values_at(-3, -4).map { |line| line[2..-1] }.join(' ')
|
||||||
tmux.send_keys :BTab, :BTab, :Enter, pane: 0
|
tmux.send_keys :BTab, :BTab, :Enter, pane: 0
|
||||||
tmux.until(pane: 0) { |lines| lines[-1].include? expected }
|
tmux.until(0) { |lines| lines[-1].include? expected }
|
||||||
tmux.send_keys 'C-c', 'C-d'
|
tmux.send_keys 'C-c', 'C-d'
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_alt_c
|
def test_alt_c
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys :Escape, :c
|
tmux.send_keys :Escape, :c, pane: 0
|
||||||
lines = tmux.until { |lines| lines[-1].start_with? '>' }
|
lines = tmux.until(1) { |lines| lines.item_count > 0 && lines[-3][2..-1] }
|
||||||
expected = lines[-3][2..-1]
|
expected = lines[-3][2..-1]
|
||||||
p expected
|
tmux.send_keys :Enter, pane: 1
|
||||||
tmux.send_keys :Enter
|
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys :pwd, :Enter
|
tmux.send_keys :pwd, :Enter
|
||||||
tmux.until { |lines| p lines; lines[-1].end_with?(expected) }
|
tmux.until { |lines| lines[-1].end_with?(expected) }
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_ctrl_r
|
def test_ctrl_r
|
||||||
@@ -519,58 +688,93 @@ module TestShell
|
|||||||
tmux.send_keys 'echo 3d', :Enter; tmux.prepare
|
tmux.send_keys 'echo 3d', :Enter; tmux.prepare
|
||||||
tmux.send_keys 'echo 3rd', :Enter; tmux.prepare
|
tmux.send_keys 'echo 3rd', :Enter; tmux.prepare
|
||||||
tmux.send_keys 'echo 4th', :Enter; tmux.prepare
|
tmux.send_keys 'echo 4th', :Enter; tmux.prepare
|
||||||
tmux.send_keys 'C-r'
|
tmux.send_keys 'C-r', pane: 0
|
||||||
tmux.until { |lines| lines[-1].start_with? '>' }
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
tmux.send_keys '3d'
|
tmux.send_keys '3d', pane: 1
|
||||||
tmux.until { |lines| lines[-3].end_with? 'echo 3rd' } # --no-sort
|
tmux.until(1) { |lines| lines[-3].end_with? 'echo 3rd' } # --no-sort
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter, pane: 1
|
||||||
tmux.until { |lines| lines[-1] == 'echo 3rd' }
|
tmux.until { |lines| lines[-1] == 'echo 3rd' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1] == '3rd' }
|
tmux.until { |lines| lines[-1] == '3rd' }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class TestBash < TestBase
|
module CompletionTest
|
||||||
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
|
def test_file_completion
|
||||||
tmux.send_keys 'mkdir -p /tmp/fzf-test; touch /tmp/fzf-test/{1..100}', :Enter
|
FileUtils.mkdir_p '/tmp/fzf-test'
|
||||||
|
FileUtils.mkdir_p '/tmp/fzf test'
|
||||||
|
(1..100).each { |i| FileUtils.touch "/tmp/fzf-test/#{i}" }
|
||||||
|
['no~such~user', '/tmp/fzf test/foobar', '~/.fzf-home'].each do |f|
|
||||||
|
FileUtils.touch File.expand_path(f)
|
||||||
|
end
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab
|
tmux.send_keys 'cat /tmp/fzf-test/10**', :Tab, pane: 0
|
||||||
tmux.until { |lines| lines[-1].start_with? '>' }
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
tmux.send_keys :BTab, :BTab, :Enter
|
tmux.send_keys :BTab, :BTab, :Enter
|
||||||
tmux.until { |lines|
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
lines[-1].include?('/tmp/fzf-test/10') &&
|
lines[-1].include?('/tmp/fzf-test/10') &&
|
||||||
lines[-1].include?('/tmp/fzf-test/100')
|
lines[-1].include?('/tmp/fzf-test/100')
|
||||||
}
|
end
|
||||||
|
|
||||||
|
# ~USERNAME**<TAB>
|
||||||
|
tmux.send_keys 'C-u'
|
||||||
|
tmux.send_keys "cat ~#{ENV['USER']}**", :Tab, pane: 0
|
||||||
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
|
tmux.send_keys '.fzf-home'
|
||||||
|
tmux.until(1) { |lines| lines[-3].end_with? '.fzf-home' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
|
lines[-1].end_with?('.fzf-home')
|
||||||
|
end
|
||||||
|
|
||||||
|
# ~INVALID_USERNAME**<TAB>
|
||||||
|
tmux.send_keys 'C-u'
|
||||||
|
tmux.send_keys "cat ~such**", :Tab, pane: 0
|
||||||
|
tmux.until(1) { |lines| lines[-3].end_with? 'no~such~user' }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
|
lines[-1].end_with?('no~such~user')
|
||||||
|
end
|
||||||
|
|
||||||
|
# /tmp/fzf\ test**<TAB>
|
||||||
|
tmux.send_keys 'C-u'
|
||||||
|
tmux.send_keys 'cat /tmp/fzf\ test/**', :Tab, pane: 0
|
||||||
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
|
tmux.send_keys :Enter
|
||||||
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
|
lines[-1].end_with?('/tmp/fzf\ test/foobar')
|
||||||
|
end
|
||||||
|
ensure
|
||||||
|
['/tmp/fzf-test', '/tmp/fzf test', '~/.fzf-home', 'no~such~user'].each do |f|
|
||||||
|
FileUtils.rm_rf File.expand_path(f)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_dir_completion
|
def test_dir_completion
|
||||||
tmux.send_keys 'mkdir -p /tmp/fzf-test/d{1..100}; touch /tmp/fzf-test/d55/xxx', :Enter
|
tmux.send_keys 'mkdir -p /tmp/fzf-test/d{1..100}; touch /tmp/fzf-test/d55/xxx', :Enter
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'cd /tmp/fzf-test/**', :Tab
|
tmux.send_keys 'cd /tmp/fzf-test/**', :Tab, pane: 0
|
||||||
tmux.until { |lines| lines[-1].start_with? '>' }
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
tmux.send_keys :BTab, :BTab # BTab does not work here
|
tmux.send_keys :BTab, :BTab # BTab does not work here
|
||||||
tmux.send_keys 55
|
tmux.send_keys 55
|
||||||
tmux.until { |lines| lines[-2].start_with? ' 1/' }
|
tmux.until(1) { |lines| lines[-2].start_with? ' 1/' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/' }
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
|
lines[-1] == 'cd /tmp/fzf-test/d55/'
|
||||||
|
end
|
||||||
tmux.send_keys :xx
|
tmux.send_keys :xx
|
||||||
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
||||||
|
|
||||||
# Should not match regular files
|
# Should not match regular files (bash-only)
|
||||||
|
if self.class == TestBash
|
||||||
tmux.send_keys :Tab
|
tmux.send_keys :Tab
|
||||||
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
tmux.until { |lines| lines[-1] == 'cd /tmp/fzf-test/d55/xx' }
|
||||||
|
end
|
||||||
|
|
||||||
# Fail back to plusdirs
|
# Fail back to plusdirs
|
||||||
tmux.send_keys :BSpace, :BSpace, :BSpace
|
tmux.send_keys :BSpace, :BSpace, :BSpace
|
||||||
@@ -584,17 +788,39 @@ class TestBash < TestBase
|
|||||||
lines = tmux.until { |lines| lines[-1].start_with? '[1]' }
|
lines = tmux.until { |lines| lines[-1].start_with? '[1]' }
|
||||||
pid = lines[-1].split.last
|
pid = lines[-1].split.last
|
||||||
tmux.prepare
|
tmux.prepare
|
||||||
tmux.send_keys 'kill ', :Tab
|
tmux.send_keys 'kill ', :Tab, pane: 0
|
||||||
tmux.until { |lines| lines[-1].start_with? '>' }
|
tmux.until(1) { |lines| lines.item_count > 0 }
|
||||||
tmux.send_keys 'sleep12345'
|
tmux.send_keys 'sleep12345'
|
||||||
tmux.until { |lines| lines[-3].include? 'sleep 12345' }
|
tmux.until(1) { |lines| lines[-3].include? 'sleep 12345' }
|
||||||
tmux.send_keys :Enter
|
tmux.send_keys :Enter
|
||||||
tmux.until { |lines| lines[-1] == "kill #{pid}" }
|
tmux.until do |lines|
|
||||||
|
tmux.send_keys 'C-L'
|
||||||
|
lines[-1] == "kill #{pid}"
|
||||||
|
end
|
||||||
|
ensure
|
||||||
|
Process.kill 'KILL', pid.to_i rescue nil if pid
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class TestBash < TestBase
|
||||||
|
include TestShell
|
||||||
|
include CompletionTest
|
||||||
|
|
||||||
|
def new_shell
|
||||||
|
tmux.prepare
|
||||||
|
tmux.send_keys "FZF_TMUX=0 #{Shell.bash}", :Enter
|
||||||
|
tmux.prepare
|
||||||
|
end
|
||||||
|
|
||||||
|
def setup
|
||||||
|
super
|
||||||
|
@tmux = Tmux.new :bash
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class TestZsh < TestBase
|
class TestZsh < TestBase
|
||||||
include TestShell
|
include TestShell
|
||||||
|
include CompletionTest
|
||||||
|
|
||||||
def new_shell
|
def new_shell
|
||||||
tmux.send_keys "FZF_TMUX=0 #{Shell.zsh}", :Enter
|
tmux.send_keys "FZF_TMUX=0 #{Shell.zsh}", :Enter
|
||||||
|
Reference in New Issue
Block a user