mirror of
https://github.com/junegunn/fzf.git
synced 2025-08-16 04:33:51 -07:00
Compare commits
472 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
3e1d6a7bcf | ||
|
2bbc12063c | ||
|
b8737b724b | ||
|
d91c3a2f5e | ||
|
fe5db5aadc | ||
|
cf9c957c66 | ||
|
68b60c6d19 | ||
|
3a644b16a4 | ||
|
95b34de339 | ||
|
6a431cbf49 | ||
|
56fb2f00b3 | ||
|
1c86aaf342 | ||
|
cfc0b18eaa | ||
|
412c211655 | ||
|
923feb69ab | ||
|
92dba7035a | ||
|
b8a3ba16a2 | ||
|
cd5e4d9402 | ||
|
f074709fc9 | ||
|
e0b29e437b | ||
|
bdb94fba7d | ||
|
2f364c62f4 | ||
|
7ed9f83662 | ||
|
f498a9b3fb | ||
|
13330738b8 | ||
|
e53535cc61 | ||
|
c62fc5e75c | ||
|
70245ad98c | ||
|
6d235bceee | ||
|
4adebfc856 | ||
|
faccc0a410 | ||
|
9078688baf | ||
|
9bd8b1d25f | ||
|
dd4be1da38 | ||
|
66f86e1870 | ||
|
4ab75b68dc | ||
|
73cb70dbb3 | ||
|
d082cccb6d | ||
|
88a80e3c2c | ||
|
24516bcf4d | ||
|
b4c4a642ed | ||
|
0231617857 | ||
|
7f64fba80f | ||
|
633aec38f5 | ||
|
d1b402a23c | ||
|
35a9aff8e1 | ||
|
988c9bd9be | ||
|
095f31b316 | ||
|
d86cee2a69 | ||
|
e986f20a85 | ||
|
c727ba1d99 | ||
|
bb70923cd8 | ||
|
772fa42dcb | ||
|
85ef3263fc | ||
|
4bde8de63f | ||
|
654a7df9b0 | ||
|
c3aa836ec0 | ||
|
95764bef6f | ||
|
63dbf48546 | ||
|
e2401350a3 | ||
|
e867355b2a | ||
|
b28c14b93a | ||
|
879ead210f | ||
|
2f6d23b91e | ||
|
5f63a7b587 | ||
|
d9ce797d88 | ||
|
12230f8043 | ||
|
0c8de1ca44 | ||
|
89687105f4 | ||
|
74d1694be9 | ||
|
935e986be5 | ||
|
e5ac2ebd7c | ||
|
8d6e13bf94 | ||
|
2ca704405a | ||
|
802c1c2937 | ||
|
3cb5fef6b6 | ||
|
6da2e0aa1e | ||
|
24f3ec7f33 | ||
|
a57b375b41 | ||
|
6cc9d53978 | ||
|
df32c05833 | ||
|
c0652adf4c | ||
|
6ea760a336 | ||
|
f704b94603 | ||
|
444a67cafa | ||
|
f91cbd5688 | ||
|
3073ca3e5a | ||
|
b47ab633e2 | ||
|
09a2ab39fe | ||
|
6cf54833f7 | ||
|
2ccdf21a1f | ||
|
cf8afc527e | ||
|
1d6f05f974 | ||
|
85751966e9 | ||
|
a7bc9d5351 | ||
|
42c006d07c | ||
|
1b9ca314b8 | ||
|
e72a360337 | ||
|
45108ddd53 | ||
|
e3401a0645 | ||
|
26b9100709 | ||
|
a568120e42 | ||
|
e57182c658 | ||
|
6354dbbbdf | ||
|
2b3e740569 | ||
|
40d934e378 | ||
|
e95d82748f | ||
|
30bd0b53db | ||
|
1893eca41a | ||
|
82067463b8 | ||
|
ce9c51d399 | ||
|
96176476f3 | ||
|
68c84264af | ||
|
69438a55ca | ||
|
8695b5e319 | ||
|
95970164ad | ||
|
f6c6e59a50 | ||
|
45143f9541 | ||
|
23244bb410 | ||
|
edb647667e | ||
|
8d3a302a17 | ||
|
1d2d32c847 | ||
|
d635b3fd3c | ||
|
0f281ef894 | ||
|
b18db4733c | ||
|
6e08fe337c | ||
|
2a2c0a0957 | ||
|
4230b6f3c9 | ||
|
aa171b45cb | ||
|
661d06c90a | ||
|
a9aa263d3a | ||
|
6208fc9cfd | ||
|
e1dd798482 | ||
|
c8a3f6f06a | ||
|
3b9984379c | ||
|
a1b60b1d42 | ||
|
b5850ebd4c | ||
|
ac0a62e494 | ||
|
54b4b0c56f | ||
|
033afde3b5 | ||
|
a07944a5bb | ||
|
32010055e1 | ||
|
971ea2217c | ||
|
d513a210c6 | ||
|
a1db64e7b1 | ||
|
0b9c4e1e74 | ||
|
248320fa55 | ||
|
d4e26707c7 | ||
|
99ea1056ac | ||
|
7bcf4effa5 | ||
|
e1df876b61 | ||
|
28ffb9638d | ||
|
1c20255504 | ||
|
1fd884b34f | ||
|
701687faab | ||
|
bbc3055feb | ||
|
95c69083c7 | ||
|
57a37b5832 | ||
|
d29ae1c462 | ||
|
df468fc482 | ||
|
31278bcc68 | ||
|
e7e86b68f4 | ||
|
a89d8995c3 | ||
|
dbc854d5f4 | ||
|
f1cd0e2daf | ||
|
90d32bd756 | ||
|
e99731ea85 | ||
|
15659ac6e6 | ||
|
3ef41845a9 | ||
|
c84e681581 | ||
|
c3cf3427b1 | ||
|
2c4f71d85b | ||
|
c6328affae | ||
|
aaef18295d | ||
|
14f0d2035e | ||
|
64afff6b9a | ||
|
6bddffbca4 | ||
|
81a88693c1 | ||
|
68541e66b7 | ||
|
672b593634 | ||
|
5769d3867d | ||
|
724ffa3756 | ||
|
5694b5ed30 | ||
|
a1184ceb4e | ||
|
02203c7739 | ||
|
4d709e0dd2 | ||
|
ae04f56dbd | ||
|
f80ff8c917 | ||
|
b4ce89bbf5 | ||
|
486b87d821 | ||
|
b3010a4624 | ||
|
7d53051ec8 | ||
|
ed893c5f47 | ||
|
a4eb3323da | ||
|
1da065e50e | ||
|
86bc9d506f | ||
|
eee45a9578 | ||
|
659f49a09a | ||
|
8fa9e85980 | ||
|
92a75c9563 | ||
|
7c7a30c472 | ||
|
ea271cd4e2 | ||
|
6a38d07a4c | ||
|
c4e5ee63bb | ||
|
862da2c0b1 | ||
|
545370d2b3 | ||
|
59220c63a6 | ||
|
86306dd45a | ||
|
98d2bfa0db | ||
|
aec48f159b | ||
|
ad7e433a7d | ||
|
5a60aa5050 | ||
|
ebea470875 | ||
|
d980e00961 | ||
|
987799f8fb | ||
|
d2f3604c1d | ||
|
72cc558fdc | ||
|
6bc3fe6e67 | ||
|
9398878048 | ||
|
ca19762e58 | ||
|
8764be07e2 | ||
|
2022a3ad96 | ||
|
65d9d416b4 | ||
|
fa2f9f1f21 | ||
|
c656cfbdce | ||
|
de829c0938 | ||
|
64443221aa | ||
|
9017e29741 | ||
|
0a22142d88 | ||
|
ac160f98a8 | ||
|
62e01a2a62 | ||
|
5660cebaf6 | ||
|
a7e588ceac | ||
|
5baf1c5536 | ||
|
9a2d9ad947 | ||
|
90b0cd44ac | ||
|
698e8008df | ||
|
1de4cc3ba8 | ||
|
0d66ad23c6 | ||
|
7f7741099b | ||
|
5a72dc6922 | ||
|
80ed02e72e | ||
|
8fb31e1b4d | ||
|
148f21415a | ||
|
1c31e07d34 | ||
|
55d566b72f | ||
|
60336c7423 | ||
|
7ae877bd3a | ||
|
c601fc6437 | ||
|
e5fec408c4 | ||
|
8156e9894e | ||
|
cacc212f12 | ||
|
d0f2c00f9f | ||
|
766427de0c | ||
|
a7b75c99a5 | ||
|
bae10a6582 | ||
|
c4cf90a3d2 | ||
|
15c49a3e08 | ||
|
ae87f6548a | ||
|
7833fa7396 | ||
|
9278f3acd2 | ||
|
e83ae34a3b | ||
|
e13bafc1ab | ||
|
0ea66329b8 | ||
|
634670e3ea | ||
|
dea60b11bc | ||
|
5e90f0a57b | ||
|
0b4542fcdf | ||
|
02bd2d2adf | ||
|
dce6fe6f2d | ||
|
fcae99f09b | ||
|
fb1b026d3d | ||
|
9f953fc944 | ||
|
909ea1a698 | ||
|
7231acd442 | ||
|
7814371a9a | ||
|
6166e2dd80 | ||
|
ee0c8a2635 | ||
|
2bebddefc0 | ||
|
fdbf3d3fec | ||
|
f9136cffe6 | ||
|
51d84b1869 | ||
|
13e040baee | ||
|
cc0d5539ba | ||
|
b53f61fc59 | ||
|
4e0e03403e | ||
|
928fccc15b | ||
|
bbaa3ab8bd | ||
|
5e3cb3a4ea | ||
|
f71ea5f3ea | ||
|
f469c25730 | ||
|
18469b6954 | ||
|
d01db4862b | ||
|
8b2adba8d6 | ||
|
d459e9abce | ||
|
c9abe1b1ff | ||
|
a0e6147bb5 | ||
|
b0f491d3c3 | ||
|
392da53f53 | ||
|
ae72b0fb70 | ||
|
a79d080ea8 | ||
|
ec85fd552d | ||
|
11db046fc7 | ||
|
938151a834 | ||
|
14e3b84073 | ||
|
56100f0fa7 | ||
|
5254ee2e2a | ||
|
355d004895 | ||
|
a336494f5d | ||
|
8270f7f0ca | ||
|
638a956a9e | ||
|
d395ebd28f | ||
|
c0d3faa84f | ||
|
3492c8b780 | ||
|
a8b2c257cd | ||
|
5e8d8dab82 | ||
|
b504c6eb39 | ||
|
d261c36cde | ||
|
fe4e452d68 | ||
|
d54a4fa223 | ||
|
45bd323cab | ||
|
8677dbded1 | ||
|
794ad5785d | ||
|
fa5b58968e | ||
|
e720f56ea8 | ||
|
7db53e6459 | ||
|
e287bd7f04 | ||
|
022435a90a | ||
|
6c99cc1700 | ||
|
fe5b190a7d | ||
|
77bab51696 | ||
|
77048f3e3b | ||
|
8b618f7439 | ||
|
8973207bb4 | ||
|
6ad1736832 | ||
|
9fca611c4a | ||
|
8e7164553f | ||
|
3b52811796 | ||
|
2e84b1db64 | ||
|
9f33068ab3 | ||
|
eaa3c67a5e | ||
|
1b9b1d15bc | ||
|
97f433a274 | ||
|
45a3655eaf | ||
|
81ffde92fb | ||
|
0be4cead20 | ||
|
f6dd32046e | ||
|
443a80f254 | ||
|
8017635a71 | ||
|
98f62b191a | ||
|
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 |
29
.github/ISSUE_TEMPLATE.md
vendored
Normal file
29
.github/ISSUE_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<!-- Check all that apply [x] -->
|
||||||
|
- Category
|
||||||
|
- [ ] fzf binary
|
||||||
|
- [ ] fzf-tmux script
|
||||||
|
- [ ] Key bindings
|
||||||
|
- [ ] Completion
|
||||||
|
- [ ] Vim
|
||||||
|
- [ ] Neovim
|
||||||
|
- [ ] Etc.
|
||||||
|
- OS
|
||||||
|
- [ ] Linux
|
||||||
|
- [ ] Mac OS X
|
||||||
|
- [ ] Windows
|
||||||
|
- [ ] Etc.
|
||||||
|
- Shell
|
||||||
|
- [ ] bash
|
||||||
|
- [ ] zsh
|
||||||
|
- [ ] fish
|
||||||
|
|
||||||
|
<!--
|
||||||
|
### Before submitting
|
||||||
|
|
||||||
|
- Make sure that you have the latest version of fzf
|
||||||
|
- If you use tmux, make sure $TERM is set to screen or screen-256color
|
||||||
|
- For more Vim stuff, check out https://github.com/junegunn/fzf.vim
|
||||||
|
|
||||||
|
Describe your problem or suggestion from here ...
|
||||||
|
-->
|
||||||
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,6 @@
|
|||||||
bin
|
bin
|
||||||
src/fzf/fzf_*
|
src/fzf/fzf-*
|
||||||
|
gopath
|
||||||
pkg
|
pkg
|
||||||
Gemfile.lock
|
Gemfile.lock
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
12
.travis.yml
12
.travis.yml
@@ -4,7 +4,7 @@ rvm:
|
|||||||
|
|
||||||
install:
|
install:
|
||||||
- sudo apt-get update
|
- sudo apt-get update
|
||||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev
|
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev libgpm-dev
|
||||||
- sudo add-apt-repository -y ppa:pi-rho/dev
|
- sudo add-apt-repository -y ppa:pi-rho/dev
|
||||||
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
||||||
- sudo apt-get update
|
- sudo apt-get update
|
||||||
@@ -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 ]
|
||||||
|
292
CHANGELOG.md
292
CHANGELOG.md
@@ -1,6 +1,298 @@
|
|||||||
CHANGELOG
|
CHANGELOG
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
0.13.0
|
||||||
|
------
|
||||||
|
- Added preview feature
|
||||||
|
- `--preview CMD`
|
||||||
|
- `--preview-window POS[:SIZE][:hidden]`
|
||||||
|
- `{}` in execute action is now replaced to the single-quoted (instead of
|
||||||
|
double-quoted) string of the current line
|
||||||
|
- Fixed to ignore control characters for bracketed paste mode
|
||||||
|
|
||||||
|
0.12.2
|
||||||
|
------
|
||||||
|
|
||||||
|
- 256-color capability detection does not require `256` in `$TERM`
|
||||||
|
- Added `print-query` action
|
||||||
|
- More named keys for binding; <kbd>F1</kbd> ~ <kbd>F10</kbd>,
|
||||||
|
<kbd>ALT-/</kbd>, <kbd>ALT-space</kbd>, and <kbd>ALT-enter</kbd>
|
||||||
|
- Added `jump` and `jump-accept` actions that implement [EasyMotion][em]-like
|
||||||
|
movement
|
||||||
|
![][jump]
|
||||||
|
|
||||||
|
[em]: https://github.com/easymotion/vim-easymotion
|
||||||
|
[jump]: https://cloud.githubusercontent.com/assets/700826/15367574/b3999dc4-1d64-11e6-85da-28ceeb1a9bc2.png
|
||||||
|
|
||||||
|
0.12.1
|
||||||
|
------
|
||||||
|
|
||||||
|
- Ranking algorithm introduced in 0.12.0 is now universally applied
|
||||||
|
- Fixed invalid cache reference in exact mode
|
||||||
|
- Fixes and improvements in Vim plugin and shell extensions
|
||||||
|
|
||||||
|
0.12.0
|
||||||
|
------
|
||||||
|
|
||||||
|
- Enhanced ranking algorithm
|
||||||
|
- Minor bug fixes
|
||||||
|
|
||||||
|
0.11.4
|
||||||
|
------
|
||||||
|
|
||||||
|
- Added `--hscroll-off=COL` option (default: 10) (#513)
|
||||||
|
- Some fixes in Vim plugin and shell extensions
|
||||||
|
|
||||||
|
0.11.3
|
||||||
|
------
|
||||||
|
|
||||||
|
- Graceful exit on SIGTERM (#482)
|
||||||
|
- `$SHELL` instead of `sh` for `execute` action and `$FZF_DEFAULT_COMMAND` (#481)
|
||||||
|
- Changes in fuzzy completion API
|
||||||
|
- [`_fzf_compgen_{path,dir}`](https://github.com/junegunn/fzf/commit/9617647)
|
||||||
|
- [`_fzf_complete_COMMAND_post`](https://github.com/junegunn/fzf/commit/8206746)
|
||||||
|
for post-processing
|
||||||
|
|
||||||
|
0.11.2
|
||||||
|
------
|
||||||
|
|
||||||
|
- `--tiebreak` now accepts comma-separated list of sort criteria
|
||||||
|
- Each criterion should appear only once in the list
|
||||||
|
- `index` is only allowed at the end of the list
|
||||||
|
- `index` is implicitly appended to the list when not specified
|
||||||
|
- Default is `length` (or equivalently `length,index`)
|
||||||
|
- `begin` criterion will ignore leading whitespaces when calculating the index
|
||||||
|
- Added `toggle-in` and `toggle-out` actions
|
||||||
|
- Switch direction depending on `--reverse`-ness
|
||||||
|
- `export FZF_DEFAULT_OPTS="--bind tab:toggle-out,shift-tab:toggle-in"`
|
||||||
|
- Reduced the initial delay when `--tac` is not given
|
||||||
|
- fzf defers the initial rendering of the screen up to 100ms if the input
|
||||||
|
stream is ongoing to prevent unnecessary redraw during the initial
|
||||||
|
phase. However, 100ms delay is quite noticeable and might give the
|
||||||
|
impression that fzf is not snappy enough. This commit reduces the
|
||||||
|
maximum delay down to 20ms when `--tac` is not specified, in which case
|
||||||
|
the input list quickly fills the entire screen.
|
||||||
|
|
||||||
|
0.11.1
|
||||||
|
------
|
||||||
|
|
||||||
|
- Added `--tabstop=SPACES` option
|
||||||
|
|
||||||
|
0.11.0
|
||||||
|
------
|
||||||
|
|
||||||
|
- Added OR operator for extended-search mode
|
||||||
|
- Added `--execute-multi` action
|
||||||
|
- Fixed incorrect cursor position when unicode wide characters are used in
|
||||||
|
`--prompt`
|
||||||
|
- Fixes and improvements in shell extensions
|
||||||
|
|
||||||
|
0.10.9
|
||||||
|
------
|
||||||
|
|
||||||
|
- Extended-search mode is now enabled by default
|
||||||
|
- `--extended-exact` is deprecated and instead we have `--exact` for
|
||||||
|
orthogonally controlling "exactness" of search
|
||||||
|
- Fixed not to display non-printable characters
|
||||||
|
- Added `double-click` for `--bind` option
|
||||||
|
- More robust handling of SIGWINCH
|
||||||
|
|
||||||
|
0.10.8
|
||||||
|
------
|
||||||
|
|
||||||
|
- Fixed panic when trying to set colors after colors are disabled (#370)
|
||||||
|
|
||||||
|
0.10.7
|
||||||
|
------
|
||||||
|
|
||||||
|
- Fixed unserialized interrupt handling during execute action which often
|
||||||
|
caused invalid memory access and crash
|
||||||
|
- Changed `--tiebreak=length` (default) to use trimmed length when `--nth` is
|
||||||
|
used
|
||||||
|
|
||||||
|
0.10.6
|
||||||
|
------
|
||||||
|
|
||||||
|
- Replaced `--header-file` with `--header` option
|
||||||
|
- `--header` and `--header-lines` can be used together
|
||||||
|
- Changed exit status
|
||||||
|
- 0: Okay
|
||||||
|
- 1: No match
|
||||||
|
- 2: Error
|
||||||
|
- 130: Interrupted
|
||||||
|
- 64-bit linux binary is statically-linked with ncurses to avoid
|
||||||
|
compatibility issues.
|
||||||
|
|
||||||
|
0.10.5
|
||||||
|
------
|
||||||
|
|
||||||
|
- `'`-prefix to unquote the term in `--extended-exact` mode
|
||||||
|
- Backward scan when `--tiebreak=end` is set
|
||||||
|
|
||||||
|
0.10.4
|
||||||
|
------
|
||||||
|
|
||||||
|
- Fixed to remove ANSI code from output when `--with-nth` is set
|
||||||
|
|
||||||
|
0.10.3
|
||||||
|
------
|
||||||
|
|
||||||
|
- Fixed slow performance of `--with-nth` when used with `--delimiter`
|
||||||
|
- Regular expression engine of Golang as of now is very slow, so the fixed
|
||||||
|
version will treat the given delimiter pattern as a plain string instead
|
||||||
|
of a regular expression unless it contains special characters and is
|
||||||
|
a valid regular expression.
|
||||||
|
- Simpler regular expression for delimiter for better performance
|
||||||
|
|
||||||
|
0.10.2
|
||||||
|
------
|
||||||
|
|
||||||
|
### Fixes and improvements
|
||||||
|
|
||||||
|
- Improvement in perceived response time of queries
|
||||||
|
- Eager, efficient rune array conversion
|
||||||
|
- Graceful exit when failed to initialize ncurses (invalid $TERM)
|
||||||
|
- Improved ranking algorithm when `--nth` option is set
|
||||||
|
- Changed the default command not to fail when there are files whose names
|
||||||
|
start with dash
|
||||||
|
|
||||||
|
0.10.1
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- Added `--margin` option
|
||||||
|
- Added options for sticky header
|
||||||
|
- `--header-file`
|
||||||
|
- `--header-lines`
|
||||||
|
- Added `cancel` action which clears the input or closes the finder when the
|
||||||
|
input is already empty
|
||||||
|
- e.g. `export FZF_DEFAULT_OPTS="--bind esc:cancel"`
|
||||||
|
- Added `delete-char/eof` action to differentiate `CTRL-D` and `DEL`
|
||||||
|
|
||||||
|
### Minor improvements/fixes
|
||||||
|
|
||||||
|
- Fixed to allow binding colon and comma keys
|
||||||
|
- Fixed ANSI processor to handle color regions spanning multiple lines
|
||||||
|
|
||||||
|
0.10.0
|
||||||
|
------
|
||||||
|
|
||||||
|
### New features
|
||||||
|
|
||||||
|
- More actions for `--bind`
|
||||||
|
- `select-all`
|
||||||
|
- `deselect-all`
|
||||||
|
- `toggle-all`
|
||||||
|
- `ignore`
|
||||||
|
- `execute(...)` action for running arbitrary command without leaving fzf
|
||||||
|
- `fzf --bind "ctrl-m:execute(less {})"`
|
||||||
|
- `fzf --bind "ctrl-t:execute(tmux new-window -d 'vim {}')"`
|
||||||
|
- If the command contains parentheses, use any of the follows alternative
|
||||||
|
notations to avoid parse errors
|
||||||
|
- `execute[...]`
|
||||||
|
- `execute~...~`
|
||||||
|
- `execute!...!`
|
||||||
|
- `execute@...@`
|
||||||
|
- `execute#...#`
|
||||||
|
- `execute$...$`
|
||||||
|
- `execute%...%`
|
||||||
|
- `execute^...^`
|
||||||
|
- `execute&...&`
|
||||||
|
- `execute*...*`
|
||||||
|
- `execute;...;`
|
||||||
|
- `execute/.../`
|
||||||
|
- `execute|...|`
|
||||||
|
- `execute:...`
|
||||||
|
- This is the special form that frees you from parse errors as it
|
||||||
|
does not expect the closing character
|
||||||
|
- The catch is that it should be the last one in the
|
||||||
|
comma-separated list
|
||||||
|
- Added support for optional search history
|
||||||
|
- `--history HISTORY_FILE`
|
||||||
|
- When used, `CTRL-N` and `CTRL-P` are automatically remapped to
|
||||||
|
`next-history` and `previous-history`
|
||||||
|
- `--history-size MAX_ENTRIES` (default: 1000)
|
||||||
|
- Cyclic scrolling can be enabled with `--cycle`
|
||||||
|
- Fixed the bug where the spinner was not spinning on idle input stream
|
||||||
|
- e.g. `sleep 100 | fzf`
|
||||||
|
|
||||||
|
### Minor improvements/fixes
|
||||||
|
|
||||||
|
- Added synonyms for key names that can be specified for `--bind`,
|
||||||
|
`--toggle-sort`, and `--expect`
|
||||||
|
- Fixed the color of multi-select marker on the current line
|
||||||
|
- Fixed to allow `^pattern$` in extended-search mode
|
||||||
|
|
||||||
|
|
||||||
|
0.9.13
|
||||||
|
------
|
||||||
|
|
||||||
|
### 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
|
||||||
-----
|
-----
|
||||||
|
|
||||||
|
2
LICENSE
2
LICENSE
@@ -1,6 +1,6 @@
|
|||||||
The MIT License (MIT)
|
The MIT License (MIT)
|
||||||
|
|
||||||
Copyright (c) 2015 Junegunn Choi
|
Copyright (c) 2016 Junegunn Choi
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
324
README.md
324
README.md
@@ -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,18 +16,19 @@ 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
|
||||||
------------
|
------------
|
||||||
|
|
||||||
fzf project consists of the followings:
|
fzf project consists of the following:
|
||||||
|
|
||||||
- `fzf` executable
|
- `fzf` executable
|
||||||
- `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,26 +45,15 @@ 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.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
brew reinstall --HEAD fzf
|
brew install fzf
|
||||||
|
|
||||||
# Install shell extensions
|
# Install shell extensions
|
||||||
/usr/local/Cellar/fzf/HEAD/install
|
/usr/local/opt/fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Install as Vim plugin
|
#### Install as Vim plugin
|
||||||
@@ -78,7 +68,7 @@ Or you can have [vim-plug](https://github.com/junegunn/vim-plug) manage fzf
|
|||||||
(recommended):
|
(recommended):
|
||||||
|
|
||||||
```vim
|
```vim
|
||||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
|
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Upgrading fzf
|
#### Upgrading 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 update; brew reinstall fzf`
|
||||||
- vim-plug: `:PlugUpdate fzf`
|
- vim-plug: `:PlugUpdate fzf`
|
||||||
|
|
||||||
Usage
|
Usage
|
||||||
@@ -118,24 +108,41 @@ vim $(fzf)
|
|||||||
- Mouse: scroll, click, double-click; shift-click and shift-scroll on
|
- Mouse: scroll, click, double-click; shift-click and shift-scroll on
|
||||||
multi-select mode
|
multi-select mode
|
||||||
|
|
||||||
#### Extended-search mode
|
#### Search syntax
|
||||||
|
|
||||||
With `-x` or `--extended` option, fzf will start in "extended-search mode".
|
Unless otherwise specified, fzf starts in "extended-search mode" where you can
|
||||||
|
type in multiple search terms delimited by spaces. e.g. `^music .mp3$ sbtrkt
|
||||||
|
!rmx`
|
||||||
|
|
||||||
In this mode, you can specify multiple patterns delimited by spaces,
|
| Token | Match type | Description |
|
||||||
such as: `^music .mp3$ sbtrkt !rmx`
|
| -------- | -------------------- | -------------------------------- |
|
||||||
|
| `sbtrkt` | fuzzy-match | Items that match `sbtrkt` |
|
||||||
|
| `^music` | prefix-exact-match | Items that start with `music` |
|
||||||
|
| `.mp3$` | suffix-exact-match | Items that end with `.mp3` |
|
||||||
|
| `'wild` | exact-match (quoted) | Items that include `wild` |
|
||||||
|
| `!rmx` | inverse-fuzzy-match | Items that do not match `rmx` |
|
||||||
|
| `!'fire` | inverse-exact-match | Items that do not include `fire` |
|
||||||
|
|
||||||
| Token | Description | Match type |
|
If you don't prefer fuzzy matching and do not wish to "quote" every word,
|
||||||
| -------- | -------------------------------- | -------------------- |
|
start fzf with `-e` or `--exact` option. Note that when `--exact` is set,
|
||||||
| `^music` | Items that start with `music` | prefix-exact-match |
|
`'`-prefix "unquotes" the term.
|
||||||
| `.mp3$` | Items that end with `.mp3` | suffix-exact-match |
|
|
||||||
| `sbtrkt` | Items that match `sbtrkt` | fuzzy-match |
|
|
||||||
| `!rmx` | Items that do not match `rmx` | inverse-fuzzy-match |
|
|
||||||
| `'wild` | Items that include `wild` | exact-match (quoted) |
|
|
||||||
| `!'fire` | Items that do not include `fire` | inverse-exact-match |
|
|
||||||
|
|
||||||
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
A single bar character term acts as an OR operator. For example, the following
|
||||||
fzf with `-e` or `--extended-exact` option.
|
query matches entries that start with `core` and end with either `go`, `rb`,
|
||||||
|
or `py`.
|
||||||
|
|
||||||
|
```
|
||||||
|
^core go$ | rb$ | py$
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Environment variables
|
||||||
|
|
||||||
|
- `FZF_DEFAULT_COMMAND`
|
||||||
|
- Default command to use when input is tty
|
||||||
|
- e.g. `export FZF_DEFAULT_COMMAND='ag -g ""'`
|
||||||
|
- `FZF_DEFAULT_OPTS`
|
||||||
|
- Default options
|
||||||
|
- e.g. `export FZF_DEFAULT_OPTS="--reverse --inline-info"`
|
||||||
|
|
||||||
Examples
|
Examples
|
||||||
--------
|
--------
|
||||||
@@ -144,29 +151,6 @@ Many useful examples can be found on [the wiki
|
|||||||
page](https://github.com/junegunn/fzf/wiki/examples). Feel free to add your
|
page](https://github.com/junegunn/fzf/wiki/examples). Feel free to add your
|
||||||
own as well.
|
own as well.
|
||||||
|
|
||||||
Key bindings for command line
|
|
||||||
-----------------------------
|
|
||||||
|
|
||||||
The install script will setup the following key bindings for bash, zsh, and
|
|
||||||
fish.
|
|
||||||
|
|
||||||
- `CTRL-T` - Paste the selected file path(s) into the command line
|
|
||||||
- `CTRL-R` - Paste the selected command from history into the command line
|
|
||||||
- Sort is disabled by default. Press `CTRL-R` again to toggle sort.
|
|
||||||
- `ALT-C` - cd into the selected directory
|
|
||||||
|
|
||||||
If you're on a tmux session, `CTRL-T` will launch fzf in a new split-window. You
|
|
||||||
may disable this tmux integration by setting `FZF_TMUX` to 0, or change the
|
|
||||||
height of the window with `FZF_TMUX_HEIGHT` (e.g. `20`, `50%`).
|
|
||||||
|
|
||||||
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
|
|
||||||
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 +170,30 @@ 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
|
Key bindings for command line
|
||||||
-------------------------
|
-----------------------------
|
||||||
|
|
||||||
|
The install script will setup the following key bindings for bash, zsh, and
|
||||||
|
fish.
|
||||||
|
|
||||||
|
- `CTRL-T` - Paste the selected files and directories onto the command line
|
||||||
|
- Set `FZF_CTRL_T_COMMAND` to override the default command
|
||||||
|
- `CTRL-R` - Paste the selected command from history onto the command line
|
||||||
|
- Sort is disabled by default to respect chronological ordering
|
||||||
|
- Press `CTRL-R` again to toggle sort
|
||||||
|
- `ALT-C` - cd into the selected directory
|
||||||
|
- Set `FZF_ALT_C_COMMAND` to override the default command
|
||||||
|
|
||||||
|
If you're on a tmux session, fzf will start in a split pane. You may disable
|
||||||
|
this tmux integration by setting `FZF_TMUX` to 0, or change the height of the
|
||||||
|
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
|
||||||
|
~/.fzf.bash` in your .bashrc, so that it correctly sets up key bindings for vi
|
||||||
|
mode.
|
||||||
|
|
||||||
|
Fuzzy completion for bash and zsh
|
||||||
|
---------------------------------
|
||||||
|
|
||||||
#### Files and directories
|
#### Files and directories
|
||||||
|
|
||||||
@@ -254,11 +260,33 @@ export FZF_COMPLETION_TRIGGER='~~'
|
|||||||
|
|
||||||
# Options to fzf command
|
# Options to fzf command
|
||||||
export FZF_COMPLETION_OPTS='+c -x'
|
export FZF_COMPLETION_OPTS='+c -x'
|
||||||
|
|
||||||
|
# Use ag instead of the default find command for listing candidates.
|
||||||
|
# - The first argument to the function is the base path to start traversal
|
||||||
|
# - Note that ag only lists files not directories
|
||||||
|
# - See the source code (completion.{bash,zsh}) for the details.
|
||||||
|
_fzf_compgen_path() {
|
||||||
|
ag -g "" "$1"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Supported commands
|
||||||
|
|
||||||
|
On bash, fuzzy completion is enabled only for a predefined set of commands
|
||||||
|
(`complete | grep _fzf` to see the list). But you can enable it for other
|
||||||
|
commands as well like follows.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# There are also _fzf_path_completion and _fzf_dir_completion
|
||||||
|
complete -F _fzf_file_completion -o default -o bashdefault doge
|
||||||
```
|
```
|
||||||
|
|
||||||
Usage as Vim plugin
|
Usage as Vim plugin
|
||||||
-------------------
|
-------------------
|
||||||
|
|
||||||
|
This repository only enables basic integration with Vim. If you're looking for
|
||||||
|
more, check out [fzf.vim](https://github.com/junegunn/fzf.vim) project.
|
||||||
|
|
||||||
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
||||||
|
|
||||||
#### `:FZF[!]`
|
#### `:FZF[!]`
|
||||||
@@ -274,42 +302,25 @@ 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])`
|
||||||
|
|
||||||
For more advanced uses, you can call `fzf#run()` function which returns the list
|
For more advanced uses, you can use `fzf#run()` function with the following
|
||||||
of the selected items.
|
options.
|
||||||
|
|
||||||
`fzf#run()` may take an options-dictionary:
|
|
||||||
|
|
||||||
| Option name | Type | Description |
|
| Option name | Type | Description |
|
||||||
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
||||||
@@ -317,88 +328,32 @@ 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) |
|
||||||
|
|
||||||
##### Examples
|
Examples can be found on [the wiki
|
||||||
|
|
||||||
If `sink` option is not given, `fzf#run` will simply return the list.
|
|
||||||
|
|
||||||
```vim
|
|
||||||
let items = fzf#run({ 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
|
||||||
```
|
|
||||||
|
|
||||||
But if `sink` is given as a string, the command will be executed for each
|
|
||||||
selected item.
|
|
||||||
|
|
||||||
```vim
|
|
||||||
" Each selected item will be opened in a new tab
|
|
||||||
let items = fzf#run({ 'sink': 'tabe', 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
|
||||||
```
|
|
||||||
|
|
||||||
We can also use a Vim list as the source as follows:
|
|
||||||
|
|
||||||
```vim
|
|
||||||
" Choose a color scheme with fzf
|
|
||||||
nnoremap <silent> <Leader>C :call fzf#run({
|
|
||||||
\ 'source':
|
|
||||||
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
|
|
||||||
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
|
|
||||||
\ 'sink': 'colo',
|
|
||||||
\ 'options': '+m',
|
|
||||||
\ 'left': 20,
|
|
||||||
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
|
|
||||||
\ })<CR>
|
|
||||||
```
|
|
||||||
|
|
||||||
`sink` option can be a function reference. The following example creates a
|
|
||||||
handy mapping that selects an open buffer.
|
|
||||||
|
|
||||||
```vim
|
|
||||||
" List of buffers
|
|
||||||
function! BufList()
|
|
||||||
redir => ls
|
|
||||||
silent ls
|
|
||||||
redir END
|
|
||||||
return split(ls, '\n')
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
function! BufOpen(e)
|
|
||||||
execute 'buffer '. matchstr(a:e, '^[ 0-9]*')
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
|
||||||
\ 'source': reverse(BufList()),
|
|
||||||
\ 'sink': function('BufOpen'),
|
|
||||||
\ 'options': '+m',
|
|
||||||
\ 'down': '40%'
|
|
||||||
\ })<CR>
|
|
||||||
```
|
|
||||||
|
|
||||||
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
|
||||||
----
|
----
|
||||||
|
|
||||||
#### Rendering issues
|
#### Rendering issues
|
||||||
|
|
||||||
If you have any rendering issues, check the followings:
|
If you have any rendering issues, check the following:
|
||||||
|
|
||||||
1. Make sure `$TERM` is correctly set. fzf will use 256-color only if it
|
1. Make sure `$TERM` is correctly set. fzf will use 256-color only if it
|
||||||
contains `256` (e.g. `xterm-256color`)
|
contains `256` (e.g. `xterm-256color`)
|
||||||
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`
|
||||||
@@ -409,13 +364,16 @@ filtering:
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Feed the output of ag into fzf
|
# Feed the output of ag into fzf
|
||||||
ag -l -g "" | fzf
|
ag -g "" | fzf
|
||||||
|
|
||||||
# Setting ag as the default source for fzf
|
# Setting ag as the default source for fzf
|
||||||
export FZF_DEFAULT_COMMAND='ag -l -g ""'
|
export FZF_DEFAULT_COMMAND='ag -g ""'
|
||||||
|
|
||||||
# Now fzf (w/o pipe) will use ag instead of find
|
# Now fzf (w/o pipe) will use ag instead of find
|
||||||
fzf
|
fzf
|
||||||
|
|
||||||
|
# To apply the command to CTRL-T as well
|
||||||
|
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `git ls-tree` for fast traversal
|
#### `git ls-tree` for fast traversal
|
||||||
@@ -426,42 +384,8 @@ speed of the traversal.
|
|||||||
```sh
|
```sh
|
||||||
export FZF_DEFAULT_COMMAND='
|
export FZF_DEFAULT_COMMAND='
|
||||||
(git ls-tree -r --name-only HEAD ||
|
(git ls-tree -r --name-only HEAD ||
|
||||||
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
find . -path "*/\.*" -prune -o -type f -print -o -type l -print |
|
||||||
```
|
sed s/^..//) 2> /dev/null'
|
||||||
|
|
||||||
#### 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
|
||||||
@@ -472,27 +396,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
|
|
||||||
|
|
||||||
Use iconv to convert NFD paths to NFC:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
find . | iconv -f utf-8-mac -t utf8//ignore | fzf
|
|
||||||
```
|
```
|
||||||
|
|
||||||
License
|
License
|
||||||
|
72
bin/fzf-tmux
72
bin/fzf-tmux
@@ -8,6 +8,7 @@ skip=""
|
|||||||
swap=""
|
swap=""
|
||||||
close=""
|
close=""
|
||||||
term=""
|
term=""
|
||||||
|
[ -n "$LINES" ] && lines=$LINES || lines=$(tput lines)
|
||||||
while [ $# -gt 0 ]; do
|
while [ $# -gt 0 ]; do
|
||||||
arg="$1"
|
arg="$1"
|
||||||
case "$arg" in
|
case "$arg" in
|
||||||
@@ -60,7 +61,7 @@ while [ $# -gt 0 ]; do
|
|||||||
if [[ "$arg" =~ ^.l ]]; then
|
if [[ "$arg" =~ ^.l ]]; then
|
||||||
[ -n "$COLUMNS" ] && max=$COLUMNS || max=$(tput cols)
|
[ -n "$COLUMNS" ] && max=$COLUMNS || max=$(tput cols)
|
||||||
else
|
else
|
||||||
[ -n "$LINES" ] && max=$LINES || max=$(tput lines)
|
max=$lines
|
||||||
fi
|
fi
|
||||||
size=$(( max - size ))
|
size=$(( max - size ))
|
||||||
[ $size -lt 0 ] && size=0
|
[ $size -lt 0 ] && size=0
|
||||||
@@ -82,46 +83,79 @@ while [ $# -gt 0 ]; do
|
|||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
|
|
||||||
if [ -z "$TMUX_PANE" ]; then
|
if ! [ -n "$TMUX" -a "$lines" -gt 15 ]; then
|
||||||
fzf "${args[@]}"
|
fzf "${args[@]}"
|
||||||
exit $?
|
exit $?
|
||||||
fi
|
fi
|
||||||
|
|
||||||
set -e
|
# Handle zoomed tmux pane by moving it to a temp window
|
||||||
|
if tmux list-panes -F '#F' | grep -q Z; then
|
||||||
|
zoomed=1
|
||||||
|
original_window=$(tmux display-message -p "#{window_id}")
|
||||||
|
tmp_window=$(tmux new-window -d -P -F "#{window_id}" "bash -c 'while :; do for c in \\| / - \\\\; do sleep 0.2; printf \"\\r\$c fzf-tmux is running\\r\"; done; done'")
|
||||||
|
tmux swap-pane -t $tmp_window \; select-window -t $tmp_window
|
||||||
|
fi
|
||||||
|
|
||||||
# Build arguments to fzf
|
set -e
|
||||||
[ ${#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
|
||||||
fifo1=/tmp/fzf-fifo1-$id
|
argsf="${TMPDIR:-/tmp}/fzf-args-$id"
|
||||||
fifo2=/tmp/fzf-fifo2-$id
|
fifo1="${TMPDIR:-/tmp}/fzf-fifo1-$id"
|
||||||
fifo3=/tmp/fzf-fifo3-$id
|
fifo2="${TMPDIR:-/tmp}/fzf-fifo2-$id"
|
||||||
|
fifo3="${TMPDIR:-/tmp}/fzf-fifo3-$id"
|
||||||
cleanup() {
|
cleanup() {
|
||||||
rm -f $fifo1 $fifo2 $fifo3
|
rm -f $argsf $fifo1 $fifo2 $fifo3
|
||||||
|
|
||||||
|
# Remove temp window if we were zoomed
|
||||||
|
if [ -n "$zoomed" ]; then
|
||||||
|
tmux swap-pane -t $original_window \; \
|
||||||
|
select-window -t $original_window \; \
|
||||||
|
kill-window -t $tmp_window \; \
|
||||||
|
resize-pane -Z
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
trap cleanup EXIT SIGINT SIGTERM
|
trap cleanup EXIT SIGINT SIGTERM
|
||||||
|
|
||||||
fail() {
|
fail() {
|
||||||
>&2 echo "$1"
|
>&2 echo "$1"
|
||||||
exit 1
|
exit 2
|
||||||
}
|
}
|
||||||
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 TERM=$TERM "
|
||||||
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
||||||
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
||||||
|
|
||||||
mkfifo $fifo2
|
mkfifo -m o+w $fifo2
|
||||||
mkfifo $fifo3
|
mkfifo -m o+w $fifo3
|
||||||
|
|
||||||
|
# Build arguments to fzf
|
||||||
|
opts=""
|
||||||
|
for arg in "${args[@]}"; do
|
||||||
|
arg="${arg//\\/\\\\}"
|
||||||
|
arg="${arg//\"/\\\"}"
|
||||||
|
arg="${arg//\`/\\\`}"
|
||||||
|
arg="${arg//$/\\$}"
|
||||||
|
opts="$opts \"$arg\""
|
||||||
|
done
|
||||||
|
|
||||||
if [ -n "$term" -o -t 0 ]; then
|
if [ -n "$term" -o -t 0 ]; then
|
||||||
tmux set-window-option -q synchronize-panes off \;\
|
cat <<< "\"$fzf\" $opts > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||||
split-window $opt "cd $(printf %q "$PWD");$envs"' sh -c "'$fzf' '"$fzf_args"' > '$fifo2'; echo \$? > '$fifo3' '"$close"'"' $swap
|
tmux set-window-option synchronize-panes off \;\
|
||||||
|
set-window-option remain-on-exit off \;\
|
||||||
|
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap \
|
||||||
|
> /dev/null 2>&1
|
||||||
else
|
else
|
||||||
mkfifo $fifo1
|
mkfifo $fifo1
|
||||||
tmux set-window-option -q synchronize-panes off \;\
|
cat <<< "\"$fzf\" $opts < $fifo1 > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
||||||
split-window $opt "$envs"' sh -c "'$fzf' '"$fzf_args"' < '$fifo1' > '$fifo2'; echo \$? > '$fifo3' '"$close"'"' $swap
|
tmux set-window-option synchronize-panes off \;\
|
||||||
|
set-window-option remain-on-exit off \;\
|
||||||
|
split-window $opt "$envs bash $argsf" $swap \
|
||||||
|
> /dev/null 2>&1
|
||||||
cat <&0 > $fifo1 &
|
cat <&0 > $fifo1 &
|
||||||
fi
|
fi
|
||||||
cat $fifo2
|
cat $fifo2
|
||||||
[ "$(cat $fifo3)" = '0' ]
|
exit "$(cat $fifo3)"
|
||||||
|
|
||||||
|
10
fzf
10
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}"
|
||||||
@@ -368,7 +370,7 @@ class FZF
|
|||||||
+i Case-sensitive match
|
+i Case-sensitive match
|
||||||
-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 the item using index expressions for search
|
||||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||||
|
|
||||||
@@ -394,7 +396,7 @@ class FZF
|
|||||||
|
|
||||||
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
|
||||||
FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")] + $/ + $/
|
FZF_DEFAULT_OPTS Default options (e.g. "-x -m --sort 10000")] + $/ + $/
|
||||||
exit x
|
exit x
|
||||||
end
|
end
|
||||||
|
|
||||||
|
277
install
277
install
@@ -1,28 +1,91 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
version=0.9.7
|
set -u
|
||||||
|
|
||||||
cd $(dirname $BASH_SOURCE)
|
[[ "$@" =~ --pre ]] && version=0.13.0 pre=1 ||
|
||||||
fzf_base=$(pwd)
|
version=0.13.0 pre=0
|
||||||
|
|
||||||
|
auto_completion=
|
||||||
|
key_bindings=
|
||||||
|
update_config=2
|
||||||
|
binary_arch=
|
||||||
|
|
||||||
|
help() {
|
||||||
|
cat << EOF
|
||||||
|
usage: $0 [OPTIONS]
|
||||||
|
|
||||||
|
--help Show this message
|
||||||
|
--bin Download fzf binary only; Do not generate ~/.fzf.{bash,zsh}
|
||||||
|
--all Download fzf binary and update configuration files
|
||||||
|
to enable key bindings and fuzzy completion
|
||||||
|
--[no-]key-bindings Enable/disable key bindings (CTRL-T, CTRL-R, ALT-C)
|
||||||
|
--[no-]completion Enable/disable fuzzy completion (bash & zsh)
|
||||||
|
--[no-]update-rc Whether or not to update shell configuration files
|
||||||
|
|
||||||
|
--32 Download 32-bit binary
|
||||||
|
--64 Download 64-bit binary
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
for opt in "$@"; do
|
||||||
|
case $opt in
|
||||||
|
--help)
|
||||||
|
help
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
--all)
|
||||||
|
auto_completion=1
|
||||||
|
key_bindings=1
|
||||||
|
update_config=1
|
||||||
|
;;
|
||||||
|
--key-bindings) key_bindings=1 ;;
|
||||||
|
--no-key-bindings) key_bindings=0 ;;
|
||||||
|
--completion) auto_completion=1 ;;
|
||||||
|
--no-completion) auto_completion=0 ;;
|
||||||
|
--update-rc) update_config=1 ;;
|
||||||
|
--no-update-rc) update_config=0 ;;
|
||||||
|
--32) binary_arch=386 ;;
|
||||||
|
--64) binary_arch=amd64 ;;
|
||||||
|
--bin|--pre) ;;
|
||||||
|
*)
|
||||||
|
echo "unknown option: $opt"
|
||||||
|
help
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||||
|
fzf_base="$(pwd)"
|
||||||
|
|
||||||
ask() {
|
ask() {
|
||||||
read -p "$1 ([y]/n) " -n 1 -r
|
# If stdin is a tty, we are "interactive".
|
||||||
|
# non-interactive shell: wait for a linefeed
|
||||||
|
# interactive shell: continue after a single keypress
|
||||||
|
read_n=$([ -t 0 ] && echo "-n 1")
|
||||||
|
|
||||||
|
read -p "$1 ([y]/n) " $read_n -r
|
||||||
echo
|
echo
|
||||||
[[ ! $REPLY =~ ^[Nn]$ ]]
|
[[ $REPLY =~ ^[Nn]$ ]]
|
||||||
}
|
}
|
||||||
|
|
||||||
check_binary() {
|
check_binary() {
|
||||||
echo -n " - Checking fzf executable ... "
|
echo -n " - Checking fzf executable ... "
|
||||||
local output=$("$fzf_base"/bin/fzf --version 2>&1)
|
local output
|
||||||
if [ "$version" = "$output" ]; then
|
output=$("$fzf_base"/bin/fzf --version 2>&1)
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
echo "Error: $output"
|
||||||
|
binary_error="Invalid binary"
|
||||||
|
elif [ "$version" != "$output" ]; then
|
||||||
|
echo "$output != $version"
|
||||||
|
binary_error="Invalid version"
|
||||||
|
else
|
||||||
echo "$output"
|
echo "$output"
|
||||||
binary_error=""
|
binary_error=""
|
||||||
else
|
return 0
|
||||||
echo "$output != $version"
|
|
||||||
rm -f "$fzf_base"/bin/fzf
|
|
||||||
binary_error="Invalid binary"
|
|
||||||
return 1
|
|
||||||
fi
|
fi
|
||||||
|
rm -f "$fzf_base"/bin/fzf
|
||||||
|
return 1
|
||||||
}
|
}
|
||||||
|
|
||||||
symlink() {
|
symlink() {
|
||||||
@@ -36,13 +99,27 @@ symlink() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
link_fzf_in_path() {
|
||||||
|
if which_fzf="$(command -v fzf)"; then
|
||||||
|
echo " - Found in \$PATH"
|
||||||
|
echo " - Creating symlink: $which_fzf -> bin/fzf"
|
||||||
|
(cd "$fzf_base"/bin && rm -f fzf && ln -sf "$which_fzf" fzf)
|
||||||
|
check_binary && return
|
||||||
|
fi
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
download() {
|
download() {
|
||||||
echo "Downloading bin/fzf ..."
|
echo "Downloading bin/fzf ..."
|
||||||
if [[ ! $1 =~ dev && -x "$fzf_base"/bin/fzf ]]; then
|
if [ $pre = 0 ]; then
|
||||||
echo " - Already exists"
|
if [ -x "$fzf_base"/bin/fzf ]; then
|
||||||
check_binary && return
|
echo " - Already exists"
|
||||||
elif [ -x "$fzf_base"/bin/$1 ]; then
|
check_binary && return
|
||||||
symlink $1 && check_binary && return
|
fi
|
||||||
|
if [ -x "$fzf_base"/bin/$1 ]; then
|
||||||
|
symlink $1 && check_binary && return
|
||||||
|
fi
|
||||||
|
link_fzf_in_path && return
|
||||||
fi
|
fi
|
||||||
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
@@ -51,9 +128,9 @@ download() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
local url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}.tgz
|
local url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}.tgz
|
||||||
if which curl > /dev/null; then
|
if command -v curl > /dev/null; then
|
||||||
curl -fL $url | tar -xz
|
curl -fL $url | tar -xz
|
||||||
elif which wget > /dev/null; then
|
elif command -v wget > /dev/null; then
|
||||||
wget -O - $url | tar -xz
|
wget -O - $url | tar -xz
|
||||||
else
|
else
|
||||||
binary_error="curl or wget not found"
|
binary_error="curl or wget not found"
|
||||||
@@ -73,25 +150,19 @@ archi=$(uname -sm)
|
|||||||
binary_available=1
|
binary_available=1
|
||||||
binary_error=""
|
binary_error=""
|
||||||
case "$archi" in
|
case "$archi" in
|
||||||
Darwin\ x86_64) download fzf-$version-darwin_amd64 ;;
|
Darwin\ x86_64) download fzf-$version-darwin_${binary_arch:-amd64} ;;
|
||||||
Darwin\ i*86) download fzf-$version-darwin_386 ;;
|
Darwin\ i*86) download fzf-$version-darwin_${binary_arch:-386} ;;
|
||||||
Linux\ x86_64) download fzf-$version-linux_amd64 ;;
|
Linux\ x86_64) download fzf-$version-linux_${binary_arch:-amd64} ;;
|
||||||
Linux\ i*86) download fzf-$version-linux_386 ;;
|
Linux\ i*86) download fzf-$version-linux_${binary_arch:-386} ;;
|
||||||
*) binary_available=0 binary_error=1 ;;
|
*) binary_available=0 binary_error=1 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
cd "$fzf_base"
|
install_ruby_fzf() {
|
||||||
if [ -n "$binary_error" ]; then
|
|
||||||
if [ $binary_available -eq 0 ]; then
|
|
||||||
echo "No prebuilt binary for $archi ... "
|
|
||||||
else
|
|
||||||
echo " - $binary_error !!!"
|
|
||||||
fi
|
|
||||||
echo "Installing legacy Ruby version ..."
|
echo "Installing legacy Ruby version ..."
|
||||||
|
|
||||||
# ruby executable
|
# ruby executable
|
||||||
echo -n "Checking Ruby executable ... "
|
echo -n "Checking Ruby executable ... "
|
||||||
ruby=`which ruby`
|
ruby=$(command -v ruby)
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "ruby executable not found !!!"
|
echo "ruby executable not found !!!"
|
||||||
exit 1
|
exit 1
|
||||||
@@ -99,7 +170,7 @@ if [ -n "$binary_error" ]; then
|
|||||||
|
|
||||||
# System ruby is preferred
|
# System ruby is preferred
|
||||||
system_ruby=/usr/bin/ruby
|
system_ruby=/usr/bin/ruby
|
||||||
if [ -x $system_ruby -a $system_ruby != "$ruby" ]; then
|
if [ -x $system_ruby ] && [ $system_ruby != "$ruby" ]; then
|
||||||
$system_ruby --disable-gems -rcurses -e0 2> /dev/null
|
$system_ruby --disable-gems -rcurses -e0 2> /dev/null
|
||||||
[ $? -eq 0 ] && ruby=$system_ruby
|
[ $? -eq 0 ] && ruby=$system_ruby
|
||||||
fi
|
fi
|
||||||
@@ -152,41 +223,76 @@ if [ -n "$binary_error" ]; then
|
|||||||
echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf
|
echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf
|
||||||
chmod +x "$fzf_base"/bin/fzf
|
chmod +x "$fzf_base"/bin/fzf
|
||||||
echo "OK"
|
echo "OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
cd "$fzf_base"
|
||||||
|
if [ -n "$binary_error" ]; then
|
||||||
|
if [ $binary_available -eq 0 ]; then
|
||||||
|
echo "No prebuilt binary for $archi ..."
|
||||||
|
if command -v go > /dev/null; then
|
||||||
|
echo -n "Building binary (go get -u github.com/junegunn/fzf/src/fzf) ... "
|
||||||
|
if [ -z "${GOPATH-}" ]; then
|
||||||
|
export GOPATH="${TMPDIR:-/tmp}/fzf-gopath"
|
||||||
|
mkdir -p "$GOPATH"
|
||||||
|
fi
|
||||||
|
if go get -u github.com/junegunn/fzf/src/fzf; then
|
||||||
|
echo "OK"
|
||||||
|
cp "$GOPATH/bin/fzf" "$fzf_base/bin/"
|
||||||
|
else
|
||||||
|
echo "Failed to build binary ..."
|
||||||
|
install_ruby_fzf
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "go executable not found. Cannot build binary ..."
|
||||||
|
install_ruby_fzf
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " - $binary_error !!!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
[[ "$*" =~ "--bin" ]] && exit 0
|
||||||
|
|
||||||
# Auto-completion
|
# Auto-completion
|
||||||
ask "Do you want to add auto-completion support?"
|
if [ -z "$auto_completion" ]; then
|
||||||
auto_completion=$?
|
ask "Do you want to enable fuzzy auto-completion?"
|
||||||
|
auto_completion=$?
|
||||||
|
fi
|
||||||
|
|
||||||
# Key-bindings
|
# Key-bindings
|
||||||
ask "Do you want to add key bindings?"
|
if [ -z "$key_bindings" ]; then
|
||||||
key_bindings=$?
|
ask "Do you want to enable key bindings?"
|
||||||
|
key_bindings=$?
|
||||||
|
fi
|
||||||
|
|
||||||
echo
|
echo
|
||||||
for shell in bash zsh; do
|
has_zsh=$(command -v zsh > /dev/null && echo 1 || echo 0)
|
||||||
|
shells=$([ $has_zsh -eq 1 ] && echo "bash zsh" || echo "bash")
|
||||||
|
for shell in $shells; do
|
||||||
echo -n "Generate ~/.fzf.$shell ... "
|
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 -eq 0 ]; then
|
||||||
fzf_completion="# $fzf_completion"
|
fzf_completion="# $fzf_completion"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""
|
fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""
|
||||||
if [ $key_bindings -ne 0 ]; then
|
if [ $key_bindings -eq 0 ]; then
|
||||||
fzf_key_bindings="# $fzf_key_bindings"
|
fzf_key_bindings="# $fzf_key_bindings"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat > $src << EOF
|
cat > $src << EOF
|
||||||
# Setup fzf
|
# Setup fzf
|
||||||
# ---------
|
# ---------
|
||||||
if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then
|
if [[ ! "\$PATH" == *$fzf_base/bin* ]]; then
|
||||||
export PATH="\$PATH:$fzf_base/bin"
|
export PATH="\$PATH:$fzf_base/bin"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Man path
|
# Man path
|
||||||
# --------
|
# --------
|
||||||
if [[ ! "\$MANPATH" =~ "$fzf_base/man" && -d "$fzf_base/man" ]]; then
|
if [[ ! "\$MANPATH" == *$fzf_base/man* && -d "$fzf_base/man" ]]; then
|
||||||
export MANPATH="\$MANPATH:$fzf_base/man"
|
export MANPATH="\$MANPATH:$fzf_base/man"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -203,9 +309,8 @@ EOF
|
|||||||
done
|
done
|
||||||
|
|
||||||
# fish
|
# fish
|
||||||
has_fish=0
|
has_fish=$(command -v fish > /dev/null && echo 1 || echo 0)
|
||||||
if [ -n "$(which fish 2> /dev/null)" ]; then
|
if [ $has_fish -eq 1 ]; then
|
||||||
has_fish=1
|
|
||||||
echo -n "Update fish_user_paths ... "
|
echo -n "Update fish_user_paths ... "
|
||||||
fish << EOF
|
fish << EOF
|
||||||
echo \$fish_user_paths | grep $fzf_base/bin > /dev/null
|
echo \$fish_user_paths | grep $fzf_base/bin > /dev/null
|
||||||
@@ -219,50 +324,74 @@ EOF
|
|||||||
rm -f ~/.config/fish/functions/fzf.fish && echo "OK" || echo "Failed"
|
rm -f ~/.config/fish/functions/fzf.fish && echo "OK" || echo "Failed"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ $key_bindings -eq 0 ]; then
|
fish_binding=~/.config/fish/functions/fzf_key_bindings.fish
|
||||||
echo -n "Symlink ~/.config/fish/functions/fzf_key_bindings.fish ... "
|
if [ $key_bindings -ne 0 ]; then
|
||||||
ln -sf $fzf_base/shell/key-bindings.fish \
|
echo -n "Symlink $fish_binding ... "
|
||||||
~/.config/fish/functions/fzf_key_bindings.fish && echo "OK" || echo "Failed"
|
ln -sf "$fzf_base/shell/key-bindings.fish" \
|
||||||
|
"$fish_binding" && echo "OK" || echo "Failed"
|
||||||
|
else
|
||||||
|
echo -n "Removing $fish_binding ... "
|
||||||
|
rm -f "$fish_binding"
|
||||||
|
echo "OK"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
append_line() {
|
append_line() {
|
||||||
echo "Update $2:"
|
set -e
|
||||||
echo " - $1"
|
|
||||||
[ -f "$2" ] || touch "$2"
|
local update line file pat lno
|
||||||
if [ $# -lt 3 ]; then
|
update="$1"
|
||||||
line=$(\grep -nF "$1" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
line="$2"
|
||||||
|
file="$3"
|
||||||
|
pat="${4:-}"
|
||||||
|
|
||||||
|
echo "Update $file:"
|
||||||
|
echo " - $line"
|
||||||
|
[ -f "$file" ] || touch "$file"
|
||||||
|
if [ $# -lt 4 ]; then
|
||||||
|
lno=$(\grep -nF "$line" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||||
else
|
else
|
||||||
line=$(\grep -nF "$3" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
lno=$(\grep -nF "$pat" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||||
fi
|
fi
|
||||||
if [ -n "$line" ]; then
|
if [ -n "$lno" ]; then
|
||||||
echo " - Already exists: line #$line"
|
echo " - Already exists: line #$lno"
|
||||||
else
|
else
|
||||||
echo "$1" >> "$2"
|
if [ $update -eq 1 ]; then
|
||||||
echo " + Added"
|
echo >> "$file"
|
||||||
|
echo "$line" >> "$file"
|
||||||
|
echo " + Added"
|
||||||
|
else
|
||||||
|
echo " ~ Skipped"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
echo
|
echo
|
||||||
|
set +e
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if [ $update_config -eq 2 ]; then
|
||||||
|
echo
|
||||||
|
ask "Do you want to update your shell configuration files?"
|
||||||
|
update_config=$?
|
||||||
|
fi
|
||||||
echo
|
echo
|
||||||
for shell in bash zsh; do
|
for shell in $shells; do
|
||||||
append_line "[ -f ~/.fzf.${shell} ] && source ~/.fzf.${shell}" ~/.${shell}rc "~/.fzf.${shell}"
|
[ $shell = zsh ] && dest=${ZDOTDIR:-~}/.zshrc || dest=~/.bashrc
|
||||||
|
append_line $update_config "[ -f ~/.fzf.${shell} ] && source ~/.fzf.${shell}" "$dest" "~/.fzf.${shell}"
|
||||||
done
|
done
|
||||||
|
|
||||||
if [ $key_bindings -eq 0 -a $has_fish -eq 1 ]; then
|
if [ $key_bindings -eq 1 ] && [ $has_fish -eq 1 ]; then
|
||||||
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
||||||
append_line "fzf_key_bindings" "$bind_file"
|
append_line $update_config "fzf_key_bindings" "$bind_file"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat << EOF
|
if [ $update_config -eq 1 ]; then
|
||||||
Finished. Restart your shell or reload config file.
|
echo 'Finished. Restart your shell or reload config file.'
|
||||||
source ~/.bashrc # bash
|
echo ' source ~/.bashrc # bash'
|
||||||
source ~/.zshrc # zsh
|
[ $has_zsh -eq 1 ] && echo " source ${ZDOTDIR:-~}/.zshrc # zsh"
|
||||||
EOF
|
[ $has_fish -eq 1 ] && [ $key_bindings -eq 1 ] && echo ' fzf_key_bindings # fish'
|
||||||
[ $has_fish -eq 1 ] && echo " fzf_key_bindings # fish"; cat << EOF
|
echo
|
||||||
|
echo 'Use uninstall script to remove fzf.'
|
||||||
Use uninstall script to remove fzf.
|
echo
|
||||||
|
fi
|
||||||
For more information, see: https://github.com/junegunn/fzf
|
echo 'For more information, see: https://github.com/junegunn/fzf'
|
||||||
EOF
|
|
||||||
|
|
||||||
|
374
man/man1/fzf.1
374
man/man1/fzf.1
@@ -1,7 +1,7 @@
|
|||||||
.ig
|
.ig
|
||||||
The MIT License (MIT)
|
The MIT License (MIT)
|
||||||
|
|
||||||
Copyright (c) 2015 Junegunn Choi
|
Copyright (c) 2016 Junegunn Choi
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
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 "Jun 2016" "fzf 0.13.0" "fzf - a command-line fuzzy finder"
|
||||||
|
|
||||||
.SH NAME
|
.SH NAME
|
||||||
fzf - a command-line fuzzy finder
|
fzf - a command-line fuzzy finder
|
||||||
@@ -36,10 +36,11 @@ fzf is a general-purpose command-line fuzzy finder.
|
|||||||
.SS Search mode
|
.SS Search mode
|
||||||
.TP
|
.TP
|
||||||
.B "-x, --extended"
|
.B "-x, --extended"
|
||||||
Extended-search mode
|
Extended-search mode. Since 0.10.9, this is enabled by default. You can disable
|
||||||
|
it with \fB+x\fR or \fB--no-extended\fR.
|
||||||
.TP
|
.TP
|
||||||
.B "-e, --extended-exact"
|
.B "-e, --exact"
|
||||||
Extended-search mode (exact match)
|
Enable exact-match
|
||||||
.TP
|
.TP
|
||||||
.B "-i"
|
.B "-i"
|
||||||
Case-insensitive match (default: smart-case match)
|
Case-insensitive match (default: smart-case match)
|
||||||
@@ -49,13 +50,13 @@ Case-sensitive match
|
|||||||
.TP
|
.TP
|
||||||
.BI "-n, --nth=" "N[,..]"
|
.BI "-n, --nth=" "N[,..]"
|
||||||
Comma-separated list of field index expressions for limiting search scope.
|
Comma-separated list of field index expressions for limiting search scope.
|
||||||
See \fBFIELD INDEX EXPRESSION\fR for details.
|
See \fBFIELD INDEX EXPRESSION\fR for the details.
|
||||||
.TP
|
.TP
|
||||||
.BI "--with-nth=" "N[,..]"
|
.BI "--with-nth=" "N[,..]"
|
||||||
Transform the item using the list of index expressions for search
|
Transform the presentation of each line using field index expressions
|
||||||
.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"
|
||||||
@@ -63,34 +64,188 @@ Do not sort the result
|
|||||||
.TP
|
.TP
|
||||||
.B "--tac"
|
.B "--tac"
|
||||||
Reverse the order of the input
|
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[,..]"
|
||||||
|
Comma-separated list of sort criteria to apply when the scores are tied.
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
.BR length " Prefers line with shorter length"
|
||||||
|
.br
|
||||||
|
.BR begin " Prefers line with matched substring closer to the beginning"
|
||||||
|
.br
|
||||||
|
.BR end " Prefers line with matched substring closer to the end"
|
||||||
|
.br
|
||||||
|
.BR index " Prefers line that appeared earlier in the input stream"
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
- Each criterion should appear only once in the list
|
||||||
|
.br
|
||||||
|
- \fBindex\fR is only allowed at the end of the list
|
||||||
|
.br
|
||||||
|
- \fBindex\fR is implicitly appended to the list when not specified
|
||||||
|
.br
|
||||||
|
- Default is \fBlength\fR (or equivalently \fBlength\fR,index)
|
||||||
|
.br
|
||||||
|
- If \fBend\fR is found in the list, fzf will scan each line backwards
|
||||||
.SS Interface
|
.SS Interface
|
||||||
.TP
|
.TP
|
||||||
.B "-m, --multi"
|
.B "-m, --multi"
|
||||||
Enable multi-select with tab/shift-tab
|
Enable multi-select with tab/shift-tab
|
||||||
.TP
|
.TP
|
||||||
.B "--ansi"
|
|
||||||
Enable processing of ANSI color codes
|
|
||||||
.TP
|
|
||||||
.B "--no-mouse"
|
.B "--no-mouse"
|
||||||
Disable mouse
|
Disable mouse
|
||||||
.TP
|
.TP
|
||||||
.B "+c, --no-color"
|
.BI "--bind=" "KEYBINDS"
|
||||||
Disable colors
|
Comma-separated list of custom key bindings. See \fBKEY BINDINGS\fR for the
|
||||||
|
details.
|
||||||
.TP
|
.TP
|
||||||
.B "+2, --no-256"
|
.B "--cycle"
|
||||||
Disable 256-color
|
Enable cyclic scroll
|
||||||
.TP
|
.TP
|
||||||
.B "--black"
|
.B "--no-hscroll"
|
||||||
Use black background
|
Disable horizontal scroll
|
||||||
|
.TP
|
||||||
|
.BI "--hscroll-off=" "COL"
|
||||||
|
Number of screen columns to keep to the right of the highlighted substring
|
||||||
|
(default: 10). Setting it to a large value will cause the text to be positioned
|
||||||
|
on the center of the screen.
|
||||||
|
.TP
|
||||||
|
.BI "--jump-labels=" "CHARS"
|
||||||
|
Label characters for \fBjump\fR and \fBjump-accept\fR
|
||||||
|
.SS Layout
|
||||||
.TP
|
.TP
|
||||||
.B "--reverse"
|
.B "--reverse"
|
||||||
Reverse orientation
|
Reverse orientation
|
||||||
.TP
|
.TP
|
||||||
|
.BI "--margin=" MARGIN
|
||||||
|
Comma-separated expression for margins around the finder.
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
.RS
|
||||||
|
.BR TRBL " Same margin for top, right, bottom, and left"
|
||||||
|
.br
|
||||||
|
.BR TB,RL " Vertical, horizontal margin"
|
||||||
|
.br
|
||||||
|
.BR T,RL,B " Top, horizontal, bottom margin"
|
||||||
|
.br
|
||||||
|
.BR T,R,B,L " Top, right, bottom, left margin"
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
Each part can be given in absolute number or in percentage relative to the
|
||||||
|
terminal size with \fB%\fR suffix.
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
e.g. \fBfzf --margin 10%\fR
|
||||||
|
\fBfzf --margin 1,5%\fR
|
||||||
|
.RE
|
||||||
|
.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 "--header=" "STR"
|
||||||
|
The given string will be printed as the sticky header. The lines are displayed
|
||||||
|
in the given order from top to bottom regardless of \fB--reverse\fR option, and
|
||||||
|
are not affected by \fB--with-nth\fR. ANSI color codes are processed even when
|
||||||
|
\fB--ansi\fR is not set.
|
||||||
|
.TP
|
||||||
|
.BI "--header-lines=" "N"
|
||||||
|
The first N lines of the input are treated as the sticky header. When
|
||||||
|
\fB--with-nth\fR is set, the lines are transformed just like the other
|
||||||
|
lines that follow.
|
||||||
|
.SS Display
|
||||||
|
.TP
|
||||||
|
.B "--ansi"
|
||||||
|
Enable processing of ANSI color codes
|
||||||
|
.TP
|
||||||
|
.BI "--tabstop=" SPACES
|
||||||
|
Number of spaces for a tab character (default: 8)
|
||||||
|
.TP
|
||||||
|
.BI "--color=" "[BASE_SCHEME][,COLOR:ANSI]"
|
||||||
|
Color configuration. The name of the base color scheme is followed by custom
|
||||||
|
color mappings. Ansi color code of -1 denotes terminal default
|
||||||
|
foreground/background 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
|
||||||
|
\fBheader \fRHeader
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.B "--black"
|
||||||
|
Use black background
|
||||||
|
.SS History
|
||||||
|
.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 Preview
|
||||||
|
.TP
|
||||||
|
.BI "--preview=" "COMMAND"
|
||||||
|
Execute the given command for the current line and display the result on the
|
||||||
|
preview window. \fB{}\fR is the placeholder for the quoted string of the
|
||||||
|
current line.
|
||||||
|
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --preview="head -$LINES {}"\fR
|
||||||
|
.RE
|
||||||
|
.TP
|
||||||
|
.BI "--preview-window=" "[POSITION][:SIZE[%]][:hidden]"
|
||||||
|
Determine the layout of the preview window. If the argument ends with
|
||||||
|
\fB:hidden\fR, the preview window will be hidden by default until
|
||||||
|
\fBtoggle-preview\fR action is triggered.
|
||||||
|
|
||||||
|
.RS
|
||||||
|
.B POSITION: (default: right)
|
||||||
|
\fBup
|
||||||
|
\fBdown
|
||||||
|
\fBleft
|
||||||
|
\fBright
|
||||||
|
.RE
|
||||||
|
|
||||||
|
.RS
|
||||||
|
e.g. \fBfzf --preview="head {}" --preview-window=up:30%\fR
|
||||||
|
\fBfzf --preview="file {}" --preview-window=down:1\fR
|
||||||
|
.RE
|
||||||
.SS Scripting
|
.SS Scripting
|
||||||
.TP
|
.TP
|
||||||
.BI "-q, --query=" "STR"
|
.BI "-q, --query=" "STR"
|
||||||
@@ -110,44 +265,45 @@ 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.
|
||||||
|
|
||||||
.RS
|
.RS
|
||||||
e.g. \fBfzf --multi | fzf --sync\fR
|
e.g. \fBfzf --multi | fzf --sync\fR
|
||||||
.RE
|
.RE
|
||||||
|
|
||||||
.SH ENVIRONMENT
|
.SH ENVIRONMENT VARIABLES
|
||||||
.TP
|
.TP
|
||||||
.B FZF_DEFAULT_COMMAND
|
.B FZF_DEFAULT_COMMAND
|
||||||
Default command to use when input is tty
|
Default command to use when input is tty
|
||||||
.TP
|
.TP
|
||||||
.B FZF_DEFAULT_OPTS
|
.B FZF_DEFAULT_OPTS
|
||||||
Default options. e.g. \fB--extended --ansi\fR
|
Default options. e.g. \fBexport FZF_DEFAULT_OPTS="--extended --cycle"\fR
|
||||||
|
|
||||||
.SH EXIT STATUS
|
.SH EXIT STATUS
|
||||||
.BR 0 " Normal exit"
|
.BR 0 " Normal exit"
|
||||||
.br
|
.br
|
||||||
.BR 1 " Interrupted with \fBCTRL-C\fR or \fBESC\fR"
|
.BR 1 " No match"
|
||||||
|
.br
|
||||||
|
.BR 2 " Error"
|
||||||
|
.br
|
||||||
|
.BR 130 " Interrupted with \fBCTRL-C\fR or \fBESC\fR"
|
||||||
|
|
||||||
.SH FIELD INDEX EXPRESSION
|
.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,34 +326,164 @@ 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
|
Unless specified otherwise, fzf will start in "extended-search mode". In this
|
||||||
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
mode, you can specify multiple patterns delimited by spaces, such as: \fB'wild
|
||||||
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
^music .mp3$ sbtrkt !rmx\fR
|
||||||
|
|
||||||
.SS Exact-match (quoted)
|
.SS Exact-match (quoted)
|
||||||
A term that is prefixed by a single-quote character (') is interpreted as an
|
A term that is prefixed by a single-quote character (\fB'\fR) is interpreted as
|
||||||
"exact-match" (or "non-fuzzy") term. fzf will search for the exact occurrences
|
an "exact-match" (or "non-fuzzy") term. fzf will search for the exact
|
||||||
of the string.
|
occurrences of the string.
|
||||||
|
|
||||||
.SS Anchored-match
|
.SS Anchored-match
|
||||||
A term can be prefixed by ^, or suffixed by $ to become an anchored-match term.
|
A term can be prefixed by \fB^\fR, or suffixed by \fB$\fR to become an
|
||||||
Then fzf will search for the items that start with or end with the given
|
anchored-match term. Then fzf will search for the lines that start with or end
|
||||||
string. An anchored-match term is also an exact-match term.
|
with the given string. An anchored-match term is also an exact-match term.
|
||||||
|
|
||||||
.SS Negation
|
.SS Negation
|
||||||
If a term is prefixed by !, fzf will exclude the items that satisfy the term
|
If a term is prefixed by \fB!\fR, fzf will exclude the lines that satisfy the
|
||||||
from the result.
|
term from the result.
|
||||||
|
|
||||||
.SS Extended-exact mode
|
.SS Exact-match by default
|
||||||
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
If you don't prefer fuzzy matching and do not wish to "quote" (prefixing with
|
||||||
with ') every word, start fzf with \fI-e\fR or \fI--extended-exact\fR option
|
\fB'\fR) every word, start fzf with \fB-e\fR or \fB--exact\fR option. Note that
|
||||||
(instead of \fI-x\fR or \fI--extended\fR).
|
when \fB--exact\fR is set, \fB'\fR-prefix "unquotes" the term.
|
||||||
|
|
||||||
|
.SS OR operator
|
||||||
|
A single bar character term acts as an OR operator. For example, the following
|
||||||
|
query matches entries that start with \fBcore\fR and end with either \fBgo\fR,
|
||||||
|
\fBrb\fR, or \fBpy\fR.
|
||||||
|
|
||||||
|
e.g. \fB^core go$ | rb$ | py$\fR
|
||||||
|
|
||||||
|
.SH KEY BINDINGS
|
||||||
|
You can customize key bindings of fzf with \fB--bind\fR option which takes
|
||||||
|
a comma-separated list of key binding expressions. Each key binding expression
|
||||||
|
follows the following format: \fBKEY:ACTION\fR
|
||||||
|
|
||||||
|
e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||||
|
|
||||||
|
.B AVAILABLE KEYS: (SYNONYMS)
|
||||||
|
\fIctrl-[a-z]\fR
|
||||||
|
\fIalt-[a-z]\fR
|
||||||
|
\fIf[1-10]\fR
|
||||||
|
\fIenter\fR (\fIreturn\fR \fIctrl-m\fR)
|
||||||
|
\fIspace\fR
|
||||||
|
\fIbspace\fR (\fIbs\fR)
|
||||||
|
\fIalt-enter\fR
|
||||||
|
\fIalt-space\fR
|
||||||
|
\fIalt-bspace\fR (\fIalt-bs\fR)
|
||||||
|
\fIalt-/\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
|
||||||
|
\fIdouble-click\fR
|
||||||
|
or any single character
|
||||||
|
|
||||||
|
\fBACTION: DEFAULT BINDINGS (NOTES):
|
||||||
|
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
||||||
|
\fBaccept\fR \fIenter double-click\fR
|
||||||
|
\fBbackward-char\fR \fIctrl-b left\fR
|
||||||
|
\fBbackward-delete-char\fR \fIctrl-h bspace\fR
|
||||||
|
\fBbackward-kill-word\fR \fIalt-bs\fR
|
||||||
|
\fBbackward-word\fR \fIalt-b shift-left\fR
|
||||||
|
\fBbeginning-of-line\fR \fIctrl-a home\fR
|
||||||
|
\fBcancel\fR
|
||||||
|
\fBclear-screen\fR \fIctrl-l\fR
|
||||||
|
\fBdelete-char\fR \fIdel\fR
|
||||||
|
\fBdelete-char/eof\fR \fIctrl-d\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)
|
||||||
|
\fBexecute-multi(...)\fR (see below for the details)
|
||||||
|
\fBforward-char\fR \fIctrl-f right\fR
|
||||||
|
\fBforward-word\fR \fIalt-f shift-right\fR
|
||||||
|
\fBignore\fR
|
||||||
|
\fBjump\fR (EasyMotion-like 2-keystroke movement)
|
||||||
|
\fBjump-accept\fR (jump and accept)
|
||||||
|
\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)
|
||||||
|
\fBprint-query\fR (print query and exit)
|
||||||
|
\fBselect-all\fR
|
||||||
|
\fBtoggle\fR
|
||||||
|
\fBtoggle-all\fR
|
||||||
|
\fBtoggle-down\fR \fIctrl-i (tab)\fR
|
||||||
|
\fBtoggle-in\fR (\fB--reverse\fR ? \fBtoggle-up\fR : \fBtoggle-down\fR)
|
||||||
|
\fBtoggle-out\fR (\fB--reverse\fR ? \fBtoggle-down\fR : \fBtoggle-up\fR)
|
||||||
|
\fBtoggle-preview\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
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
\fBfzf --bind "enter:execute(less {})"\fR
|
||||||
|
|
||||||
|
\fB{}\fR is the placeholder for the 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
|
||||||
|
|
||||||
|
\fBexecute-multi(...)\fR is an alternative action that executes the command
|
||||||
|
with the selected entries when multi-select is enabled (\fB--multi\fR). With
|
||||||
|
this action, \fB{}\fR is replaced with the quoted strings of the selected
|
||||||
|
entries separated by spaces.
|
||||||
|
|
||||||
.SH AUTHOR
|
.SH AUTHOR
|
||||||
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||||
|
|
||||||
.SH SEE ALSO
|
.SH SEE ALSO
|
||||||
|
.B Project homepage:
|
||||||
|
.RS
|
||||||
.I https://github.com/junegunn/fzf
|
.I https://github.com/junegunn/fzf
|
||||||
|
.RE
|
||||||
|
.br
|
||||||
|
|
||||||
|
.br
|
||||||
|
.B Extra Vim plugin:
|
||||||
|
.RS
|
||||||
|
.I https://github.com/junegunn/fzf.vim
|
||||||
|
.RE
|
||||||
|
|
||||||
.SH LICENSE
|
.SH LICENSE
|
||||||
MIT
|
MIT
|
||||||
|
376
plugin/fzf.vim
376
plugin/fzf.vim
@@ -1,4 +1,4 @@
|
|||||||
" Copyright (c) 2015 Junegunn Choi
|
" Copyright (c) 2016 Junegunn Choi
|
||||||
"
|
"
|
||||||
" MIT License
|
" MIT License
|
||||||
"
|
"
|
||||||
@@ -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,22 @@ 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
|
||||||
|
elseif executable('fzf')
|
||||||
|
let s:exec = 'fzf'
|
||||||
|
elseif !s:installed && executable(s:install) &&
|
||||||
|
\ input('fzf executable not found. Download binary? (y/n) ') =~? '^y'
|
||||||
|
redraw
|
||||||
|
echo
|
||||||
|
call s:warn('Downloading fzf binary. Please wait ...')
|
||||||
|
let s:installed = 1
|
||||||
|
call system(s:install.' --bin')
|
||||||
|
return s:fzf_exec()
|
||||||
else
|
else
|
||||||
let path = split(system('which fzf 2> /dev/null'), '\n')
|
redraw
|
||||||
if !v:shell_error && !empty(path)
|
throw 'fzf executable not found'
|
||||||
let s:exec = path[0]
|
|
||||||
elseif executable(s:fzf_rb)
|
|
||||||
let s:exec = s:fzf_rb
|
|
||||||
let s:legacy = 1
|
|
||||||
else
|
|
||||||
call system('type fzf')
|
|
||||||
if v:shell_error
|
|
||||||
throw 'fzf executable not found'
|
|
||||||
else
|
|
||||||
let s:exec = 'fzf'
|
|
||||||
endif
|
|
||||||
endif
|
|
||||||
endif
|
endif
|
||||||
return s:exec
|
|
||||||
else
|
|
||||||
return s:exec
|
|
||||||
endif
|
endif
|
||||||
|
return s:shellesc(s:exec)
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_enabled()
|
function! s:tmux_enabled()
|
||||||
@@ -79,7 +74,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
|
||||||
@@ -97,7 +92,26 @@ function! s:upgrade(dict)
|
|||||||
return copy
|
return copy
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:error(msg)
|
||||||
|
echohl ErrorMsg
|
||||||
|
echom a:msg
|
||||||
|
echohl None
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:warn(msg)
|
||||||
|
echohl WarningMsg
|
||||||
|
echom a:msg
|
||||||
|
echohl None
|
||||||
|
endfunction
|
||||||
|
|
||||||
function! fzf#run(...) abort
|
function! fzf#run(...) abort
|
||||||
|
try
|
||||||
|
let oshell = &shell
|
||||||
|
set shell=sh
|
||||||
|
if has('nvim') && bufexists('term://*:FZF')
|
||||||
|
call s:warn('FZF is already running!')
|
||||||
|
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', '')
|
||||||
@@ -107,6 +121,10 @@ function! fzf#run(...) abort
|
|||||||
throw v:exception
|
throw v:exception
|
||||||
endtry
|
endtry
|
||||||
|
|
||||||
|
if !has_key(dict, 'source') && !empty($FZF_DEFAULT_COMMAND)
|
||||||
|
let dict.source = $FZF_DEFAULT_COMMAND
|
||||||
|
endif
|
||||||
|
|
||||||
if has_key(dict, 'source')
|
if has_key(dict, 'source')
|
||||||
let source = dict.source
|
let source = dict.source
|
||||||
let type = type(source)
|
let type = type(source)
|
||||||
@@ -122,18 +140,19 @@ 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') || get(g:, 'fzf_prefer_tmux', 0)) && 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
|
if has('nvim') && !tmux
|
||||||
if split
|
return s:execute_term(dict, command, temps)
|
||||||
return s:execute_tmux(dict, command, temps)
|
endif
|
||||||
else
|
|
||||||
return s:execute(dict, command, temps)
|
let ret = tmux ? s:execute_tmux(dict, command, temps) : s:execute(dict, command, temps)
|
||||||
endif
|
call s:popd(dict, ret)
|
||||||
finally
|
return ret
|
||||||
call s:popd(dict)
|
finally
|
||||||
endtry
|
let &shell = oshell
|
||||||
|
endtry
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:present(dict, ...)
|
function! s:present(dict, ...)
|
||||||
@@ -149,57 +168,98 @@ function! s:fzf_tmux(dict)
|
|||||||
let size = ''
|
let size = ''
|
||||||
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 spec = a:dict[o]
|
||||||
|
if (o == 'up' || o == 'down') && spec[0] == '~'
|
||||||
|
let size = '-'.o[0].s:calc_size(&lines, spec[1:], a:dict)
|
||||||
|
else
|
||||||
|
" Legacy boolean option
|
||||||
|
let size = '-'.o[0].(spec == 1 ? '' : spec)
|
||||||
|
endif
|
||||||
|
break
|
||||||
endif
|
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:shellesc(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()
|
||||||
execute 'chdir '.s:escape(a:dict.dir)
|
if get(a:dict, 'prev_dir', '') ==# cwd
|
||||||
|
return 1
|
||||||
|
endif
|
||||||
|
let a:dict.prev_dir = cwd
|
||||||
|
execute 'lcd' s:escape(a:dict.dir)
|
||||||
let a:dict.dir = getcwd()
|
let a:dict.dir = getcwd()
|
||||||
return 1
|
return 1
|
||||||
endif
|
endif
|
||||||
return 0
|
return 0
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:popd(dict)
|
function! s:popd(dict, lines)
|
||||||
if has_key(a:dict, 'prev_dir')
|
" Since anything can be done in the sink function, there is no telling that
|
||||||
execute 'chdir '.s:escape(remove(a:dict, 'prev_dir'))
|
" the change of the working directory was made by &autochdir setting.
|
||||||
|
"
|
||||||
|
" We use the following heuristic to determine whether to restore CWD:
|
||||||
|
" - Always restore the current directory when &autochdir is disabled.
|
||||||
|
" FIXME This makes it impossible to change directory from inside the sink
|
||||||
|
" function when &autochdir is not used.
|
||||||
|
" - In case of an error or an interrupt, a:lines will be empty.
|
||||||
|
" And it will be an array of a single empty string when fzf was finished
|
||||||
|
" without a match. In these cases, we presume that the change of the
|
||||||
|
" directory is not expected and should be undone.
|
||||||
|
if has_key(a:dict, 'prev_dir') &&
|
||||||
|
\ (!&autochdir || (empty(a:lines) || len(a:lines) == 1 && empty(a:lines[0])))
|
||||||
|
execute 'lcd' s:escape(remove(a:dict, 'prev_dir'))
|
||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:execute(dict, command, temps)
|
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:exit_handler(code, command, ...)
|
||||||
|
if a:code == 130
|
||||||
|
return 0
|
||||||
|
elseif a:code > 1
|
||||||
|
call s:error('Error running ' . a:command)
|
||||||
|
if !empty(a:000)
|
||||||
|
sleep
|
||||||
|
endif
|
||||||
|
return 0
|
||||||
|
endif
|
||||||
|
return 1
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:execute(dict, command, temps) abort
|
||||||
call s:pushd(a:dict)
|
call s:pushd(a:dict)
|
||||||
silent! !clear 2> /dev/null
|
silent! !clear 2> /dev/null
|
||||||
|
let escaped = escape(substitute(a:command, '\n', '\\n', 'g'), '%#')
|
||||||
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(escaped, "'", "'\"'\"'", 'g')."'")
|
||||||
else
|
else
|
||||||
let command = a:command
|
let command = escaped
|
||||||
endif
|
endif
|
||||||
execute 'silent !'.command
|
execute 'silent !'.command
|
||||||
redraw!
|
redraw!
|
||||||
if v:shell_error
|
return s:exit_handler(v:shell_error, command) ? s:callback(a:dict, a:temps) : []
|
||||||
" Do not print error message on exit status 1
|
|
||||||
if v:shell_error > 1
|
|
||||||
echohl ErrorMsg
|
|
||||||
echo 'Error running ' . command
|
|
||||||
endif
|
|
||||||
return []
|
|
||||||
else
|
|
||||||
return s:callback(a:dict, a:temps)
|
|
||||||
endif
|
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:execute_tmux(dict, command, temps)
|
function! s:execute_tmux(dict, command, temps) abort
|
||||||
let command = a:command
|
let command = a:command
|
||||||
if s:pushd(a:dict)
|
if s:pushd(a:dict)
|
||||||
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
||||||
@@ -207,13 +267,122 @@ function! s:execute_tmux(dict, command, temps)
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
call system(command)
|
call system(command)
|
||||||
return s:callback(a:dict, a:temps)
|
redraw!
|
||||||
|
return s:exit_handler(v:shell_error, command) ? s:callback(a:dict, a:temps) : []
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:callback(dict, temps)
|
function! s:calc_size(max, val, dict)
|
||||||
if !filereadable(a:temps.result)
|
if a:val =~ '%$'
|
||||||
let lines = []
|
let size = a:max * str2nr(a:val[:-2]) / 100
|
||||||
else
|
else
|
||||||
|
let size = min([a:max, str2nr(a:val)])
|
||||||
|
endif
|
||||||
|
|
||||||
|
let srcsz = -1
|
||||||
|
if type(get(a:dict, 'source', 0)) == type([])
|
||||||
|
let srcsz = len(a:dict.source)
|
||||||
|
endif
|
||||||
|
|
||||||
|
let opts = get(a:dict, 'options', '').$FZF_DEFAULT_OPTS
|
||||||
|
let margin = stridx(opts, '--inline-info') > stridx(opts, '--no-inline-info') ? 1 : 2
|
||||||
|
return srcsz >= 0 ? min([srcsz + margin, size]) : size
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:getpos()
|
||||||
|
return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$'), 'tcnt': tabpagenr('$')}
|
||||||
|
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 ppos = s:getpos()
|
||||||
|
try
|
||||||
|
for [dir, triple] in items(directions)
|
||||||
|
let val = get(a:dict, dir, '')
|
||||||
|
if !empty(val)
|
||||||
|
let [cmd, resz, max] = triple
|
||||||
|
if (dir == 'up' || dir == 'down') && val[0] == '~'
|
||||||
|
let sz = s:calc_size(max, val[1:], a:dict)
|
||||||
|
else
|
||||||
|
let sz = s:calc_size(max, val, {})
|
||||||
|
endif
|
||||||
|
execute cmd sz.'new'
|
||||||
|
execute resz sz
|
||||||
|
return [ppos, {}]
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
if s:present(a:dict, 'window')
|
||||||
|
execute a:dict.window
|
||||||
|
else
|
||||||
|
execute (tabpagenr()-1).'tabnew'
|
||||||
|
endif
|
||||||
|
return [ppos, { '&l:wfw': &l:wfw, '&l:wfh': &l:wfh }]
|
||||||
|
finally
|
||||||
|
setlocal winfixwidth winfixheight
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:execute_term(dict, command, temps) abort
|
||||||
|
let [ppos, winopts] = s:split(a:dict)
|
||||||
|
let fzf = { 'buf': bufnr('%'), 'ppos': ppos, 'dict': a:dict, 'temps': a:temps,
|
||||||
|
\ 'name': 'FZF', 'winopts': winopts, 'command': a:command }
|
||||||
|
function! fzf.switch_back(inplace)
|
||||||
|
if a:inplace && bufnr('') == self.buf
|
||||||
|
" FIXME: Can't re-enter normal mode from terminal mode
|
||||||
|
" execute "normal! \<c-^>"
|
||||||
|
b #
|
||||||
|
" No other listed buffer
|
||||||
|
if bufnr('') == self.buf
|
||||||
|
enew
|
||||||
|
endif
|
||||||
|
endif
|
||||||
|
endfunction
|
||||||
|
function! fzf.on_exit(id, code)
|
||||||
|
if s:getpos() == self.ppos " {'window': 'enew'}
|
||||||
|
for [opt, val] in items(self.winopts)
|
||||||
|
execute 'let' opt '=' val
|
||||||
|
endfor
|
||||||
|
call self.switch_back(1)
|
||||||
|
else
|
||||||
|
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
|
||||||
|
execute 'tabnext' self.ppos.tab
|
||||||
|
execute self.ppos.win.'wincmd w'
|
||||||
|
endif
|
||||||
|
|
||||||
|
if !s:exit_handler(a:code, self.command, 1)
|
||||||
|
return
|
||||||
|
endif
|
||||||
|
|
||||||
|
call s:pushd(self.dict)
|
||||||
|
let ret = []
|
||||||
|
try
|
||||||
|
let ret = s:callback(self.dict, self.temps)
|
||||||
|
call self.switch_back(s:getpos() == self.ppos)
|
||||||
|
finally
|
||||||
|
call s:popd(self.dict, ret)
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
call s:pushd(a:dict)
|
||||||
|
call termopen(a:command, fzf)
|
||||||
|
call s:popd(a:dict, [])
|
||||||
|
setlocal nospell bufhidden=wipe nobuflisted
|
||||||
|
setf fzf
|
||||||
|
startinsert
|
||||||
|
return []
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:callback(dict, temps) abort
|
||||||
|
let lines = []
|
||||||
|
try
|
||||||
|
if filereadable(a:temps.result)
|
||||||
let lines = readfile(a:temps.result)
|
let lines = readfile(a:temps.result)
|
||||||
if has_key(a:dict, 'sink')
|
if has_key(a:dict, 'sink')
|
||||||
for line in lines
|
for line in lines
|
||||||
@@ -224,53 +393,76 @@ 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)
|
||||||
silent! call delete(tf)
|
silent! call delete(tf)
|
||||||
endfor
|
endfor
|
||||||
|
catch
|
||||||
|
if stridx(v:exception, ':E325:') < 0
|
||||||
|
echoerr v:exception
|
||||||
|
endif
|
||||||
|
finally
|
||||||
return lines
|
return lines
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
let s:default_action = {
|
||||||
|
\ 'ctrl-m': 'e',
|
||||||
|
\ 'ctrl-t': 'tab split',
|
||||||
|
\ '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')
|
||||||
|
if len(a:lines) > 1
|
||||||
|
augroup fzf_swap
|
||||||
|
autocmd SwapExists * let v:swapchoice='o'
|
||||||
|
\| call s:warn('fzf: E325: swap file exists: '.expand('<afile>'))
|
||||||
|
augroup END
|
||||||
|
endif
|
||||||
|
try
|
||||||
|
let empty = empty(expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified
|
||||||
|
let autochdir = &autochdir
|
||||||
|
set noautochdir
|
||||||
|
for item in a:lines
|
||||||
|
if empty
|
||||||
|
execute 'e' s:escape(item)
|
||||||
|
let empty = 0
|
||||||
|
else
|
||||||
|
execute cmd s:escape(item)
|
||||||
|
endif
|
||||||
|
if exists('#BufEnter') && isdirectory(item)
|
||||||
|
doautocmd BufEnter
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
finally
|
||||||
|
let &autochdir = autochdir
|
||||||
|
silent! autocmd! fzf_swap
|
||||||
|
endtry
|
||||||
endfunction
|
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 = substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g')
|
||||||
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,42 +5,91 @@
|
|||||||
# / __/ / /_/ __/
|
# / __/ / /_/ __/
|
||||||
# /_/ /___/_/-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)
|
||||||
|
|
||||||
|
# To use custom commands instead of find, override _fzf_compgen_{path,dir}
|
||||||
|
if ! declare -f _fzf_compgen_path > /dev/null; then
|
||||||
|
_fzf_compgen_path() {
|
||||||
|
echo "$1"
|
||||||
|
\find -L "$1" \
|
||||||
|
-name .git -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \
|
||||||
|
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! declare -f _fzf_compgen_dir > /dev/null; then
|
||||||
|
_fzf_compgen_dir() {
|
||||||
|
\find -L "$1" \
|
||||||
|
-name .git -prune -o -name .svn -prune -o -type d \
|
||||||
|
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
|
||||||
|
###########################################################
|
||||||
|
|
||||||
_fzf_orig_completion_filter() {
|
_fzf_orig_completion_filter() {
|
||||||
sed 's/.*-F *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\2=\1;/' |
|
sed 's/^\(.*-F\) *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\3="\1 %s \3 #\2";/' |
|
||||||
sed 's/[^a-z0-9_= ;]/_/g'
|
awk -F= '{gsub(/[^a-z0-9_= ;]/, "_", $1); print $1"="$2}'
|
||||||
}
|
}
|
||||||
|
|
||||||
_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 --exact
|
||||||
-i +i
|
-i +i
|
||||||
-n --nth
|
-n --nth
|
||||||
-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
|
||||||
|
--header
|
||||||
|
--header-lines
|
||||||
|
--margin"
|
||||||
|
|
||||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
case "${prev}" in
|
||||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
--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
|
||||||
|
COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -48,40 +97,43 @@ _fzf_opts_completion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_fzf_handle_dynamic_completion() {
|
_fzf_handle_dynamic_completion() {
|
||||||
local cmd orig ret
|
local cmd orig_var orig ret orig_cmd
|
||||||
cmd="$1"
|
cmd="$1"
|
||||||
shift
|
shift
|
||||||
|
orig_cmd="$1"
|
||||||
orig=$(eval "echo \$_fzf_orig_completion_$cmd")
|
orig_var="_fzf_orig_completion_$cmd"
|
||||||
|
orig="${!orig_var##*#}"
|
||||||
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
||||||
$orig "$@"
|
$orig "$@"
|
||||||
elif [ -n "$_fzf_completion_loader" ]; then
|
elif [ -n "$_fzf_completion_loader" ]; then
|
||||||
_completion_loader "$@"
|
_completion_loader "$@"
|
||||||
ret=$?
|
ret=$?
|
||||||
eval $(complete | \grep "\-F.* $cmd$" | _fzf_orig_completion_filter)
|
eval "$(complete | \grep "\-F.* $orig_cmd$" | _fzf_orig_completion_filter)"
|
||||||
source $BASH_SOURCE
|
source "${BASH_SOURCE[0]}"
|
||||||
return $ret
|
return $ret
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_path_completion() {
|
__fzf_generic_path_completion() {
|
||||||
local cur base dir leftover matches trigger cmd
|
local cur base dir leftover matches trigger cmd fzf
|
||||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
[ "${FZF_TMUX:-1}" != 0 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
cmd=$(echo "${COMP_WORDS[0]}" | sed 's/[^a-z0-9_=]/_/g')
|
||||||
COMPREPLY=()
|
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}}
|
||||||
eval base=$base
|
eval "base=$base"
|
||||||
|
|
||||||
dir="$base"
|
dir="$base"
|
||||||
while [ 1 ]; do
|
while true; do
|
||||||
if [ -z "$dir" -o -d "$dir" ]; then
|
if [ -z "$dir" ] || [ -d "$dir" ]; then
|
||||||
leftover=${base/#"$dir"}
|
leftover=${base/#"$dir"}
|
||||||
leftover=${leftover/#\/}
|
leftover=${leftover/#\/}
|
||||||
[ "$dir" = './' ] && dir=''
|
[ -z "$dir" ] && 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=$(eval "$1 $(printf %q "$dir")" | $fzf $FZF_COMPLETION_OPTS $2 -q "$leftover" | while read -r item; do
|
||||||
printf "%q$3 " "$item"
|
printf "%q$3 " "$item"
|
||||||
done)
|
done)
|
||||||
matches=${matches% }
|
matches=${matches% }
|
||||||
@@ -104,18 +156,21 @@ _fzf_path_completion() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_list_completion() {
|
_fzf_complete() {
|
||||||
local cur selected trigger cmd src
|
local cur selected trigger cmd fzf post
|
||||||
read -r src
|
post="$(caller 0 | awk '{print $2}')_post"
|
||||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
type -t "$post" > /dev/null 2>&1 || post=cat
|
||||||
trigger=${FZF_COMPLETION_TRIGGER:-**}
|
[ "${FZF_TMUX:-1}" != 0 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
|
||||||
|
cmd=$(echo "${COMP_WORDS[0]}" | sed 's/[^a-z0-9_=]/_/g')
|
||||||
|
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
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=$(cat | $fzf $FZF_COMPLETION_OPTS $1 -q "$cur" | $post | tr '\n' ' ')
|
||||||
selected=${selected% }
|
selected=${selected% } # Strip trailing space not to repeat "-o nospace"
|
||||||
tput rc
|
tput rc
|
||||||
|
|
||||||
if [ -n "$selected" ]; then
|
if [ -n "$selected" ]; then
|
||||||
@@ -128,30 +183,26 @@ _fzf_list_completion() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_all_completion() {
|
_fzf_path_completion() {
|
||||||
_fzf_path_completion \
|
__fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"
|
||||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
|
||||||
"-m" "" "$@"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Deprecated. No file only completion.
|
||||||
_fzf_file_completion() {
|
_fzf_file_completion() {
|
||||||
_fzf_path_completion \
|
_fzf_path_completion "$@"
|
||||||
"-name .git -prune -o -name .svn -prune -o -type f -print -o -type l -print" \
|
|
||||||
"-m" "" "$@"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_dir_completion() {
|
_fzf_dir_completion() {
|
||||||
_fzf_path_completion \
|
__fzf_generic_path_completion _fzf_compgen_dir "" "/" "$@"
|
||||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
|
||||||
"" "/" "$@"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_kill_completion() {
|
_fzf_complete_kill() {
|
||||||
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
||||||
|
|
||||||
local selected
|
local selected fzf
|
||||||
|
[ "${FZF_TMUX:-1}" != 0 ] && 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
|
||||||
@@ -160,40 +211,49 @@ _fzf_kill_completion() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_telnet_completion() {
|
_fzf_complete_telnet() {
|
||||||
_fzf_list_completion '+m' "$@" << "EOF"
|
_fzf_complete '+m' "$@" < <(
|
||||||
\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' |
|
||||||
EOF
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_ssh_completion() {
|
_fzf_complete_ssh() {
|
||||||
_fzf_list_completion '+m' "$@" << "EOF"
|
_fzf_complete '+m' "$@" < <(
|
||||||
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 '*') \
|
||||||
EOF
|
<(\grep -oE '^[^ ]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
||||||
|
<(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') |
|
||||||
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_env_var_completion() {
|
_fzf_complete_unset() {
|
||||||
_fzf_list_completion '-m' "$@" << "EOF"
|
_fzf_complete '-m' "$@" < <(
|
||||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||||
EOF
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
_fzf_alias_completion() {
|
_fzf_complete_export() {
|
||||||
_fzf_list_completion '-m' "$@" << "EOF"
|
_fzf_complete '-m' "$@" < <(
|
||||||
alias | sed 's/=.*//' | sed 's/.* //'
|
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||||
EOF
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_unalias() {
|
||||||
|
_fzf_complete '-m' "$@" < <(
|
||||||
|
alias | sed 's/=.*//' | sed 's/.* //'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
# 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="${FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir}"
|
||||||
f_cmds="
|
|
||||||
awk cat diff diff3
|
|
||||||
emacs ex file ftp g++ gcc gvim head hg java
|
|
||||||
javac ld less more mvim patch perl python ruby
|
|
||||||
sed sftp sort source tail tee uniq vi view vim wc"
|
|
||||||
a_cmds="
|
a_cmds="
|
||||||
|
awk cat diff diff3
|
||||||
|
emacs emacsclient ex file ftp g++ gcc gvim head hg java
|
||||||
|
javac ld less more mvim nvim patch perl python ruby
|
||||||
|
sed sftp sort source tail tee uniq vi view vim wc xdg-open
|
||||||
basename bunzip2 bzip2 chmod chown curl cp dirname du
|
basename bunzip2 bzip2 chmod chown curl cp dirname du
|
||||||
find git grep gunzip gzip hg jar
|
find git grep gunzip gzip hg jar
|
||||||
ln ls mv open rm rsync scp
|
ln ls mv open rm rsync scp
|
||||||
@@ -201,42 +261,54 @@ 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.11.3' ]; 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 $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.11.3
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if type _completion_loader > /dev/null 2>&1; then
|
if type _completion_loader > /dev/null 2>&1; then
|
||||||
_fzf_completion_loader=1
|
_fzf_completion_loader=1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Directory
|
_fzf_defc() {
|
||||||
for cmd in $d_cmds; do
|
local cmd func opts orig_var orig def
|
||||||
complete -F _fzf_dir_completion -o nospace -o plusdirs $cmd
|
cmd="$1"
|
||||||
done
|
func="$2"
|
||||||
|
opts="$3"
|
||||||
# File
|
orig_var="_fzf_orig_completion_$cmd"
|
||||||
for cmd in $f_cmds; do
|
orig="${!orig_var}"
|
||||||
complete -F _fzf_file_completion -o default -o bashdefault $cmd
|
if [ -n "$orig" ]; then
|
||||||
done
|
printf -v def "$orig" "$func"
|
||||||
|
eval "$def"
|
||||||
|
else
|
||||||
|
complete -F "$func" $opts "$cmd"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
# Anything
|
# Anything
|
||||||
for cmd in $a_cmds; do
|
for cmd in $a_cmds; do
|
||||||
complete -F _fzf_all_completion -o default -o bashdefault $cmd
|
_fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# Directory
|
||||||
|
for cmd in $d_cmds; do
|
||||||
|
_fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o plusdirs"
|
||||||
|
done
|
||||||
|
|
||||||
|
unset _fzf_defc
|
||||||
|
|
||||||
# Kill completion
|
# Kill completion
|
||||||
complete -F _fzf_kill_completion -o nospace -o default -o bashdefault kill
|
complete -F _fzf_complete_kill -o nospace -o default -o bashdefault kill
|
||||||
|
|
||||||
# Host completion
|
# Host completion
|
||||||
complete -F _fzf_ssh_completion -o default -o bashdefault ssh
|
complete -F _fzf_complete_ssh -o default -o bashdefault ssh
|
||||||
complete -F _fzf_telnet_completion -o default -o bashdefault telnet
|
complete -F _fzf_complete_telnet -o default -o bashdefault telnet
|
||||||
|
|
||||||
# Environment variables / Aliases
|
# Environment variables / Aliases
|
||||||
complete -F _fzf_env_var_completion -o default -o bashdefault unset
|
complete -F _fzf_complete_unset -o default -o bashdefault unset
|
||||||
complete -F _fzf_env_var_completion -o default -o bashdefault export
|
complete -F _fzf_complete_export -o default -o bashdefault export
|
||||||
complete -F _fzf_alias_completion -o default -o bashdefault unalias
|
complete -F _fzf_complete_unalias -o default -o bashdefault unalias
|
||||||
|
|
||||||
unset cmd d_cmds f_cmds a_cmds x_cmds
|
unset cmd d_cmds a_cmds x_cmds
|
||||||
|
188
shell/completion.zsh
Normal file
188
shell/completion.zsh
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
#!/bin/zsh
|
||||||
|
# ____ ____
|
||||||
|
# / __/___ / __/
|
||||||
|
# / /_/_ / / /_
|
||||||
|
# / __/ / /_/ __/
|
||||||
|
# /_/ /___/_/-completion.zsh
|
||||||
|
#
|
||||||
|
# - $FZF_TMUX (default: 1)
|
||||||
|
# - $FZF_TMUX_HEIGHT (default: '40%')
|
||||||
|
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||||
|
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||||
|
|
||||||
|
# To use custom commands instead of find, override _fzf_compgen_{path,dir}
|
||||||
|
if ! declare -f _fzf_compgen_path > /dev/null; then
|
||||||
|
_fzf_compgen_path() {
|
||||||
|
echo "$1"
|
||||||
|
\find -L "$1" \
|
||||||
|
-name .git -prune -o -name .svn -prune -o \( -type d -o -type f -o -type l \) \
|
||||||
|
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! declare -f _fzf_compgen_dir > /dev/null; then
|
||||||
|
_fzf_compgen_dir() {
|
||||||
|
\find -L "$1" \
|
||||||
|
-name .git -prune -o -name .svn -prune -o -type d \
|
||||||
|
-a -not -path "$1" -print 2> /dev/null | sed 's@^\./@@'
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
|
||||||
|
###########################################################
|
||||||
|
|
||||||
|
__fzf_generic_path_completion() {
|
||||||
|
local base lbuf compgen fzf_opts suffix tail fzf dir leftover matches
|
||||||
|
# (Q) flag removes a quoting level: "foo\ bar" => "foo bar"
|
||||||
|
base=${(Q)1}
|
||||||
|
lbuf=$2
|
||||||
|
compgen=$3
|
||||||
|
fzf_opts=$4
|
||||||
|
suffix=$5
|
||||||
|
tail=$6
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
|
||||||
|
setopt localoptions nonomatch
|
||||||
|
dir="$base"
|
||||||
|
while [ 1 ]; do
|
||||||
|
if [ -z "$dir" -o -d ${~dir} ]; then
|
||||||
|
leftover=${base/#"$dir"}
|
||||||
|
leftover=${leftover/#\/}
|
||||||
|
[ -z "$dir" ] && dir='.'
|
||||||
|
[ "$dir" != "/" ] && dir="${dir/%\//}"
|
||||||
|
dir=${~dir}
|
||||||
|
matches=$(eval "$compgen $(printf %q "$dir")" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$leftover" | while read item; do
|
||||||
|
echo -n "${(q)item}$suffix "
|
||||||
|
done)
|
||||||
|
matches=${matches% }
|
||||||
|
if [ -n "$matches" ]; then
|
||||||
|
LBUFFER="$lbuf$matches$tail"
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
dir=$(dirname "$dir")
|
||||||
|
dir=${dir%/}/
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_path_completion() {
|
||||||
|
__fzf_generic_path_completion "$1" "$2" _fzf_compgen_path \
|
||||||
|
"-m" "" " "
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_dir_completion() {
|
||||||
|
__fzf_generic_path_completion "$1" "$2" _fzf_compgen_dir \
|
||||||
|
"" "/" ""
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_feed_fifo() (
|
||||||
|
rm -f "$1"
|
||||||
|
mkfifo "$1"
|
||||||
|
cat <&0 > "$1" &
|
||||||
|
)
|
||||||
|
|
||||||
|
_fzf_complete() {
|
||||||
|
local fifo fzf_opts lbuf fzf matches post
|
||||||
|
fifo="${TMPDIR:-/tmp}/fzf-complete-fifo-$$"
|
||||||
|
fzf_opts=$1
|
||||||
|
lbuf=$2
|
||||||
|
post="${funcstack[2]}_post"
|
||||||
|
type $post > /dev/null 2>&1 || post=cat
|
||||||
|
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||||
|
|
||||||
|
_fzf_feed_fifo "$fifo"
|
||||||
|
matches=$(cat "$fifo" | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "${(Q)prefix}" | $post | tr '\n' ' ')
|
||||||
|
if [ -n "$matches" ]; then
|
||||||
|
LBUFFER="$lbuf$matches"
|
||||||
|
fi
|
||||||
|
zle redisplay
|
||||||
|
rm -f "$fifo"
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_telnet() {
|
||||||
|
_fzf_complete '+m' "$@" < <(
|
||||||
|
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' |
|
||||||
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_ssh() {
|
||||||
|
_fzf_complete '+m' "$@" < <(
|
||||||
|
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') \
|
||||||
|
<(\grep -oE '^[^ ]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
||||||
|
<(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') |
|
||||||
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_export() {
|
||||||
|
_fzf_complete '-m' "$@" < <(
|
||||||
|
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_unset() {
|
||||||
|
_fzf_complete '-m' "$@" < <(
|
||||||
|
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
_fzf_complete_unalias() {
|
||||||
|
_fzf_complete '+m' "$@" < <(
|
||||||
|
alias | sed 's/=.*//'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fzf-completion() {
|
||||||
|
local tokens cmd prefix trigger tail fzf matches lbuf d_cmds
|
||||||
|
setopt localoptions noshwordsplit
|
||||||
|
|
||||||
|
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
||||||
|
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
||||||
|
tokens=(${(z)LBUFFER})
|
||||||
|
if [ ${#tokens} -lt 1 ]; then
|
||||||
|
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=(${=FZF_COMPLETION_DIR_COMMANDS:-cd pushd rmdir})
|
||||||
|
|
||||||
|
[ -z "$trigger" ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}
|
||||||
|
[ -z "${tokens[-1]}" ] && lbuf=$LBUFFER || lbuf=${LBUFFER:0:-${#tokens[-1]}}
|
||||||
|
|
||||||
|
if eval "type _fzf_complete_${cmd} > /dev/null"; then
|
||||||
|
eval "prefix=\"$prefix\" _fzf_complete_${cmd} \"$lbuf\""
|
||||||
|
elif [ ${d_cmds[(i)$cmd]} -le ${#d_cmds} ]; then
|
||||||
|
_fzf_dir_completion "$prefix" "$lbuf"
|
||||||
|
else
|
||||||
|
_fzf_path_completion "$prefix" "$lbuf"
|
||||||
|
fi
|
||||||
|
# Fall back to default completion
|
||||||
|
else
|
||||||
|
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,10 +1,11 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
__fsel() {
|
__fzf_select__() {
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | fzf -m | while read item; do
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
|
eval "$cmd" | fzf -m | while read -r item; do
|
||||||
printf '%q ' "$item"
|
printf '%q ' "$item"
|
||||||
done
|
done
|
||||||
echo
|
echo
|
||||||
@@ -12,7 +13,11 @@ __fsel() {
|
|||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
if [[ $- =~ i ]]; then
|
||||||
|
|
||||||
__fsel_tmux() {
|
__fzfcmd() {
|
||||||
|
[ "${FZF_TMUX:-1}" != 0 ] && 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,56 +25,101 @@ __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"); FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS") PATH=$(printf %q "$PATH") FZF_CTRL_T_COMMAND=$(printf %q "$FZF_CTRL_T_COMMAND") bash -c 'source \"${BASH_SOURCE[0]}\"; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||||
}
|
}
|
||||||
|
|
||||||
__fcd() {
|
fzf-file-widget() {
|
||||||
local dir
|
if __fzf_use_tmux__; then
|
||||||
dir=$(command find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
__fzf_select_tmux__
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m) && printf 'cd %q' "$dir"
|
else
|
||||||
|
local selected="$(__fzf_select__)"
|
||||||
|
READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}$selected${READLINE_LINE:$READLINE_POINT}"
|
||||||
|
READLINE_POINT=$(( READLINE_POINT + ${#selected} ))
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
__use_tmux=0
|
__fzf_cd__() {
|
||||||
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
local cmd dir
|
||||||
|
cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
|
dir=$(eval "$cmd" | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||||
|
}
|
||||||
|
|
||||||
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
__fzf_history__() (
|
||||||
|
local line
|
||||||
|
shopt -u nocaseglob nocasematch
|
||||||
|
line=$(
|
||||||
|
HISTTIMEFORMAT= history |
|
||||||
|
eval "$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r $FZF_CTRL_R_OPTS" |
|
||||||
|
\grep '^ *[0-9]') &&
|
||||||
|
if [[ $- =~ H ]]; then
|
||||||
|
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||||
|
else
|
||||||
|
sed 's/^ *\([0-9]*\)\** *//' <<< "$line"
|
||||||
|
fi
|
||||||
|
)
|
||||||
|
|
||||||
|
__fzf_use_tmux__() {
|
||||||
|
[ -n "$TMUX_PANE" ] && [ "${FZF_TMUX:-1}" != 0 ] && [ ${LINES:-40} -gt 15 ]
|
||||||
|
}
|
||||||
|
|
||||||
|
[ $BASH_VERSINFO -gt 3 ] && __use_bind_x=1 || __use_bind_x=0
|
||||||
|
__fzf_use_tmux__ && __use_tmux=1 || __use_tmux=0
|
||||||
|
|
||||||
|
if [[ ! -o vi ]]; 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_bind_x -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 -x '"\C-t": "fzf-file-widget"'
|
||||||
|
elif [ $__use_tmux -eq 1 ]; then
|
||||||
|
bind '"\C-t": " \C-u \C-a\C-k$(__fzf_select_tmux__)\e\C-e\C-y\C-a\C-d\C-y\ey\C-h"'
|
||||||
else
|
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
|
||||||
|
# We'd usually use "\e" to enter vi-movement-mode so we can do our magic,
|
||||||
|
# but this incurs a very noticeable delay of a half second or so,
|
||||||
|
# because many other commands start with "\e".
|
||||||
|
# Instead, we bind an unused key, "\C-x\C-a",
|
||||||
|
# to also enter vi-movement-mode,
|
||||||
|
# and then use that thereafter.
|
||||||
|
# (We imagine that "\C-x\C-a" is relatively unlikely to be in use.)
|
||||||
|
bind '"\C-x\C-a": vi-movement-mode'
|
||||||
|
|
||||||
bind '"\C-x\C-e": shell-expand-line'
|
bind '"\C-x\C-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_bind_x -eq 1 ]; then
|
||||||
bind '"\C-t": "\e$a \eddi$(__fsel_tmux)\C-x\C-e\e0P$xa"'
|
bind -x '"\C-t": "fzf-file-widget"'
|
||||||
|
elif [ $__use_tmux -eq 1 ]; then
|
||||||
|
bind '"\C-t": "\C-x\C-a$a \C-x\C-addi$(__fzf_select_tmux__)\C-x\C-e\C-x\C-a0P$xa"'
|
||||||
else
|
else
|
||||||
bind '"\C-t": "\e$a \eddi$(__fsel)\C-x\C-e\e0Px$a \C-x\C-r\exa "'
|
bind '"\C-t": "\C-x\C-a$a \C-x\C-addi$(__fzf_select__)\C-x\C-e\C-x\C-a0Px$a \C-x\C-r\C-x\C-axa "'
|
||||||
fi
|
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": "\C-x\C-addi$(__fzf_history__)\C-x\C-e\C-x^\C-x\C-a$a\C-x\C-r"'
|
||||||
bind -m vi-command '"\C-r": "i\C-r"'
|
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": "\C-x\C-addi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||||
bind -m vi-command '"\ec": "i\ec"'
|
bind -m vi-command '"\ec": "ddi$(__fzf_cd__)\C-x\C-e\C-x\C-r\C-m"'
|
||||||
fi
|
fi
|
||||||
|
|
||||||
unset __use_tmux
|
unset -v __use_tmux __use_bind_x
|
||||||
|
|
||||||
fi
|
fi
|
||||||
|
@@ -7,74 +7,65 @@ 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')' '
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_ctrl_t
|
function fzf-file-widget
|
||||||
if [ -n "$TMUX_PANE" -a "$FZF_TMUX" != "0" ]
|
set -q FZF_CTRL_T_COMMAND; or set -l FZF_CTRL_T_COMMAND "
|
||||||
# FIXME need to handle directory with double-quotes
|
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
tmux split-window (__fzf_tmux_height) "cd \"$PWD\";fish -c 'fzf_key_bindings; __fzf_ctrl_t_tmux \\$TMUX_PANE'"
|
-o -type f -print \
|
||||||
else
|
-o -type d -print \
|
||||||
__fzf_list | fzf -m > $TMPDIR/fzf.result
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"
|
||||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
eval "$FZF_CTRL_T_COMMAND | "(__fzfcmd)" -m > $TMPDIR/fzf.result"
|
||||||
commandline -f repaint
|
and for i in (seq 20); commandline -i (cat $TMPDIR/fzf.result | __fzf_escape) 2> /dev/null; and break; sleep 0.1; end
|
||||||
rm -f $TMPDIR/fzf.result
|
commandline -f repaint
|
||||||
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
|
rm -f $TMPDIR/fzf.result
|
||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_ctrl_r
|
function fzf-history-widget
|
||||||
history | fzf +s +m --toggle-sort=ctrl-r > $TMPDIR/fzf.result
|
history | eval (__fzfcmd) +s +m --tiebreak=index --toggle-sort=ctrl-r $FZF_CTRL_R_OPTS > $TMPDIR/fzf.result
|
||||||
and commandline (cat $TMPDIR/fzf.result)
|
and commandline (cat $TMPDIR/fzf.result)
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
rm -f $TMPDIR/fzf.result
|
rm -f $TMPDIR/fzf.result
|
||||||
end
|
end
|
||||||
|
|
||||||
function __fzf_alt_c
|
function fzf-cd-widget
|
||||||
|
set -q FZF_ALT_C_COMMAND; or set -l FZF_ALT_C_COMMAND "
|
||||||
|
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"
|
||||||
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
||||||
__fzf_list_dir | fzf +m > $TMPDIR/fzf.result
|
eval "$FZF_ALT_C_COMMAND | "(__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
|
||||||
if set -q FZF_TMUX_HEIGHT
|
set -q FZF_TMUX; or set FZF_TMUX 1
|
||||||
set height $FZF_TMUX_HEIGHT
|
|
||||||
|
if [ $FZF_TMUX -eq 1 ]
|
||||||
|
if set -q FZF_TMUX_HEIGHT
|
||||||
|
echo "fzf-tmux -d$FZF_TMUX_HEIGHT"
|
||||||
|
else
|
||||||
|
echo "fzf-tmux -d40%"
|
||||||
|
end
|
||||||
else
|
else
|
||||||
set height 40%
|
echo "fzf"
|
||||||
end
|
end
|
||||||
if echo $height | \grep -q -E '%$'
|
|
||||||
echo "-p "(echo $height | sed 's/%$//')
|
|
||||||
else
|
|
||||||
echo "-l $height"
|
|
||||||
end
|
|
||||||
set -e height
|
|
||||||
end
|
end
|
||||||
|
|
||||||
bind \ct '__fzf_ctrl_t'
|
bind \ct fzf-file-widget
|
||||||
bind \cr '__fzf_ctrl_r'
|
bind \cr fzf-history-widget
|
||||||
bind \ec '__fzf_alt_c'
|
bind \ec fzf-cd-widget
|
||||||
|
|
||||||
|
if bind -M insert > /dev/null 2>&1
|
||||||
|
bind -M insert \ct fzf-file-widget
|
||||||
|
bind -M insert \cr fzf-history-widget
|
||||||
|
bind -M insert \ec fzf-cd-widget
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@@ -1,42 +1,35 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
|
if [[ $- == *i* ]]; then
|
||||||
|
|
||||||
# CTRL-T - Paste the selected file path(s) into the command line
|
# CTRL-T - Paste the selected file path(s) into the command line
|
||||||
__fsel() {
|
__fsel() {
|
||||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | fzf -m | while read item; do
|
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
printf '%q ' "$item"
|
eval "$cmd" | $(__fzfcmd) -m | while read item; do
|
||||||
|
echo -n "${(q)item} "
|
||||||
done
|
done
|
||||||
echo
|
echo
|
||||||
}
|
}
|
||||||
|
|
||||||
if [[ $- =~ i ]]; then
|
__fzfcmd() {
|
||||||
|
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||||
|
}
|
||||||
|
|
||||||
if [ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ]; then
|
fzf-file-widget() {
|
||||||
fzf-file-widget() {
|
LBUFFER="${LBUFFER}$(__fsel)"
|
||||||
local height
|
zle redisplay
|
||||||
height=${FZF_TMUX_HEIGHT:-40%}
|
}
|
||||||
if [[ $height =~ %$ ]]; then
|
|
||||||
height="-p ${height%\%}"
|
|
||||||
else
|
|
||||||
height="-l $height"
|
|
||||||
fi
|
|
||||||
tmux split-window $height "cd $(printf %q "$PWD");zsh -c 'source ~/.fzf.zsh; tmux send-keys -t $TMUX_PANE \"\$(__fsel)\"'"
|
|
||||||
}
|
|
||||||
else
|
|
||||||
fzf-file-widget() {
|
|
||||||
LBUFFER="${LBUFFER}$(__fsel)"
|
|
||||||
zle redisplay
|
|
||||||
}
|
|
||||||
fi
|
|
||||||
zle -N fzf-file-widget
|
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 \
|
local cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m):-.}"
|
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||||
|
cd "${$(eval "$cmd" | $(__fzfcmd) +m):-.}"
|
||||||
zle reset-prompt
|
zle reset-prompt
|
||||||
}
|
}
|
||||||
zle -N fzf-cd-widget
|
zle -N fzf-cd-widget
|
||||||
@@ -44,11 +37,14 @@ 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 num
|
||||||
if selected=$(fc -l 1 | fzf +s --tac +m -n2..,.. --toggle-sort=ctrl-r -q "$LBUFFER"); then
|
setopt localoptions noglobsubst
|
||||||
num=$(echo "$selected" | head -1 | awk '{print $1}' | sed 's/[^0-9]//g')
|
selected=( $(fc -l 1 | eval "$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r $FZF_CTRL_R_OPTS -q ${(q)LBUFFER}") )
|
||||||
LBUFFER=!$num
|
if [ -n "$selected" ]; then
|
||||||
zle expand-history
|
num=$selected[1]
|
||||||
|
if [ -n "$num" ]; then
|
||||||
|
zle vi-fetch-history -n $num
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
zle redisplay
|
zle redisplay
|
||||||
}
|
}
|
||||||
|
40
src/Dockerfile.android
Normal file
40
src/Dockerfile.android
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
FROM ubuntu:14.04
|
||||||
|
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||||
|
|
||||||
|
# apt-get
|
||||||
|
RUN apt-get update && apt-get -y upgrade && \
|
||||||
|
apt-get install -y --force-yes git curl build-essential
|
||||||
|
|
||||||
|
# Install Go 1.4
|
||||||
|
RUN cd / && curl \
|
||||||
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
|
tar -xz && mv go go1.4 && \
|
||||||
|
sed -i 's@#define PTHREAD_KEYS_MAX 128@@' /go1.4/src/runtime/cgo/gcc_android_arm.c
|
||||||
|
|
||||||
|
ENV GOROOT /go1.4
|
||||||
|
ENV PATH /go1.4/bin:$PATH
|
||||||
|
|
||||||
|
RUN cd / && \
|
||||||
|
curl -O http://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin && \
|
||||||
|
chmod 755 /android-ndk* && /android-ndk-r10e-linux-x86_64.bin && \
|
||||||
|
mv android-ndk-r10e /android-ndk
|
||||||
|
|
||||||
|
RUN cd /android-ndk && bash ./build/tools/make-standalone-toolchain.sh --platform=android-21 --install-dir=/ndk --arch=arm
|
||||||
|
|
||||||
|
ENV NDK_CC /ndk/bin/arm-linux-androideabi-gcc
|
||||||
|
|
||||||
|
RUN cd $GOROOT/src && \
|
||||||
|
CC_FOR_TARGET=$NDK_CC GOOS=android GOARCH=arm GOARM=7 ./make.bash
|
||||||
|
|
||||||
|
RUN cd / && curl \
|
||||||
|
http://ftp.gnu.org/gnu/ncurses/ncurses-5.9.tar.gz | \
|
||||||
|
tar -xz && cd /ncurses-5.9 && \
|
||||||
|
./configure CC=$NDK_CC CFLAGS="-fPIE -march=armv7-a -mfpu=neon -mhard-float -Wl,--no-warn-mismatch" LDFLAGS="-march=armv7-a -Wl,--no-warn-mismatch" --host=arm-linux --enable-overwrite --enable-const --without-cxx-binding --without-shared --without-debug --enable-widec --enable-ext-colors --enable-ext-mouse --enable-pc-files --with-pkg-config-libdir=$PKG_CONFIG_LIBDIR --without-manpages --without-ada --disable-shared --without-tests --prefix=/ndk/sysroot/usr --with-default-terminfo-dirs=/usr/share/terminfo --with-terminfo-dirs=/usr/share/terminfo ac_cv_header_locale_h=n ac_cv_func_getpwent=no ac_cv_func_getpwnam=no ac_cv_func_getpwuid=no && \
|
||||||
|
sed -i 's@#define HAVE_LOCALE_H 1@/* #undef HAVE_LOCALE_H */@' include/ncurses_cfg.h && \
|
||||||
|
make && \
|
||||||
|
sed -i '0,/echo.*/{s/echo.*/exit 0/}' misc/run_tic.sh && \
|
||||||
|
make install && \
|
||||||
|
mv /ndk/sysroot/usr/lib/libncursesw.a /ndk/sysroot/usr/lib/libncurses.a
|
||||||
|
|
||||||
|
# Default CMD
|
||||||
|
CMD cd /fzf/src && /bin/bash
|
@@ -2,6 +2,7 @@ FROM base/archlinux:2014.07.03
|
|||||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||||
|
|
||||||
# apt-get
|
# apt-get
|
||||||
|
RUN pacman-key --populate archlinux && pacman-key --refresh-keys
|
||||||
RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git
|
RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git
|
||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
@@ -9,7 +10,6 @@ RUN cd / && curl \
|
|||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
|
||||||
ENV GOROOT /go1.4
|
ENV GOROOT /go1.4
|
||||||
ENV PATH /go1.4/bin:$PATH
|
ENV PATH /go1.4/bin:$PATH
|
||||||
|
|
||||||
@@ -19,9 +19,6 @@ RUN echo '[multilib]' >> /etc/pacman.conf && \
|
|||||||
pacman-db-upgrade && yes | pacman -Sy gcc-multilib lib32-ncurses && \
|
pacman-db-upgrade && yes | pacman -Sy gcc-multilib lib32-ncurses && \
|
||||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||||
|
|
||||||
# Volume
|
|
||||||
VOLUME /go
|
|
||||||
|
|
||||||
# Default CMD
|
# Default CMD
|
||||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
CMD cd /fzf/src && /bin/bash
|
||||||
|
|
||||||
|
@@ -1,21 +1,32 @@
|
|||||||
FROM centos:centos7
|
FROM centos:centos6
|
||||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||||
|
|
||||||
# yum
|
# yum
|
||||||
RUN yum install -y git gcc make tar ncurses-devel
|
RUN yum install -y git gcc make tar glibc-devel glibc-devel.i686 \
|
||||||
|
ncurses-devel ncurses-static ncurses-devel.i686 \
|
||||||
|
gpm-devel gpm-static libgcc.i686
|
||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
RUN cd / && curl \
|
RUN cd / && curl \
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
# Install Go 1.5
|
||||||
ENV GOROOT /go1.4
|
RUN cd / && curl \
|
||||||
ENV PATH /go1.4/bin:$PATH
|
https://storage.googleapis.com/golang/go1.5.3.linux-amd64.tar.gz | \
|
||||||
|
tar -xz && mv go go1.5
|
||||||
|
|
||||||
# Volume
|
# Install RPMs for building static 32-bit binary
|
||||||
VOLUME /go
|
RUN curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.7/os/i386/Packages/ncurses-static-5.7-4.20090207.el6.i686.rpm -o rpm && rpm -i rpm && \
|
||||||
|
curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.7/os/i386/Packages/gpm-static-1.20.6-12.el6.i686.rpm -o rpm && rpm -i rpm
|
||||||
|
|
||||||
|
ENV GOROOT_BOOTSTRAP /go1.4
|
||||||
|
ENV GOROOT /go1.5
|
||||||
|
ENV PATH /go1.5/bin:$PATH
|
||||||
|
|
||||||
|
# For i386 build
|
||||||
|
RUN cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||||
|
|
||||||
# Default CMD
|
# Default CMD
|
||||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
CMD cd /fzf/src && /bin/bash
|
||||||
|
|
||||||
|
@@ -3,14 +3,13 @@ MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
|||||||
|
|
||||||
# apt-get
|
# apt-get
|
||||||
RUN apt-get update && apt-get -y upgrade && \
|
RUN apt-get update && apt-get -y upgrade && \
|
||||||
apt-get install -y --force-yes git curl build-essential libncurses-dev
|
apt-get install -y --force-yes git curl build-essential libncurses-dev libgpm-dev
|
||||||
|
|
||||||
# Install Go 1.4
|
# Install Go 1.4
|
||||||
RUN cd / && curl \
|
RUN cd / && curl \
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
||||||
tar -xz && mv go go1.4
|
tar -xz && mv go go1.4
|
||||||
|
|
||||||
ENV GOPATH /go
|
|
||||||
ENV GOROOT /go1.4
|
ENV GOROOT /go1.4
|
||||||
ENV PATH /go1.4/bin:$PATH
|
ENV PATH /go1.4/bin:$PATH
|
||||||
|
|
||||||
@@ -18,9 +17,6 @@ ENV PATH /go1.4/bin:$PATH
|
|||||||
RUN apt-get install -y lib32ncurses5-dev && \
|
RUN apt-get install -y lib32ncurses5-dev && \
|
||||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||||
|
|
||||||
# Volume
|
|
||||||
VOLUME /go
|
|
||||||
|
|
||||||
# Default CMD
|
# Default CMD
|
||||||
CMD cd /go/src/github.com/junegunn/fzf/src && /bin/bash
|
CMD cd /fzf/src && /bin/bash
|
||||||
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
The MIT License (MIT)
|
The MIT License (MIT)
|
||||||
|
|
||||||
Copyright (c) 2015 Junegunn Choi
|
Copyright (c) 2016 Junegunn Choi
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
126
src/Makefile
126
src/Makefile
@@ -1,74 +1,116 @@
|
|||||||
ifndef GOPATH
|
ifndef GOOS
|
||||||
$(error GOPATH is undefined)
|
|
||||||
endif
|
|
||||||
|
|
||||||
UNAME_S := $(shell uname -s)
|
UNAME_S := $(shell uname -s)
|
||||||
ifeq ($(UNAME_S),Darwin)
|
ifeq ($(UNAME_S),Darwin)
|
||||||
GOOS := darwin
|
GOOS := darwin
|
||||||
else ifeq ($(UNAME_S),Linux)
|
else ifeq ($(UNAME_S),Linux)
|
||||||
GOOS := linux
|
GOOS := linux
|
||||||
endif
|
endif
|
||||||
|
endif
|
||||||
|
|
||||||
ifneq ($(shell uname -m),x86_64)
|
SOURCES := $(wildcard *.go */*.go)
|
||||||
|
ROOTDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
|
||||||
|
BINDIR := $(shell dirname $(ROOTDIR))/bin
|
||||||
|
GOPATH := $(shell dirname $(ROOTDIR))/gopath
|
||||||
|
SRCDIR := $(GOPATH)/src/github.com/junegunn/fzf/src
|
||||||
|
DOCKEROPTS := -i -t -v $(ROOTDIR):/fzf/src
|
||||||
|
BINARY32 := fzf-$(GOOS)_386
|
||||||
|
BINARY64 := fzf-$(GOOS)_amd64
|
||||||
|
BINARYARM7 := fzf-$(GOOS)_arm7
|
||||||
|
VERSION := $(shell awk -F= '/version =/ {print $$2}' constants.go | tr -d "\" ")
|
||||||
|
RELEASE32 := fzf-$(VERSION)-$(GOOS)_386
|
||||||
|
RELEASE64 := fzf-$(VERSION)-$(GOOS)_amd64
|
||||||
|
RELEASEARM7 := fzf-$(VERSION)-$(GOOS)_arm7
|
||||||
|
export GOPATH
|
||||||
|
|
||||||
|
UNAME_M := $(shell uname -m)
|
||||||
|
ifeq ($(UNAME_M),x86_64)
|
||||||
|
BINARY := $(BINARY64)
|
||||||
|
else ifeq ($(UNAME_M),i686)
|
||||||
|
BINARY := $(BINARY32)
|
||||||
|
else
|
||||||
$(error "Build on $(UNAME_M) is not supported, yet.")
|
$(error "Build on $(UNAME_M) is not supported, yet.")
|
||||||
endif
|
endif
|
||||||
|
|
||||||
SOURCES := $(wildcard *.go */*.go)
|
all: fzf/$(BINARY)
|
||||||
BINDIR := ../bin
|
|
||||||
|
|
||||||
BINARY32 := fzf-$(GOOS)_386
|
release: test fzf/$(BINARY32) fzf/$(BINARY64)
|
||||||
BINARY64 := fzf-$(GOOS)_amd64
|
-cd fzf && cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32)
|
||||||
VERSION = $(shell fzf/$(BINARY64) --version)
|
cd fzf && cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
||||||
RELEASE32 = fzf-$(VERSION)-$(GOOS)_386
|
rm -f $(RELEASE32) $(RELEASE64)
|
||||||
RELEASE64 = fzf-$(VERSION)-$(GOOS)_amd64
|
|
||||||
|
|
||||||
all: release
|
$(SRCDIR):
|
||||||
|
mkdir -p $(shell dirname $(SRCDIR))
|
||||||
|
ln -s $(ROOTDIR) $(SRCDIR)
|
||||||
|
|
||||||
release: build
|
deps: $(SRCDIR) $(SOURCES)
|
||||||
cd fzf && \
|
cd $(SRCDIR) && go get
|
||||||
cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32) && \
|
|
||||||
cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
|
||||||
rm $(RELEASE32) $(RELEASE64)
|
|
||||||
|
|
||||||
build: test fzf/$(BINARY32) fzf/$(BINARY64)
|
android-build: $(SRCDIR)
|
||||||
|
cd $(SRCDIR) && GOARCH=arm GOARM=7 CGO_ENABLED=1 go get
|
||||||
|
cd $(SRCDIR)/fzf && GOARCH=arm GOARM=7 CGO_ENABLED=1 go build -a -ldflags="-w -extldflags=-pie" -o $(BINARYARM7)
|
||||||
|
cd $(SRCDIR)/fzf && cp $(BINARYARM7) $(RELEASEARM7) && tar -czf $(RELEASEARM7).tgz $(RELEASEARM7) && \
|
||||||
|
rm -f $(RELEASEARM7)
|
||||||
|
|
||||||
test:
|
test: deps
|
||||||
go get
|
SHELL=/bin/sh go test -v ./...
|
||||||
go test -v ./...
|
|
||||||
|
|
||||||
install: $(BINDIR)/fzf
|
install: $(BINDIR)/fzf
|
||||||
|
|
||||||
uninstall:
|
uninstall:
|
||||||
rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY64)
|
rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY)
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
cd fzf && rm -f $(BINARY32) $(BINARY64) $(RELEASE32).tgz $(RELEASE64).tgz
|
cd fzf && rm -f fzf-*
|
||||||
|
|
||||||
fzf/$(BINARY32): $(SOURCES)
|
fzf/$(BINARY32): deps
|
||||||
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -o $(BINARY32)
|
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -a -ldflags -w -tags "$(TAGS)" -o $(BINARY32)
|
||||||
|
|
||||||
fzf/$(BINARY64): $(SOURCES)
|
fzf/$(BINARY64): deps
|
||||||
cd fzf && go build -o $(BINARY64)
|
cd fzf && go build -a -ldflags -w -tags "$(TAGS)" -o $(BINARY64)
|
||||||
|
|
||||||
$(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)
|
$(BINDIR)/fzf: fzf/$(BINARY) | $(BINDIR)
|
||||||
cp -f fzf/$(BINARY64) $(BINDIR)
|
cp -f fzf/$(BINARY) $(BINDIR)
|
||||||
cd $(BINDIR) && ln -sf $(BINARY64) fzf
|
cd $(BINDIR) && ln -sf $(BINARY) fzf
|
||||||
|
|
||||||
$(BINDIR):
|
$(BINDIR):
|
||||||
mkdir -p $@
|
mkdir -p $@
|
||||||
|
|
||||||
# Linux distribution to build fzf on
|
docker-arch:
|
||||||
DISTRO := arch
|
docker build -t junegunn/arch-sandbox - < Dockerfile.arch
|
||||||
|
|
||||||
docker:
|
docker-ubuntu:
|
||||||
docker build -t junegunn/$(DISTRO)-sandbox - < Dockerfile.$(DISTRO)
|
docker build -t junegunn/ubuntu-sandbox - < Dockerfile.ubuntu
|
||||||
|
|
||||||
linux: docker
|
docker-centos:
|
||||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
docker build -t junegunn/centos-sandbox - < Dockerfile.centos
|
||||||
/bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make'
|
|
||||||
|
|
||||||
$(DISTRO): docker
|
docker-android:
|
||||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
docker build -t junegunn/android-sandbox - < Dockerfile.android
|
||||||
sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'
|
|
||||||
|
|
||||||
.PHONY: all build release test install uninstall clean docker linux $(DISTRO)
|
arch: docker-arch
|
||||||
|
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||||
|
sh -c 'cd /fzf/src; /bin/bash'
|
||||||
|
|
||||||
|
ubuntu: docker-ubuntu
|
||||||
|
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||||
|
sh -c 'cd /fzf/src; /bin/bash'
|
||||||
|
|
||||||
|
centos: docker-centos
|
||||||
|
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
||||||
|
sh -c 'cd /fzf/src; /bin/bash'
|
||||||
|
|
||||||
|
linux: docker-centos
|
||||||
|
docker run $(DOCKEROPTS) junegunn/centos-sandbox \
|
||||||
|
/bin/bash -ci 'cd /fzf/src; make TAGS=static release'
|
||||||
|
|
||||||
|
ubuntu-android: docker-android
|
||||||
|
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
||||||
|
sh -c 'cd /fzf/src; /bin/bash'
|
||||||
|
|
||||||
|
android: docker-android
|
||||||
|
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
||||||
|
/bin/bash -ci 'cd /fzf/src; GOOS=android make android-build'
|
||||||
|
|
||||||
|
.PHONY: all deps release test install uninstall clean \
|
||||||
|
linux arch ubuntu centos docker-arch docker-ubuntu docker-centos \
|
||||||
|
android-build docker-android ubuntu-android android
|
||||||
|
@@ -79,7 +79,7 @@ Build
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Build fzf executables and tarballs
|
# Build fzf executables and tarballs
|
||||||
make
|
make release
|
||||||
|
|
||||||
# Install the executable to ../bin directory
|
# Install the executable to ../bin directory
|
||||||
make install
|
make install
|
||||||
|
264
src/algo/algo.go
264
src/algo/algo.go
@@ -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
|
||||||
@@ -10,13 +15,102 @@ import "strings"
|
|||||||
* In short: They try to do as little work as possible.
|
* In short: They try to do as little work as possible.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// FuzzyMatch performs fuzzy-match
|
func runeAt(runes []rune, index int, max int, forward bool) rune {
|
||||||
func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
if forward {
|
||||||
if len(pattern) == 0 {
|
return runes[index]
|
||||||
return 0, 0
|
|
||||||
}
|
}
|
||||||
|
return runes[max-index-1]
|
||||||
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
// Result conatins the results of running a match function.
|
||||||
|
type Result struct {
|
||||||
|
Start int32
|
||||||
|
End int32
|
||||||
|
|
||||||
|
// Items are basically sorted by the lengths of matched substrings.
|
||||||
|
// But we slightly adjust the score with bonus for better results.
|
||||||
|
Bonus int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type charClass int
|
||||||
|
|
||||||
|
const (
|
||||||
|
charNonWord charClass = iota
|
||||||
|
charLower
|
||||||
|
charUpper
|
||||||
|
charLetter
|
||||||
|
charNumber
|
||||||
|
)
|
||||||
|
|
||||||
|
func evaluateBonus(caseSensitive bool, runes []rune, pattern []rune, sidx int, eidx int) int32 {
|
||||||
|
var bonus int32
|
||||||
|
pidx := 0
|
||||||
|
lenPattern := len(pattern)
|
||||||
|
consecutive := false
|
||||||
|
prevClass := charNonWord
|
||||||
|
for index := 0; index < eidx; index++ {
|
||||||
|
char := runes[index]
|
||||||
|
var class charClass
|
||||||
|
if unicode.IsLower(char) {
|
||||||
|
class = charLower
|
||||||
|
} else if unicode.IsUpper(char) {
|
||||||
|
class = charUpper
|
||||||
|
} else if unicode.IsLetter(char) {
|
||||||
|
class = charLetter
|
||||||
|
} else if unicode.IsNumber(char) {
|
||||||
|
class = charNumber
|
||||||
|
} else {
|
||||||
|
class = charNonWord
|
||||||
|
}
|
||||||
|
|
||||||
|
var point int32
|
||||||
|
if prevClass == charNonWord && class != charNonWord {
|
||||||
|
// Word boundary
|
||||||
|
point = 2
|
||||||
|
} else if prevClass == charLower && class == charUpper ||
|
||||||
|
prevClass != charNumber && class == charNumber {
|
||||||
|
// camelCase letter123
|
||||||
|
point = 1
|
||||||
|
}
|
||||||
|
prevClass = class
|
||||||
|
|
||||||
|
if index >= sidx {
|
||||||
|
if !caseSensitive {
|
||||||
|
if char >= 'A' && char <= 'Z' {
|
||||||
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pchar := pattern[pidx]
|
||||||
|
if pchar == char {
|
||||||
|
// Boost bonus for the first character in the pattern
|
||||||
|
if pidx == 0 {
|
||||||
|
point *= 2
|
||||||
|
}
|
||||||
|
// Bonus to consecutive matching chars
|
||||||
|
if consecutive {
|
||||||
|
point++
|
||||||
|
}
|
||||||
|
bonus += point
|
||||||
|
|
||||||
|
if pidx++; pidx == lenPattern {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
consecutive = true
|
||||||
|
} else {
|
||||||
|
consecutive = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bonus
|
||||||
|
}
|
||||||
|
|
||||||
|
// FuzzyMatch performs fuzzy-match
|
||||||
|
func FuzzyMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||||
|
if len(pattern) == 0 {
|
||||||
|
return Result{0, 0, 0}
|
||||||
|
}
|
||||||
|
|
||||||
// 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,17 +125,29 @@ func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
|||||||
sidx := -1
|
sidx := -1
|
||||||
eidx := -1
|
eidx := -1
|
||||||
|
|
||||||
for index, char := range runes {
|
lenRunes := len(runes)
|
||||||
|
lenPattern := len(pattern)
|
||||||
|
|
||||||
|
for index := range runes {
|
||||||
|
char := runeAt(runes, index, lenRunes, forward)
|
||||||
// This is considerably faster than blindly applying strings.ToLower to the
|
// This is considerably faster than blindly applying strings.ToLower to the
|
||||||
// whole string
|
// whole string
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
char += 32
|
// 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
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if char == pattern[pidx] {
|
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||||
|
if char == pchar {
|
||||||
if sidx < 0 {
|
if sidx < 0 {
|
||||||
sidx = index
|
sidx = index
|
||||||
}
|
}
|
||||||
if pidx++; pidx == len(pattern) {
|
if pidx++; pidx == lenPattern {
|
||||||
eidx = index + 1
|
eidx = index + 1
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -51,41 +157,34 @@ 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 := runeAt(runes, index, lenRunes, forward)
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
char += 32
|
if char >= 'A' && char <= 'Z' {
|
||||||
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if char == pattern[pidx] {
|
|
||||||
|
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||||
|
if char == pchar {
|
||||||
if pidx--; pidx < 0 {
|
if pidx--; pidx < 0 {
|
||||||
sidx = index
|
sidx = index
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return sidx, eidx
|
|
||||||
}
|
|
||||||
return -1, -1
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExactMatchStrings performs exact-match using strings package.
|
// Calculate the bonus. This can't be done at the same time as the
|
||||||
// Currently not used.
|
// pattern scan above because 'forward' may be false.
|
||||||
func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
if !forward {
|
||||||
if len(pattern) == 0 {
|
sidx, eidx = lenRunes-eidx, lenRunes-sidx
|
||||||
return 0, 0
|
}
|
||||||
}
|
|
||||||
|
|
||||||
var str string
|
return Result{int32(sidx), int32(eidx),
|
||||||
if caseSensitive {
|
evaluateBonus(caseSensitive, runes, pattern, sidx, eidx)}
|
||||||
str = *input
|
|
||||||
} else {
|
|
||||||
str = strings.ToLower(*input)
|
|
||||||
}
|
}
|
||||||
|
return Result{-1, -1, 0}
|
||||||
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
|
||||||
@@ -95,73 +194,108 @@ 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, forward bool, runes []rune, pattern []rune) Result {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return 0, 0
|
return Result{0, 0, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
runes := []rune(*input)
|
lenRunes := len(runes)
|
||||||
numRunes := len(runes)
|
lenPattern := len(pattern)
|
||||||
plen := len(pattern)
|
|
||||||
if numRunes < plen {
|
if lenRunes < lenPattern {
|
||||||
return -1, -1
|
return Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
pidx := 0
|
pidx := 0
|
||||||
for index := 0; index < numRunes; index++ {
|
for index := 0; index < lenRunes; index++ {
|
||||||
char := runes[index]
|
char := runeAt(runes, index, lenRunes, forward)
|
||||||
if !caseSensitive && char >= 65 && char <= 90 {
|
if !caseSensitive {
|
||||||
char += 32
|
if char >= 'A' && char <= 'Z' {
|
||||||
|
char += 32
|
||||||
|
} else if char > unicode.MaxASCII {
|
||||||
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if pattern[pidx] == char {
|
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||||
|
if pchar == char {
|
||||||
pidx++
|
pidx++
|
||||||
if pidx == plen {
|
if pidx == lenPattern {
|
||||||
return index - plen + 1, index + 1
|
var sidx, eidx int
|
||||||
|
if forward {
|
||||||
|
sidx = index - lenPattern + 1
|
||||||
|
eidx = index + 1
|
||||||
|
} else {
|
||||||
|
sidx = lenRunes - (index + 1)
|
||||||
|
eidx = lenRunes - (index - lenPattern + 1)
|
||||||
|
}
|
||||||
|
return Result{int32(sidx), int32(eidx),
|
||||||
|
evaluateBonus(caseSensitive, runes, pattern, sidx, eidx)}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
index -= pidx
|
index -= pidx
|
||||||
pidx = 0
|
pidx = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1, -1
|
return Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
// PrefixMatch performs prefix-match
|
// PrefixMatch performs prefix-match
|
||||||
func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func PrefixMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||||
runes := []rune(*input)
|
|
||||||
if len(runes) < len(pattern) {
|
if len(runes) < len(pattern) {
|
||||||
return -1, -1
|
return Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return 0, len(pattern)
|
lenPattern := len(pattern)
|
||||||
|
return Result{0, int32(lenPattern),
|
||||||
|
evaluateBonus(caseSensitive, runes, pattern, 0, lenPattern)}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SuffixMatch performs suffix-match
|
// SuffixMatch performs suffix-match
|
||||||
func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {
|
func SuffixMatch(caseSensitive bool, forward bool, input []rune, pattern []rune) Result {
|
||||||
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 {
|
||||||
return -1, -1
|
return Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return trimmedLen - len(pattern), trimmedLen
|
lenPattern := len(pattern)
|
||||||
|
sidx := trimmedLen - lenPattern
|
||||||
|
eidx := trimmedLen
|
||||||
|
return Result{int32(sidx), int32(eidx),
|
||||||
|
evaluateBonus(caseSensitive, runes, pattern, sidx, eidx)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// EqualMatch performs equal-match
|
||||||
|
func EqualMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) Result {
|
||||||
|
// Note: EqualMatch always return a zero bonus.
|
||||||
|
if len(runes) != len(pattern) {
|
||||||
|
return Result{-1, -1, 0}
|
||||||
|
}
|
||||||
|
runesStr := string(runes)
|
||||||
|
if !caseSensitive {
|
||||||
|
runesStr = strings.ToLower(runesStr)
|
||||||
|
}
|
||||||
|
if runesStr == string(pattern) {
|
||||||
|
return Result{0, int32(len(pattern)), 0}
|
||||||
|
}
|
||||||
|
return Result{-1, -1, 0}
|
||||||
}
|
}
|
||||||
|
@@ -5,48 +5,91 @@ 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, bool, []rune, []rune) Result, caseSensitive, forward bool, input, pattern string, sidx int32, eidx int32, bonus int32) {
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
pattern = strings.ToLower(pattern)
|
pattern = strings.ToLower(pattern)
|
||||||
}
|
}
|
||||||
s, e := fun(caseSensitive, &input, []rune(pattern))
|
res := fun(caseSensitive, forward, []rune(input), []rune(pattern))
|
||||||
if s != sidx {
|
if res.Start != 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)", res.Start, sidx, input, pattern)
|
||||||
}
|
}
|
||||||
if e != eidx {
|
if res.End != eidx {
|
||||||
t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", e, eidx, input, pattern)
|
t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", res.End, eidx, input, pattern)
|
||||||
|
}
|
||||||
|
if res.Bonus != bonus {
|
||||||
|
t.Errorf("Invalid bonus: %d (expected: %d, %s / %s)", res.Bonus, bonus, input, pattern)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFuzzyMatch(t *testing.T) {
|
func TestFuzzyMatch(t *testing.T) {
|
||||||
assertMatch(t, FuzzyMatch, false, "fooBarbaz", "oBZ", 2, 9)
|
assertMatch(t, FuzzyMatch, false, true, "fooBarbaz", "oBZ", 2, 9, 2)
|
||||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBZ", -1, -1)
|
assertMatch(t, FuzzyMatch, false, true, "foo bar baz", "fbb", 0, 9, 8)
|
||||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBz", 2, 9)
|
assertMatch(t, FuzzyMatch, false, true, "/AutomatorDocument.icns", "rdoc", 9, 13, 4)
|
||||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
assertMatch(t, FuzzyMatch, false, true, "/man1/zshcompctl.1", "zshc", 6, 10, 7)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "/.oh-my-zsh/cache", "zshc", 8, 13, 8)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "ab0123 456", "12356", 3, 10, 3)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "abc123 456", "12356", 3, 10, 5)
|
||||||
|
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "foo/bar/baz", "fbb", 0, 9, 8)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "fooBarBaz", "fbb", 0, 7, 6)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "foo barbaz", "fbb", 0, 8, 6)
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "fooBar Baz", "foob", 0, 4, 8)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBZ", -1, -1, 0)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBz", 2, 9, 2)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "Foo Bar Baz", "fbb", -1, -1, 0)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "Foo/Bar/Baz", "FBB", 0, 9, 8)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "FooBarBaz", "FBB", 0, 7, 6)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "foo BarBaz", "fBB", 0, 8, 7)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "FooBar Baz", "FooB", 0, 4, 8)
|
||||||
|
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "fooBarbazz", -1, -1, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFuzzyMatchBackward(t *testing.T) {
|
||||||
|
assertMatch(t, FuzzyMatch, false, true, "foobar fb", "fb", 0, 4, 4)
|
||||||
|
assertMatch(t, FuzzyMatch, false, false, "foobar fb", "fb", 7, 9, 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExactMatchNaive(t *testing.T) {
|
func TestExactMatchNaive(t *testing.T) {
|
||||||
assertMatch(t, ExactMatchNaive, false, "fooBarbaz", "oBA", 2, 5)
|
for _, dir := range []bool{true, false} {
|
||||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "oBA", -1, -1)
|
assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5, 3)
|
||||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1, 0)
|
||||||
|
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1, 0)
|
||||||
|
|
||||||
|
assertMatch(t, ExactMatchNaive, false, dir, "/AutomatorDocument.icns", "rdoc", 9, 13, 4)
|
||||||
|
assertMatch(t, ExactMatchNaive, false, dir, "/man1/zshcompctl.1", "zshc", 6, 10, 7)
|
||||||
|
assertMatch(t, ExactMatchNaive, false, dir, "/.oh-my-zsh/cache", "zsh/c", 8, 13, 10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExactMatchNaiveBackward(t *testing.T) {
|
||||||
|
assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3, 1)
|
||||||
|
assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPrefixMatch(t *testing.T) {
|
func TestPrefixMatch(t *testing.T) {
|
||||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "Foo", 0, 3)
|
for _, dir := range []bool{true, false} {
|
||||||
assertMatch(t, PrefixMatch, true, "fooBarbaz", "Foo", -1, -1)
|
assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1, 0)
|
||||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "baz", -1, -1)
|
assertMatch(t, PrefixMatch, false, dir, "fooBarBaz", "baz", -1, -1, 0)
|
||||||
|
assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, 6)
|
||||||
|
assertMatch(t, PrefixMatch, false, dir, "foOBarBaZ", "foo", 0, 3, 7)
|
||||||
|
assertMatch(t, PrefixMatch, false, dir, "f-oBarbaz", "f-o", 0, 3, 8)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSuffixMatch(t *testing.T) {
|
func TestSuffixMatch(t *testing.T) {
|
||||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "Foo", -1, -1)
|
for _, dir := range []bool{true, false} {
|
||||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)
|
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0)
|
||||||
assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)
|
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9, 2)
|
||||||
|
assertMatch(t, SuffixMatch, false, dir, "fooBarBaZ", "baz", 6, 9, 5)
|
||||||
|
assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1, 0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEmptyPattern(t *testing.T) {
|
func TestEmptyPattern(t *testing.T) {
|
||||||
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
for _, dir := range []bool{true, false} {
|
||||||
assertMatch(t, ExactMatchStrings, true, "foobar", "", 0, 0)
|
assertMatch(t, FuzzyMatch, true, dir, "foobar", "", 0, 0, 0)
|
||||||
assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)
|
assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0, 0)
|
||||||
assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)
|
assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0, 0)
|
||||||
assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)
|
assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6, 0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
21
src/ansi.go
21
src/ansi.go
@@ -36,21 +36,23 @@ func init() {
|
|||||||
ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")
|
ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractColor(str *string) (*string, []ansiOffset) {
|
func extractColor(str string, state *ansiState) (string, []ansiOffset, *ansiState) {
|
||||||
var offsets []ansiOffset
|
var offsets []ansiOffset
|
||||||
|
|
||||||
var output bytes.Buffer
|
var output bytes.Buffer
|
||||||
var state *ansiState
|
|
||||||
|
if state != nil {
|
||||||
|
offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})
|
||||||
|
}
|
||||||
|
|
||||||
idx := 0
|
idx := 0
|
||||||
for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {
|
for _, offset := range ansiRegex.FindAllStringIndex(str, -1) {
|
||||||
output.WriteString((*str)[idx:offset[0]])
|
output.WriteString(str[idx:offset[0]])
|
||||||
newState := interpretCode((*str)[offset[0]:offset[1]], state)
|
newState := interpretCode(str[offset[0]:offset[1]], state)
|
||||||
|
|
||||||
if !newState.equals(state) {
|
if !newState.equals(state) {
|
||||||
if state != nil {
|
if state != nil {
|
||||||
// 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() {
|
||||||
@@ -67,7 +69,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
|||||||
idx = offset[1]
|
idx = offset[1]
|
||||||
}
|
}
|
||||||
|
|
||||||
rest := (*str)[idx:]
|
rest := str[idx:]
|
||||||
if len(rest) > 0 {
|
if len(rest) > 0 {
|
||||||
output.WriteString(rest)
|
output.WriteString(rest)
|
||||||
if state != nil {
|
if state != nil {
|
||||||
@@ -75,8 +77,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
|||||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outputStr := output.String()
|
return output.String(), offsets, state
|
||||||
return &outputStr, offsets
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
||||||
|
@@ -14,79 +14,89 @@ func TestExtractColor(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
src := "hello world"
|
src := "hello world"
|
||||||
|
var state *ansiState
|
||||||
clean := "\x1b[0m"
|
clean := "\x1b[0m"
|
||||||
check := func(assertion func(ansiOffsets []ansiOffset)) {
|
check := func(assertion func(ansiOffsets []ansiOffset, state *ansiState)) {
|
||||||
output, ansiOffsets := extractColor(&src)
|
output, ansiOffsets, newState := extractColor(src, state)
|
||||||
if *output != "hello world" {
|
state = newState
|
||||||
|
if output != "hello world" {
|
||||||
t.Errorf("Invalid output: {}", output)
|
t.Errorf("Invalid output: {}", output)
|
||||||
}
|
}
|
||||||
fmt.Println(src, ansiOffsets, clean)
|
fmt.Println(src, ansiOffsets, clean)
|
||||||
assertion(ansiOffsets)
|
assertion(ansiOffsets, state)
|
||||||
}
|
}
|
||||||
|
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) > 0 {
|
if len(offsets) > 0 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[0mhello world"
|
src = "\x1b[0mhello world"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) > 0 {
|
if len(offsets) > 0 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello world"
|
src = "\x1b[1mhello world"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 11, -1, -1, true)
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello \x1b[mworld"
|
src = "\x1b[1mhello \x1b[mworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 6, -1, -1, true)
|
assert(offsets[0], 0, 6, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "\x1b[1mhello \x1b[Kworld"
|
src = "\x1b[1mhello \x1b[Kworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 0, 11, -1, -1, true)
|
assert(offsets[0], 0, 11, -1, -1, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mworld"
|
src = "hello \x1b[34;45;1mworld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 11, 4, 5, true)
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 11, 4, 5, true)
|
assert(offsets[0], 6, 11, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 1 {
|
if len(offsets) != 1 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 9, 4, 5, true)
|
assert(offsets[0], 6, 9, 4, 5, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
|
src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 3 {
|
if len(offsets) != 3 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
@@ -96,12 +106,47 @@ func TestExtractColor(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// {38,48};5;{38,48}
|
// {38,48};5;{38,48}
|
||||||
|
state = nil
|
||||||
src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
|
src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
|
||||||
check(func(offsets []ansiOffset) {
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
if len(offsets) != 2 {
|
if len(offsets) != 2 {
|
||||||
t.Fail()
|
t.Fail()
|
||||||
}
|
}
|
||||||
assert(offsets[0], 6, 9, 38, 48, true)
|
assert(offsets[0], 6, 9, 38, 48, true)
|
||||||
assert(offsets[1], 9, 10, 48, 38, true)
|
assert(offsets[1], 9, 10, 48, 38, true)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[32;1mworld"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 6, 11, 2, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello world"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 1 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 11, 2, -1, true)
|
||||||
|
})
|
||||||
|
|
||||||
|
src = "hello \x1b[0;38;5;200;48;5;100mworld"
|
||||||
|
check(func(offsets []ansiOffset, state *ansiState) {
|
||||||
|
if len(offsets) != 2 {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
if state.fg != 200 || state.bg != 100 || state.bold {
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
assert(offsets[0], 0, 6, 2, -1, true)
|
||||||
|
assert(offsets[1], 6, 11, 200, 100, false)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
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,15 +2,12 @@ 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
|
||||||
// string and an integer
|
// string and an integer
|
||||||
type ItemBuilder func(*string, int) *Item
|
type ItemBuilder func([]byte, int) *Item
|
||||||
|
|
||||||
// ChunkList is a list of Chunks
|
// ChunkList is a list of Chunks
|
||||||
type ChunkList struct {
|
type ChunkList struct {
|
||||||
@@ -29,13 +26,18 @@ func NewChunkList(trans ItemBuilder) *ChunkList {
|
|||||||
trans: trans}
|
trans: trans}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Chunk) push(trans ItemBuilder, data *string, index int) {
|
func (c *Chunk) push(trans ItemBuilder, data []byte, index int) bool {
|
||||||
*c = append(*c, trans(data, index))
|
item := trans(data, index)
|
||||||
|
if item != nil {
|
||||||
|
*c = append(*c, item)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsFull returns true if the Chunk is full
|
// IsFull returns true if the Chunk is full
|
||||||
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,21 +49,24 @@ 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
|
||||||
func (cl *ChunkList) Push(data string) {
|
func (cl *ChunkList) Push(data []byte) bool {
|
||||||
cl.mutex.Lock()
|
cl.mutex.Lock()
|
||||||
defer cl.mutex.Unlock()
|
defer cl.mutex.Unlock()
|
||||||
|
|
||||||
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
cl.lastChunk().push(cl.trans, &data, cl.count)
|
if cl.lastChunk().push(cl.trans, data, cl.count) {
|
||||||
cl.count++
|
cl.count++
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot returns immutable snapshot of the ChunkList
|
// Snapshot returns immutable snapshot of the ChunkList
|
||||||
|
@@ -6,8 +6,11 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestChunkList(t *testing.T) {
|
func TestChunkList(t *testing.T) {
|
||||||
cl := NewChunkList(func(s *string, i int) *Item {
|
// FIXME global
|
||||||
return &Item{text: s, rank: Rank{0, 0, uint32(i * 2)}}
|
sortCriteria = []criterion{byMatchLen, byLength}
|
||||||
|
|
||||||
|
cl := NewChunkList(func(s []byte, i int) *Item {
|
||||||
|
return &Item{text: []rune(string(s)), rank: buildEmptyRank(int32(i * 2))}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Snapshot
|
// Snapshot
|
||||||
@@ -17,8 +20,8 @@ func TestChunkList(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add some data
|
// Add some data
|
||||||
cl.Push("hello")
|
cl.Push([]byte("hello"))
|
||||||
cl.Push("world")
|
cl.Push([]byte("world"))
|
||||||
|
|
||||||
// Previously created snapshot should remain the same
|
// Previously created snapshot should remain the same
|
||||||
if len(snapshot) > 0 {
|
if len(snapshot) > 0 {
|
||||||
@@ -36,8 +39,11 @@ func TestChunkList(t *testing.T) {
|
|||||||
if len(*chunk1) != 2 {
|
if len(*chunk1) != 2 {
|
||||||
t.Error("Snapshot should contain only two items")
|
t.Error("Snapshot should contain only two items")
|
||||||
}
|
}
|
||||||
if *(*chunk1)[0].text != "hello" || (*chunk1)[0].rank.index != 0 ||
|
last := func(arr [5]int32) int32 {
|
||||||
*(*chunk1)[1].text != "world" || (*chunk1)[1].rank.index != 2 {
|
return arr[len(arr)-1]
|
||||||
|
}
|
||||||
|
if string((*chunk1)[0].text) != "hello" || last((*chunk1)[0].rank) != 0 ||
|
||||||
|
string((*chunk1)[1].text) != "world" || last((*chunk1)[1].rank) != 2 {
|
||||||
t.Error("Invalid data")
|
t.Error("Invalid data")
|
||||||
}
|
}
|
||||||
if chunk1.IsFull() {
|
if chunk1.IsFull() {
|
||||||
@@ -45,8 +51,8 @@ func TestChunkList(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add more data
|
// Add more data
|
||||||
for i := 0; i < ChunkSize*2; i++ {
|
for i := 0; i < chunkSize*2; i++ {
|
||||||
cl.Push(fmt.Sprintf("item %d", i))
|
cl.Push([]byte(fmt.Sprintf("item %d", i)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Previous snapshot should remain the same
|
// Previous snapshot should remain the same
|
||||||
@@ -57,15 +63,15 @@ 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 {
|
||||||
t.Error("Unexpected number of items")
|
t.Error("Unexpected number of items")
|
||||||
}
|
}
|
||||||
|
|
||||||
cl.Push("hello")
|
cl.Push([]byte("hello"))
|
||||||
cl.Push("world")
|
cl.Push([]byte("world"))
|
||||||
|
|
||||||
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
||||||
if lastChunkCount != 2 {
|
if lastChunkCount != 2 {
|
||||||
|
@@ -1,11 +1,45 @@
|
|||||||
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.13.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 | sed s/^..//`
|
||||||
|
|
||||||
|
// Terminal
|
||||||
|
initialDelay = 20 * time.Millisecond
|
||||||
|
initialDelayTac = 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
|
||||||
|
|
||||||
|
// Jump labels
|
||||||
|
defaultJumpLabels string = "asdfghjklqwertyuiopzxcvbnm1234567890ASDFGHJKLQWERTYUIOPZXCVBNM`~;:,<.>/?'\"!@#$%^&*()[{]}-_=+"
|
||||||
|
)
|
||||||
|
|
||||||
// fzf events
|
// fzf events
|
||||||
const (
|
const (
|
||||||
@@ -14,5 +48,13 @@ const (
|
|||||||
EvtSearchNew
|
EvtSearchNew
|
||||||
EvtSearchProgress
|
EvtSearchProgress
|
||||||
EvtSearchFin
|
EvtSearchFin
|
||||||
|
EvtHeader
|
||||||
EvtClose
|
EvtClose
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
exitOk = 0
|
||||||
|
exitNoMatch = 1
|
||||||
|
exitError = 2
|
||||||
|
exitInterrupt = 130
|
||||||
|
)
|
||||||
|
126
src/core.go
126
src/core.go
@@ -3,7 +3,7 @@ Package fzf implements fzf, a command-line fuzzy finder.
|
|||||||
|
|
||||||
The MIT License (MIT)
|
The MIT License (MIT)
|
||||||
|
|
||||||
Copyright (c) 2015 Junegunn Choi
|
Copyright (c) 2016 Junegunn Choi
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
@@ -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())
|
||||||
}
|
}
|
||||||
@@ -47,65 +44,85 @@ Reader -> EvtReadNew -> Matcher (restart)
|
|||||||
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
||||||
Matcher -> EvtSearchProgress -> Terminal (update info)
|
Matcher -> EvtSearchProgress -> Terminal (update info)
|
||||||
Matcher -> EvtSearchFin -> Terminal (update list)
|
Matcher -> EvtSearchFin -> Terminal (update list)
|
||||||
|
Matcher -> EvtHeader -> Terminal (update header)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Run starts fzf
|
// Run starts fzf
|
||||||
func Run(options *Options) {
|
func Run(opts *Options) {
|
||||||
initProcs()
|
initProcs()
|
||||||
|
|
||||||
opts := ParseOptions()
|
|
||||||
sort := opts.Sort > 0
|
sort := opts.Sort > 0
|
||||||
|
sortCriteria = opts.Criteria
|
||||||
|
|
||||||
if opts.Version {
|
if opts.Version {
|
||||||
fmt.Println(Version)
|
fmt.Println(version)
|
||||||
os.Exit(0)
|
os.Exit(exitOk)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Event channel
|
// Event channel
|
||||||
eventBox := util.NewEventBox()
|
eventBox := util.NewEventBox()
|
||||||
|
|
||||||
// ANSI code processor
|
// ANSI code processor
|
||||||
ansiProcessor := func(data *string) (*string, []ansiOffset) {
|
ansiProcessor := func(data []byte) ([]rune, []ansiOffset) {
|
||||||
// By default, we do nothing
|
return util.BytesToRunes(data), nil
|
||||||
|
}
|
||||||
|
ansiProcessorRunes := func(data []rune) ([]rune, []ansiOffset) {
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
if opts.Ansi {
|
if opts.Ansi {
|
||||||
if opts.Color {
|
if opts.Theme != nil {
|
||||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
var state *ansiState
|
||||||
return extractColor(data)
|
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||||
|
trimmed, offsets, newState := extractColor(string(data), state)
|
||||||
|
state = newState
|
||||||
|
return []rune(trimmed), offsets
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// When color is disabled but ansi option is given,
|
// When color is disabled but ansi option is given,
|
||||||
// we simply strip out ANSI codes from the input
|
// we simply strip out ANSI codes from the input
|
||||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||||
trimmed, _ := extractColor(data)
|
trimmed, _, _ := extractColor(string(data), nil)
|
||||||
return trimmed, nil
|
return []rune(trimmed), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ansiProcessorRunes = func(data []rune) ([]rune, []ansiOffset) {
|
||||||
|
return ansiProcessor([]byte(string(data)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chunk list
|
// Chunk list
|
||||||
var chunkList *ChunkList
|
var chunkList *ChunkList
|
||||||
|
header := make([]string, 0, opts.HeaderLines)
|
||||||
if len(opts.WithNth) == 0 {
|
if len(opts.WithNth) == 0 {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||||
data, colors := ansiProcessor(data)
|
if len(header) < opts.HeaderLines {
|
||||||
|
header = append(header, string(data))
|
||||||
|
eventBox.Set(EvtHeader, header)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
runes, colors := ansiProcessor(data)
|
||||||
return &Item{
|
return &Item{
|
||||||
text: data,
|
text: runes,
|
||||||
index: uint32(index),
|
|
||||||
colors: colors,
|
colors: colors,
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
rank: buildEmptyRank(int32(index))}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||||
tokens := Tokenize(data, opts.Delimiter)
|
runes := util.BytesToRunes(data)
|
||||||
|
tokens := Tokenize(runes, opts.Delimiter)
|
||||||
|
trans := Transform(tokens, opts.WithNth)
|
||||||
|
if len(header) < opts.HeaderLines {
|
||||||
|
header = append(header, string(joinTokens(trans)))
|
||||||
|
eventBox.Set(EvtHeader, header)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
item := Item{
|
item := Item{
|
||||||
text: Transform(tokens, opts.WithNth).whole,
|
text: joinTokens(trans),
|
||||||
origText: data,
|
origText: &runes,
|
||||||
index: uint32(index),
|
|
||||||
colors: nil,
|
colors: nil,
|
||||||
rank: Rank{0, 0, uint32(index)}}
|
rank: buildEmptyRank(int32(index))}
|
||||||
|
|
||||||
trimmed, colors := ansiProcessor(item.text)
|
trimmed, colors := ansiProcessorRunes(item.text)
|
||||||
item.text = trimmed
|
item.text = trimmed
|
||||||
item.colors = colors
|
item.colors = colors
|
||||||
return &item
|
return &item
|
||||||
@@ -115,14 +132,27 @@ 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(data []byte) bool {
|
||||||
|
return chunkList.Push(data)
|
||||||
|
}, eventBox, opts.ReadZero}
|
||||||
go reader.ReadSource()
|
go reader.ReadSource()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matcher
|
// Matcher
|
||||||
|
forward := true
|
||||||
|
for _, cri := range opts.Criteria[1:] {
|
||||||
|
if cri == byEnd {
|
||||||
|
forward = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if cri == byBegin {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
patternBuilder := func(runes []rune) *Pattern {
|
patternBuilder := func(runes []rune) *Pattern {
|
||||||
return BuildPattern(
|
return BuildPattern(
|
||||||
opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)
|
opts.Fuzzy, opts.Extended, opts.Case, forward,
|
||||||
|
opts.Nth, opts.Delimiter, runes)
|
||||||
}
|
}
|
||||||
matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)
|
matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)
|
||||||
|
|
||||||
@@ -134,14 +164,17 @@ func Run(options *Options) {
|
|||||||
|
|
||||||
pattern := patternBuilder([]rune(*opts.Filter))
|
pattern := patternBuilder([]rune(*opts.Filter))
|
||||||
|
|
||||||
|
found := false
|
||||||
if streamingFilter {
|
if streamingFilter {
|
||||||
reader := Reader{
|
reader := Reader{
|
||||||
func(str string) {
|
func(runes []byte) bool {
|
||||||
item := chunkList.trans(&str, 0)
|
item := chunkList.trans(runes, 0)
|
||||||
if pattern.MatchItem(item) {
|
if item != nil && pattern.MatchItem(item) {
|
||||||
fmt.Println(*item.text)
|
fmt.Println(string(item.text))
|
||||||
|
found = true
|
||||||
}
|
}
|
||||||
}, eventBox}
|
return false
|
||||||
|
}, eventBox, opts.ReadZero}
|
||||||
reader.ReadSource()
|
reader.ReadSource()
|
||||||
} else {
|
} else {
|
||||||
eventBox.Unwatch(EvtReadNew)
|
eventBox.Unwatch(EvtReadNew)
|
||||||
@@ -152,10 +185,14 @@ func Run(options *Options) {
|
|||||||
chunks: snapshot,
|
chunks: snapshot,
|
||||||
pattern: pattern})
|
pattern: pattern})
|
||||||
for i := 0; i < merger.Length(); i++ {
|
for i := 0; i < merger.Length(); i++ {
|
||||||
fmt.Println(merger.Get(i).AsString())
|
fmt.Println(merger.Get(i).AsString(opts.Ansi))
|
||||||
|
found = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
os.Exit(0)
|
if found {
|
||||||
|
os.Exit(exitOk)
|
||||||
|
}
|
||||||
|
os.Exit(exitNoMatch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Synchronous search
|
// Synchronous search
|
||||||
@@ -194,8 +231,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)
|
||||||
@@ -207,6 +245,9 @@ func Run(options *Options) {
|
|||||||
terminal.UpdateProgress(val)
|
terminal.UpdateProgress(val)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case EvtHeader:
|
||||||
|
terminal.UpdateHeader(value.([]string))
|
||||||
|
|
||||||
case EvtSearchFin:
|
case EvtSearchFin:
|
||||||
switch val := value.(type) {
|
switch val := value.(type) {
|
||||||
case *Merger:
|
case *Merger:
|
||||||
@@ -224,9 +265,12 @@ func Run(options *Options) {
|
|||||||
fmt.Println()
|
fmt.Println()
|
||||||
}
|
}
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
fmt.Println(val.Get(i).AsString())
|
fmt.Println(val.Get(i).AsString(opts.Ansi))
|
||||||
}
|
}
|
||||||
os.Exit(0)
|
if count > 0 {
|
||||||
|
os.Exit(exitOk)
|
||||||
|
}
|
||||||
|
os.Exit(exitNoMatch)
|
||||||
}
|
}
|
||||||
deferred = false
|
deferred = false
|
||||||
terminal.startChan <- true
|
terminal.startChan <- true
|
||||||
|
@@ -3,18 +3,21 @@ package curses
|
|||||||
/*
|
/*
|
||||||
#include <ncurses.h>
|
#include <ncurses.h>
|
||||||
#include <locale.h>
|
#include <locale.h>
|
||||||
#cgo LDFLAGS: -lncurses
|
#cgo !static LDFLAGS: -lncurses
|
||||||
void swapOutput() {
|
#cgo static LDFLAGS: -l:libncursesw.a -l:libtinfo.a -l:libgpm.a -ldl
|
||||||
FILE* temp = stdout;
|
#cgo android static LDFLAGS: -l:libncurses.a -fPIE -march=armv7-a -mfpu=neon -mhard-float -Wl,--no-warn-mismatch
|
||||||
stdout = stderr;
|
|
||||||
stderr = temp;
|
SCREEN *c_newterm () {
|
||||||
|
return newterm(NULL, stderr, stdin);
|
||||||
}
|
}
|
||||||
|
|
||||||
*/
|
*/
|
||||||
import "C"
|
import "C"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
@@ -54,18 +57,39 @@ const (
|
|||||||
|
|
||||||
Invalid
|
Invalid
|
||||||
Mouse
|
Mouse
|
||||||
|
DoubleClick
|
||||||
|
|
||||||
BTab
|
BTab
|
||||||
|
BSpace
|
||||||
|
|
||||||
Del
|
Del
|
||||||
PgUp
|
PgUp
|
||||||
PgDn
|
PgDn
|
||||||
|
|
||||||
|
Up
|
||||||
|
Down
|
||||||
|
Left
|
||||||
|
Right
|
||||||
|
Home
|
||||||
|
End
|
||||||
|
|
||||||
|
SLeft
|
||||||
|
SRight
|
||||||
|
|
||||||
F1
|
F1
|
||||||
F2
|
F2
|
||||||
F3
|
F3
|
||||||
F4
|
F4
|
||||||
|
F5
|
||||||
|
F6
|
||||||
|
F7
|
||||||
|
F8
|
||||||
|
F9
|
||||||
|
F10
|
||||||
|
|
||||||
|
AltEnter
|
||||||
|
AltSpace
|
||||||
|
AltSlash
|
||||||
AltBS
|
AltBS
|
||||||
AltA
|
AltA
|
||||||
AltB
|
AltB
|
||||||
@@ -88,13 +112,34 @@ const (
|
|||||||
ColInfo
|
ColInfo
|
||||||
ColCursor
|
ColCursor
|
||||||
ColSelected
|
ColSelected
|
||||||
ColUser
|
ColHeader
|
||||||
|
ColBorder
|
||||||
|
ColUser // Should be the last entry
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
doubleClickDuration = 500 * time.Millisecond
|
doubleClickDuration = 500 * time.Millisecond
|
||||||
|
colDefault = -1
|
||||||
|
colUndefined = -2
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
Header int16
|
||||||
|
Border int16
|
||||||
|
}
|
||||||
|
|
||||||
type Event struct {
|
type Event struct {
|
||||||
Type int
|
Type int
|
||||||
Char rune
|
Char rune
|
||||||
@@ -116,15 +161,109 @@ 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
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type Window struct {
|
||||||
|
win *C.WINDOW
|
||||||
|
Top int
|
||||||
|
Left int
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWindow(top int, left int, width int, height int, border bool) *Window {
|
||||||
|
win := C.newwin(C.int(height), C.int(width), C.int(top), C.int(left))
|
||||||
|
if border {
|
||||||
|
attr := _color(ColBorder, false)
|
||||||
|
C.wattron(win, attr)
|
||||||
|
C.box(win, 0, 0)
|
||||||
|
C.wattroff(win, attr)
|
||||||
|
}
|
||||||
|
return &Window{
|
||||||
|
win: win,
|
||||||
|
Top: top,
|
||||||
|
Left: left,
|
||||||
|
Width: width,
|
||||||
|
Height: height,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func EmptyTheme() *ColorTheme {
|
||||||
|
return &ColorTheme{
|
||||||
|
UseDefault: true,
|
||||||
|
Fg: colUndefined,
|
||||||
|
Bg: colUndefined,
|
||||||
|
DarkBg: colUndefined,
|
||||||
|
Prompt: colUndefined,
|
||||||
|
Match: colUndefined,
|
||||||
|
Current: colUndefined,
|
||||||
|
CurrentMatch: colUndefined,
|
||||||
|
Spinner: colUndefined,
|
||||||
|
Info: colUndefined,
|
||||||
|
Cursor: colUndefined,
|
||||||
|
Selected: colUndefined,
|
||||||
|
Header: colUndefined,
|
||||||
|
Border: colUndefined}
|
||||||
|
}
|
||||||
|
|
||||||
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,
|
||||||
|
Header: C.COLOR_CYAN,
|
||||||
|
Border: C.COLOR_BLACK}
|
||||||
|
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,
|
||||||
|
Header: 109,
|
||||||
|
Border: 59}
|
||||||
|
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,
|
||||||
|
Header: 31,
|
||||||
|
Border: 145}
|
||||||
}
|
}
|
||||||
|
|
||||||
func attrColored(pair int, bold bool) C.int {
|
func attrColored(pair int, bold bool) C.int {
|
||||||
@@ -174,7 +313,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,64 +324,79 @@ 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.c_newterm()
|
||||||
|
if _screen == nil {
|
||||||
|
fmt.Println("Invalid $TERM: " + os.Getenv("TERM"))
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
C.set_term(_screen)
|
||||||
if mouse {
|
if mouse {
|
||||||
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
||||||
}
|
}
|
||||||
C.cbreak()
|
|
||||||
C.noecho()
|
C.noecho()
|
||||||
C.raw() // stty dsusp undef
|
C.raw() // stty dsusp undef
|
||||||
|
|
||||||
intChan := make(chan os.Signal, 1)
|
if theme != nil {
|
||||||
signal.Notify(intChan, os.Interrupt, os.Kill)
|
|
||||||
go func() {
|
|
||||||
<-intChan
|
|
||||||
Close()
|
|
||||||
os.Exit(1)
|
|
||||||
}()
|
|
||||||
|
|
||||||
if color {
|
|
||||||
C.start_color()
|
C.start_color()
|
||||||
var bg C.short
|
var baseTheme *ColorTheme
|
||||||
if black {
|
if C.tigetnum(C.CString("colors")) >= 256 {
|
||||||
bg = C.COLOR_BLACK
|
baseTheme = Dark256
|
||||||
} else {
|
} else {
|
||||||
C.use_default_colors()
|
baseTheme = Default16
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
initPairs(baseTheme, theme, black)
|
||||||
_color = attrColored
|
_color = attrColored
|
||||||
} else {
|
} else {
|
||||||
_color = attrMono
|
_color = attrMono
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func override(a int16, b int16) C.short {
|
||||||
|
if b == colUndefined {
|
||||||
|
return C.short(a)
|
||||||
|
}
|
||||||
|
return C.short(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func initPairs(baseTheme *ColorTheme, theme *ColorTheme, black bool) {
|
||||||
|
fg := override(baseTheme.Fg, theme.Fg)
|
||||||
|
bg := override(baseTheme.Bg, theme.Bg)
|
||||||
|
if black {
|
||||||
|
bg = C.COLOR_BLACK
|
||||||
|
} else if theme.UseDefault {
|
||||||
|
fg = colDefault
|
||||||
|
bg = colDefault
|
||||||
|
C.use_default_colors()
|
||||||
|
}
|
||||||
|
if theme.UseDefault {
|
||||||
|
FG = colDefault
|
||||||
|
BG = colDefault
|
||||||
|
} else {
|
||||||
|
FG = int(fg)
|
||||||
|
BG = int(bg)
|
||||||
|
C.assume_default_colors(C.int(override(baseTheme.Fg, theme.Fg)), C.int(bg))
|
||||||
|
}
|
||||||
|
|
||||||
|
currentFG := override(baseTheme.Current, theme.Current)
|
||||||
|
darkBG := override(baseTheme.DarkBg, theme.DarkBg)
|
||||||
|
CurrentFG = int(currentFG)
|
||||||
|
DarkBG = int(darkBG)
|
||||||
|
C.init_pair(ColPrompt, override(baseTheme.Prompt, theme.Prompt), bg)
|
||||||
|
C.init_pair(ColMatch, override(baseTheme.Match, theme.Match), bg)
|
||||||
|
C.init_pair(ColCurrent, currentFG, darkBG)
|
||||||
|
C.init_pair(ColCurrentMatch, override(baseTheme.CurrentMatch, theme.CurrentMatch), darkBG)
|
||||||
|
C.init_pair(ColSpinner, override(baseTheme.Spinner, theme.Spinner), bg)
|
||||||
|
C.init_pair(ColInfo, override(baseTheme.Info, theme.Info), bg)
|
||||||
|
C.init_pair(ColCursor, override(baseTheme.Cursor, theme.Cursor), darkBG)
|
||||||
|
C.init_pair(ColSelected, override(baseTheme.Selected, theme.Selected), darkBG)
|
||||||
|
C.init_pair(ColHeader, override(baseTheme.Header, theme.Header), bg)
|
||||||
|
C.init_pair(ColBorder, override(baseTheme.Border, theme.Border), bg)
|
||||||
|
}
|
||||||
|
|
||||||
func Close() {
|
func Close() {
|
||||||
C.endwin()
|
C.endwin()
|
||||||
C.swapOutput()
|
C.delscreen(_screen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetBytes() []byte {
|
func GetBytes() []byte {
|
||||||
@@ -293,7 +447,9 @@ func mouseSequence(sz *int) Event {
|
|||||||
97, 101, 105, 113: // scroll-down / shift / cmd / ctrl
|
97, 101, 105, 113: // scroll-down / shift / cmd / ctrl
|
||||||
mod := _buf[3] >= 100
|
mod := _buf[3] >= 100
|
||||||
s := 1 - int(_buf[3]%2)*2
|
s := 1 - int(_buf[3]%2)*2
|
||||||
return Event{Mouse, 0, &MouseEvent{0, 0, s, false, false, mod}}
|
x := int(_buf[4] - 33)
|
||||||
|
y := int(_buf[5] - 33)
|
||||||
|
return Event{Mouse, 0, &MouseEvent{y, x, s, false, false, mod}}
|
||||||
}
|
}
|
||||||
return Event{Invalid, 0, nil}
|
return Event{Invalid, 0, nil}
|
||||||
}
|
}
|
||||||
@@ -304,6 +460,12 @@ func escSequence(sz *int) Event {
|
|||||||
}
|
}
|
||||||
*sz = 2
|
*sz = 2
|
||||||
switch _buf[1] {
|
switch _buf[1] {
|
||||||
|
case 13:
|
||||||
|
return Event{AltEnter, 0, nil}
|
||||||
|
case 32:
|
||||||
|
return Event{AltSpace, 0, nil}
|
||||||
|
case 47:
|
||||||
|
return Event{AltSlash, 0, nil}
|
||||||
case 98:
|
case 98:
|
||||||
return Event{AltB, 0, nil}
|
return Event{AltB, 0, nil}
|
||||||
case 100:
|
case 100:
|
||||||
@@ -319,19 +481,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:
|
||||||
@@ -349,11 +511,25 @@ func escSequence(sz *int) Event {
|
|||||||
*sz = 4
|
*sz = 4
|
||||||
switch _buf[2] {
|
switch _buf[2] {
|
||||||
case 50:
|
case 50:
|
||||||
|
if len(_buf) == 5 && _buf[4] == 126 {
|
||||||
|
*sz = 5
|
||||||
|
switch _buf[3] {
|
||||||
|
case 48:
|
||||||
|
return Event{F9, 0, nil}
|
||||||
|
case 49:
|
||||||
|
return Event{F10, 0, nil}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Bracketed paste mode \e[200~ / \e[201
|
||||||
|
if _buf[3] == 48 && (_buf[4] == 48 || _buf[4] == 49) && _buf[5] == 126 {
|
||||||
|
*sz = 6
|
||||||
|
return Event{Invalid, 0, nil}
|
||||||
|
}
|
||||||
return Event{Invalid, 0, nil} // INS
|
return Event{Invalid, 0, nil} // INS
|
||||||
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 +537,22 @@ 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 53, 55, 56, 57:
|
||||||
|
if len(_buf) == 5 && _buf[4] == 126 {
|
||||||
|
*sz = 5
|
||||||
|
switch _buf[3] {
|
||||||
|
case 53:
|
||||||
|
return Event{F5, 0, nil}
|
||||||
|
case 55:
|
||||||
|
return Event{F6, 0, nil}
|
||||||
|
case 56:
|
||||||
|
return Event{F7, 0, nil}
|
||||||
|
case 57:
|
||||||
|
return Event{F8, 0, nil}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Event{Invalid, 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 +562,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 +598,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,28 +615,44 @@ 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}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Move(y int, x int) {
|
func (w *Window) Close() {
|
||||||
C.move(C.int(y), C.int(x))
|
C.delwin(w.win)
|
||||||
}
|
}
|
||||||
|
|
||||||
func MoveAndClear(y int, x int) {
|
func (w *Window) Enclose(y int, x int) bool {
|
||||||
Move(y, x)
|
return bool(C.wenclose(w.win, C.int(y), C.int(x)))
|
||||||
C.clrtoeol()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Print(text string) {
|
func (w *Window) Move(y int, x int) {
|
||||||
C.addstr(C.CString(text))
|
C.wmove(w.win, C.int(y), C.int(x))
|
||||||
}
|
}
|
||||||
|
|
||||||
func CPrint(pair int, bold bool, text string) {
|
func (w *Window) MoveAndClear(y int, x int) {
|
||||||
|
w.Move(y, x)
|
||||||
|
C.wclrtoeol(w.win)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Window) Print(text string) {
|
||||||
|
C.waddstr(w.win, C.CString(strings.Map(func(r rune) rune {
|
||||||
|
if r < 32 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}, text)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Window) CPrint(pair int, bold bool, text string) {
|
||||||
attr := _color(pair, bold)
|
attr := _color(pair, bold)
|
||||||
C.attron(attr)
|
C.wattron(w.win, attr)
|
||||||
Print(text)
|
w.Print(text)
|
||||||
C.attroff(attr)
|
C.wattroff(w.win, attr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Clear() {
|
func Clear() {
|
||||||
@@ -456,6 +667,30 @@ func Refresh() {
|
|||||||
C.refresh()
|
C.refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *Window) Erase() {
|
||||||
|
C.werase(w.win)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Window) Fill(str string) bool {
|
||||||
|
return C.waddstr(w.win, C.CString(str)) == C.OK
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Window) CFill(str string, fg int, bg int, bold bool) bool {
|
||||||
|
attr := _color(PairFor(fg, bg), bold)
|
||||||
|
C.wattron(w.win, attr)
|
||||||
|
ret := w.Fill(str)
|
||||||
|
C.wattroff(w.win, attr)
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Window) Refresh() {
|
||||||
|
C.wnoutrefresh(w.win)
|
||||||
|
}
|
||||||
|
|
||||||
|
func DoUpdate() {
|
||||||
|
C.doupdate()
|
||||||
|
}
|
||||||
|
|
||||||
func PairFor(fg int, bg int) int {
|
func PairFor(fg int, bg int) int {
|
||||||
key := (fg << 8) + bg
|
key := (fg << 8) + bg
|
||||||
if found, prs := _colorMap[key]; prs {
|
if found, prs := _colorMap[key]; prs {
|
||||||
|
96
src/history.go
Normal file
96
src/history.go
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// History struct represents input history
|
||||||
|
type History struct {
|
||||||
|
path string
|
||||||
|
lines []string
|
||||||
|
modified map[int]string
|
||||||
|
maxSize int
|
||||||
|
cursor int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHistory returns the pointer to a new History struct
|
||||||
|
func NewHistory(path string, maxSize int) (*History, error) {
|
||||||
|
fmtError := func(e error) error {
|
||||||
|
if os.IsPermission(e) {
|
||||||
|
return errors.New("permission denied: " + path)
|
||||||
|
}
|
||||||
|
return errors.New("invalid history file: " + e.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read history file
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
// If it doesn't exist, check if we can create a file with the name
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
data = []byte{}
|
||||||
|
if err := ioutil.WriteFile(path, data, 0600); err != nil {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nil, fmtError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Split lines and limit the maximum number of lines
|
||||||
|
lines := strings.Split(strings.Trim(string(data), "\n"), "\n")
|
||||||
|
if len(lines[len(lines)-1]) > 0 {
|
||||||
|
lines = append(lines, "")
|
||||||
|
}
|
||||||
|
return &History{
|
||||||
|
path: path,
|
||||||
|
maxSize: maxSize,
|
||||||
|
lines: lines,
|
||||||
|
modified: make(map[int]string),
|
||||||
|
cursor: len(lines) - 1}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) append(line string) error {
|
||||||
|
// We don't append empty lines
|
||||||
|
if len(line) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := append(h.lines[:len(h.lines)-1], line)
|
||||||
|
if len(lines) > h.maxSize {
|
||||||
|
lines = lines[len(lines)-h.maxSize : len(lines)]
|
||||||
|
}
|
||||||
|
h.lines = append(lines, "")
|
||||||
|
return ioutil.WriteFile(h.path, []byte(strings.Join(h.lines, "\n")), 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) override(str string) {
|
||||||
|
// You can update the history but they're not written to the file
|
||||||
|
if h.cursor == len(h.lines)-1 {
|
||||||
|
h.lines[h.cursor] = str
|
||||||
|
} else if h.cursor < len(h.lines)-1 {
|
||||||
|
h.modified[h.cursor] = str
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) current() string {
|
||||||
|
if str, prs := h.modified[h.cursor]; prs {
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
return h.lines[h.cursor]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) previous() string {
|
||||||
|
if h.cursor > 0 {
|
||||||
|
h.cursor--
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *History) next() string {
|
||||||
|
if h.cursor < len(h.lines)-1 {
|
||||||
|
h.cursor++
|
||||||
|
}
|
||||||
|
return h.current()
|
||||||
|
}
|
59
src/history_test.go
Normal file
59
src/history_test.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package fzf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/user"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHistory(t *testing.T) {
|
||||||
|
maxHistory := 50
|
||||||
|
|
||||||
|
// Invalid arguments
|
||||||
|
user, _ := user.Current()
|
||||||
|
paths := []string{"/etc", "/proc"}
|
||||||
|
if user.Name != "root" {
|
||||||
|
paths = append(paths, "/etc/sudoers")
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
if _, e := NewHistory(path, maxHistory); e == nil {
|
||||||
|
t.Error("Error expected for: " + path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
for i := 0; i < maxHistory+10; i++ {
|
||||||
|
h.append("foobar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Read lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
for i := 0; i < maxHistory; i++ {
|
||||||
|
if h.lines[i] != "foobar" {
|
||||||
|
t.Error("Expected: foobar, actual: " + h.lines[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{ // Append lines
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
h.append("barfoo")
|
||||||
|
h.append("")
|
||||||
|
h.append("foobarbaz")
|
||||||
|
}
|
||||||
|
{ // Read lines again
|
||||||
|
h, _ := NewHistory("/tmp/fzf-history", maxHistory)
|
||||||
|
if len(h.lines) != maxHistory+1 {
|
||||||
|
t.Errorf("Expected: %d, actual: %d\n", maxHistory+1, len(h.lines))
|
||||||
|
}
|
||||||
|
compare := func(idx int, exp string) {
|
||||||
|
if h.lines[idx] != exp {
|
||||||
|
t.Errorf("Expected: %s, actual: %s\n", exp, h.lines[idx])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compare(maxHistory-3, "foobar")
|
||||||
|
compare(maxHistory-2, "barfoo")
|
||||||
|
compare(maxHistory-1, "foobarbaz")
|
||||||
|
}
|
||||||
|
}
|
164
src/item.go
164
src/item.go
@@ -1,11 +1,13 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/curses"
|
"github.com/junegunn/fzf/src/curses"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Offset holds two 32-bit integers denoting the offsets of a matched substring
|
// Offset holds three 32-bit integers denoting the offsets of a matched substring
|
||||||
type Offset [2]int32
|
type Offset [3]int32
|
||||||
|
|
||||||
type colorOffset struct {
|
type colorOffset struct {
|
||||||
offset [2]int32
|
offset [2]int32
|
||||||
@@ -15,32 +17,50 @@ type colorOffset struct {
|
|||||||
|
|
||||||
// Item represents each input line
|
// Item represents each input line
|
||||||
type Item struct {
|
type Item struct {
|
||||||
text *string
|
text []rune
|
||||||
origText *string
|
origText *[]rune
|
||||||
transformed *Transformed
|
transformed []Token
|
||||||
index uint32
|
|
||||||
offsets []Offset
|
offsets []Offset
|
||||||
colors []ansiOffset
|
colors []ansiOffset
|
||||||
rank Rank
|
rank [5]int32
|
||||||
|
bonus int32
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rank is used to sort the search result
|
// Sort criteria to use. Never changes once fzf is started.
|
||||||
type Rank struct {
|
var sortCriteria []criterion
|
||||||
matchlen uint16
|
|
||||||
strlen uint16
|
func isRankValid(rank [5]int32) bool {
|
||||||
index uint32
|
// Exclude ordinal index
|
||||||
|
for _, r := range rank[:4] {
|
||||||
|
if r > 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildEmptyRank(index int32) [5]int32 {
|
||||||
|
return [5]int32{0, 0, 0, 0, index}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (item *Item) Index() int32 {
|
||||||
|
return item.rank[4]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rank calculates rank of the Item
|
// Rank calculates rank of the Item
|
||||||
func (i *Item) Rank(cache bool) Rank {
|
func (item *Item) Rank(cache bool) [5]int32 {
|
||||||
if cache && (i.rank.matchlen > 0 || i.rank.strlen > 0) {
|
if cache && isRankValid(item.rank) {
|
||||||
return i.rank
|
return item.rank
|
||||||
}
|
}
|
||||||
matchlen := 0
|
matchlen := 0
|
||||||
prevEnd := 0
|
prevEnd := 0
|
||||||
for _, offset := range i.offsets {
|
lenSum := 0
|
||||||
|
minBegin := math.MaxInt32
|
||||||
|
for _, offset := range item.offsets {
|
||||||
begin := int(offset[0])
|
begin := int(offset[0])
|
||||||
end := int(offset[1])
|
end := int(offset[1])
|
||||||
|
trimLen := int(offset[2])
|
||||||
|
lenSum += trimLen
|
||||||
if prevEnd > begin {
|
if prevEnd > begin {
|
||||||
begin = prevEnd
|
begin = prevEnd
|
||||||
}
|
}
|
||||||
@@ -48,29 +68,82 @@ 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}
|
rank := buildEmptyRank(item.Index())
|
||||||
|
for idx, criterion := range sortCriteria {
|
||||||
|
var val int32
|
||||||
|
switch criterion {
|
||||||
|
case byMatchLen:
|
||||||
|
if matchlen == 0 {
|
||||||
|
val = math.MaxInt32
|
||||||
|
} else {
|
||||||
|
// It is extremely unlikely that bonus exceeds 128
|
||||||
|
val = 128*int32(matchlen) - item.bonus
|
||||||
|
}
|
||||||
|
case byLength:
|
||||||
|
// It is guaranteed that .transformed in not null in normal execution
|
||||||
|
if item.transformed != nil {
|
||||||
|
// If offsets is empty, lenSum will be 0, but we don't care
|
||||||
|
val = int32(lenSum)
|
||||||
|
} else {
|
||||||
|
val = int32(len(item.text))
|
||||||
|
}
|
||||||
|
case byBegin:
|
||||||
|
// We can't just look at item.offsets[0][0] because it can be an inverse term
|
||||||
|
whitePrefixLen := 0
|
||||||
|
for idx, r := range item.text {
|
||||||
|
whitePrefixLen = idx
|
||||||
|
if idx == minBegin || r != ' ' && r != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val = int32(minBegin - whitePrefixLen)
|
||||||
|
case byEnd:
|
||||||
|
if prevEnd > 0 {
|
||||||
|
val = int32(1 + len(item.text) - prevEnd)
|
||||||
|
} else {
|
||||||
|
// Empty offsets due to inverse terms.
|
||||||
|
val = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rank[idx] = val
|
||||||
|
}
|
||||||
if cache {
|
if cache {
|
||||||
i.rank = rank
|
item.rank = rank
|
||||||
}
|
}
|
||||||
return rank
|
return rank
|
||||||
}
|
}
|
||||||
|
|
||||||
// AsString returns the original string
|
// AsString returns the original string
|
||||||
func (i *Item) AsString() string {
|
func (item *Item) AsString(stripAnsi bool) string {
|
||||||
if i.origText != nil {
|
return *item.StringPtr(stripAnsi)
|
||||||
return *i.origText
|
}
|
||||||
|
|
||||||
|
// StringPtr returns the pointer to the original string
|
||||||
|
func (item *Item) StringPtr(stripAnsi bool) *string {
|
||||||
|
if item.origText != nil {
|
||||||
|
if stripAnsi {
|
||||||
|
trimmed, _, _ := extractColor(string(*item.origText), nil)
|
||||||
|
return &trimmed
|
||||||
|
}
|
||||||
|
orig := string(*item.origText)
|
||||||
|
return &orig
|
||||||
}
|
}
|
||||||
return *i.text
|
str := string(item.text)
|
||||||
|
return &str
|
||||||
}
|
}
|
||||||
|
|
||||||
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {
|
||||||
if len(item.colors) == 0 {
|
if len(item.colors) == 0 {
|
||||||
var offsets []colorOffset
|
var offsets []colorOffset
|
||||||
for _, off := range item.offsets {
|
for _, off := range item.offsets {
|
||||||
offsets = append(offsets, colorOffset{offset: off, color: color, bold: bold})
|
|
||||||
|
offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, bold: bold})
|
||||||
}
|
}
|
||||||
return offsets
|
return offsets
|
||||||
}
|
}
|
||||||
@@ -114,16 +187,28 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
|||||||
if curr != 0 && idx > start {
|
if curr != 0 && idx > start {
|
||||||
if curr == -1 {
|
if curr == -1 {
|
||||||
offsets = append(offsets, colorOffset{
|
offsets = append(offsets, colorOffset{
|
||||||
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
offset: [2]int32{int32(start), int32(idx)}, color: color, bold: bold})
|
||||||
} else {
|
} 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: [2]int32{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})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -192,18 +277,15 @@ func (a ByRelevanceTac) Less(i, j int) bool {
|
|||||||
return compareRanks(irank, jrank, true)
|
return compareRanks(irank, jrank, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func compareRanks(irank Rank, jrank Rank, tac bool) bool {
|
func compareRanks(irank [5]int32, jrank [5]int32, tac bool) bool {
|
||||||
if irank.matchlen < jrank.matchlen {
|
for idx := 0; idx < 4; idx++ {
|
||||||
return true
|
left := irank[idx]
|
||||||
} else if irank.matchlen > jrank.matchlen {
|
right := jrank[idx]
|
||||||
return false
|
if left < right {
|
||||||
|
return true
|
||||||
|
} else if left > right {
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return (irank[4] <= jrank[4]) != tac
|
||||||
if irank.strlen < jrank.strlen {
|
|
||||||
return true
|
|
||||||
} else if irank.strlen > jrank.strlen {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return (irank.index <= jrank.index) != tac
|
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"math"
|
||||||
"sort"
|
"sort"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -22,31 +23,34 @@ func TestOffsetSort(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRankComparison(t *testing.T) {
|
func TestRankComparison(t *testing.T) {
|
||||||
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, false) ||
|
if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, false) ||
|
||||||
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||
|
!compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||
|
||||||
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, false) ||
|
!compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, false) ||
|
||||||
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {
|
!compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {
|
||||||
t.Error("Invalid order")
|
t.Error("Invalid order")
|
||||||
}
|
}
|
||||||
|
|
||||||
if compareRanks(Rank{3, 0, 5}, Rank{2, 0, 7}, true) ||
|
if compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{2, 0, 0, 0, 7}, true) ||
|
||||||
!compareRanks(Rank{3, 0, 5}, Rank{3, 0, 6}, false) ||
|
!compareRanks([5]int32{3, 0, 0, 0, 5}, [5]int32{3, 0, 0, 0, 6}, false) ||
|
||||||
!compareRanks(Rank{1, 2, 3}, Rank{1, 3, 2}, true) ||
|
!compareRanks([5]int32{1, 2, 0, 0, 3}, [5]int32{1, 3, 0, 0, 2}, true) ||
|
||||||
!compareRanks(Rank{0, 0, 0}, Rank{0, 0, 0}, false) {
|
!compareRanks([5]int32{0, 0, 0, 0, 0}, [5]int32{0, 0, 0, 0, 0}, false) {
|
||||||
t.Error("Invalid order (tac)")
|
t.Error("Invalid order (tac)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Match length, string length, index
|
// Match length, string length, index
|
||||||
func TestItemRank(t *testing.T) {
|
func TestItemRank(t *testing.T) {
|
||||||
strs := []string{"foo", "foobar", "bar", "baz"}
|
// FIXME global
|
||||||
item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}
|
sortCriteria = []criterion{byMatchLen, byLength}
|
||||||
|
|
||||||
|
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
||||||
|
item1 := Item{text: strs[0], offsets: []Offset{}, rank: [5]int32{0, 0, 0, 0, 1}}
|
||||||
rank1 := item1.Rank(true)
|
rank1 := item1.Rank(true)
|
||||||
if rank1.matchlen != 0 || rank1.strlen != 3 || rank1.index != 1 {
|
if rank1[0] != math.MaxInt32 || rank1[1] != 3 || rank1[4] != 1 {
|
||||||
t.Error(item1.Rank(true))
|
t.Error(item1.Rank(true))
|
||||||
}
|
}
|
||||||
// Only differ in index
|
// Only differ in index
|
||||||
item2 := Item{text: &strs[0], index: 0, offsets: []Offset{}}
|
item2 := Item{text: strs[0], offsets: []Offset{}}
|
||||||
|
|
||||||
items := []*Item{&item1, &item2}
|
items := []*Item{&item1, &item2}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
@@ -62,15 +66,15 @@ func TestItemRank(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Sort by relevance
|
// Sort by relevance
|
||||||
item3 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
item3 := Item{text: strs[1], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||||
item4 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
item4 := Item{text: strs[1], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||||
item5 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
item5 := Item{text: strs[2], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||||
item6 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
item6 := Item{text: strs[2], rank: [5]int32{0, 0, 0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||||
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
if items[0] != &item2 || items[1] != &item1 ||
|
if items[0] != &item6 || items[1] != &item4 ||
|
||||||
items[2] != &item6 || items[3] != &item4 ||
|
items[2] != &item5 || items[3] != &item3 ||
|
||||||
items[4] != &item5 || items[5] != &item3 {
|
items[4] != &item2 || items[5] != &item1 {
|
||||||
t.Error(items)
|
t.Error(items)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -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 {
|
||||||
m.mergerCache[patternString] = merger
|
if merger.cacheable() {
|
||||||
|
m.mergerCache[patternString] = merger
|
||||||
|
}
|
||||||
merger.final = request.final
|
merger.final = request.final
|
||||||
m.eventBox.Set(EvtSearchFin, merger)
|
m.eventBox.Set(EvtSearchFin, merger)
|
||||||
}
|
}
|
||||||
@@ -202,7 +200,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
partialResults := make([][]*Item, numSlices)
|
partialResults := make([][]*Item, numSlices)
|
||||||
for range slices {
|
for _, _ = range slices {
|
||||||
partialResult := <-resultChan
|
partialResult := <-resultChan
|
||||||
partialResults[partialResult.index] = partialResult.matches
|
partialResults[partialResult.index] = partialResult.matches
|
||||||
}
|
}
|
||||||
|
@@ -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,9 +82,13 @@ 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 := buildEmptyRank(0)
|
||||||
minIdx := -1
|
minIdx := -1
|
||||||
for listIdx, list := range mg.lists {
|
for listIdx, list := range mg.lists {
|
||||||
cursor := mg.cursors[listIdx]
|
cursor := mg.cursors[listIdx]
|
||||||
|
@@ -22,8 +22,8 @@ func randItem() *Item {
|
|||||||
offsets[idx] = Offset{sidx, eidx}
|
offsets[idx] = Offset{sidx, eidx}
|
||||||
}
|
}
|
||||||
return &Item{
|
return &Item{
|
||||||
text: &str,
|
text: []rune(str),
|
||||||
index: rand.Uint32(),
|
rank: buildEmptyRank(rand.Int31()),
|
||||||
offsets: offsets}
|
offsets: offsets}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
961
src/options.go
961
src/options.go
File diff suppressed because it is too large
Load Diff
@@ -1,17 +1,66 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/curses"
|
"github.com/junegunn/fzf/src/curses"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDelimiterRegex(t *testing.T) {
|
func TestDelimiterRegex(t *testing.T) {
|
||||||
rx := delimiterRegexp("*")
|
// Valid regex
|
||||||
tokens := rx.FindAllString("-*--*---**---", -1)
|
delim := delimiterRegexp(".")
|
||||||
if tokens[0] != "-*" || tokens[1] != "--*" || tokens[2] != "---*" ||
|
if delim.regex == nil || delim.str != nil {
|
||||||
tokens[3] != "*" || tokens[4] != "---" {
|
t.Error(delim)
|
||||||
t.Errorf("%s %s %d", rx, tokens, len(tokens))
|
}
|
||||||
|
// Broken regex -> string
|
||||||
|
delim = delimiterRegexp("[0-9")
|
||||||
|
if delim.regex != nil || *delim.str != "[0-9" {
|
||||||
|
t.Error(delim)
|
||||||
|
}
|
||||||
|
// Valid regex
|
||||||
|
delim = delimiterRegexp("[0-9]")
|
||||||
|
if delim.regex.String() != "[0-9]" || delim.str != nil {
|
||||||
|
t.Error(delim)
|
||||||
|
}
|
||||||
|
// Tab character
|
||||||
|
delim = delimiterRegexp("\t")
|
||||||
|
if delim.regex != nil || *delim.str != "\t" {
|
||||||
|
t.Error(delim)
|
||||||
|
}
|
||||||
|
// Tab expression
|
||||||
|
delim = delimiterRegexp("\\t")
|
||||||
|
if delim.regex != nil || *delim.str != "\t" {
|
||||||
|
t.Error(delim)
|
||||||
|
}
|
||||||
|
// Tabs -> regex
|
||||||
|
delim = delimiterRegexp("\t+")
|
||||||
|
if delim.regex == nil || delim.str != nil {
|
||||||
|
t.Error(delim)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDelimiterRegexString(t *testing.T) {
|
||||||
|
delim := delimiterRegexp("*")
|
||||||
|
tokens := Tokenize([]rune("-*--*---**---"), delim)
|
||||||
|
if delim.regex != nil ||
|
||||||
|
string(tokens[0].text) != "-*" ||
|
||||||
|
string(tokens[1].text) != "--*" ||
|
||||||
|
string(tokens[2].text) != "---*" ||
|
||||||
|
string(tokens[3].text) != "*" ||
|
||||||
|
string(tokens[4].text) != "---" {
|
||||||
|
t.Errorf("%s %s %d", delim, tokens, len(tokens))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDelimiterRegexRegex(t *testing.T) {
|
||||||
|
delim := delimiterRegexp("--\\*")
|
||||||
|
tokens := Tokenize([]rune("-*--*---**---"), delim)
|
||||||
|
if delim.str != nil ||
|
||||||
|
string(tokens[0].text) != "-*--*" ||
|
||||||
|
string(tokens[1].text) != "---*" ||
|
||||||
|
string(tokens[2].text) != "*---" {
|
||||||
|
t.Errorf("%s %d", tokens, len(tokens))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,14 +96,16 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
opts := defaultOptions()
|
opts := defaultOptions()
|
||||||
words := []string{"--nth", "..", "-x"}
|
words := []string{"--nth", "..", "-x"}
|
||||||
parseOptions(opts, words)
|
parseOptions(opts, words)
|
||||||
|
postProcessOptions(opts)
|
||||||
if len(opts.Nth) != 0 {
|
if len(opts.Nth) != 0 {
|
||||||
t.Errorf("nth should be empty: %s", opts.Nth)
|
t.Errorf("nth should be empty: %s", opts.Nth)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, words := range [][]string{[]string{"--nth", "..,3"}, []string{"--nth", "3,1.."}, []string{"--nth", "..-1,1"}} {
|
for _, words := range [][]string{[]string{"--nth", "..,3", "+x"}, []string{"--nth", "3,1..", "+x"}, []string{"--nth", "..-1,1", "+x"}} {
|
||||||
{
|
{
|
||||||
opts := defaultOptions()
|
opts := defaultOptions()
|
||||||
parseOptions(opts, words)
|
parseOptions(opts, words)
|
||||||
|
postProcessOptions(opts)
|
||||||
if len(opts.Nth) != 0 {
|
if len(opts.Nth) != 0 {
|
||||||
t.Errorf("nth should be empty: %s", opts.Nth)
|
t.Errorf("nth should be empty: %s", opts.Nth)
|
||||||
}
|
}
|
||||||
@@ -63,6 +114,7 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
opts := defaultOptions()
|
opts := defaultOptions()
|
||||||
words = append(words, "-x")
|
words = append(words, "-x")
|
||||||
parseOptions(opts, words)
|
parseOptions(opts, words)
|
||||||
|
postProcessOptions(opts)
|
||||||
if len(opts.Nth) != 2 {
|
if len(opts.Nth) != 2 {
|
||||||
t.Errorf("nth should not be empty: %s", opts.Nth)
|
t.Errorf("nth should not be empty: %s", opts.Nth)
|
||||||
}
|
}
|
||||||
@@ -71,61 +123,255 @@ 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,ALT-enter,alt-SPACE", "")
|
||||||
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) != 11 {
|
||||||
check(keys[0], curses.CtrlZ)
|
t.Error(11)
|
||||||
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")
|
||||||
|
check(curses.AltEnter, "ALT-enter")
|
||||||
|
check(curses.AltSpace, "alt-SPACE")
|
||||||
|
|
||||||
|
// 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])
|
||||||
|
parseKeymap(keymap, execmap,
|
||||||
|
"ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+
|
||||||
|
"f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+
|
||||||
|
"alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+
|
||||||
|
",,:abort,::accept,X:execute:\nfoobar,Y:execute(baz)")
|
||||||
|
check(actKillLine, keymap[curses.CtrlA])
|
||||||
|
check(actToggleSort, keymap[curses.CtrlB])
|
||||||
|
check(actPageUp, keymap[curses.AltZ+'c'])
|
||||||
|
check(actAbort, keymap[curses.AltZ+','])
|
||||||
|
check(actAccept, keymap[curses.AltZ+':'])
|
||||||
|
check(actPageDown, keymap[curses.AltZ])
|
||||||
|
check(actExecute, keymap[curses.F1])
|
||||||
|
check(actExecute, keymap[curses.F2])
|
||||||
|
check(actExecute, keymap[curses.F3])
|
||||||
|
check(actExecute, keymap[curses.F4])
|
||||||
|
checkString("ls {}", execmap[curses.F1])
|
||||||
|
checkString("echo {}, {}, {}", execmap[curses.F2])
|
||||||
|
checkString("echo '({})'", execmap[curses.F3])
|
||||||
|
checkString("less {}", execmap[curses.F4])
|
||||||
|
checkString("echo (,),[,],/,:,;,%,{}", execmap[curses.AltA])
|
||||||
|
checkString("echo (,),[,],/,:,@,%,{}", execmap[curses.AltB])
|
||||||
|
checkString("\nfoobar,Y:execute(baz)", execmap[curses.AltZ+'X'])
|
||||||
|
|
||||||
|
for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {
|
||||||
|
parseKeymap(keymap, execmap, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))
|
||||||
|
checkString("foobar", execmap[curses.AltZ+int([]rune(fmt.Sprintf("%d", idx%10))[0])])
|
||||||
|
}
|
||||||
|
|
||||||
|
parseKeymap(keymap, execmap, "f1:abort")
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseNilTheme(t *testing.T) {
|
||||||
|
var theme *curses.ColorTheme
|
||||||
|
newTheme := parseTheme(theme, "prompt:12")
|
||||||
|
if newTheme != nil {
|
||||||
|
t.Errorf("color is disabled. keep it that way.")
|
||||||
|
}
|
||||||
|
newTheme = parseTheme(theme, "prompt:12,dark,prompt:13")
|
||||||
|
if newTheme.Prompt != 13 {
|
||||||
|
t.Errorf("color should now be enabled and customized")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultCtrlNP(t *testing.T) {
|
||||||
|
check := func(words []string, key int, expected actionType) {
|
||||||
|
opts := defaultOptions()
|
||||||
|
parseOptions(opts, words)
|
||||||
|
postProcessOptions(opts)
|
||||||
|
if opts.Keymap[key] != expected {
|
||||||
|
t.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check([]string{}, curses.CtrlN, actDown)
|
||||||
|
check([]string{}, curses.CtrlP, actUp)
|
||||||
|
|
||||||
|
check([]string{"--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)
|
||||||
|
check([]string{"--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)
|
||||||
|
|
||||||
|
hist := "--history=/tmp/foo"
|
||||||
|
check([]string{hist}, curses.CtrlN, actNextHistory)
|
||||||
|
check([]string{hist}, curses.CtrlP, actPreviousHistory)
|
||||||
|
|
||||||
|
check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)
|
||||||
|
check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlP, actPreviousHistory)
|
||||||
|
|
||||||
|
check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlN, actNextHistory)
|
||||||
|
check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToggle(t *testing.T) {
|
||||||
|
optsFor := func(words ...string) *Options {
|
||||||
|
opts := defaultOptions()
|
||||||
|
parseOptions(opts, words)
|
||||||
|
postProcessOptions(opts)
|
||||||
|
return opts
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := optsFor()
|
||||||
|
if opts.ToggleSort {
|
||||||
|
t.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
opts = optsFor("--bind=a:toggle-sort")
|
||||||
|
if !opts.ToggleSort {
|
||||||
|
t.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
opts = optsFor("--bind=a:toggle-sort", "--bind=a:up")
|
||||||
|
if opts.ToggleSort {
|
||||||
|
t.Error()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
249
src/pattern.go
249
src/pattern.go
@@ -6,10 +6,9 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/algo"
|
"github.com/junegunn/fzf/src/algo"
|
||||||
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
||||||
|
|
||||||
// fuzzy
|
// fuzzy
|
||||||
// 'exact
|
// 'exact
|
||||||
// ^exact-prefix
|
// ^exact-prefix
|
||||||
@@ -26,25 +25,31 @@ 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
|
||||||
origText []rune
|
caseSensitive bool
|
||||||
|
origText []rune
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type termSet []term
|
||||||
|
|
||||||
// Pattern represents search pattern
|
// Pattern represents search pattern
|
||||||
type Pattern struct {
|
type Pattern struct {
|
||||||
mode Mode
|
fuzzy bool
|
||||||
|
extended bool
|
||||||
caseSensitive bool
|
caseSensitive bool
|
||||||
|
forward bool
|
||||||
text []rune
|
text []rune
|
||||||
terms []term
|
termSets []termSet
|
||||||
hasInvTerm bool
|
cacheable bool
|
||||||
delimiter *regexp.Regexp
|
delimiter Delimiter
|
||||||
nth []Range
|
nth []Range
|
||||||
procFun map[termType]func(bool, *string, []rune) (int, int)
|
procFun map[termType]func(bool, bool, []rune, []rune) algo.Result
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -61,7 +66,7 @@ func init() {
|
|||||||
|
|
||||||
func clearPatternCache() {
|
func clearPatternCache() {
|
||||||
// We can uniquely identify the pattern for a given string since
|
// We can uniquely identify the pattern for a given string since
|
||||||
// mode and caseMode do not change while the program is running
|
// search mode and caseMode do not change while the program is running
|
||||||
_patternCache = make(map[string]*Pattern)
|
_patternCache = make(map[string]*Pattern)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,14 +75,13 @@ func clearChunkCache() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// BuildPattern builds Pattern object from the given arguments
|
// BuildPattern builds Pattern object from the given arguments
|
||||||
func BuildPattern(mode Mode, caseMode Case,
|
func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,
|
||||||
nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {
|
nth []Range, delimiter Delimiter, runes []rune) *Pattern {
|
||||||
|
|
||||||
var asString string
|
var asString string
|
||||||
switch mode {
|
if extended {
|
||||||
case ModeExtended, ModeExtendedExact:
|
|
||||||
asString = strings.Trim(string(runes), " ")
|
asString = strings.Trim(string(runes), " ")
|
||||||
default:
|
} else {
|
||||||
asString = string(runes)
|
asString = string(runes)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,39 +90,45 @@ func BuildPattern(mode Mode, caseMode Case,
|
|||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
|
|
||||||
caseSensitive, hasInvTerm := true, false
|
caseSensitive, cacheable := true, true
|
||||||
terms := []term{}
|
termSets := []termSet{}
|
||||||
|
|
||||||
switch caseMode {
|
if extended {
|
||||||
case CaseSmart:
|
termSets = parseTerms(fuzzy, caseMode, asString)
|
||||||
if !strings.ContainsAny(asString, uppercaseLetters) {
|
Loop:
|
||||||
runes, caseSensitive = []rune(strings.ToLower(asString)), false
|
for _, termSet := range termSets {
|
||||||
}
|
for idx, term := range termSet {
|
||||||
case CaseIgnore:
|
// If the query contains inverse search terms or OR operators,
|
||||||
runes, caseSensitive = []rune(strings.ToLower(asString)), false
|
// we cannot cache the search scope
|
||||||
}
|
if idx > 0 || term.inv {
|
||||||
|
cacheable = false
|
||||||
switch mode {
|
break Loop
|
||||||
case ModeExtended, ModeExtendedExact:
|
}
|
||||||
terms = parseTerms(mode, string(runes))
|
|
||||||
for _, term := range terms {
|
|
||||||
if term.inv {
|
|
||||||
hasInvTerm = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
lowerString := strings.ToLower(asString)
|
||||||
|
caseSensitive = caseMode == CaseRespect ||
|
||||||
|
caseMode == CaseSmart && lowerString != asString
|
||||||
|
if !caseSensitive {
|
||||||
|
asString = lowerString
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ptr := &Pattern{
|
ptr := &Pattern{
|
||||||
mode: mode,
|
fuzzy: fuzzy,
|
||||||
|
extended: extended,
|
||||||
caseSensitive: caseSensitive,
|
caseSensitive: caseSensitive,
|
||||||
text: runes,
|
forward: forward,
|
||||||
terms: terms,
|
text: []rune(asString),
|
||||||
hasInvTerm: hasInvTerm,
|
termSets: termSets,
|
||||||
|
cacheable: cacheable,
|
||||||
nth: nth,
|
nth: nth,
|
||||||
delimiter: delimiter,
|
delimiter: delimiter,
|
||||||
procFun: make(map[termType]func(bool, *string, []rune) (int, int))}
|
procFun: make(map[termType]func(bool, bool, []rune, []rune) algo.Result)}
|
||||||
|
|
||||||
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,51 +137,82 @@ func BuildPattern(mode Mode, caseMode Case,
|
|||||||
return ptr
|
return ptr
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseTerms(mode Mode, str string) []term {
|
func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {
|
||||||
tokens := _splitRegex.Split(str, -1)
|
tokens := _splitRegex.Split(str, -1)
|
||||||
terms := []term{}
|
sets := []termSet{}
|
||||||
|
set := termSet{}
|
||||||
|
switchSet := false
|
||||||
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 !fuzzy {
|
||||||
typ = termExact
|
typ = termExact
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if text == "|" {
|
||||||
|
switchSet = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(text, "!") {
|
if strings.HasPrefix(text, "!") {
|
||||||
inv = true
|
inv = true
|
||||||
text = text[1:]
|
text = text[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(text, "'") {
|
if strings.HasPrefix(text, "'") {
|
||||||
if mode == ModeExtended {
|
// Flip exactness
|
||||||
|
if fuzzy {
|
||||||
typ = termExact
|
typ = termExact
|
||||||
text = text[1:]
|
text = text[1:]
|
||||||
|
} else {
|
||||||
|
typ = termFuzzy
|
||||||
|
text = text[1:]
|
||||||
}
|
}
|
||||||
} else if strings.HasPrefix(text, "^") {
|
} else if strings.HasPrefix(text, "^") {
|
||||||
typ = termPrefix
|
if strings.HasSuffix(text, "$") {
|
||||||
text = text[1:]
|
typ = termEqual
|
||||||
|
text = text[1 : len(text)-1]
|
||||||
|
} else {
|
||||||
|
typ = termPrefix
|
||||||
|
text = text[1:]
|
||||||
|
}
|
||||||
} else if strings.HasSuffix(text, "$") {
|
} else if strings.HasSuffix(text, "$") {
|
||||||
typ = termSuffix
|
typ = termSuffix
|
||||||
text = text[:len(text)-1]
|
text = text[:len(text)-1]
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(text) > 0 {
|
if len(text) > 0 {
|
||||||
terms = append(terms, term{
|
if switchSet {
|
||||||
typ: typ,
|
sets = append(sets, set)
|
||||||
inv: inv,
|
set = termSet{}
|
||||||
text: []rune(text),
|
}
|
||||||
origText: origText})
|
set = append(set, term{
|
||||||
|
typ: typ,
|
||||||
|
inv: inv,
|
||||||
|
text: []rune(text),
|
||||||
|
caseSensitive: caseSensitive,
|
||||||
|
origText: origText})
|
||||||
|
switchSet = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return terms
|
if len(set) > 0 {
|
||||||
|
sets = append(sets, set)
|
||||||
|
}
|
||||||
|
return sets
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsEmpty returns true if the pattern is effectively empty
|
// IsEmpty returns true if the pattern is effectively empty
|
||||||
func (p *Pattern) IsEmpty() bool {
|
func (p *Pattern) IsEmpty() bool {
|
||||||
if p.mode == ModeFuzzy {
|
if !p.extended {
|
||||||
return len(p.text) == 0
|
return len(p.text) == 0
|
||||||
}
|
}
|
||||||
return len(p.terms) == 0
|
return len(p.termSets) == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// AsString returns the search query in string type
|
// AsString returns the search query in string type
|
||||||
@@ -181,15 +222,14 @@ func (p *Pattern) AsString() string {
|
|||||||
|
|
||||||
// CacheKey is used to build string to be used as the key of result cache
|
// CacheKey is used to build string to be used as the key of result cache
|
||||||
func (p *Pattern) CacheKey() string {
|
func (p *Pattern) CacheKey() string {
|
||||||
if p.mode == ModeFuzzy {
|
if !p.extended {
|
||||||
return p.AsString()
|
return p.AsString()
|
||||||
}
|
}
|
||||||
cacheableTerms := []string{}
|
cacheableTerms := []string{}
|
||||||
for _, term := range p.terms {
|
for _, termSet := range p.termSets {
|
||||||
if term.inv {
|
if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {
|
||||||
continue
|
cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
|
||||||
}
|
}
|
||||||
cacheableTerms = append(cacheableTerms, string(term.origText))
|
|
||||||
}
|
}
|
||||||
return strings.Join(cacheableTerms, " ")
|
return strings.Join(cacheableTerms, " ")
|
||||||
}
|
}
|
||||||
@@ -200,7 +240,7 @@ func (p *Pattern) Match(chunk *Chunk) []*Item {
|
|||||||
|
|
||||||
// ChunkCache: Exact match
|
// ChunkCache: Exact match
|
||||||
cacheKey := p.CacheKey()
|
cacheKey := p.CacheKey()
|
||||||
if !p.hasInvTerm { // Because we're excluding Inv-term from cache key
|
if p.cacheable {
|
||||||
if cached, found := _cache.Find(chunk, cacheKey); found {
|
if cached, found := _cache.Find(chunk, cacheKey); found {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
@@ -225,7 +265,7 @@ Loop:
|
|||||||
|
|
||||||
matches := p.matchChunk(space)
|
matches := p.matchChunk(space)
|
||||||
|
|
||||||
if !p.hasInvTerm {
|
if p.cacheable {
|
||||||
_cache.Add(chunk, cacheKey, matches)
|
_cache.Add(chunk, cacheKey, matches)
|
||||||
}
|
}
|
||||||
return matches
|
return matches
|
||||||
@@ -233,17 +273,18 @@ Loop:
|
|||||||
|
|
||||||
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||||
matches := []*Item{}
|
matches := []*Item{}
|
||||||
if p.mode == ModeFuzzy {
|
if !p.extended {
|
||||||
for _, item := range *chunk {
|
for _, item := range *chunk {
|
||||||
if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {
|
offset, bonus := p.basicMatch(item)
|
||||||
|
if sidx := offset[0]; sidx >= 0 {
|
||||||
matches = append(matches,
|
matches = append(matches,
|
||||||
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
|
dupItem(item, []Offset{offset}, bonus))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for _, item := range *chunk {
|
for _, item := range *chunk {
|
||||||
if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {
|
if offsets, bonus := p.extendedMatch(item); len(offsets) == len(p.termSets) {
|
||||||
matches = append(matches, dupItem(item, offsets))
|
matches = append(matches, dupItem(item, offsets, bonus))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -252,74 +293,90 @@ func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
|||||||
|
|
||||||
// MatchItem returns true if the Item is a match
|
// MatchItem returns true if the Item is a match
|
||||||
func (p *Pattern) MatchItem(item *Item) bool {
|
func (p *Pattern) MatchItem(item *Item) bool {
|
||||||
if p.mode == ModeFuzzy {
|
if !p.extended {
|
||||||
sidx, _ := p.fuzzyMatch(item)
|
offset, _ := p.basicMatch(item)
|
||||||
|
sidx := offset[0]
|
||||||
return sidx >= 0
|
return sidx >= 0
|
||||||
}
|
}
|
||||||
offsets := p.extendedMatch(item)
|
offsets, _ := p.extendedMatch(item)
|
||||||
return len(offsets) == len(p.terms)
|
return len(offsets) == len(p.termSets)
|
||||||
}
|
}
|
||||||
|
|
||||||
func dupItem(item *Item, offsets []Offset) *Item {
|
func dupItem(item *Item, offsets []Offset, bonus int32) *Item {
|
||||||
sort.Sort(ByOrder(offsets))
|
sort.Sort(ByOrder(offsets))
|
||||||
return &Item{
|
return &Item{
|
||||||
text: item.text,
|
text: item.text,
|
||||||
origText: item.origText,
|
origText: item.origText,
|
||||||
transformed: item.transformed,
|
transformed: item.transformed,
|
||||||
index: item.index,
|
|
||||||
offsets: offsets,
|
offsets: offsets,
|
||||||
|
bonus: bonus,
|
||||||
colors: item.colors,
|
colors: item.colors,
|
||||||
rank: Rank{0, 0, item.index}}
|
rank: buildEmptyRank(item.Index())}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
func (p *Pattern) basicMatch(item *Item) (Offset, int32) {
|
||||||
input := p.prepareInput(item)
|
input := p.prepareInput(item)
|
||||||
return p.iter(algo.FuzzyMatch, input, p.text)
|
if p.fuzzy {
|
||||||
|
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)
|
||||||
|
}
|
||||||
|
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
func (p *Pattern) extendedMatch(item *Item) ([]Offset, int32) {
|
||||||
input := p.prepareInput(item)
|
input := p.prepareInput(item)
|
||||||
offsets := []Offset{}
|
offsets := []Offset{}
|
||||||
for _, term := range p.terms {
|
var totalBonus int32
|
||||||
pfun := p.procFun[term.typ]
|
for _, termSet := range p.termSets {
|
||||||
if sidx, eidx := p.iter(pfun, input, term.text); sidx >= 0 {
|
var offset *Offset
|
||||||
if term.inv {
|
var bonus int32
|
||||||
|
for _, term := range termSet {
|
||||||
|
pfun := p.procFun[term.typ]
|
||||||
|
off, pen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text)
|
||||||
|
if sidx := off[0]; sidx >= 0 {
|
||||||
|
if term.inv {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offset, bonus = &off, pen
|
||||||
break
|
break
|
||||||
|
} else if term.inv {
|
||||||
|
offset, bonus = &Offset{0, 0, 0}, 0
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
|
}
|
||||||
} else if term.inv {
|
if offset != nil {
|
||||||
offsets = append(offsets, Offset{0, 0})
|
offsets = append(offsets, *offset)
|
||||||
|
totalBonus += bonus
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return offsets
|
return offsets, totalBonus
|
||||||
}
|
}
|
||||||
|
|
||||||
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{
|
ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}
|
||||||
whole: item.text,
|
|
||||||
parts: []Token{Token{text: item.text, prefixLength: 0}}}
|
|
||||||
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, bool, []rune, []rune) algo.Result,
|
||||||
inputs *Transformed, pattern []rune) (int, int) {
|
tokens []Token, caseSensitive bool, forward bool, pattern []rune) (Offset, int32) {
|
||||||
for _, part := range inputs.parts {
|
for _, part := range tokens {
|
||||||
prefixLength := part.prefixLength
|
prefixLength := int32(part.prefixLength)
|
||||||
if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {
|
if res := pfun(caseSensitive, forward, part.text, pattern); res.Start >= 0 {
|
||||||
return sidx + prefixLength, eidx + prefixLength
|
var sidx int32 = res.Start + prefixLength
|
||||||
|
var eidx int32 = res.End + prefixLength
|
||||||
|
return Offset{sidx, eidx, int32(part.trimLength)}, res.Bonus
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return -1, -1
|
// TODO: math.MaxUint16
|
||||||
|
return Offset{-1, -1, -1}, 0.0
|
||||||
}
|
}
|
||||||
|
@@ -1,26 +1,33 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/algo"
|
"github.com/junegunn/fzf/src/algo"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestParseTermsExtended(t *testing.T) {
|
func TestParseTermsExtended(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtended,
|
terms := parseTerms(true, CaseSmart,
|
||||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
"| aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | | zzz$ | !ZZZ |")
|
||||||
if len(terms) != 8 ||
|
if len(terms) != 9 ||
|
||||||
terms[0].typ != termFuzzy || terms[0].inv ||
|
terms[0][0].typ != termFuzzy || terms[0][0].inv ||
|
||||||
terms[1].typ != termExact || terms[1].inv ||
|
terms[1][0].typ != termExact || terms[1][0].inv ||
|
||||||
terms[2].typ != termPrefix || terms[2].inv ||
|
terms[2][0].typ != termPrefix || terms[2][0].inv ||
|
||||||
terms[3].typ != termSuffix || terms[3].inv ||
|
terms[3][0].typ != termSuffix || terms[3][0].inv ||
|
||||||
terms[4].typ != termFuzzy || !terms[4].inv ||
|
terms[4][0].typ != termFuzzy || !terms[4][0].inv ||
|
||||||
terms[5].typ != termExact || !terms[5].inv ||
|
terms[5][0].typ != termExact || !terms[5][0].inv ||
|
||||||
terms[6].typ != termPrefix || !terms[6].inv ||
|
terms[6][0].typ != termPrefix || !terms[6][0].inv ||
|
||||||
terms[7].typ != termSuffix || !terms[7].inv {
|
terms[7][0].typ != termSuffix || !terms[7][0].inv ||
|
||||||
|
terms[7][1].typ != termEqual || terms[7][1].inv ||
|
||||||
|
terms[8][0].typ != termPrefix || terms[8][0].inv ||
|
||||||
|
terms[8][1].typ != termExact || terms[8][1].inv ||
|
||||||
|
terms[8][2].typ != termSuffix || terms[8][2].inv ||
|
||||||
|
terms[8][3].typ != termFuzzy || !terms[8][3].inv {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
for idx, term := range terms {
|
for idx, termSet := range terms[:8] {
|
||||||
|
term := termSet[0]
|
||||||
if len(term.text) != 3 {
|
if len(term.text) != 3 {
|
||||||
t.Errorf("%s", term)
|
t.Errorf("%s", term)
|
||||||
}
|
}
|
||||||
@@ -28,26 +35,31 @@ func TestParseTermsExtended(t *testing.T) {
|
|||||||
t.Errorf("%s", term)
|
t.Errorf("%s", term)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for _, term := range terms[8] {
|
||||||
|
if len(term.origText) != 4 {
|
||||||
|
t.Errorf("%s", term)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTermsExtendedExact(t *testing.T) {
|
func TestParseTermsExtendedExact(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtendedExact,
|
terms := parseTerms(false, 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][0].typ != termExact || terms[0][0].inv || len(terms[0][0].text) != 3 ||
|
||||||
terms[1].typ != termExact || terms[1].inv || len(terms[1].text) != 4 ||
|
terms[1][0].typ != termFuzzy || terms[1][0].inv || len(terms[1][0].text) != 3 ||
|
||||||
terms[2].typ != termPrefix || terms[2].inv || len(terms[2].text) != 3 ||
|
terms[2][0].typ != termPrefix || terms[2][0].inv || len(terms[2][0].text) != 3 ||
|
||||||
terms[3].typ != termSuffix || terms[3].inv || len(terms[3].text) != 3 ||
|
terms[3][0].typ != termSuffix || terms[3][0].inv || len(terms[3][0].text) != 3 ||
|
||||||
terms[4].typ != termExact || !terms[4].inv || len(terms[4].text) != 3 ||
|
terms[4][0].typ != termExact || !terms[4][0].inv || len(terms[4][0].text) != 3 ||
|
||||||
terms[5].typ != termExact || !terms[5].inv || len(terms[5].text) != 4 ||
|
terms[5][0].typ != termFuzzy || !terms[5][0].inv || len(terms[5][0].text) != 3 ||
|
||||||
terms[6].typ != termPrefix || !terms[6].inv || len(terms[6].text) != 3 ||
|
terms[6][0].typ != termPrefix || !terms[6][0].inv || len(terms[6][0].text) != 3 ||
|
||||||
terms[7].typ != termSuffix || !terms[7].inv || len(terms[7].text) != 3 {
|
terms[7][0].typ != termSuffix || !terms[7][0].inv || len(terms[7][0].text) != 3 {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTermsEmpty(t *testing.T) {
|
func TestParseTermsEmpty(t *testing.T) {
|
||||||
terms := parseTerms(ModeExtended, "' $ ^ !' !^ !$")
|
terms := parseTerms(true, CaseSmart, "' $ ^ !' !^ !$")
|
||||||
if len(terms) != 0 {
|
if len(terms) != 0 {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
@@ -56,29 +68,45 @@ func TestParseTermsEmpty(t *testing.T) {
|
|||||||
func TestExact(t *testing.T) {
|
func TestExact(t *testing.T) {
|
||||||
defer clearPatternCache()
|
defer clearPatternCache()
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pattern := BuildPattern(ModeExtended, CaseSmart,
|
pattern := BuildPattern(true, true, CaseSmart, true,
|
||||||
[]Range{}, nil, []rune("'abc"))
|
[]Range{}, Delimiter{}, []rune("'abc"))
|
||||||
str := "aabbcc abc"
|
res := algo.ExactMatchNaive(
|
||||||
sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &str, pattern.terms[0].text)
|
pattern.caseSensitive, pattern.forward, []rune("aabbcc abc"), pattern.termSets[0][0].text)
|
||||||
if sidx != 7 || eidx != 10 {
|
if res.Start != 7 || res.End != 10 {
|
||||||
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEqual(t *testing.T) {
|
||||||
|
defer clearPatternCache()
|
||||||
|
clearPatternCache()
|
||||||
|
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("^AbC$"))
|
||||||
|
|
||||||
|
match := func(str string, sidxExpected int32, eidxExpected int32) {
|
||||||
|
res := algo.EqualMatch(
|
||||||
|
pattern.caseSensitive, pattern.forward, []rune(str), pattern.termSets[0][0].text)
|
||||||
|
if res.Start != sidxExpected || res.End != eidxExpected {
|
||||||
|
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match("ABC", -1, -1)
|
||||||
|
match("AbC", 0, 3)
|
||||||
|
}
|
||||||
|
|
||||||
func TestCaseSensitivity(t *testing.T) {
|
func TestCaseSensitivity(t *testing.T) {
|
||||||
defer clearPatternCache()
|
defer clearPatternCache()
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat1 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("abc"))
|
pat1 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat2 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("Abc"))
|
pat2 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat3 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("abc"))
|
pat3 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat4 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("Abc"))
|
pat4 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat5 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, nil, []rune("abc"))
|
pat5 := BuildPattern(true, false, CaseRespect, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat6 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, nil, []rune("Abc"))
|
pat6 := BuildPattern(true, false, CaseRespect, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||||
|
|
||||||
if string(pat1.text) != "abc" || pat1.caseSensitive != false ||
|
if string(pat1.text) != "abc" || pat1.caseSensitive != false ||
|
||||||
string(pat2.text) != "Abc" || pat2.caseSensitive != true ||
|
string(pat2.text) != "Abc" || pat2.caseSensitive != true ||
|
||||||
@@ -91,26 +119,46 @@ func TestCaseSensitivity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestOrigTextAndTransformed(t *testing.T) {
|
func TestOrigTextAndTransformed(t *testing.T) {
|
||||||
strptr := func(str string) *string {
|
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("jg"))
|
||||||
return &str
|
tokens := Tokenize([]rune("junegunn"), Delimiter{})
|
||||||
}
|
|
||||||
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))
|
|
||||||
tokens := Tokenize(strptr("junegunn"), nil)
|
|
||||||
trans := Transform(tokens, []Range{Range{1, 1}})
|
trans := Transform(tokens, []Range{Range{1, 1}})
|
||||||
|
|
||||||
for _, mode := range []Mode{ModeFuzzy, ModeExtended} {
|
origRunes := []rune("junegunn.choi")
|
||||||
|
for _, extended := range []bool{false, true} {
|
||||||
chunk := Chunk{
|
chunk := Chunk{
|
||||||
&Item{
|
&Item{
|
||||||
text: strptr("junegunn"),
|
text: []rune("junegunn"),
|
||||||
origText: strptr("junegunn.choi"),
|
origText: &origRunes,
|
||||||
transformed: trans},
|
transformed: trans},
|
||||||
}
|
}
|
||||||
pattern.mode = mode
|
pattern.extended = extended
|
||||||
matches := pattern.matchChunk(&chunk)
|
matches := pattern.matchChunk(&chunk)
|
||||||
if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||
|
if string(matches[0].text) != "junegunn" || string(*matches[0].origText) != "junegunn.choi" ||
|
||||||
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||
|
||||||
matches[0].transformed != trans {
|
!reflect.DeepEqual(matches[0].transformed, trans) {
|
||||||
t.Error("Invalid match result", matches)
|
t.Error("Invalid match result", matches)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCacheKey(t *testing.T) {
|
||||||
|
test := func(extended bool, patStr string, expected string, cacheable bool) {
|
||||||
|
pat := BuildPattern(true, extended, CaseSmart, true, []Range{}, Delimiter{}, []rune(patStr))
|
||||||
|
if pat.CacheKey() != expected {
|
||||||
|
t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())
|
||||||
|
}
|
||||||
|
if pat.cacheable != cacheable {
|
||||||
|
t.Errorf("Expected: %s, actual: %s (%s)", cacheable, pat.cacheable, patStr)
|
||||||
|
}
|
||||||
|
clearPatternCache()
|
||||||
|
}
|
||||||
|
test(false, "foo !bar", "foo !bar", true)
|
||||||
|
test(false, "foo | bar !baz", "foo | bar !baz", true)
|
||||||
|
test(true, "foo bar baz", "foo bar baz", true)
|
||||||
|
test(true, "foo !bar", "foo", false)
|
||||||
|
test(true, "foo !bar baz", "foo baz", false)
|
||||||
|
test(true, "foo | bar baz", "baz", false)
|
||||||
|
test(true, "foo | bar | baz", "", false)
|
||||||
|
test(true, "foo | bar !baz", "", false)
|
||||||
|
test(true, "| | | foo", "foo", true)
|
||||||
|
}
|
||||||
|
@@ -4,17 +4,15 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
|
||||||
|
|
||||||
"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([]byte) bool
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
|
delimNil bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadSource reads data from the default command or from standard input
|
// ReadSource reads data from the default command or from standard input
|
||||||
@@ -32,10 +30,25 @@ 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'
|
||||||
r.eventBox.Set(EvtReadNew, nil)
|
}
|
||||||
|
reader := bufio.NewReader(src)
|
||||||
|
for {
|
||||||
|
// ReadBytes returns err != nil if and only if the returned data does not
|
||||||
|
// end in delim.
|
||||||
|
bytea, err := reader.ReadBytes(delim)
|
||||||
|
if len(bytea) > 0 {
|
||||||
|
if err == nil {
|
||||||
|
bytea = bytea[:len(bytea)-1]
|
||||||
|
}
|
||||||
|
if r.pusher(bytea) {
|
||||||
|
r.eventBox.Set(EvtReadNew, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,7 +58,7 @@ func (r *Reader) readFromStdin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) readFromCommand(cmd string) {
|
func (r *Reader) readFromCommand(cmd string) {
|
||||||
listCommand := exec.Command("sh", "-c", cmd)
|
listCommand := util.ExecCommand(cmd)
|
||||||
out, err := listCommand.StdoutPipe()
|
out, err := listCommand.StdoutPipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
@@ -10,7 +10,7 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
strs := []string{}
|
strs := []string{}
|
||||||
eb := util.NewEventBox()
|
eb := util.NewEventBox()
|
||||||
reader := Reader{
|
reader := Reader{
|
||||||
pusher: func(s string) { strs = append(strs, s) },
|
pusher: func(s []byte) bool { strs = append(strs, string(s)); return true },
|
||||||
eventBox: eb}
|
eventBox: eb}
|
||||||
|
|
||||||
// Check EventBox
|
// Check EventBox
|
||||||
|
1149
src/terminal.go
1149
src/terminal.go
File diff suppressed because it is too large
Load Diff
@@ -16,16 +16,17 @@ 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
|
||||||
|
trimLength int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delimiter for tokenizing the input
|
||||||
|
type Delimiter struct {
|
||||||
|
regex *regexp.Regexp
|
||||||
|
str *string
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRange(begin int, end int) Range {
|
func newRange(begin int, end int) Range {
|
||||||
@@ -74,16 +75,15 @@ func ParseRange(str *string) (Range, bool) {
|
|||||||
return newRange(n, n), true
|
return newRange(n, n), true
|
||||||
}
|
}
|
||||||
|
|
||||||
func withPrefixLengths(tokens []string, begin int) []Token {
|
func withPrefixLengths(tokens [][]rune, begin int) []Token {
|
||||||
ret := make([]Token, len(tokens))
|
ret := make([]Token, len(tokens))
|
||||||
|
|
||||||
prefixLength := begin
|
prefixLength := begin
|
||||||
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
|
ret[idx] = Token{token, prefixLength, util.TrimLen(token)}
|
||||||
ret[idx] = Token{text: &str, prefixLength: prefixLength}
|
prefixLength += len(token)
|
||||||
prefixLength += len([]rune(token))
|
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
@@ -94,13 +94,13 @@ const (
|
|||||||
awkWhite
|
awkWhite
|
||||||
)
|
)
|
||||||
|
|
||||||
func awkTokenizer(input *string) ([]string, int) {
|
func awkTokenizer(input []rune) ([][]rune, int) {
|
||||||
// 9, 32
|
// 9, 32
|
||||||
ret := []string{}
|
ret := [][]rune{}
|
||||||
str := []rune{}
|
str := []rune{}
|
||||||
prefixLength := 0
|
prefixLength := 0
|
||||||
state := awkNil
|
state := awkNil
|
||||||
for _, r := range []rune(*input) {
|
for _, r := range input {
|
||||||
white := r == 9 || r == 32
|
white := r == 9 || r == 32
|
||||||
switch state {
|
switch state {
|
||||||
case awkNil:
|
case awkNil:
|
||||||
@@ -119,56 +119,85 @@ func awkTokenizer(input *string) ([]string, int) {
|
|||||||
if white {
|
if white {
|
||||||
str = append(str, r)
|
str = append(str, r)
|
||||||
} else {
|
} else {
|
||||||
ret = append(ret, string(str))
|
ret = append(ret, str)
|
||||||
state = awkBlack
|
state = awkBlack
|
||||||
str = []rune{r}
|
str = []rune{r}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(str) > 0 {
|
if len(str) > 0 {
|
||||||
ret = append(ret, string(str))
|
ret = append(ret, str)
|
||||||
}
|
}
|
||||||
return ret, prefixLength
|
return ret, prefixLength
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tokenize tokenizes the given string with the delimiter
|
// Tokenize tokenizes the given string with the delimiter
|
||||||
func Tokenize(str *string, delimiter *regexp.Regexp) []Token {
|
func Tokenize(runes []rune, delimiter Delimiter) []Token {
|
||||||
if delimiter == nil {
|
if delimiter.str == nil && delimiter.regex == nil {
|
||||||
// AWK-style (\S+\s*)
|
// AWK-style (\S+\s*)
|
||||||
tokens, prefixLength := awkTokenizer(str)
|
tokens, prefixLength := awkTokenizer(runes)
|
||||||
return withPrefixLengths(tokens, prefixLength)
|
return withPrefixLengths(tokens, prefixLength)
|
||||||
}
|
}
|
||||||
tokens := delimiter.FindAllString(*str, -1)
|
|
||||||
return withPrefixLengths(tokens, 0)
|
var tokens []string
|
||||||
|
if delimiter.str != nil {
|
||||||
|
tokens = strings.Split(string(runes), *delimiter.str)
|
||||||
|
for i := 0; i < len(tokens)-1; i++ {
|
||||||
|
tokens[i] = tokens[i] + *delimiter.str
|
||||||
|
}
|
||||||
|
} else if delimiter.regex != nil {
|
||||||
|
str := string(runes)
|
||||||
|
for len(str) > 0 {
|
||||||
|
loc := delimiter.regex.FindStringIndex(str)
|
||||||
|
if loc == nil {
|
||||||
|
loc = []int{0, len(str)}
|
||||||
|
}
|
||||||
|
last := util.Max(loc[1], 1)
|
||||||
|
tokens = append(tokens, str[:last])
|
||||||
|
str = str[last:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
asRunes := make([][]rune, len(tokens))
|
||||||
|
for i, token := range tokens {
|
||||||
|
asRunes[i] = []rune(token)
|
||||||
|
}
|
||||||
|
return withPrefixLengths(asRunes, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinTokens(tokens []Token) string {
|
func joinTokens(tokens []Token) []rune {
|
||||||
ret := ""
|
ret := []rune{}
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
ret += *token.text
|
ret = append(ret, token.text...)
|
||||||
|
}
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinTokensAsRunes(tokens []Token) []rune {
|
||||||
|
ret := []rune{}
|
||||||
|
for _, token := range tokens {
|
||||||
|
ret = append(ret, token.text...)
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform is used to transform the input when --with-nth option is given
|
// Transform is used to transform the input when --with-nth option is given
|
||||||
func Transform(tokens []Token, withNth []Range) *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,20 +224,17 @@ 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
|
||||||
} else {
|
} else {
|
||||||
prefixLength = 0
|
prefixLength = 0
|
||||||
}
|
}
|
||||||
transTokens[idx] = Token{&part, prefixLength}
|
transTokens[idx] = Token{part, prefixLength, util.TrimLen(part)}
|
||||||
}
|
}
|
||||||
return &Transformed{
|
return transTokens
|
||||||
whole: &whole,
|
|
||||||
parts: transTokens}
|
|
||||||
}
|
}
|
||||||
|
@@ -43,14 +43,23 @@ func TestParseRange(t *testing.T) {
|
|||||||
func TestTokenize(t *testing.T) {
|
func TestTokenize(t *testing.T) {
|
||||||
// AWK-style
|
// AWK-style
|
||||||
input := " abc: def: ghi "
|
input := " abc: def: ghi "
|
||||||
tokens := Tokenize(&input, nil)
|
tokens := Tokenize([]rune(input), Delimiter{})
|
||||||
if *tokens[0].text != "abc: " || tokens[0].prefixLength != 2 {
|
if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 || tokens[0].trimLength != 4 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With delimiter
|
// With delimiter
|
||||||
tokens = Tokenize(&input, delimiterRegexp(":"))
|
tokens = Tokenize([]rune(input), delimiterRegexp(":"))
|
||||||
if *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {
|
if string(tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 || tokens[0].trimLength != 4 {
|
||||||
|
t.Errorf("%s", tokens)
|
||||||
|
}
|
||||||
|
|
||||||
|
// With delimiter regex
|
||||||
|
tokens = Tokenize([]rune(input), delimiterRegexp("\\s+"))
|
||||||
|
if string(tokens[0].text) != " " || tokens[0].prefixLength != 0 || tokens[0].trimLength != 0 ||
|
||||||
|
string(tokens[1].text) != "abc: " || tokens[1].prefixLength != 2 || tokens[1].trimLength != 4 ||
|
||||||
|
string(tokens[2].text) != "def: " || tokens[2].prefixLength != 8 || tokens[2].trimLength != 4 ||
|
||||||
|
string(tokens[3].text) != "ghi " || tokens[3].prefixLength != 14 || tokens[3].trimLength != 3 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -58,39 +67,39 @@ func TestTokenize(t *testing.T) {
|
|||||||
func TestTransform(t *testing.T) {
|
func TestTransform(t *testing.T) {
|
||||||
input := " abc: def: ghi: jkl"
|
input := " abc: def: ghi: jkl"
|
||||||
{
|
{
|
||||||
tokens := Tokenize(&input, nil)
|
tokens := Tokenize([]rune(input), Delimiter{})
|
||||||
{
|
{
|
||||||
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 string(joinTokens(tx)) != "abc: def: ghi: " {
|
||||||
t.Errorf("%s", *tx)
|
t.Errorf("%s", tx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *tx.whole != "abc: def: ghi: def: ghi: jklabc: " ||
|
if string(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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
tokens := Tokenize(&input, delimiterRegexp(":"))
|
tokens := Tokenize([]rune(input), delimiterRegexp(":"))
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
if *tx.whole != " abc: def: ghi: def: ghi: jkl abc:" ||
|
if string(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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -5,7 +5,9 @@ import "C"
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Max returns the largest integer
|
// Max returns the largest integer
|
||||||
@@ -19,6 +21,22 @@ func Max(first int, items ...int) int {
|
|||||||
return max
|
return max
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Min returns the smallest integer
|
||||||
|
func Min(first int, second int) int {
|
||||||
|
if first <= second {
|
||||||
|
return first
|
||||||
|
}
|
||||||
|
return second
|
||||||
|
}
|
||||||
|
|
||||||
|
// Min32 returns the smallest 32-bit integer
|
||||||
|
func Min32(first int32, second int32) int32 {
|
||||||
|
if first <= second {
|
||||||
|
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 {
|
||||||
@@ -61,11 +79,68 @@ func DurWithin(
|
|||||||
return val
|
return val
|
||||||
}
|
}
|
||||||
|
|
||||||
func Between(val int, min int, max int) bool {
|
|
||||||
return val >= min && val <= max
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsTty returns true is stdin is a terminal
|
// IsTty returns true is stdin is a terminal
|
||||||
func IsTty() bool {
|
func IsTty() bool {
|
||||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TrimRight returns rune array with trailing white spaces cut off
|
||||||
|
func TrimRight(runes []rune) []rune {
|
||||||
|
var i int
|
||||||
|
for i = len(runes) - 1; i >= 0; i-- {
|
||||||
|
char := runes[i]
|
||||||
|
if char != ' ' && char != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return runes[0 : i+1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// BytesToRunes converts byte array into rune array
|
||||||
|
func BytesToRunes(bytea []byte) []rune {
|
||||||
|
runes := make([]rune, 0, len(bytea))
|
||||||
|
for i := 0; i < len(bytea); {
|
||||||
|
if bytea[i] < utf8.RuneSelf {
|
||||||
|
runes = append(runes, rune(bytea[i]))
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
r, sz := utf8.DecodeRune(bytea[i:])
|
||||||
|
i += sz
|
||||||
|
runes = append(runes, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return runes
|
||||||
|
}
|
||||||
|
|
||||||
|
// TrimLen returns the length of trimmed rune array
|
||||||
|
func TrimLen(runes []rune) int {
|
||||||
|
var i int
|
||||||
|
for i = len(runes) - 1; i >= 0; i-- {
|
||||||
|
char := runes[i]
|
||||||
|
if char != ' ' && char != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Completely empty
|
||||||
|
if i < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var j int
|
||||||
|
for j = 0; j < len(runes); j++ {
|
||||||
|
char := runes[j]
|
||||||
|
if char != ' ' && char != '\t' {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return i - j + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecCommand executes the given command with $SHELL
|
||||||
|
func ExecCommand(command string) *exec.Cmd {
|
||||||
|
shell := os.Getenv("SHELL")
|
||||||
|
if len(shell) == 0 {
|
||||||
|
shell = "sh"
|
||||||
|
}
|
||||||
|
return exec.Command(shell, "-c", command)
|
||||||
|
}
|
||||||
|
@@ -20,3 +20,23 @@ func TestContrain(t *testing.T) {
|
|||||||
t.Error("Expected", 3)
|
t.Error("Expected", 3)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTrimLen(t *testing.T) {
|
||||||
|
check := func(str string, exp int) {
|
||||||
|
trimmed := TrimLen([]rune(str))
|
||||||
|
if trimmed != exp {
|
||||||
|
t.Errorf("Invalid TrimLen result for '%s': %d (expected %d)",
|
||||||
|
str, trimmed, exp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check("hello", 5)
|
||||||
|
check("hello ", 5)
|
||||||
|
check("hello ", 5)
|
||||||
|
check(" hello", 5)
|
||||||
|
check(" hello", 5)
|
||||||
|
check(" hello ", 5)
|
||||||
|
check(" hello ", 5)
|
||||||
|
check("h o", 5)
|
||||||
|
check(" h o ", 5)
|
||||||
|
check(" ", 0)
|
||||||
|
}
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
Execute (Setup):
|
Execute (Setup):
|
||||||
let g:dir = fnamemodify(g:vader_file, ':p:h')
|
let g:dir = fnamemodify(g:vader_file, ':p:h')
|
||||||
Log 'Test directory: ' . g:dir
|
Log 'Test directory: ' . g:dir
|
||||||
|
Save &acd
|
||||||
|
|
||||||
Execute (fzf#run with dir option):
|
Execute (fzf#run with dir option):
|
||||||
let cwd = getcwd()
|
let cwd = getcwd()
|
||||||
@@ -35,6 +36,34 @@ Execute (fzf#run with string source):
|
|||||||
let result = sort(fzf#run({ 'source': 'echo hi', 'options': '-f i' }))
|
let result = sort(fzf#run({ 'source': 'echo hi', 'options': '-f i' }))
|
||||||
AssertEqual ['hi'], result
|
AssertEqual ['hi'], result
|
||||||
|
|
||||||
|
Execute (fzf#run with dir option and noautochdir):
|
||||||
|
set noacd
|
||||||
|
let cwd = getcwd()
|
||||||
|
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})
|
||||||
|
" No change in working directory
|
||||||
|
AssertEqual cwd, getcwd()
|
||||||
|
|
||||||
|
Execute (Incomplete fzf#run with dir option and autochdir):
|
||||||
|
set acd
|
||||||
|
let cwd = getcwd()
|
||||||
|
call fzf#run({'source': [], 'sink': 'e', 'dir': '/tmp', 'options': '-0'})
|
||||||
|
" No change in working directory even if &acd is set
|
||||||
|
AssertEqual cwd, getcwd()
|
||||||
|
|
||||||
|
Execute (fzf#run with dir option and autochdir):
|
||||||
|
set acd
|
||||||
|
let cwd = getcwd()
|
||||||
|
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/tmp', 'options': '-1'})
|
||||||
|
" Working directory changed due to &acd
|
||||||
|
AssertEqual '/', getcwd()
|
||||||
|
|
||||||
|
Execute (fzf#run with dir option and autochdir when final cwd is same as dir):
|
||||||
|
set acd
|
||||||
|
cd /tmp
|
||||||
|
call fzf#run({'source': ['/foobar'], 'sink': 'e', 'dir': '/', 'options': '-1'})
|
||||||
|
" Working directory changed due to &acd
|
||||||
|
AssertEqual '/', getcwd()
|
||||||
|
|
||||||
Execute (Cleanup):
|
Execute (Cleanup):
|
||||||
unlet g:dir
|
unlet g:dir
|
||||||
Restore
|
Restore
|
||||||
|
1287
test/test_go.rb
1287
test/test_go.rb
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user