mirror of
https://github.com/junegunn/fzf.git
synced 2025-07-31 04:02:01 -07:00
Compare commits
252 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
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 |
@@ -4,7 +4,7 @@ rvm:
|
||||
|
||||
install:
|
||||
- sudo apt-get update
|
||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev
|
||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev libgpm-dev
|
||||
- sudo add-apt-repository -y ppa:pi-rho/dev
|
||||
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
||||
- sudo apt-get update
|
||||
|
171
CHANGELOG.md
171
CHANGELOG.md
@@ -1,6 +1,177 @@
|
||||
CHANGELOG
|
||||
=========
|
||||
|
||||
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
|
||||
------
|
||||
|
||||
|
158
README.md
158
README.md
@@ -1,4 +1,4 @@
|
||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf) <a href="http://flattr.com/thing/3115381/junegunnfzf-on-GitHub" target="_blank"><img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a>
|
||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf)
|
||||
===
|
||||
|
||||
fzf is a general-purpose command-line fuzzy finder.
|
||||
@@ -8,7 +8,7 @@ fzf is a general-purpose command-line fuzzy finder.
|
||||
Pros
|
||||
----
|
||||
|
||||
- No dependency
|
||||
- No dependencies
|
||||
- Blazingly fast
|
||||
- e.g. `locate / | fzf`
|
||||
- Flexible layout
|
||||
@@ -27,7 +27,7 @@ fzf project consists of the followings:
|
||||
- `fzf-tmux` script for launching fzf in a tmux pane
|
||||
- Shell extensions
|
||||
- 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
|
||||
@@ -50,10 +50,10 @@ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
|
||||
On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
||||
|
||||
```sh
|
||||
brew reinstall --HEAD fzf
|
||||
brew install fzf
|
||||
|
||||
# Install shell extensions
|
||||
/usr/local/Cellar/fzf/HEAD/install
|
||||
/usr/local/opt/fzf/install
|
||||
```
|
||||
|
||||
#### Install as Vim plugin
|
||||
@@ -68,7 +68,7 @@ Or you can have [vim-plug](https://github.com/junegunn/vim-plug) manage fzf
|
||||
(recommended):
|
||||
|
||||
```vim
|
||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': 'yes \| ./install' }
|
||||
Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
|
||||
```
|
||||
|
||||
#### Upgrading fzf
|
||||
@@ -78,7 +78,7 @@ while. Please follow the instruction below depending on the installation
|
||||
method.
|
||||
|
||||
- git: `cd ~/.fzf && git pull && ./install`
|
||||
- brew: `brew reinstall --HEAD fzf`
|
||||
- brew: `brew update; brew reinstall fzf`
|
||||
- vim-plug: `:PlugUpdate fzf`
|
||||
|
||||
Usage
|
||||
@@ -108,24 +108,41 @@ vim $(fzf)
|
||||
- Mouse: scroll, click, double-click; shift-click and shift-scroll on
|
||||
multi-select mode
|
||||
|
||||
#### Extended-search mode
|
||||
#### Search syntax
|
||||
|
||||
With `-x` or `--extended` option, fzf will start in "extended-search mode".
|
||||
Unless otherwise specified, fzf starts in "extended-search mode" where you can
|
||||
type in multiple search terms delimited by spaces. e.g. `^music .mp3$ sbtrkt
|
||||
!rmx`
|
||||
|
||||
In this mode, you can specify multiple patterns delimited by spaces,
|
||||
such as: `^music .mp3$ sbtrkt !rmx`
|
||||
| Token | Match type | Description |
|
||||
| -------- | -------------------- | -------------------------------- |
|
||||
| `sbtrkt` | fuzzy-match | Items that match `sbtrkt` |
|
||||
| `^music` | prefix-exact-match | Items that start with `music` |
|
||||
| `.mp3$` | suffix-exact-match | Items that end with `.mp3` |
|
||||
| `'wild` | exact-match (quoted) | Items that include `wild` |
|
||||
| `!rmx` | inverse-fuzzy-match | Items that do not match `rmx` |
|
||||
| `!'fire` | inverse-exact-match | Items that do not include `fire` |
|
||||
|
||||
| Token | Description | Match type |
|
||||
| -------- | -------------------------------- | -------------------- |
|
||||
| `^music` | Items that start with `music` | prefix-exact-match |
|
||||
| `.mp3$` | Items that end with `.mp3` | suffix-exact-match |
|
||||
| `sbtrkt` | Items that match `sbtrkt` | fuzzy-match |
|
||||
| `!rmx` | Items that do not match `rmx` | inverse-fuzzy-match |
|
||||
| `'wild` | Items that include `wild` | exact-match (quoted) |
|
||||
| `!'fire` | Items that do not include `fire` | inverse-exact-match |
|
||||
If you don't prefer fuzzy matching and do not wish to "quote" every word,
|
||||
start fzf with `-e` or `--exact` option. Note that when `--exact` is set,
|
||||
`'`-prefix "unquotes" the term.
|
||||
|
||||
If you don't need fuzzy matching and do not wish to "quote" every word, start
|
||||
fzf with `-e` or `--extended-exact` option.
|
||||
A single bar character term acts as an OR operator. For example, the following
|
||||
query matches entries that start with `core` and end with either `go`, `rb`,
|
||||
or `py`.
|
||||
|
||||
```
|
||||
^core go$ | rb$ | py$
|
||||
```
|
||||
|
||||
#### Environment variables
|
||||
|
||||
- `FZF_DEFAULT_COMMAND`
|
||||
- Default command to use when input is tty
|
||||
- e.g. `export FZF_DEFAULT_COMMAND='ag -g ""'`
|
||||
- `FZF_DEFAULT_OPTS`
|
||||
- Default options
|
||||
- e.g. `export FZF_DEFAULT_OPTS="--reverse --inline-info"`
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -140,8 +157,9 @@ 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
|
||||
- `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
|
||||
@@ -173,8 +191,8 @@ cat /usr/share/dict/words | fzf-tmux -l 20% --multi --reverse
|
||||
It will still work even when you're not on tmux, silently ignoring `-[udlr]`
|
||||
options, so you can invariably use `fzf-tmux` in your scripts.
|
||||
|
||||
Fuzzy completion for bash
|
||||
-------------------------
|
||||
Fuzzy completion for bash and zsh
|
||||
---------------------------------
|
||||
|
||||
#### Files and directories
|
||||
|
||||
@@ -246,6 +264,9 @@ export FZF_COMPLETION_OPTS='+c -x'
|
||||
Usage as Vim plugin
|
||||
-------------------
|
||||
|
||||
This repository only enables basic integration with Vim. If you're looking for
|
||||
more, check out [fzf.vim](https://github.com/junegunn/fzf.vim) project.
|
||||
|
||||
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
||||
|
||||
#### `:FZF[!]`
|
||||
@@ -278,10 +299,8 @@ customization.
|
||||
|
||||
#### `fzf#run([options])`
|
||||
|
||||
For more advanced uses, you can call `fzf#run()` function which returns the list
|
||||
of the selected items.
|
||||
|
||||
`fzf#run()` may take an options-dictionary:
|
||||
For more advanced uses, you can use `fzf#run()` function with the following
|
||||
options.
|
||||
|
||||
| Option name | Type | Description |
|
||||
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
||||
@@ -294,67 +313,10 @@ of the selected items.
|
||||
| `dir` | string | Working directory |
|
||||
| `up`/`down`/`left`/`right` | number/string | Use tmux pane with the given size (e.g. `20`, `50%`) |
|
||||
| `window` (*Neovim only*) | string | Command to open fzf window (e.g. `vertical aboveleft 30new`) |
|
||||
| `launcher` | string | External terminal emulator to start fzf with (Only used in GVim) |
|
||||
| `launcher` | string | External terminal emulator to start fzf with (GVim only) |
|
||||
| `launcher` | funcref | Function for generating `launcher` string (GVim only) |
|
||||
|
||||
_However on Neovim `fzf#run` is asynchronous and does not return values so you
|
||||
should use `sink` or `sink*` to process the output from fzf._
|
||||
|
||||
##### Examples
|
||||
|
||||
If `sink` option is not given, `fzf#run` will simply return the list.
|
||||
|
||||
```vim
|
||||
let items = fzf#run({ 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
||||
```
|
||||
|
||||
But if `sink` is given as a string, the command will be executed for each
|
||||
selected item.
|
||||
|
||||
```vim
|
||||
" Each selected item will be opened in a new tab
|
||||
let items = fzf#run({ 'sink': 'tabe', 'options': '-m +c', 'dir': '~', 'source': 'ls' })
|
||||
```
|
||||
|
||||
We can also use a Vim list as the source as follows:
|
||||
|
||||
```vim
|
||||
" Choose a color scheme with fzf
|
||||
nnoremap <silent> <Leader>C :call fzf#run({
|
||||
\ 'source':
|
||||
\ map(split(globpath(&rtp, "colors/*.vim"), "\n"),
|
||||
\ "substitute(fnamemodify(v:val, ':t'), '\\..\\{-}$', '', '')"),
|
||||
\ 'sink': 'colo',
|
||||
\ 'options': '+m',
|
||||
\ 'left': 20,
|
||||
\ 'launcher': 'xterm -geometry 20x30 -e bash -ic %s'
|
||||
\ })<CR>
|
||||
```
|
||||
|
||||
`sink` option can be a function reference. The following example creates a
|
||||
handy mapping that selects an open buffer.
|
||||
|
||||
```vim
|
||||
" List of buffers
|
||||
function! s:buflist()
|
||||
redir => ls
|
||||
silent ls
|
||||
redir END
|
||||
return split(ls, '\n')
|
||||
endfunction
|
||||
|
||||
function! s:bufopen(e)
|
||||
execute 'buffer' matchstr(a:e, '^[ 0-9]*')
|
||||
endfunction
|
||||
|
||||
nnoremap <silent> <Leader><Enter> :call fzf#run({
|
||||
\ 'source': reverse(<sid>buflist()),
|
||||
\ 'sink': function('<sid>bufopen'),
|
||||
\ 'options': '+m',
|
||||
\ 'down': len(<sid>buflist()) + 2
|
||||
\ })<CR>
|
||||
```
|
||||
|
||||
More examples can be found on [the wiki
|
||||
Examples can be found on [the wiki
|
||||
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
||||
|
||||
Tips
|
||||
@@ -382,13 +344,16 @@ filtering:
|
||||
|
||||
```sh
|
||||
# Feed the output of ag into fzf
|
||||
ag -l -g "" | fzf
|
||||
ag -g "" | fzf
|
||||
|
||||
# Setting ag as the default source for fzf
|
||||
export FZF_DEFAULT_COMMAND='ag -l -g ""'
|
||||
export FZF_DEFAULT_COMMAND='ag -g ""'
|
||||
|
||||
# Now fzf (w/o pipe) will use ag instead of find
|
||||
fzf
|
||||
|
||||
# To apply the command to CTRL-T as well
|
||||
export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
|
||||
```
|
||||
|
||||
#### `git ls-tree` for fast traversal
|
||||
@@ -399,7 +364,8 @@ speed of the traversal.
|
||||
```sh
|
||||
export FZF_DEFAULT_COMMAND='
|
||||
(git ls-tree -r --name-only HEAD ||
|
||||
find * -name ".*" -prune -o -type f -print -o -type l -print) 2> /dev/null'
|
||||
find . -path "*/\.*" -prune -o -type f -print -o -type l -print |
|
||||
sed s/^..//) 2> /dev/null'
|
||||
```
|
||||
|
||||
#### Fish shell
|
||||
@@ -413,14 +379,6 @@ of fzf to a temporary file.
|
||||
fzf > $TMPDIR/fzf.result; and vim (cat $TMPDIR/fzf.result)
|
||||
```
|
||||
|
||||
#### Handling UTF-8 NFD paths on OSX
|
||||
|
||||
Use iconv to convert NFD paths to NFC:
|
||||
|
||||
```sh
|
||||
find . | iconv -f utf-8-mac -t utf8//ignore | fzf
|
||||
```
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
|
20
bin/fzf-tmux
20
bin/fzf-tmux
@@ -82,7 +82,7 @@ while [ $# -gt 0 ]; do
|
||||
shift
|
||||
done
|
||||
|
||||
if [ -z "$TMUX_PANE" ]; then
|
||||
if [ -z "$TMUX_PANE" ] || tmux list-panes -F '#F' | grep -q Z; then
|
||||
fzf "${args[@]}"
|
||||
exit $?
|
||||
fi
|
||||
@@ -91,10 +91,10 @@ set -e
|
||||
|
||||
# Clean up named pipes on exit
|
||||
id=$RANDOM
|
||||
argsf=/tmp/fzf-args-$id
|
||||
fifo1=/tmp/fzf-fifo1-$id
|
||||
fifo2=/tmp/fzf-fifo2-$id
|
||||
fifo3=/tmp/fzf-fifo3-$id
|
||||
argsf="${TMPDIR:-/tmp}/fzf-args-$id"
|
||||
fifo1="${TMPDIR:-/tmp}/fzf-fifo1-$id"
|
||||
fifo2="${TMPDIR:-/tmp}/fzf-fifo2-$id"
|
||||
fifo3="${TMPDIR:-/tmp}/fzf-fifo3-$id"
|
||||
cleanup() {
|
||||
rm -f $argsf $fifo1 $fifo2 $fifo3
|
||||
}
|
||||
@@ -102,12 +102,12 @@ trap cleanup EXIT SIGINT SIGTERM
|
||||
|
||||
fail() {
|
||||
>&2 echo "$1"
|
||||
exit 1
|
||||
exit 2
|
||||
}
|
||||
fzf="$(which fzf 2> /dev/null)" || fzf="$(dirname "$0")/fzf"
|
||||
[ -x "$fzf" ] || fail "fzf executable not found"
|
||||
|
||||
envs=""
|
||||
envs="env TERM=$TERM "
|
||||
[ -n "$FZF_DEFAULT_OPTS" ] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
||||
[ -n "$FZF_DEFAULT_COMMAND" ] && envs="$envs FZF_DEFAULT_COMMAND=$(printf %q "$FZF_DEFAULT_COMMAND")"
|
||||
|
||||
@@ -117,7 +117,9 @@ mkfifo $fifo3
|
||||
# Build arguments to fzf
|
||||
opts=""
|
||||
for arg in "${args[@]}"; do
|
||||
opts="$opts \"${arg//\"/\\\"}\""
|
||||
arg="${arg//\"/\\\"}"
|
||||
arg="${arg//\`/\\\`}"
|
||||
opts="$opts \"$arg\""
|
||||
done
|
||||
|
||||
if [ -n "$term" -o -t 0 ]; then
|
||||
@@ -132,5 +134,5 @@ else
|
||||
cat <&0 > $fifo1 &
|
||||
fi
|
||||
cat $fifo2
|
||||
[ "$(cat $fifo3)" = '0' ]
|
||||
exit "$(cat $fifo3)"
|
||||
|
||||
|
6
fzf
6
fzf
@@ -206,11 +206,11 @@ class FZF
|
||||
@expect = true
|
||||
when /^--expect=(.*)$/
|
||||
@expect = true
|
||||
when '--toggle-sort', '--tiebreak', '--color'
|
||||
when '--toggle-sort', '--tiebreak', '--color', '--bind', '--history', '--history-size'
|
||||
argv.shift
|
||||
when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',
|
||||
'--inline-info', '--no-inline-info',
|
||||
/^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/
|
||||
'--inline-info', '--no-inline-info', '--read0', '--cycle', /^--bind=(.*)$/,
|
||||
/^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/, /^--history(-max)?=(.*)$/
|
||||
# XXX
|
||||
else
|
||||
usage 1, "illegal option: #{o}"
|
||||
|
172
install
172
install
@@ -1,11 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
version=0.9.11
|
||||
set -u
|
||||
|
||||
[[ "$@" =~ --pre ]] && version=0.11.0 pre=1 ||
|
||||
version=0.11.0 pre=0
|
||||
|
||||
auto_completion=
|
||||
key_bindings=
|
||||
update_config=1
|
||||
|
||||
help() {
|
||||
cat << EOF
|
||||
usage: $0 [OPTIONS]
|
||||
|
||||
--help Show this message
|
||||
--bin Download fzf binary only
|
||||
--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
|
||||
|
||||
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 ;;
|
||||
--bin) ;;
|
||||
*)
|
||||
echo "unknown option: $opt"
|
||||
help
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
cd $(dirname $BASH_SOURCE)
|
||||
fzf_base=$(pwd)
|
||||
fzf_base="$(pwd)"
|
||||
|
||||
# If stdin is a tty, we are "interactive".
|
||||
interactive=
|
||||
[ -t 0 ] && interactive=yes
|
||||
|
||||
ask() {
|
||||
@@ -15,21 +64,26 @@ ask() {
|
||||
|
||||
read -p "$1 ([y]/n) " $read_n -r
|
||||
echo
|
||||
[[ ! $REPLY =~ ^[Nn]$ ]]
|
||||
[[ $REPLY =~ ^[Nn]$ ]]
|
||||
}
|
||||
|
||||
check_binary() {
|
||||
echo -n " - Checking fzf executable ... "
|
||||
local output=$("$fzf_base"/bin/fzf --version 2>&1)
|
||||
if [ "$version" = "$output" ]; then
|
||||
local output
|
||||
output=$("$fzf_base"/bin/fzf --version 2>&1)
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Error: $output"
|
||||
binary_error="Invalid binary"
|
||||
elif [ "$version" != "$output" ]; then
|
||||
echo "$output != $version"
|
||||
binary_error="Invalid version"
|
||||
else
|
||||
echo "$output"
|
||||
binary_error=""
|
||||
else
|
||||
echo "$output != $version"
|
||||
rm -f "$fzf_base"/bin/fzf
|
||||
binary_error="Invalid binary"
|
||||
return 1
|
||||
return 0
|
||||
fi
|
||||
rm -f "$fzf_base"/bin/fzf
|
||||
return 1
|
||||
}
|
||||
|
||||
symlink() {
|
||||
@@ -45,11 +99,20 @@ symlink() {
|
||||
|
||||
download() {
|
||||
echo "Downloading bin/fzf ..."
|
||||
if [[ ! $1 =~ dev && -x "$fzf_base"/bin/fzf ]]; then
|
||||
echo " - Already exists"
|
||||
check_binary && return
|
||||
elif [ -x "$fzf_base"/bin/$1 ]; then
|
||||
symlink $1 && check_binary && return
|
||||
if [ $pre = 0 ]; then
|
||||
if [ -x "$fzf_base"/bin/fzf ]; then
|
||||
echo " - Already exists"
|
||||
check_binary && return
|
||||
fi
|
||||
if [ -x "$fzf_base"/bin/$1 ]; then
|
||||
symlink $1 && check_binary && return
|
||||
fi
|
||||
if which_fzf="$(which fzf 2> /dev/null)"; 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
|
||||
fi
|
||||
mkdir -p "$fzf_base"/bin && cd "$fzf_base"/bin
|
||||
if [ $? -ne 0 ]; then
|
||||
@@ -93,6 +156,7 @@ if [ -n "$binary_error" ]; then
|
||||
echo "No prebuilt binary for $archi ... "
|
||||
else
|
||||
echo " - $binary_error !!!"
|
||||
exit 1
|
||||
fi
|
||||
echo "Installing legacy Ruby version ..."
|
||||
|
||||
@@ -164,38 +228,42 @@ fi
|
||||
[[ "$*" =~ "--bin" ]] && exit 0
|
||||
|
||||
# Auto-completion
|
||||
ask "Do you want to add auto-completion support?"
|
||||
auto_completion=$?
|
||||
if [ -z "$auto_completion" ]; then
|
||||
ask "Do you want to enable fuzzy auto-completion?"
|
||||
auto_completion=$?
|
||||
fi
|
||||
|
||||
# Key-bindings
|
||||
ask "Do you want to add key bindings?"
|
||||
key_bindings=$?
|
||||
if [ -z "$key_bindings" ]; then
|
||||
ask "Do you want to enable key bindings?"
|
||||
key_bindings=$?
|
||||
fi
|
||||
|
||||
echo
|
||||
for shell in bash zsh; do
|
||||
echo -n "Generate ~/.fzf.$shell ... "
|
||||
src=~/.fzf.${shell}
|
||||
|
||||
fzf_completion="[[ \$- =~ i ]] && source \"$fzf_base/shell/completion.${shell}\""
|
||||
if [ $shell != bash -o $auto_completion -ne 0 ]; then
|
||||
fzf_completion="[[ \$- == *i* ]] && source \"$fzf_base/shell/completion.${shell}\" 2> /dev/null"
|
||||
if [ $auto_completion -eq 0 ]; then
|
||||
fzf_completion="# $fzf_completion"
|
||||
fi
|
||||
|
||||
fzf_key_bindings="source \"$fzf_base/shell/key-bindings.${shell}\""
|
||||
if [ $key_bindings -ne 0 ]; then
|
||||
if [ $key_bindings -eq 0 ]; then
|
||||
fzf_key_bindings="# $fzf_key_bindings"
|
||||
fi
|
||||
|
||||
cat > $src << EOF
|
||||
# Setup fzf
|
||||
# ---------
|
||||
if [[ ! "\$PATH" =~ "$fzf_base/bin" ]]; then
|
||||
if [[ ! "\$PATH" == *$fzf_base/bin* ]]; then
|
||||
export PATH="\$PATH:$fzf_base/bin"
|
||||
fi
|
||||
|
||||
# Man path
|
||||
# --------
|
||||
if [[ ! "\$MANPATH" =~ "$fzf_base/man" && -d "$fzf_base/man" ]]; then
|
||||
if [[ ! "\$MANPATH" == *$fzf_base/man* && -d "$fzf_base/man" ]]; then
|
||||
export MANPATH="\$MANPATH:$fzf_base/man"
|
||||
fi
|
||||
|
||||
@@ -228,45 +296,65 @@ EOF
|
||||
rm -f ~/.config/fish/functions/fzf.fish && echo "OK" || echo "Failed"
|
||||
fi
|
||||
|
||||
if [ $key_bindings -eq 0 ]; then
|
||||
echo -n "Symlink ~/.config/fish/functions/fzf_key_bindings.fish ... "
|
||||
ln -sf $fzf_base/shell/key-bindings.fish \
|
||||
~/.config/fish/functions/fzf_key_bindings.fish && echo "OK" || echo "Failed"
|
||||
fish_binding=~/.config/fish/functions/fzf_key_bindings.fish
|
||||
if [ $key_bindings -ne 0 ]; then
|
||||
echo -n "Symlink $fish_binding ... "
|
||||
ln -sf "$fzf_base/shell/key-bindings.fish" \
|
||||
"$fish_binding" && echo "OK" || echo "Failed"
|
||||
else
|
||||
echo -n "Removing $fish_binding ... "
|
||||
rm -f "$fish_binding"
|
||||
echo "OK"
|
||||
fi
|
||||
fi
|
||||
|
||||
append_line() {
|
||||
echo "Update $2:"
|
||||
echo " - $1"
|
||||
[ -f "$2" ] || touch "$2"
|
||||
if [ $# -lt 3 ]; then
|
||||
line=$(\grep -nF "$1" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
||||
set -e
|
||||
|
||||
local skip line file pat lno
|
||||
skip="$1"
|
||||
line="$2"
|
||||
file="$3"
|
||||
pat="${4:-}"
|
||||
|
||||
echo "Update $file:"
|
||||
echo " - $line"
|
||||
[ -f "$file" ] || touch "$file"
|
||||
if [ $# -lt 4 ]; then
|
||||
lno=$(\grep -nF "$line" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||
else
|
||||
line=$(\grep -nF "$3" "$2" | sed 's/:.*//' | tr '\n' ' ')
|
||||
lno=$(\grep -nF "$pat" "$file" | sed 's/:.*//' | tr '\n' ' ')
|
||||
fi
|
||||
if [ -n "$line" ]; then
|
||||
echo " - Already exists: line #$line"
|
||||
if [ -n "$lno" ]; then
|
||||
echo " - Already exists: line #$lno"
|
||||
else
|
||||
echo "$1" >> "$2"
|
||||
echo " + Added"
|
||||
if [ $skip -eq 1 ]; then
|
||||
echo >> "$file"
|
||||
echo "$line" >> "$file"
|
||||
echo " + Added"
|
||||
else
|
||||
echo " ~ Skipped"
|
||||
fi
|
||||
fi
|
||||
echo
|
||||
set +e
|
||||
}
|
||||
|
||||
echo
|
||||
for shell in bash zsh; 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
|
||||
|
||||
if [ $key_bindings -eq 0 -a $has_fish -eq 1 ]; then
|
||||
if [ $key_bindings -eq 1 -a $has_fish -eq 1 ]; then
|
||||
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
||||
append_line "fzf_key_bindings" "$bind_file"
|
||||
append_line $update_config "fzf_key_bindings" "$bind_file"
|
||||
fi
|
||||
|
||||
cat << EOF
|
||||
Finished. Restart your shell or reload config file.
|
||||
source ~/.bashrc # bash
|
||||
source ~/.zshrc # zsh
|
||||
source ${ZDOTDIR:-~}/.zshrc # zsh
|
||||
EOF
|
||||
[ $has_fish -eq 1 ] && echo " fzf_key_bindings # fish"; cat << EOF
|
||||
|
||||
|
287
man/man1/fzf.1
287
man/man1/fzf.1
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
..
|
||||
.TH fzf 1 "April 2015" "fzf 0.9.11" "fzf - a command-line fuzzy finder"
|
||||
.TH fzf 1 "Nov 2015" "fzf 0.11.0" "fzf - a command-line fuzzy finder"
|
||||
|
||||
.SH NAME
|
||||
fzf - a command-line fuzzy finder
|
||||
@@ -36,10 +36,11 @@ fzf is a general-purpose command-line fuzzy finder.
|
||||
.SS Search mode
|
||||
.TP
|
||||
.B "-x, --extended"
|
||||
Extended-search mode
|
||||
Extended-search mode. Since 0.10.9, this is enabled by default. You can disable
|
||||
it with \fB+x\fR or \fB--no-extended\fR.
|
||||
.TP
|
||||
.B "-e, --extended-exact"
|
||||
Extended-search mode (exact match)
|
||||
.B "-e, --exact"
|
||||
Enable exact-match
|
||||
.TP
|
||||
.B "-i"
|
||||
Case-insensitive match (default: smart-case match)
|
||||
@@ -52,10 +53,10 @@ Comma-separated list of field index expressions for limiting search scope.
|
||||
See \fBFIELD INDEX EXPRESSION\fR for details.
|
||||
.TP
|
||||
.BI "--with-nth=" "N[,..]"
|
||||
Transform the item using the list of index expressions for search
|
||||
Transform each item using index expressions within finder
|
||||
.TP
|
||||
.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
|
||||
.TP
|
||||
.B "+s, --no-sort"
|
||||
@@ -91,21 +92,39 @@ Enable processing of ANSI color codes
|
||||
.B "--no-mouse"
|
||||
Disable mouse
|
||||
.TP
|
||||
.B "--color=COL"
|
||||
Color scheme: [dark|light|16|bw]
|
||||
.br
|
||||
(default: dark on 256-color terminal, otherwise 16)
|
||||
.br
|
||||
.R ""
|
||||
.br
|
||||
.BR dark " Color scheme for dark 256-color terminal"
|
||||
.br
|
||||
.BR light " Color scheme for light 256-color terminal"
|
||||
.br
|
||||
.BR 16 " Color scheme for 16-color terminal"
|
||||
.br
|
||||
.BR bw " No colors"
|
||||
.br
|
||||
.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
|
||||
@@ -113,6 +132,34 @@ Use black background
|
||||
.B "--reverse"
|
||||
Reverse orientation
|
||||
.TP
|
||||
.BI "--margin=" MARGIN
|
||||
Comma-separated expression for margins around the finder.
|
||||
.br
|
||||
.R ""
|
||||
.br
|
||||
.RS
|
||||
.BR TRBL " Same margin for top, right, bottom, and left"
|
||||
.br
|
||||
.BR TB,RL " Vertical, horizontal margin"
|
||||
.br
|
||||
.BR T,RL,B " Top, horizontal, bottom margin"
|
||||
.br
|
||||
.BR T,R,B,L " Top, right, bottom, left margin"
|
||||
.br
|
||||
.R ""
|
||||
.br
|
||||
Each part can be given in absolute number or in percentage relative to the
|
||||
terminal size with \fB%\fR suffix.
|
||||
.br
|
||||
.R ""
|
||||
.br
|
||||
e.g. \fBfzf --margin 10%\fR
|
||||
\fBfzf --margin 1,5%\fR
|
||||
.RE
|
||||
.TP
|
||||
.B "--cycle"
|
||||
Enable cyclic scroll
|
||||
.TP
|
||||
.B "--no-hscroll"
|
||||
Disable horizontal scroll
|
||||
.TP
|
||||
@@ -121,6 +168,142 @@ Display finder info inline with the query
|
||||
.TP
|
||||
.BI "--prompt=" "STR"
|
||||
Input prompt (default: '> ')
|
||||
.TP
|
||||
.BI "--toggle-sort=" "KEY"
|
||||
Key to toggle sort. For the list of the allowed key names, see \fB--bind\fR.
|
||||
.TP
|
||||
.BI "--bind=" "KEYBINDS"
|
||||
Comma-separated list of custom key bindings. Each key binding expression
|
||||
follows the following format: \fBKEY:ACTION\fR
|
||||
.RS
|
||||
e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
||||
.RE
|
||||
|
||||
.RS
|
||||
.B AVAILABLE KEYS: (SYNONYMS)
|
||||
\fIctrl-[a-z]\fR
|
||||
\fIalt-[a-z]\fR
|
||||
\fIf[1-4]\fR
|
||||
\fIenter\fR (\fIreturn\fR \fIctrl-m\fR)
|
||||
\fIspace\fR
|
||||
\fIbspace\fR (\fIbs\fR)
|
||||
\fIalt-bspace\fR (\fIalt-bs\fR)
|
||||
\fItab\fR
|
||||
\fIbtab\fR (\fIshift-tab\fR)
|
||||
\fIesc\fR
|
||||
\fIdel\fR
|
||||
\fIup\fR
|
||||
\fIdown\fR
|
||||
\fIleft\fR
|
||||
\fIright\fR
|
||||
\fIhome\fR
|
||||
\fIend\fR
|
||||
\fIpgup\fR (\fIpage-up\fR)
|
||||
\fIpgdn\fR (\fIpage-down\fR)
|
||||
\fIshift-left\fR
|
||||
\fIshift-right\fR
|
||||
\fIdouble-click\fR
|
||||
or any single character
|
||||
.RE
|
||||
|
||||
.RS
|
||||
\fBACTION: DEFAULT BINDINGS:
|
||||
\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
|
||||
\fBkill-line\fR
|
||||
\fBkill-word\fR \fIalt-d\fR
|
||||
\fBnext-history\fR (\fIctrl-n\fR on \fB--history\fR)
|
||||
\fBpage-down\fR \fIpgdn\fR
|
||||
\fBpage-up\fR \fIpgup\fR
|
||||
\fBprevious-history\fR (\fIctrl-p\fR on \fB--history\fR)
|
||||
\fBselect-all\fR
|
||||
\fBtoggle\fR
|
||||
\fBtoggle-all\fR
|
||||
\fBtoggle-down\fR \fIctrl-i (tab)\fR
|
||||
\fBtoggle-sort\fR (equivalent to \fB--toggle-sort\fR)
|
||||
\fBtoggle-up\fR \fIbtab (shift-tab)\fR
|
||||
\fBunix-line-discard\fR \fIctrl-u\fR
|
||||
\fBunix-word-rubout\fR \fIctrl-w\fR
|
||||
\fBup\fR \fIctrl-k ctrl-p up\fR
|
||||
\fByank\fR \fIctrl-y\fR
|
||||
.RE
|
||||
|
||||
.RS
|
||||
With \fBexecute(...)\fR action, you can execute arbitrary commands without
|
||||
leaving fzf. For example, you can turn fzf into a simple file browser by
|
||||
binding \fBenter\fR key to \fBless\fR command like follows.
|
||||
|
||||
.RS
|
||||
\fBfzf --bind "enter:execute(less {})"\fR
|
||||
.RE
|
||||
|
||||
\fB{}\fR is the placeholder for the double-quoted string of the current line.
|
||||
If the command contains parentheses, you can use any of the following
|
||||
alternative notations to avoid parse errors.
|
||||
|
||||
\fBexecute[...]\fR
|
||||
\fBexecute~...~\fR
|
||||
\fBexecute!...!\fR
|
||||
\fBexecute@...@\fR
|
||||
\fBexecute#...#\fR
|
||||
\fBexecute$...$\fR
|
||||
\fBexecute%...%\fR
|
||||
\fBexecute^...^\fR
|
||||
\fBexecute&...&\fR
|
||||
\fBexecute*...*\fR
|
||||
\fBexecute;...;\fR
|
||||
\fBexecute/.../\fR
|
||||
\fBexecute|...|\fR
|
||||
\fBexecute:...\fR
|
||||
.RS
|
||||
This is the special form that frees you from parse errors as it does not expect
|
||||
the closing character. The catch is that it should be the last one in the
|
||||
comma-separated list.
|
||||
.RE
|
||||
|
||||
\fBexecute-multi(...)\fR is an alternative action that executes the command
|
||||
with the selected entries when multi-select is enabled (\fB--multi\fR). With
|
||||
this action, \fB{}\fR is replaced with the double-quoted strings of the
|
||||
selected entries separated by spaces.
|
||||
|
||||
.RE
|
||||
.TP
|
||||
.BI "--history=" "HISTORY_FILE"
|
||||
Load search history from the specified file and update the file on completion.
|
||||
When enabled, \fBCTRL-N\fR and \fBCTRL-P\fR are automatically remapped to
|
||||
\fBnext-history\fR and \fBprevious-history\fR.
|
||||
.TP
|
||||
.BI "--history-size=" "N"
|
||||
Maximum number of entries in the history file (default: 1000). The file is
|
||||
automatically truncated when the number of the lines exceeds the value.
|
||||
.TP
|
||||
.BI "--header=" "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 Scripting
|
||||
.TP
|
||||
.BI "-q, --query=" "STR"
|
||||
@@ -140,20 +323,15 @@ fzf becomes a fuzzy-version of grep.
|
||||
Print query as the first line
|
||||
.TP
|
||||
.BI "--expect=" "KEY[,..]"
|
||||
Comma-separated list of keys (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
||||
or any single character) that can be used to complete fzf in addition to the
|
||||
default enter key. When this option is set, fzf will print the name of the key
|
||||
pressed as the first line of its output (or as the second line if
|
||||
Comma-separated list of keys that can be used to complete fzf in addition to
|
||||
the default enter key. When this option is set, fzf will print the name of the
|
||||
key pressed as the first line of its output (or as the second line if
|
||||
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
||||
with the default enter key.
|
||||
.RS
|
||||
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR
|
||||
.RE
|
||||
.TP
|
||||
.BI "--toggle-sort=" "KEY"
|
||||
Key to toggle sort (\fIctrl-[a-z]\fR, \fIalt-[a-z]\fR, \fIf[1-4]\fR,
|
||||
or any single character)
|
||||
.TP
|
||||
.B "--sync"
|
||||
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
||||
ncurses finder only after the input stream is complete.
|
||||
@@ -167,7 +345,7 @@ e.g. \fBfzf --multi | fzf --sync\fR
|
||||
Default command to use when input is tty
|
||||
.TP
|
||||
.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
|
||||
.BR 0 " Normal exit"
|
||||
@@ -177,7 +355,7 @@ Default options. e.g. \fB--extended --ansi\fR
|
||||
.SH FIELD INDEX EXPRESSION
|
||||
|
||||
A field index expression can be a non-zero integer or a range expression
|
||||
([BEGIN]..[END]). \fI--nth\fR and \fI--with-nth\fR take a comma-separated list
|
||||
([BEGIN]..[END]). \fB--nth\fR and \fB--with-nth\fR take a comma-separated list
|
||||
of field index expressions.
|
||||
|
||||
.SS Examples
|
||||
@@ -200,34 +378,51 @@ of field index expressions.
|
||||
|
||||
.SH EXTENDED SEARCH MODE
|
||||
|
||||
With \fI-x\fR or \fI--extended\fR option, fzf will start in "extended-search
|
||||
mode". In this mode, you can specify multiple patterns delimited by spaces,
|
||||
such as: \fB'wild ^music .mp3$ sbtrkt !rmx\fR
|
||||
Unless specified otherwise, fzf will start in "extended-search mode". In this
|
||||
mode, you can specify multiple patterns delimited by spaces, such as: \fB'wild
|
||||
^music .mp3$ sbtrkt !rmx\fR
|
||||
|
||||
.SS Exact-match (quoted)
|
||||
A term that is prefixed by a single-quote character (') is interpreted as an
|
||||
"exact-match" (or "non-fuzzy") term. fzf will search for the exact occurrences
|
||||
of the string.
|
||||
A term that is prefixed by a single-quote character (\fB'\fR) is interpreted as
|
||||
an "exact-match" (or "non-fuzzy") term. fzf will search for the exact
|
||||
occurrences of the string.
|
||||
|
||||
.SS Anchored-match
|
||||
A term can be prefixed by ^, or suffixed by $ to become an anchored-match term.
|
||||
Then fzf will search for the items that start with or end with the given
|
||||
string. An anchored-match term is also an exact-match term.
|
||||
A term can be prefixed by \fB^\fR, or suffixed by \fB$\fR to become an
|
||||
anchored-match term. Then fzf will search for the items that start with or end
|
||||
with the given string. An anchored-match term is also an exact-match term.
|
||||
|
||||
.SS Negation
|
||||
If a term is prefixed by !, fzf will exclude the items that satisfy the term
|
||||
from the result.
|
||||
If a term is prefixed by \fB!\fR, fzf will exclude the items that satisfy the
|
||||
term from the result.
|
||||
|
||||
.SS Extended-exact mode
|
||||
If you don't need fuzzy matching at all and do not wish to "quote" (prefixing
|
||||
with ') every word, start fzf with \fI-e\fR or \fI--extended-exact\fR option
|
||||
(instead of \fI-x\fR or \fI--extended\fR).
|
||||
.SS Exact-match by default
|
||||
If you don't prefer fuzzy matching and do not wish to "quote" (prefixing with
|
||||
\fB'\fR) every word, start fzf with \fB-e\fR or \fB--exact\fR option. Note that
|
||||
when \fB--exact\fR is set, \fB'\fR-prefix "unquotes" the term.
|
||||
|
||||
.SS OR operator
|
||||
A single bar character term acts as an OR operator. For example, the following
|
||||
query matches entries that start with \fBcore\fR and end with either \fBgo\fR,
|
||||
\fBrb\fR, or \fBpy\fR.
|
||||
|
||||
e.g. \fB^core go$ | rb$ | py$\fR
|
||||
|
||||
.SH AUTHOR
|
||||
Junegunn Choi (\fIjunegunn.c@gmail.com\fR)
|
||||
|
||||
.SH SEE ALSO
|
||||
.B Project homepage:
|
||||
.RS
|
||||
.I https://github.com/junegunn/fzf
|
||||
.RE
|
||||
.br
|
||||
.R ""
|
||||
.br
|
||||
.B Extra Vim plugin:
|
||||
.RS
|
||||
.I https://github.com/junegunn/fzf.vim
|
||||
.RE
|
||||
|
||||
.SH LICENSE
|
||||
MIT
|
||||
|
215
plugin/fzf.vim
215
plugin/fzf.vim
@@ -22,11 +22,9 @@
|
||||
" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
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:install = expand('<sfile>:h:h').'/install'
|
||||
let s:installed = 0
|
||||
let s:fzf_rb = expand('<sfile>:h:h').'/fzf'
|
||||
let s:fzf_tmux = expand('<sfile>:h:h').'/bin/fzf-tmux'
|
||||
|
||||
let s:cpo_save = &cpo
|
||||
@@ -36,32 +34,26 @@ function! s:fzf_exec()
|
||||
if !exists('s:exec')
|
||||
if executable(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
|
||||
let path = split(system('which fzf 2> /dev/null'), '\n')
|
||||
if !v:shell_error && !empty(path)
|
||||
let s:exec = path[0]
|
||||
elseif !s:installed && executable(s:install)
|
||||
echohl WarningMsg
|
||||
echo 'Downloading fzf binary. Please wait ...'
|
||||
echohl None
|
||||
let s:installed = 1
|
||||
call system(s:install.' --bin')
|
||||
return s:fzf_exec()
|
||||
elseif executable(s:fzf_rb)
|
||||
let s:exec = s:fzf_rb
|
||||
else
|
||||
call system('type fzf')
|
||||
if v:shell_error
|
||||
throw 'fzf executable not found'
|
||||
else
|
||||
let s:exec = 'fzf'
|
||||
endif
|
||||
endif
|
||||
redraw
|
||||
throw 'fzf executable not found'
|
||||
endif
|
||||
return s:exec
|
||||
else
|
||||
return s:exec
|
||||
endif
|
||||
return s:exec
|
||||
endfunction
|
||||
|
||||
function! s:tmux_not_zoomed()
|
||||
return system('tmux list-panes -F "#F"') !~# 'Z'
|
||||
endfunction
|
||||
|
||||
function! s:tmux_enabled()
|
||||
@@ -70,7 +62,7 @@ function! s:tmux_enabled()
|
||||
endif
|
||||
|
||||
if exists('s:tmux')
|
||||
return s:tmux
|
||||
return s:tmux && s:tmux_not_zoomed()
|
||||
endif
|
||||
|
||||
let s:tmux = 0
|
||||
@@ -78,7 +70,7 @@ function! s:tmux_enabled()
|
||||
let output = system('tmux -V')
|
||||
let s:tmux = !v:shell_error && output >= 'tmux 1.7'
|
||||
endif
|
||||
return s:tmux
|
||||
return s:tmux && s:tmux_not_zoomed()
|
||||
endfunction
|
||||
|
||||
function! s:shellesc(arg)
|
||||
@@ -86,7 +78,7 @@ function! s:shellesc(arg)
|
||||
endfunction
|
||||
|
||||
function! s:escape(path)
|
||||
return substitute(a:path, ' ', '\\ ', 'g')
|
||||
return escape(a:path, ' %#''"\')
|
||||
endfunction
|
||||
|
||||
" Upgrade legacy options
|
||||
@@ -104,14 +96,24 @@ function! s:upgrade(dict)
|
||||
return copy
|
||||
endfunction
|
||||
|
||||
function! s:error(msg)
|
||||
echohl ErrorMsg
|
||||
echom a:msg
|
||||
echohl None
|
||||
endfunction
|
||||
|
||||
function! s:warn(msg)
|
||||
echohl WarningMsg
|
||||
echom a:msg
|
||||
echohl None
|
||||
endfunction
|
||||
|
||||
function! fzf#run(...) abort
|
||||
try
|
||||
let oshell = &shell
|
||||
set shell=sh
|
||||
if has('nvim') && bufexists('[FZF]')
|
||||
echohl WarningMsg
|
||||
echomsg 'FZF is already running!'
|
||||
echohl None
|
||||
if has('nvim') && bufexists('term://*:FZF')
|
||||
call s:warn('FZF is already running!')
|
||||
return []
|
||||
endif
|
||||
let dict = exists('a:1') ? s:upgrade(a:1) : {}
|
||||
@@ -170,7 +172,13 @@ function! s:fzf_tmux(dict)
|
||||
let size = ''
|
||||
for o in ['up', 'down', 'left', 'right']
|
||||
if s:present(a:dict, o)
|
||||
let size = '-'.o[0].(a:dict[o] == 1 ? '' : a:dict[o])
|
||||
let spec = a:dict[o]
|
||||
if (o == 'up' || o == 'down') && spec[0] == '~'
|
||||
let size = '-'.o[0].s:calc_size(&lines, spec[1:], a:dict)
|
||||
else
|
||||
" Legacy boolean option
|
||||
let size = '-'.o[0].(spec == 1 ? '' : spec)
|
||||
endif
|
||||
break
|
||||
endif
|
||||
endfor
|
||||
@@ -202,27 +210,45 @@ function! s:popd(dict)
|
||||
endif
|
||||
endfunction
|
||||
|
||||
function! s:xterm_launcher()
|
||||
let fmt = 'xterm -T "[fzf]" -bg "\%s" -fg "\%s" -geometry %dx%d+%d+%d -e bash -ic %%s'
|
||||
if has('gui_macvim')
|
||||
let fmt .= '&& osascript -e "tell application \"MacVim\" to activate"'
|
||||
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)
|
||||
call s:pushd(a:dict)
|
||||
silent! !clear 2> /dev/null
|
||||
let escaped = escape(substitute(a:command, '\n', '\\n', 'g'), '%#')
|
||||
if has('gui_running')
|
||||
let launcher = get(a:dict, 'launcher', get(g:, 'fzf_launcher', s:launcher))
|
||||
let command = printf(launcher, "'".substitute(a:command, "'", "'\"'\"'", 'g')."'")
|
||||
let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))
|
||||
let fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher
|
||||
let command = printf(fmt, "'".substitute(escaped, "'", "'\"'\"'", 'g')."'")
|
||||
else
|
||||
let command = a:command
|
||||
let command = escaped
|
||||
endif
|
||||
execute 'silent !'.command
|
||||
redraw!
|
||||
if v:shell_error
|
||||
" Do not print error message on exit status 1
|
||||
if v:shell_error > 1
|
||||
echohl ErrorMsg
|
||||
echo 'Error running ' . command
|
||||
endif
|
||||
return []
|
||||
else
|
||||
return s:callback(a:dict, a:temps)
|
||||
endif
|
||||
return s:exit_handler(v:shell_error, command) ? s:callback(a:dict, a:temps) : []
|
||||
endfunction
|
||||
|
||||
function! s:execute_tmux(dict, command, temps)
|
||||
@@ -233,15 +259,29 @@ function! s:execute_tmux(dict, command, temps)
|
||||
endif
|
||||
|
||||
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
|
||||
|
||||
function! s:calc_size(max, val)
|
||||
function! s:calc_size(max, val, dict)
|
||||
if a:val =~ '%$'
|
||||
return a:max * str2nr(a:val[:-2]) / 100
|
||||
let size = a:max * str2nr(a:val[:-2]) / 100
|
||||
else
|
||||
return min([a:max, a:val])
|
||||
let size = min([a:max, str2nr(a:val)])
|
||||
endif
|
||||
|
||||
let srcsz = -1
|
||||
if type(get(a:dict, 'source', 0)) == type([])
|
||||
let srcsz = len(a:dict.source)
|
||||
endif
|
||||
|
||||
let opts = get(a:dict, 'options', '').$FZF_DEFAULT_OPTS
|
||||
let margin = stridx(opts, '--inline-info') > stridx(opts, '--no-inline-info') ? 1 : 2
|
||||
return srcsz >= 0 ? min([srcsz + margin, size]) : size
|
||||
endfunction
|
||||
|
||||
function! s:getpos()
|
||||
return {'tab': tabpagenr(), 'win': winnr(), 'cnt': winnr('$')}
|
||||
endfunction
|
||||
|
||||
function! s:split(dict)
|
||||
@@ -250,13 +290,17 @@ function! s:split(dict)
|
||||
\ 'down': ['botright', 'resize', &lines],
|
||||
\ 'left': ['vertical topleft', 'vertical resize', &columns],
|
||||
\ 'right': ['vertical botright', 'vertical resize', &columns] }
|
||||
let s:ptab = tabpagenr()
|
||||
let s:ppos = s:getpos()
|
||||
try
|
||||
for [dir, triple] in items(directions)
|
||||
let val = get(a:dict, dir, '')
|
||||
if !empty(val)
|
||||
let [cmd, resz, max] = triple
|
||||
let sz = s:calc_size(max, val)
|
||||
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
|
||||
@@ -268,7 +312,7 @@ function! s:split(dict)
|
||||
tabnew
|
||||
endif
|
||||
finally
|
||||
setlocal winfixwidth winfixheight
|
||||
setlocal winfixwidth winfixheight buftype=nofile bufhidden=wipe nobuflisted
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
@@ -276,28 +320,50 @@ function! s:execute_term(dict, command, temps)
|
||||
call s:split(a:dict)
|
||||
call s:pushd(a:dict)
|
||||
|
||||
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps }
|
||||
let fzf = { 'buf': bufnr('%'), 'dict': a:dict, 'temps': a:temps, 'name': 'FZF' }
|
||||
let s:command = a:command
|
||||
function! fzf.on_exit(id, code)
|
||||
let tab = tabpagenr()
|
||||
execute 'bd!' self.buf
|
||||
if s:ptab == tab
|
||||
wincmd p
|
||||
let pos = s:getpos()
|
||||
let inplace = pos == s:ppos " {'window': 'enew'}
|
||||
if !inplace
|
||||
if bufnr('') == self.buf
|
||||
" We use close instead of bd! since Vim does not close the split when
|
||||
" there's no other listed buffer (nvim +'set nobuflisted')
|
||||
close
|
||||
endif
|
||||
if pos.tab == s:ppos.tab
|
||||
wincmd p
|
||||
endif
|
||||
endif
|
||||
|
||||
if !s:exit_handler(a:code, s:command, 1)
|
||||
return
|
||||
endif
|
||||
|
||||
call s:pushd(self.dict)
|
||||
try
|
||||
call s:callback(self.dict, self.temps)
|
||||
|
||||
if inplace && bufnr('') == self.buf
|
||||
execute "normal! \<c-^>"
|
||||
" No other listed buffer
|
||||
if bufnr('') == self.buf
|
||||
bd!
|
||||
endif
|
||||
endif
|
||||
finally
|
||||
call s:popd(self.dict)
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
call termopen(a:command, fzf)
|
||||
silent file [FZF]
|
||||
setf fzf
|
||||
startinsert
|
||||
return []
|
||||
endfunction
|
||||
|
||||
function! s:callback(dict, temps)
|
||||
try
|
||||
if !filereadable(a:temps.result)
|
||||
let lines = []
|
||||
else
|
||||
@@ -321,11 +387,16 @@ function! s:callback(dict, temps)
|
||||
endfor
|
||||
|
||||
return lines
|
||||
catch
|
||||
if stridx(v:exception, ':E325:') < 0
|
||||
echoerr v:exception
|
||||
endif
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
let s:default_action = {
|
||||
\ 'ctrl-m': 'e',
|
||||
\ 'ctrl-t': 'tabedit',
|
||||
\ 'ctrl-t': 'tab split',
|
||||
\ 'ctrl-x': 'split',
|
||||
\ 'ctrl-v': 'vsplit' }
|
||||
|
||||
@@ -335,9 +406,25 @@ function! s:cmd_callback(lines) abort
|
||||
endif
|
||||
let key = remove(a:lines, 0)
|
||||
let cmd = get(s:action, key, 'e')
|
||||
for item in a:lines
|
||||
execute cmd s:escape(item)
|
||||
endfor
|
||||
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 autochdir = &autochdir
|
||||
set noautochdir
|
||||
for item in a:lines
|
||||
execute cmd s:escape(item)
|
||||
if exists('#BufEnter') && isdirectory(item)
|
||||
doautocmd BufEnter
|
||||
endif
|
||||
endfor
|
||||
finally
|
||||
let &autochdir = autochdir
|
||||
silent! autocmd! fzf_swap
|
||||
endtry
|
||||
endfunction
|
||||
|
||||
function! s:cmd(bang, ...) abort
|
||||
@@ -345,7 +432,7 @@ function! s:cmd(bang, ...) abort
|
||||
let args = extend(['--expect='.join(keys(s:action), ',')], a:000)
|
||||
let opts = {}
|
||||
if len(args) > 0 && isdirectory(expand(args[-1]))
|
||||
let opts.dir = remove(args, -1)
|
||||
let opts.dir = substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g')
|
||||
endif
|
||||
if !a:bang
|
||||
let opts.down = get(g:, 'fzf_height', get(g:, 'fzf_tmux_height', s:default_height))
|
||||
|
@@ -11,8 +11,8 @@
|
||||
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||
|
||||
_fzf_orig_completion_filter() {
|
||||
sed 's/.*-F *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\2=\1;/' |
|
||||
sed 's/[^a-z0-9_= ;]/_/g'
|
||||
sed 's/^\(.*-F\) *\([^ ]*\).* \([^ ]*\)$/export _fzf_orig_completion_\3="\1 %s \3 #\2";/' |
|
||||
awk -F= '{gsub(/[^a-z0-9_= ;]/, "_", $1); print $1"="$2}'
|
||||
}
|
||||
|
||||
_fzf_opts_completion() {
|
||||
@@ -22,20 +22,21 @@ _fzf_opts_completion() {
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
opts="
|
||||
-x --extended
|
||||
-e --extended-exact
|
||||
-e --exact
|
||||
-i +i
|
||||
-n --nth
|
||||
-d --delimiter
|
||||
+s --no-sort
|
||||
--tac
|
||||
--tiebreak
|
||||
--bind
|
||||
-m --multi
|
||||
--no-mouse
|
||||
+c --no-color
|
||||
+2 --no-256
|
||||
--color
|
||||
--black
|
||||
--reverse
|
||||
--no-hscroll
|
||||
--inline-info
|
||||
--prompt
|
||||
-q --query
|
||||
-1 --select-1
|
||||
@@ -44,13 +45,27 @@ _fzf_opts_completion() {
|
||||
--print-query
|
||||
--expect
|
||||
--toggle-sort
|
||||
--sync"
|
||||
--sync
|
||||
--cycle
|
||||
--history
|
||||
--history-size
|
||||
--header
|
||||
--header-lines
|
||||
--margin"
|
||||
|
||||
case "${prev}" in
|
||||
--tiebreak)
|
||||
COMPREPLY=( $(compgen -W "length begin end index" -- ${cur}) )
|
||||
return 0
|
||||
;;
|
||||
--color)
|
||||
COMPREPLY=( $(compgen -W "dark light 16 bw" -- ${cur}) )
|
||||
return 0
|
||||
;;
|
||||
--history)
|
||||
COMPREPLY=()
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ ${cur} =~ ^-|\+ ]]; then
|
||||
@@ -62,28 +77,29 @@ _fzf_opts_completion() {
|
||||
}
|
||||
|
||||
_fzf_handle_dynamic_completion() {
|
||||
local cmd orig ret
|
||||
local cmd orig_var orig ret orig_cmd
|
||||
cmd="$1"
|
||||
shift
|
||||
|
||||
orig=$(eval "echo \$_fzf_orig_completion_$cmd")
|
||||
orig_cmd="$1"
|
||||
orig_var="_fzf_orig_completion_$cmd"
|
||||
orig="${!orig_var##*#}"
|
||||
if [ -n "$orig" ] && type "$orig" > /dev/null 2>&1; then
|
||||
$orig "$@"
|
||||
elif [ -n "$_fzf_completion_loader" ]; then
|
||||
_completion_loader "$@"
|
||||
ret=$?
|
||||
eval $(complete | \grep "\-F.* $cmd$" | _fzf_orig_completion_filter)
|
||||
eval $(complete | \grep "\-F.* $orig_cmd$" | _fzf_orig_completion_filter)
|
||||
source $BASH_SOURCE
|
||||
return $ret
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion() {
|
||||
local cur base dir leftover matches trigger cmd fzf
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||
COMPREPLY=()
|
||||
trigger=${FZF_COMPLETION_TRIGGER:-**}
|
||||
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
if [[ ${cur} == *"$trigger" ]]; then
|
||||
base=${cur:0:${#cur}-${#trigger}}
|
||||
@@ -119,20 +135,29 @@ _fzf_path_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_list_completion() {
|
||||
local cur selected trigger cmd src fzf
|
||||
_fzf_feed_fifo() (
|
||||
rm -f "$fifo"
|
||||
mkfifo "$fifo"
|
||||
cat <&0 > "$fifo" &
|
||||
)
|
||||
|
||||
_fzf_complete() {
|
||||
local fifo cur selected trigger cmd fzf
|
||||
fifo="${TMPDIR:-/tmp}/fzf-complete-fifo-$$"
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
read -r src
|
||||
|
||||
cmd=$(echo ${COMP_WORDS[0]} | sed 's/[^a-z0-9_=]/_/g')
|
||||
trigger=${FZF_COMPLETION_TRIGGER:-**}
|
||||
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
if [[ ${cur} == *"$trigger" ]]; then
|
||||
cur=${cur:0:${#cur}-${#trigger}}
|
||||
|
||||
_fzf_feed_fifo "$fifo"
|
||||
tput sc
|
||||
selected=$(eval "$src | $fzf $FZF_COMPLETION_OPTS $1 -q '$cur'" | tr '\n' ' ')
|
||||
selected=${selected% }
|
||||
selected=$(eval "cat '$fifo' | $fzf $FZF_COMPLETION_OPTS $1 -q '$cur'" | tr '\n' ' ')
|
||||
selected=${selected% } # Strip trailing space not to repeat "-o nospace"
|
||||
tput rc
|
||||
rm -f "$fifo"
|
||||
|
||||
if [ -n "$selected" ]; then
|
||||
COMPREPLY=("$selected")
|
||||
@@ -144,25 +169,25 @@ _fzf_list_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_all_completion() {
|
||||
_fzf_path_completion \
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||
"-m" "" "$@"
|
||||
}
|
||||
|
||||
_fzf_file_completion() {
|
||||
_fzf_path_completion \
|
||||
__fzf_generic_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type f -print -o -type l -print" \
|
||||
"-m" "" "$@"
|
||||
}
|
||||
|
||||
_fzf_dir_completion() {
|
||||
_fzf_path_completion \
|
||||
__fzf_generic_path_completion \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||
"" "/" "$@"
|
||||
}
|
||||
|
||||
_fzf_kill_completion() {
|
||||
_fzf_complete_kill() {
|
||||
[ -n "${COMP_WORDS[COMP_CWORD]}" ] && return 1
|
||||
|
||||
local selected fzf
|
||||
@@ -177,38 +202,47 @@ _fzf_kill_completion() {
|
||||
fi
|
||||
}
|
||||
|
||||
_fzf_telnet_completion() {
|
||||
_fzf_list_completion '+m' "$@" << "EOF"
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_telnet() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0' |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_ssh_completion() {
|
||||
_fzf_list_completion '+m' "$@" << "EOF"
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i ^host | \grep -v '*') <(\grep -v '^\s*\(#\|$\)' /etc/hosts) | awk '{print $2}' | sort -u
|
||||
EOF
|
||||
_fzf_complete_ssh() {
|
||||
_fzf_complete '+m' "$@" < <(
|
||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | \grep -i '^host' | \grep -v '*') \
|
||||
<(\grep -v '^\s*\(#\|$\)' /etc/hosts | \grep -Fv '0.0.0.0') |
|
||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_env_var_completion() {
|
||||
_fzf_list_completion '-m' "$@" << "EOF"
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
EOF
|
||||
_fzf_complete_unset() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_alias_completion() {
|
||||
_fzf_list_completion '-m' "$@" << "EOF"
|
||||
alias | sed 's/=.*//' | sed 's/.* //'
|
||||
EOF
|
||||
_fzf_complete_export() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
declare -xp | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
_fzf_complete_unalias() {
|
||||
_fzf_complete '-m' "$@" < <(
|
||||
alias | sed 's/=.*//' | sed 's/.* //'
|
||||
)
|
||||
}
|
||||
|
||||
# fzf options
|
||||
complete -F _fzf_opts_completion fzf
|
||||
complete -o default -F _fzf_opts_completion fzf
|
||||
|
||||
d_cmds="cd pushd rmdir"
|
||||
f_cmds="
|
||||
awk cat diff diff3
|
||||
emacs ex file ftp g++ gcc gvim head hg java
|
||||
javac ld less more mvim patch perl python ruby
|
||||
javac ld less more mvim nvim patch perl python ruby
|
||||
sed sftp sort source tail tee uniq vi view vim wc"
|
||||
a_cmds="
|
||||
basename bunzip2 bzip2 chmod chown curl cp dirname du
|
||||
@@ -218,42 +252,58 @@ a_cmds="
|
||||
x_cmds="kill ssh telnet unset unalias export"
|
||||
|
||||
# Preserve existing completion
|
||||
if [ "$_fzf_completion_loaded" != '0.8.6-1' ]; then
|
||||
if [ "$_fzf_completion_loaded" != '0.10.8' ]; then
|
||||
# Really wish I could use associative array but OSX comes with bash 3.2 :(
|
||||
eval $(complete | \grep '\-F' | \grep -v _fzf_ |
|
||||
\grep -E " ($(echo $d_cmds $f_cmds $a_cmds $x_cmds | sed 's/ /|/g' | sed 's/+/\\+/g'))$" | _fzf_orig_completion_filter)
|
||||
export _fzf_completion_loaded=0.8.6-1
|
||||
export _fzf_completion_loaded=0.10.8
|
||||
fi
|
||||
|
||||
if type _completion_loader > /dev/null 2>&1; then
|
||||
_fzf_completion_loader=1
|
||||
fi
|
||||
|
||||
_fzf_defc() {
|
||||
local cmd func opts orig_var orig
|
||||
cmd="$1"
|
||||
func="$2"
|
||||
opts="$3"
|
||||
orig_var="_fzf_orig_completion_$cmd"
|
||||
orig="${!orig_var}"
|
||||
if [ -n "$orig" ]; then
|
||||
eval "$(printf "$orig" "$func")"
|
||||
else
|
||||
complete -F "$func" $opts "$cmd"
|
||||
fi
|
||||
}
|
||||
|
||||
# Directory
|
||||
for cmd in $d_cmds; do
|
||||
complete -F _fzf_dir_completion -o nospace -o plusdirs $cmd
|
||||
_fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o plusdirs"
|
||||
done
|
||||
|
||||
# File
|
||||
for cmd in $f_cmds; do
|
||||
complete -F _fzf_file_completion -o default -o bashdefault $cmd
|
||||
_fzf_defc "$cmd" _fzf_file_completion "-o default -o bashdefault"
|
||||
done
|
||||
|
||||
# Anything
|
||||
for cmd in $a_cmds; do
|
||||
complete -F _fzf_all_completion -o default -o bashdefault $cmd
|
||||
_fzf_defc "$cmd" _fzf_path_completion "-o default -o bashdefault"
|
||||
done
|
||||
|
||||
unset _fzf_defc
|
||||
|
||||
# Kill completion
|
||||
complete -F _fzf_kill_completion -o nospace -o default -o bashdefault kill
|
||||
complete -F _fzf_complete_kill -o nospace -o default -o bashdefault kill
|
||||
|
||||
# Host completion
|
||||
complete -F _fzf_ssh_completion -o default -o bashdefault ssh
|
||||
complete -F _fzf_telnet_completion -o default -o bashdefault telnet
|
||||
complete -F _fzf_complete_ssh -o default -o bashdefault ssh
|
||||
complete -F _fzf_complete_telnet -o default -o bashdefault telnet
|
||||
|
||||
# Environment variables / Aliases
|
||||
complete -F _fzf_env_var_completion -o default -o bashdefault unset
|
||||
complete -F _fzf_env_var_completion -o default -o bashdefault export
|
||||
complete -F _fzf_alias_completion -o default -o bashdefault unalias
|
||||
complete -F _fzf_complete_unset -o default -o bashdefault unset
|
||||
complete -F _fzf_complete_export -o default -o bashdefault export
|
||||
complete -F _fzf_complete_unalias -o default -o bashdefault unalias
|
||||
|
||||
unset cmd d_cmds f_cmds a_cmds x_cmds
|
||||
|
174
shell/completion.zsh
Normal file
174
shell/completion.zsh
Normal file
@@ -0,0 +1,174 @@
|
||||
#!/bin/zsh
|
||||
# ____ ____
|
||||
# / __/___ / __/
|
||||
# / /_/_ / / /_
|
||||
# / __/ / /_/ __/
|
||||
# /_/ /___/_/-completion.zsh
|
||||
#
|
||||
# - $FZF_TMUX (default: 1)
|
||||
# - $FZF_TMUX_HEIGHT (default: '40%')
|
||||
# - $FZF_COMPLETION_TRIGGER (default: '**')
|
||||
# - $FZF_COMPLETION_OPTS (default: empty)
|
||||
|
||||
__fzf_generic_path_completion() {
|
||||
local base lbuf find_opts fzf_opts suffix tail fzf dir leftover matches nnm
|
||||
# (Q) flag removes a quoting level: "foo\ bar" => "foo bar"
|
||||
base=${(Q)1}
|
||||
lbuf=$2
|
||||
find_opts=$3
|
||||
fzf_opts=$4
|
||||
suffix=$5
|
||||
tail=$6
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
|
||||
if ! setopt | grep nonomatch > /dev/null; then
|
||||
nnm=1
|
||||
setopt nonomatch
|
||||
fi
|
||||
dir="$base"
|
||||
while [ 1 ]; do
|
||||
if [ -z "$dir" -o -d ${~dir} ]; then
|
||||
leftover=${base/#"$dir"}
|
||||
leftover=${leftover/#\/}
|
||||
[ "$dir" = './' ] && dir=''
|
||||
dir=${~dir}
|
||||
matches=$(\find -L $dir* ${=find_opts} 2> /dev/null | ${=fzf} ${=FZF_COMPLETION_OPTS} ${=fzf_opts} -q "$leftover" | while read item; do
|
||||
printf "%q$suffix " "$item"
|
||||
done)
|
||||
matches=${matches% }
|
||||
if [ -n "$matches" ]; then
|
||||
LBUFFER="$lbuf$matches$tail"
|
||||
fi
|
||||
zle redisplay
|
||||
break
|
||||
fi
|
||||
dir=$(dirname "$dir")
|
||||
dir=${dir%/}/
|
||||
done
|
||||
[ -n "$nnm" ] && unsetopt nonomatch
|
||||
}
|
||||
|
||||
_fzf_path_completion() {
|
||||
__fzf_generic_path_completion "$1" "$2" \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print -o -type f -print -o -type l -print" \
|
||||
"-m" "" " "
|
||||
}
|
||||
|
||||
_fzf_dir_completion() {
|
||||
__fzf_generic_path_completion "$1" "$2" \
|
||||
"-name .git -prune -o -name .svn -prune -o -type d -print" \
|
||||
"" "/" ""
|
||||
}
|
||||
|
||||
_fzf_feed_fifo() (
|
||||
rm -f "$fifo"
|
||||
mkfifo "$fifo"
|
||||
cat <&0 > "$fifo" &
|
||||
)
|
||||
|
||||
_fzf_complete() {
|
||||
local fifo fzf_opts lbuf fzf matches
|
||||
fifo="${TMPDIR:-/tmp}/fzf-complete-fifo-$$"
|
||||
fzf_opts=$1
|
||||
lbuf=$2
|
||||
[ ${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}" | 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 -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 sws
|
||||
if setopt | grep shwordsplit > /dev/null; then
|
||||
sws=1
|
||||
unsetopt shwordsplit
|
||||
fi
|
||||
|
||||
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
||||
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
||||
tokens=(${(z)LBUFFER})
|
||||
if [ ${#tokens} -lt 1 ]; then
|
||||
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||
return
|
||||
fi
|
||||
|
||||
cmd=${tokens[1]}
|
||||
|
||||
# Explicitly allow for empty trigger.
|
||||
trigger=${FZF_COMPLETION_TRIGGER-'**'}
|
||||
[ -z "$trigger" -a ${LBUFFER[-1]} = ' ' ] && tokens+=("")
|
||||
|
||||
tail=${LBUFFER:$(( ${#LBUFFER} - ${#trigger} ))}
|
||||
# Kill completion (do not require trigger sequence)
|
||||
if [ $cmd = kill -a ${LBUFFER[-1]} = ' ' ]; then
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && fzf="fzf-tmux -d ${FZF_TMUX_HEIGHT:-40%}" || fzf="fzf"
|
||||
matches=$(ps -ef | sed 1d | ${=fzf} ${=FZF_COMPLETION_OPTS} -m | awk '{print $2}' | tr '\n' ' ')
|
||||
if [ -n "$matches" ]; then
|
||||
LBUFFER="$LBUFFER$matches"
|
||||
fi
|
||||
zle redisplay
|
||||
# Trigger sequence given
|
||||
elif [ ${#tokens} -gt 1 -a "$tail" = "$trigger" ]; then
|
||||
d_cmds=(cd pushd rmdir)
|
||||
|
||||
[ -z "$trigger" ] && prefix=${tokens[-1]} || prefix=${tokens[-1]:0:-${#trigger}}
|
||||
[ -z "${tokens[-1]}" ] && lbuf=$LBUFFER || lbuf=${LBUFFER:0:-${#tokens[-1]}}
|
||||
|
||||
if 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
|
||||
eval "zle ${fzf_default_completion:-expand-or-complete}"
|
||||
fi
|
||||
[ -n "$sws" ] && setopt shwordsplit
|
||||
}
|
||||
|
||||
[ -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
|
||||
# ------------
|
||||
__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 d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | fzf -m | while read item; do
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
eval "$cmd" | fzf -m | while read item; do
|
||||
printf '%q ' "$item"
|
||||
done
|
||||
echo
|
||||
@@ -24,18 +25,29 @@ __fzf_select_tmux__() {
|
||||
else
|
||||
height="-l $height"
|
||||
fi
|
||||
tmux split-window $height "cd $(printf %q "$PWD");bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||
tmux split-window $height "cd $(printf %q "$PWD"); FZF_CTRL_T_COMMAND=$(printf %q "$FZF_CTRL_T_COMMAND") bash -c 'source ~/.fzf.bash; tmux send-keys -t $TMUX_PANE \"\$(__fzf_select__)\"'"
|
||||
}
|
||||
|
||||
__fzf_cd__() {
|
||||
local dir
|
||||
dir=$(command find -L ${1:-.} \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||
local cmd dir
|
||||
cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
dir=$(eval "$cmd" | $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||
}
|
||||
|
||||
__fzf_history__() {
|
||||
HISTTIMEFORMAT= history | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r | sed "s/ *[0-9]* *//"
|
||||
}
|
||||
__fzf_history__() (
|
||||
local line
|
||||
shopt -u nocaseglob nocasematch
|
||||
line=$(
|
||||
HISTTIMEFORMAT= history |
|
||||
$(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r |
|
||||
\grep '^ *[0-9]') &&
|
||||
if [[ $- =~ H ]]; then
|
||||
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||
else
|
||||
sed 's/^ *\([0-9]*\)\** *//' <<< "$line"
|
||||
fi
|
||||
)
|
||||
|
||||
__use_tmux=0
|
||||
[ -n "$TMUX_PANE" -a ${FZF_TMUX:-1} -ne 0 -a ${LINES:-40} -gt 15 ] && __use_tmux=1
|
||||
@@ -43,6 +55,7 @@ __use_tmux=0
|
||||
if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||
# Required to refresh the prompt after fzf
|
||||
bind '"\er": redraw-current-line'
|
||||
bind '"\e^": history-expand-line'
|
||||
|
||||
# CTRL-T - Paste the selected file path into the command line
|
||||
if [ $__use_tmux -eq 1 ]; then
|
||||
@@ -52,13 +65,14 @@ if [ -z "$(set -o | \grep '^vi.*on')" ]; then
|
||||
fi
|
||||
|
||||
# CTRL-R - Paste the selected command from history into the command line
|
||||
bind '"\C-r": " \C-e\C-u$(__fzf_history__)\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
|
||||
bind '"\ec": " \C-e\C-u$(__fzf_cd__)\e\C-e\er\C-m"'
|
||||
else
|
||||
bind '"\C-x\C-e": shell-expand-line'
|
||||
bind '"\C-x\C-r": redraw-current-line'
|
||||
bind '"\C-x^": history-expand-line'
|
||||
|
||||
# CTRL-T - Paste the selected file path into the command line
|
||||
# - FIXME: Selected items are attached to the end regardless of cursor position
|
||||
@@ -70,7 +84,7 @@ else
|
||||
bind -m vi-command '"\C-t": "i\C-t"'
|
||||
|
||||
# CTRL-R - Paste the selected command from history into the command line
|
||||
bind '"\C-r": "\eddi$(__fzf_history__)\C-x\C-e\e$a\C-x\C-r"'
|
||||
bind '"\C-r": "\eddi$(__fzf_history__)\C-x\C-e\C-x^\e$a\C-x\C-r"'
|
||||
bind -m vi-command '"\C-r": "i\C-r"'
|
||||
|
||||
# ALT-C - cd into the selected directory
|
||||
|
@@ -14,10 +14,12 @@ function fzf_key_bindings
|
||||
end
|
||||
|
||||
function __fzf_ctrl_t
|
||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||
set -q FZF_CTRL_T_COMMAND; or set -l FZF_CTRL_T_COMMAND "
|
||||
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type f -print \
|
||||
-o -type d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) -m > $TMPDIR/fzf.result
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"
|
||||
eval "$FZF_CTRL_T_COMMAND | "(__fzfcmd)" -m > $TMPDIR/fzf.result"
|
||||
and commandline -i (cat $TMPDIR/fzf.result | __fzf_escape)
|
||||
commandline -f repaint
|
||||
rm -f $TMPDIR/fzf.result
|
||||
@@ -31,9 +33,11 @@ function fzf_key_bindings
|
||||
end
|
||||
|
||||
function __fzf_alt_c
|
||||
set -q FZF_ALT_C_COMMAND; or set -l FZF_ALT_C_COMMAND "
|
||||
command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"
|
||||
# Fish hangs if the command before pipe redirects (2> /dev/null)
|
||||
command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) \
|
||||
-prune -o -type d -print 2> /dev/null | sed 1d | cut -b3- | eval (__fzfcmd) +m > $TMPDIR/fzf.result
|
||||
eval "$FZF_ALT_C_COMMAND | "(__fzfcmd)" +m > $TMPDIR/fzf.result"
|
||||
[ (cat $TMPDIR/fzf.result | wc -l) -gt 0 ]
|
||||
and cd (cat $TMPDIR/fzf.result)
|
||||
commandline -f repaint
|
||||
@@ -57,5 +61,11 @@ function fzf_key_bindings
|
||||
bind \ct '__fzf_ctrl_t'
|
||||
bind \cr '__fzf_ctrl_r'
|
||||
bind \ec '__fzf_alt_c'
|
||||
|
||||
if bind -M insert > /dev/null 2>&1
|
||||
bind -M insert \ct '__fzf_ctrl_t'
|
||||
bind -M insert \cr '__fzf_ctrl_r'
|
||||
bind -M insert \ec '__fzf_alt_c'
|
||||
end
|
||||
end
|
||||
|
||||
|
@@ -1,11 +1,14 @@
|
||||
# Key bindings
|
||||
# ------------
|
||||
if [[ $- == *i* ]]; then
|
||||
|
||||
# CTRL-T - Paste the selected file path(s) into the command line
|
||||
__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 d -print \
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) -m | while read item; do
|
||||
-o -type l -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
eval "$cmd" | $(__fzfcmd) -m | while read item; do
|
||||
printf '%q ' "$item"
|
||||
done
|
||||
echo
|
||||
@@ -15,8 +18,6 @@ __fzfcmd() {
|
||||
[ ${FZF_TMUX:-1} -eq 1 ] && echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-40%}" || echo "fzf"
|
||||
}
|
||||
|
||||
if [[ $- =~ i ]]; then
|
||||
|
||||
fzf-file-widget() {
|
||||
LBUFFER="${LBUFFER}$(__fsel)"
|
||||
zle redisplay
|
||||
@@ -26,8 +27,9 @@ bindkey '^T' fzf-file-widget
|
||||
|
||||
# ALT-C - cd into the selected directory
|
||||
fzf-cd-widget() {
|
||||
cd "${$(command find -L . \( -path '*/\.*' -o -fstype 'dev' -o -fstype 'proc' \) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3- | $(__fzfcmd) +m):-.}"
|
||||
local cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \
|
||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
||||
cd "${$(eval "$cmd" | $(__fzfcmd) +m):-.}"
|
||||
zle reset-prompt
|
||||
}
|
||||
zle -N fzf-cd-widget
|
||||
@@ -35,11 +37,13 @@ bindkey '\ec' fzf-cd-widget
|
||||
|
||||
# CTRL-R - Paste the selected command from history into the command line
|
||||
fzf-history-widget() {
|
||||
local selected
|
||||
if selected=$(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r -q "$LBUFFER"); then
|
||||
num=$(echo "$selected" | head -1 | awk '{print $1}' | sed 's/[^0-9]//g')
|
||||
LBUFFER=!$num
|
||||
zle expand-history
|
||||
local selected num
|
||||
selected=( $(fc -l 1 | $(__fzfcmd) +s --tac +m -n2..,.. --tiebreak=index --toggle-sort=ctrl-r -q "${LBUFFER//$/\\$}") )
|
||||
if [ -n "$selected" ]; then
|
||||
num=$selected[1]
|
||||
if [ -n "$num" ]; then
|
||||
zle vi-fetch-history -n $num
|
||||
fi
|
||||
fi
|
||||
zle redisplay
|
||||
}
|
||||
|
@@ -2,6 +2,7 @@ FROM base/archlinux:2014.07.03
|
||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# apt-get
|
||||
RUN pacman-key --populate archlinux && pacman-key --refresh-keys
|
||||
RUN pacman-db-upgrade && pacman -Syu --noconfirm base-devel git
|
||||
|
||||
# Install Go 1.4
|
||||
|
@@ -1,8 +1,10 @@
|
||||
FROM centos:centos7
|
||||
FROM centos:centos6
|
||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# yum
|
||||
RUN yum install -y git gcc make tar ncurses-devel
|
||||
RUN yum install -y git gcc make tar glibc-devel glibc-devel.i686 \
|
||||
ncurses-devel ncurses-static ncurses-devel.i686 \
|
||||
gpm-devel gpm-static libgcc.i686
|
||||
|
||||
# Install Go 1.4
|
||||
RUN cd / && curl \
|
||||
@@ -13,6 +15,9 @@ ENV GOPATH /go
|
||||
ENV GOROOT /go1.4
|
||||
ENV PATH /go1.4/bin:$PATH
|
||||
|
||||
# For i386 build
|
||||
RUN cd $GOROOT/src && GOARCH=386 ./make.bash
|
||||
|
||||
# Volume
|
||||
VOLUME /go
|
||||
|
||||
|
@@ -3,7 +3,7 @@ MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
||||
|
||||
# apt-get
|
||||
RUN apt-get update && apt-get -y upgrade && \
|
||||
apt-get install -y --force-yes git curl build-essential libncurses-dev
|
||||
apt-get install -y --force-yes git curl build-essential libncurses-dev libgpm-dev
|
||||
|
||||
# Install Go 1.4
|
||||
RUN cd / && curl \
|
||||
|
45
src/Makefile
45
src/Makefile
@@ -25,10 +25,9 @@ RELEASE64 = fzf-$(VERSION)-$(GOOS)_amd64
|
||||
all: release
|
||||
|
||||
release: build
|
||||
cd fzf && \
|
||||
cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32) && \
|
||||
cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
||||
rm $(RELEASE32) $(RELEASE64)
|
||||
-cd fzf && cp $(BINARY32) $(RELEASE32) && tar -czf $(RELEASE32).tgz $(RELEASE32)
|
||||
cd fzf && cp $(BINARY64) $(RELEASE64) && tar -czf $(RELEASE64).tgz $(RELEASE64) && \
|
||||
rm -f $(RELEASE32) $(RELEASE64)
|
||||
|
||||
build: test fzf/$(BINARY32) fzf/$(BINARY64)
|
||||
|
||||
@@ -42,13 +41,13 @@ uninstall:
|
||||
rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY64)
|
||||
|
||||
clean:
|
||||
cd fzf && rm -f $(BINARY32) $(BINARY64) $(RELEASE32).tgz $(RELEASE64).tgz
|
||||
cd fzf && rm -f fzf-*
|
||||
|
||||
fzf/$(BINARY32): $(SOURCES)
|
||||
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -o $(BINARY32)
|
||||
cd fzf && GOARCH=386 CGO_ENABLED=1 go build -a -o $(BINARY32)
|
||||
|
||||
fzf/$(BINARY64): $(SOURCES)
|
||||
cd fzf && go build -o $(BINARY64)
|
||||
cd fzf && go build -a -tags "$(TAGS)" -o $(BINARY64)
|
||||
|
||||
$(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)
|
||||
cp -f fzf/$(BINARY64) $(BINDIR)
|
||||
@@ -57,18 +56,30 @@ $(BINDIR)/fzf: fzf/$(BINARY64) | $(BINDIR)
|
||||
$(BINDIR):
|
||||
mkdir -p $@
|
||||
|
||||
# Linux distribution to build fzf on
|
||||
DISTRO := arch
|
||||
docker-arch:
|
||||
docker build -t junegunn/arch-sandbox - < Dockerfile.arch
|
||||
|
||||
docker:
|
||||
docker build -t junegunn/$(DISTRO)-sandbox - < Dockerfile.$(DISTRO)
|
||||
docker-ubuntu:
|
||||
docker build -t junegunn/ubuntu-sandbox - < Dockerfile.ubuntu
|
||||
|
||||
linux: docker
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
||||
/bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make'
|
||||
docker-centos:
|
||||
docker build -t junegunn/centos-sandbox - < Dockerfile.centos
|
||||
|
||||
$(DISTRO): docker
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$(DISTRO)-sandbox \
|
||||
arch: docker-arch
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$@-sandbox \
|
||||
sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'
|
||||
|
||||
.PHONY: all build release test install uninstall clean docker linux $(DISTRO)
|
||||
ubuntu: docker-ubuntu
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$@-sandbox \
|
||||
sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'
|
||||
|
||||
centos: docker-centos
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/$@-sandbox \
|
||||
sh -c 'cd /go/src/github.com/junegunn/fzf/src; /bin/bash'
|
||||
|
||||
linux: docker-centos
|
||||
docker run -i -t -v $(GOPATH):/go junegunn/centos-sandbox \
|
||||
/bin/bash -ci 'cd /go/src/github.com/junegunn/fzf/src; make TAGS=static'
|
||||
|
||||
.PHONY: all build release test install uninstall clean docker \
|
||||
linux arch ubuntu centos docker-arch docker-ubuntu docker-centos
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package algo
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/junegunn/fzf/src/util"
|
||||
@@ -14,8 +15,15 @@ import (
|
||||
* In short: They try to do as little work as possible.
|
||||
*/
|
||||
|
||||
func runeAt(runes []rune, index int, max int, forward bool) rune {
|
||||
if forward {
|
||||
return runes[index]
|
||||
}
|
||||
return runes[max-index-1]
|
||||
}
|
||||
|
||||
// FuzzyMatch performs fuzzy-match
|
||||
func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
func FuzzyMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) (int, int) {
|
||||
if len(pattern) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
@@ -33,7 +41,11 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
sidx := -1
|
||||
eidx := -1
|
||||
|
||||
for index, char := range *runes {
|
||||
lenRunes := len(runes)
|
||||
lenPattern := len(pattern)
|
||||
|
||||
for index := range runes {
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
// This is considerably faster than blindly applying strings.ToLower to the
|
||||
// whole string
|
||||
if !caseSensitive {
|
||||
@@ -46,11 +58,12 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if char == pattern[pidx] {
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if char == pchar {
|
||||
if sidx < 0 {
|
||||
sidx = index
|
||||
}
|
||||
if pidx++; pidx == len(pattern) {
|
||||
if pidx++; pidx == lenPattern {
|
||||
eidx = index + 1
|
||||
break
|
||||
}
|
||||
@@ -60,7 +73,7 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
if sidx >= 0 && eidx >= 0 {
|
||||
pidx--
|
||||
for index := eidx - 1; index >= sidx; index-- {
|
||||
char := (*runes)[index]
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
if !caseSensitive {
|
||||
if char >= 'A' && char <= 'Z' {
|
||||
char += 32
|
||||
@@ -68,14 +81,19 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if char == pattern[pidx] {
|
||||
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if char == pchar {
|
||||
if pidx--; pidx < 0 {
|
||||
sidx = index
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return sidx, eidx
|
||||
if forward {
|
||||
return sidx, eidx
|
||||
}
|
||||
return lenRunes - eidx, lenRunes - sidx
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
@@ -87,20 +105,21 @@ func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
//
|
||||
// We might try to implement better algorithms in the future:
|
||||
// http://en.wikipedia.org/wiki/String_searching_algorithm
|
||||
func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
func ExactMatchNaive(caseSensitive bool, forward bool, runes []rune, pattern []rune) (int, int) {
|
||||
if len(pattern) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
numRunes := len(*runes)
|
||||
plen := len(pattern)
|
||||
if numRunes < plen {
|
||||
lenRunes := len(runes)
|
||||
lenPattern := len(pattern)
|
||||
|
||||
if lenRunes < lenPattern {
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
pidx := 0
|
||||
for index := 0; index < numRunes; index++ {
|
||||
char := (*runes)[index]
|
||||
for index := 0; index < lenRunes; index++ {
|
||||
char := runeAt(runes, index, lenRunes, forward)
|
||||
if !caseSensitive {
|
||||
if char >= 'A' && char <= 'Z' {
|
||||
char += 32
|
||||
@@ -108,10 +127,14 @@ func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, in
|
||||
char = unicode.To(unicode.LowerCase, char)
|
||||
}
|
||||
}
|
||||
if pattern[pidx] == char {
|
||||
pchar := runeAt(pattern, pidx, lenPattern, forward)
|
||||
if pchar == char {
|
||||
pidx++
|
||||
if pidx == plen {
|
||||
return index - plen + 1, index + 1
|
||||
if pidx == lenPattern {
|
||||
if forward {
|
||||
return index - lenPattern + 1, index + 1
|
||||
}
|
||||
return lenRunes - (index + 1), lenRunes - (index - lenPattern + 1)
|
||||
}
|
||||
} else {
|
||||
index -= pidx
|
||||
@@ -122,13 +145,13 @@ func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, in
|
||||
}
|
||||
|
||||
// PrefixMatch performs prefix-match
|
||||
func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
if len(*runes) < len(pattern) {
|
||||
func PrefixMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) (int, int) {
|
||||
if len(runes) < len(pattern) {
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
for index, r := range pattern {
|
||||
char := (*runes)[index]
|
||||
char := runes[index]
|
||||
if !caseSensitive {
|
||||
char = unicode.ToLower(char)
|
||||
}
|
||||
@@ -140,7 +163,7 @@ func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {
|
||||
}
|
||||
|
||||
// SuffixMatch performs suffix-match
|
||||
func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {
|
||||
func SuffixMatch(caseSensitive bool, forward bool, input []rune, pattern []rune) (int, int) {
|
||||
runes := util.TrimRight(input)
|
||||
trimmedLen := len(runes)
|
||||
diff := trimmedLen - len(pattern)
|
||||
@@ -159,3 +182,18 @@ func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {
|
||||
}
|
||||
return trimmedLen - len(pattern), trimmedLen
|
||||
}
|
||||
|
||||
// EqualMatch performs equal-match
|
||||
func EqualMatch(caseSensitive bool, forward bool, runes []rune, pattern []rune) (int, int) {
|
||||
if len(runes) != len(pattern) {
|
||||
return -1, -1
|
||||
}
|
||||
runesStr := string(runes)
|
||||
if !caseSensitive {
|
||||
runesStr = strings.ToLower(runesStr)
|
||||
}
|
||||
if runesStr == string(pattern) {
|
||||
return 0, len(pattern)
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
@@ -5,12 +5,11 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {
|
||||
func assertMatch(t *testing.T, fun func(bool, bool, []rune, []rune) (int, int), caseSensitive bool, forward bool, input string, pattern string, sidx int, eidx int) {
|
||||
if !caseSensitive {
|
||||
pattern = strings.ToLower(pattern)
|
||||
}
|
||||
runes := []rune(input)
|
||||
s, e := fun(caseSensitive, &runes, []rune(pattern))
|
||||
s, e := fun(caseSensitive, forward, []rune(input), []rune(pattern))
|
||||
if s != sidx {
|
||||
t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)
|
||||
}
|
||||
@@ -20,33 +19,51 @@ func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseS
|
||||
}
|
||||
|
||||
func TestFuzzyMatch(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, false, "fooBarbaz", "oBZ", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBZ", -1, -1)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "oBz", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
assertMatch(t, FuzzyMatch, false, true, "fooBarbaz", "oBZ", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBZ", -1, -1)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "oBz", 2, 9)
|
||||
assertMatch(t, FuzzyMatch, true, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
}
|
||||
|
||||
func TestFuzzyMatchBackward(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, false, true, "foobar fb", "fb", 0, 4)
|
||||
assertMatch(t, FuzzyMatch, false, false, "foobar fb", "fb", 7, 9)
|
||||
}
|
||||
|
||||
func TestExactMatchNaive(t *testing.T) {
|
||||
assertMatch(t, ExactMatchNaive, false, "fooBarbaz", "oBA", 2, 5)
|
||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "oBA", -1, -1)
|
||||
assertMatch(t, ExactMatchNaive, true, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExactMatchNaiveBackward(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, false, true, "foobar foob", "oo", 1, 3)
|
||||
assertMatch(t, FuzzyMatch, false, false, "foobar foob", "oo", 8, 10)
|
||||
}
|
||||
|
||||
func TestPrefixMatch(t *testing.T) {
|
||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "Foo", 0, 3)
|
||||
assertMatch(t, PrefixMatch, true, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, PrefixMatch, false, "fooBarbaz", "baz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3)
|
||||
assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "baz", -1, -1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuffixMatch(t *testing.T) {
|
||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, SuffixMatch, false, "fooBarbaz", "baz", 6, 9)
|
||||
assertMatch(t, SuffixMatch, true, "fooBarbaz", "Baz", -1, -1)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1)
|
||||
assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9)
|
||||
assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyPattern(t *testing.T) {
|
||||
assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)
|
||||
assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)
|
||||
for _, dir := range []bool{true, false} {
|
||||
assertMatch(t, FuzzyMatch, true, dir, "foobar", "", 0, 0)
|
||||
assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0)
|
||||
assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0)
|
||||
assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6)
|
||||
}
|
||||
}
|
||||
|
21
src/ansi.go
21
src/ansi.go
@@ -36,21 +36,23 @@ func init() {
|
||||
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 output bytes.Buffer
|
||||
var state *ansiState
|
||||
|
||||
if state != nil {
|
||||
offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})
|
||||
}
|
||||
|
||||
idx := 0
|
||||
for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {
|
||||
output.WriteString((*str)[idx:offset[0]])
|
||||
newState := interpretCode((*str)[offset[0]:offset[1]], state)
|
||||
for _, offset := range ansiRegex.FindAllStringIndex(str, -1) {
|
||||
output.WriteString(str[idx:offset[0]])
|
||||
newState := interpretCode(str[offset[0]:offset[1]], state)
|
||||
|
||||
if !newState.equals(state) {
|
||||
if state != nil {
|
||||
// Update last offset
|
||||
(&offsets[len(offsets)-1]).offset[1] = int32(output.Len())
|
||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||
}
|
||||
|
||||
if newState.colored() {
|
||||
@@ -67,7 +69,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
||||
idx = offset[1]
|
||||
}
|
||||
|
||||
rest := (*str)[idx:]
|
||||
rest := str[idx:]
|
||||
if len(rest) > 0 {
|
||||
output.WriteString(rest)
|
||||
if state != nil {
|
||||
@@ -75,8 +77,7 @@ func extractColor(str *string) (*string, []ansiOffset) {
|
||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
||||
}
|
||||
}
|
||||
outputStr := output.String()
|
||||
return &outputStr, offsets
|
||||
return output.String(), offsets, state
|
||||
}
|
||||
|
||||
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
||||
|
@@ -14,79 +14,89 @@ func TestExtractColor(t *testing.T) {
|
||||
}
|
||||
|
||||
src := "hello world"
|
||||
var state *ansiState
|
||||
clean := "\x1b[0m"
|
||||
check := func(assertion func(ansiOffsets []ansiOffset)) {
|
||||
output, ansiOffsets := extractColor(&src)
|
||||
if *output != "hello world" {
|
||||
check := func(assertion func(ansiOffsets []ansiOffset, state *ansiState)) {
|
||||
output, ansiOffsets, newState := extractColor(src, state)
|
||||
state = newState
|
||||
if output != "hello world" {
|
||||
t.Errorf("Invalid output: {}", output)
|
||||
}
|
||||
fmt.Println(src, ansiOffsets, clean)
|
||||
assertion(ansiOffsets)
|
||||
assertion(ansiOffsets, state)
|
||||
}
|
||||
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) > 0 {
|
||||
t.Fail()
|
||||
}
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "\x1b[0mhello world"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) > 0 {
|
||||
t.Fail()
|
||||
}
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "\x1b[1mhello world"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 0, 11, -1, -1, true)
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "\x1b[1mhello \x1b[mworld"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 0, 6, -1, -1, true)
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "\x1b[1mhello \x1b[Kworld"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 0, 11, -1, -1, true)
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "hello \x1b[34;45;1mworld"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 6, 11, 4, 5, true)
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 6, 11, 4, 5, true)
|
||||
})
|
||||
|
||||
state = nil
|
||||
src = "hello \x1b[34;45;1mwor\x1b[0mld"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
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"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 3 {
|
||||
t.Fail()
|
||||
}
|
||||
@@ -96,12 +106,47 @@ func TestExtractColor(t *testing.T) {
|
||||
})
|
||||
|
||||
// {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"
|
||||
check(func(offsets []ansiOffset) {
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 2 {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 6, 9, 38, 48, true)
|
||||
assert(offsets[1], 9, 10, 48, 38, true)
|
||||
})
|
||||
|
||||
src = "hello \x1b[32;1mworld"
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 6, 11, 2, -1, true)
|
||||
})
|
||||
|
||||
src = "hello world"
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 1 {
|
||||
t.Fail()
|
||||
}
|
||||
if state.fg != 2 || state.bg != -1 || !state.bold {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 0, 11, 2, -1, true)
|
||||
})
|
||||
|
||||
src = "hello \x1b[0;38;5;200;48;5;100mworld"
|
||||
check(func(offsets []ansiOffset, state *ansiState) {
|
||||
if len(offsets) != 2 {
|
||||
t.Fail()
|
||||
}
|
||||
if state.fg != 200 || state.bg != 100 || state.bold {
|
||||
t.Fail()
|
||||
}
|
||||
assert(offsets[0], 0, 6, 2, -1, true)
|
||||
assert(offsets[1], 6, 11, 200, 100, false)
|
||||
})
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ type Chunk []*Item // >>> []Item
|
||||
|
||||
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
||||
// string and an integer
|
||||
type ItemBuilder func(*string, int) *Item
|
||||
type ItemBuilder func([]byte, int) *Item
|
||||
|
||||
// ChunkList is a list of Chunks
|
||||
type ChunkList struct {
|
||||
@@ -26,8 +26,13 @@ func NewChunkList(trans ItemBuilder) *ChunkList {
|
||||
trans: trans}
|
||||
}
|
||||
|
||||
func (c *Chunk) push(trans ItemBuilder, data *string, index int) {
|
||||
*c = append(*c, trans(data, index))
|
||||
func (c *Chunk) push(trans ItemBuilder, data []byte, index int) bool {
|
||||
item := trans(data, index)
|
||||
if item != nil {
|
||||
*c = append(*c, item)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFull returns true if the Chunk is full
|
||||
@@ -48,7 +53,7 @@ func CountItems(cs []*Chunk) int {
|
||||
}
|
||||
|
||||
// Push adds the item to the list
|
||||
func (cl *ChunkList) Push(data string) {
|
||||
func (cl *ChunkList) Push(data []byte) bool {
|
||||
cl.mutex.Lock()
|
||||
defer cl.mutex.Unlock()
|
||||
|
||||
@@ -57,8 +62,11 @@ func (cl *ChunkList) Push(data string) {
|
||||
cl.chunks = append(cl.chunks, &newChunk)
|
||||
}
|
||||
|
||||
cl.lastChunk().push(cl.trans, &data, cl.count)
|
||||
cl.count++
|
||||
if cl.lastChunk().push(cl.trans, data, cl.count) {
|
||||
cl.count++
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Snapshot returns immutable snapshot of the ChunkList
|
||||
|
@@ -6,8 +6,8 @@ import (
|
||||
)
|
||||
|
||||
func TestChunkList(t *testing.T) {
|
||||
cl := NewChunkList(func(s *string, i int) *Item {
|
||||
return &Item{text: s, rank: Rank{0, 0, uint32(i * 2)}}
|
||||
cl := NewChunkList(func(s []byte, i int) *Item {
|
||||
return &Item{text: []rune(string(s)), rank: Rank{0, 0, uint32(i * 2)}}
|
||||
})
|
||||
|
||||
// Snapshot
|
||||
@@ -17,8 +17,8 @@ func TestChunkList(t *testing.T) {
|
||||
}
|
||||
|
||||
// Add some data
|
||||
cl.Push("hello")
|
||||
cl.Push("world")
|
||||
cl.Push([]byte("hello"))
|
||||
cl.Push([]byte("world"))
|
||||
|
||||
// Previously created snapshot should remain the same
|
||||
if len(snapshot) > 0 {
|
||||
@@ -36,8 +36,8 @@ func TestChunkList(t *testing.T) {
|
||||
if len(*chunk1) != 2 {
|
||||
t.Error("Snapshot should contain only two items")
|
||||
}
|
||||
if *(*chunk1)[0].text != "hello" || (*chunk1)[0].rank.index != 0 ||
|
||||
*(*chunk1)[1].text != "world" || (*chunk1)[1].rank.index != 2 {
|
||||
if string((*chunk1)[0].text) != "hello" || (*chunk1)[0].rank.index != 0 ||
|
||||
string((*chunk1)[1].text) != "world" || (*chunk1)[1].rank.index != 2 {
|
||||
t.Error("Invalid data")
|
||||
}
|
||||
if chunk1.IsFull() {
|
||||
@@ -46,7 +46,7 @@ func TestChunkList(t *testing.T) {
|
||||
|
||||
// Add more data
|
||||
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
|
||||
@@ -64,8 +64,8 @@ func TestChunkList(t *testing.T) {
|
||||
t.Error("Unexpected number of items")
|
||||
}
|
||||
|
||||
cl.Push("hello")
|
||||
cl.Push("world")
|
||||
cl.Push([]byte("hello"))
|
||||
cl.Push([]byte("world"))
|
||||
|
||||
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
||||
if lastChunkCount != 2 {
|
||||
|
@@ -8,14 +8,14 @@ import (
|
||||
|
||||
const (
|
||||
// Current version
|
||||
Version = "0.9.11"
|
||||
version = "0.11.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`
|
||||
defaultCommand = `find . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
|
||||
|
||||
// Terminal
|
||||
initialDelay = 100 * time.Millisecond
|
||||
@@ -32,6 +32,9 @@ const (
|
||||
|
||||
// Not to cache mergers with large lists
|
||||
mergerCacheMax int = 100000
|
||||
|
||||
// History
|
||||
defaultHistoryMax int = 1000
|
||||
)
|
||||
|
||||
// fzf events
|
||||
@@ -41,5 +44,13 @@ const (
|
||||
EvtSearchNew
|
||||
EvtSearchProgress
|
||||
EvtSearchFin
|
||||
EvtHeader
|
||||
EvtClose
|
||||
)
|
||||
|
||||
const (
|
||||
exitOk = 0
|
||||
exitNoMatch = 1
|
||||
exitError = 2
|
||||
exitInterrupt = 130
|
||||
)
|
||||
|
94
src/core.go
94
src/core.go
@@ -44,67 +44,87 @@ Reader -> EvtReadNew -> Matcher (restart)
|
||||
Terminal -> EvtSearchNew:bool -> Matcher (restart)
|
||||
Matcher -> EvtSearchProgress -> Terminal (update info)
|
||||
Matcher -> EvtSearchFin -> Terminal (update list)
|
||||
Matcher -> EvtHeader -> Terminal (update header)
|
||||
*/
|
||||
|
||||
// Run starts fzf
|
||||
func Run(options *Options) {
|
||||
func Run(opts *Options) {
|
||||
initProcs()
|
||||
|
||||
opts := ParseOptions()
|
||||
sort := opts.Sort > 0
|
||||
rankTiebreak = opts.Tiebreak
|
||||
|
||||
if opts.Version {
|
||||
fmt.Println(Version)
|
||||
os.Exit(0)
|
||||
fmt.Println(version)
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
|
||||
// Event channel
|
||||
eventBox := util.NewEventBox()
|
||||
|
||||
// ANSI code processor
|
||||
ansiProcessor := func(data *string) (*string, []ansiOffset) {
|
||||
// By default, we do nothing
|
||||
ansiProcessor := func(data []byte) ([]rune, []ansiOffset) {
|
||||
return util.BytesToRunes(data), nil
|
||||
}
|
||||
ansiProcessorRunes := func(data []rune) ([]rune, []ansiOffset) {
|
||||
return data, nil
|
||||
}
|
||||
if opts.Ansi {
|
||||
if opts.Theme != nil {
|
||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
||||
return extractColor(data)
|
||||
var state *ansiState
|
||||
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||
trimmed, offsets, newState := extractColor(string(data), state)
|
||||
state = newState
|
||||
return []rune(trimmed), offsets
|
||||
}
|
||||
} else {
|
||||
// When color is disabled but ansi option is given,
|
||||
// we simply strip out ANSI codes from the input
|
||||
ansiProcessor = func(data *string) (*string, []ansiOffset) {
|
||||
trimmed, _ := extractColor(data)
|
||||
return trimmed, nil
|
||||
ansiProcessor = func(data []byte) ([]rune, []ansiOffset) {
|
||||
trimmed, _, _ := extractColor(string(data), nil)
|
||||
return []rune(trimmed), nil
|
||||
}
|
||||
}
|
||||
ansiProcessorRunes = func(data []rune) ([]rune, []ansiOffset) {
|
||||
return ansiProcessor([]byte(string(data)))
|
||||
}
|
||||
}
|
||||
|
||||
// Chunk list
|
||||
var chunkList *ChunkList
|
||||
header := make([]string, 0, opts.HeaderLines)
|
||||
if len(opts.WithNth) == 0 {
|
||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
||||
data, colors := ansiProcessor(data)
|
||||
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||
if len(header) < opts.HeaderLines {
|
||||
header = append(header, string(data))
|
||||
eventBox.Set(EvtHeader, header)
|
||||
return nil
|
||||
}
|
||||
runes, colors := ansiProcessor(data)
|
||||
return &Item{
|
||||
text: data,
|
||||
text: runes,
|
||||
index: uint32(index),
|
||||
colors: colors,
|
||||
rank: Rank{0, 0, uint32(index)}}
|
||||
})
|
||||
} else {
|
||||
chunkList = NewChunkList(func(data *string, index int) *Item {
|
||||
tokens := Tokenize(data, opts.Delimiter)
|
||||
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
||||
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{
|
||||
text: joinTokens(trans),
|
||||
origText: data,
|
||||
origText: &runes,
|
||||
index: uint32(index),
|
||||
colors: nil,
|
||||
rank: Rank{0, 0, uint32(index)}}
|
||||
|
||||
trimmed, colors := ansiProcessor(item.text)
|
||||
trimmed, colors := ansiProcessorRunes(item.text)
|
||||
item.text = trimmed
|
||||
item.colors = colors
|
||||
return &item
|
||||
@@ -114,14 +134,17 @@ func Run(options *Options) {
|
||||
// Reader
|
||||
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
||||
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()
|
||||
}
|
||||
|
||||
// Matcher
|
||||
patternBuilder := func(runes []rune) *Pattern {
|
||||
return BuildPattern(
|
||||
opts.Mode, opts.Case, opts.Nth, opts.Delimiter, runes)
|
||||
opts.Fuzzy, opts.Extended, opts.Case, opts.Tiebreak != byEnd,
|
||||
opts.Nth, opts.Delimiter, runes)
|
||||
}
|
||||
matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox)
|
||||
|
||||
@@ -133,14 +156,17 @@ func Run(options *Options) {
|
||||
|
||||
pattern := patternBuilder([]rune(*opts.Filter))
|
||||
|
||||
found := false
|
||||
if streamingFilter {
|
||||
reader := Reader{
|
||||
func(str string) {
|
||||
item := chunkList.trans(&str, 0)
|
||||
if pattern.MatchItem(item) {
|
||||
fmt.Println(*item.text)
|
||||
func(runes []byte) bool {
|
||||
item := chunkList.trans(runes, 0)
|
||||
if item != nil && pattern.MatchItem(item) {
|
||||
fmt.Println(string(item.text))
|
||||
found = true
|
||||
}
|
||||
}, eventBox}
|
||||
return false
|
||||
}, eventBox, opts.ReadZero}
|
||||
reader.ReadSource()
|
||||
} else {
|
||||
eventBox.Unwatch(EvtReadNew)
|
||||
@@ -151,10 +177,14 @@ func Run(options *Options) {
|
||||
chunks: snapshot,
|
||||
pattern: pattern})
|
||||
for i := 0; i < merger.Length(); i++ {
|
||||
fmt.Println(merger.Get(i).AsString())
|
||||
fmt.Println(merger.Get(i).AsString(opts.Ansi))
|
||||
found = true
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
if found {
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
os.Exit(exitNoMatch)
|
||||
}
|
||||
|
||||
// Synchronous search
|
||||
@@ -207,6 +237,9 @@ func Run(options *Options) {
|
||||
terminal.UpdateProgress(val)
|
||||
}
|
||||
|
||||
case EvtHeader:
|
||||
terminal.UpdateHeader(value.([]string))
|
||||
|
||||
case EvtSearchFin:
|
||||
switch val := value.(type) {
|
||||
case *Merger:
|
||||
@@ -224,9 +257,12 @@ func Run(options *Options) {
|
||||
fmt.Println()
|
||||
}
|
||||
for i := 0; i < count; i++ {
|
||||
fmt.Println(val.Get(i).AsString())
|
||||
fmt.Println(val.Get(i).AsString(opts.Ansi))
|
||||
}
|
||||
os.Exit(0)
|
||||
if count > 0 {
|
||||
os.Exit(exitOk)
|
||||
}
|
||||
os.Exit(exitNoMatch)
|
||||
}
|
||||
deferred = false
|
||||
terminal.startChan <- true
|
||||
|
@@ -3,18 +3,15 @@ package curses
|
||||
/*
|
||||
#include <ncurses.h>
|
||||
#include <locale.h>
|
||||
#cgo LDFLAGS: -lncurses
|
||||
void swapOutput() {
|
||||
FILE* temp = stdout;
|
||||
stdout = stderr;
|
||||
stderr = temp;
|
||||
}
|
||||
#cgo !static LDFLAGS: -lncurses
|
||||
#cgo static LDFLAGS: -l:libncursesw.a -l:libtinfo.a -l:libgpm.a -ldl
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -54,13 +51,25 @@ const (
|
||||
|
||||
Invalid
|
||||
Mouse
|
||||
DoubleClick
|
||||
|
||||
BTab
|
||||
BSpace
|
||||
|
||||
Del
|
||||
PgUp
|
||||
PgDn
|
||||
|
||||
Up
|
||||
Down
|
||||
Left
|
||||
Right
|
||||
Home
|
||||
End
|
||||
|
||||
SLeft
|
||||
SRight
|
||||
|
||||
F1
|
||||
F2
|
||||
F3
|
||||
@@ -88,6 +97,7 @@ const (
|
||||
ColInfo
|
||||
ColCursor
|
||||
ColSelected
|
||||
ColHeader
|
||||
ColUser
|
||||
)
|
||||
|
||||
@@ -96,15 +106,19 @@ const (
|
||||
)
|
||||
|
||||
type ColorTheme struct {
|
||||
darkBg C.short
|
||||
prompt C.short
|
||||
match C.short
|
||||
current C.short
|
||||
currentMatch C.short
|
||||
spinner C.short
|
||||
info C.short
|
||||
cursor C.short
|
||||
selected C.short
|
||||
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
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
@@ -129,10 +143,14 @@ var (
|
||||
_colorMap map[int]int
|
||||
_prevDownTime time.Time
|
||||
_clickY []int
|
||||
_screen *C.SCREEN
|
||||
Default16 *ColorTheme
|
||||
Dark256 *ColorTheme
|
||||
Light256 *ColorTheme
|
||||
DarkBG C.short
|
||||
FG int
|
||||
CurrentFG int
|
||||
BG int
|
||||
DarkBG int
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -140,35 +158,47 @@ func init() {
|
||||
_clickY = []int{}
|
||||
_colorMap = make(map[int]int)
|
||||
Default16 = &ColorTheme{
|
||||
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}
|
||||
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}
|
||||
Dark256 = &ColorTheme{
|
||||
darkBg: 236,
|
||||
prompt: 110,
|
||||
match: 108,
|
||||
current: 254,
|
||||
currentMatch: 151,
|
||||
spinner: 148,
|
||||
info: 144,
|
||||
cursor: 161,
|
||||
selected: 168}
|
||||
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}
|
||||
Light256 = &ColorTheme{
|
||||
darkBg: 251,
|
||||
prompt: 25,
|
||||
match: 66,
|
||||
current: 237,
|
||||
currentMatch: 23,
|
||||
spinner: 65,
|
||||
info: 101,
|
||||
cursor: 161,
|
||||
selected: 168}
|
||||
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}
|
||||
}
|
||||
|
||||
func attrColored(pair int, bold bool) C.int {
|
||||
@@ -229,25 +259,19 @@ func Init(theme *ColorTheme, black bool, mouse bool) {
|
||||
// syscall.Dup2(int(in.Fd()), int(os.Stdin.Fd()))
|
||||
}
|
||||
|
||||
C.swapOutput()
|
||||
|
||||
C.setlocale(C.LC_ALL, C.CString(""))
|
||||
C.initscr()
|
||||
_screen = C.newterm(nil, C.stderr, C.stdin)
|
||||
if _screen == nil {
|
||||
fmt.Println("Invalid $TERM: " + os.Getenv("TERM"))
|
||||
os.Exit(2)
|
||||
}
|
||||
C.set_term(_screen)
|
||||
if mouse {
|
||||
C.mousemask(C.ALL_MOUSE_EVENTS, nil)
|
||||
}
|
||||
C.cbreak()
|
||||
C.noecho()
|
||||
C.raw() // stty dsusp undef
|
||||
|
||||
intChan := make(chan os.Signal, 1)
|
||||
signal.Notify(intChan, os.Interrupt, os.Kill)
|
||||
go func() {
|
||||
<-intChan
|
||||
Close()
|
||||
os.Exit(1)
|
||||
}()
|
||||
|
||||
if theme != nil {
|
||||
C.start_color()
|
||||
initPairs(theme, black)
|
||||
@@ -258,28 +282,41 @@ func Init(theme *ColorTheme, black bool, mouse bool) {
|
||||
}
|
||||
|
||||
func initPairs(theme *ColorTheme, black bool) {
|
||||
var bg C.short
|
||||
fg := C.short(theme.Fg)
|
||||
bg := C.short(theme.Bg)
|
||||
if black {
|
||||
bg = C.COLOR_BLACK
|
||||
} else {
|
||||
C.use_default_colors()
|
||||
} else if theme.UseDefault {
|
||||
fg = -1
|
||||
bg = -1
|
||||
C.use_default_colors()
|
||||
}
|
||||
if theme.UseDefault {
|
||||
FG = -1
|
||||
BG = -1
|
||||
} else {
|
||||
FG = int(fg)
|
||||
BG = int(bg)
|
||||
C.assume_default_colors(C.int(theme.Fg), C.int(bg))
|
||||
}
|
||||
|
||||
DarkBG = theme.darkBg
|
||||
C.init_pair(ColPrompt, theme.prompt, bg)
|
||||
C.init_pair(ColMatch, theme.match, bg)
|
||||
C.init_pair(ColCurrent, theme.current, DarkBG)
|
||||
C.init_pair(ColCurrentMatch, theme.currentMatch, DarkBG)
|
||||
C.init_pair(ColSpinner, theme.spinner, bg)
|
||||
C.init_pair(ColInfo, theme.info, bg)
|
||||
C.init_pair(ColCursor, theme.cursor, DarkBG)
|
||||
C.init_pair(ColSelected, theme.selected, DarkBG)
|
||||
CurrentFG = int(theme.Current)
|
||||
DarkBG = int(theme.DarkBg)
|
||||
darkBG := C.short(DarkBG)
|
||||
C.init_pair(ColPrompt, C.short(theme.Prompt), bg)
|
||||
C.init_pair(ColMatch, C.short(theme.Match), bg)
|
||||
C.init_pair(ColCurrent, C.short(theme.Current), darkBG)
|
||||
C.init_pair(ColCurrentMatch, C.short(theme.CurrentMatch), darkBG)
|
||||
C.init_pair(ColSpinner, C.short(theme.Spinner), bg)
|
||||
C.init_pair(ColInfo, C.short(theme.Info), bg)
|
||||
C.init_pair(ColCursor, C.short(theme.Cursor), darkBG)
|
||||
C.init_pair(ColSelected, C.short(theme.Selected), darkBG)
|
||||
C.init_pair(ColHeader, C.short(theme.Header), bg)
|
||||
}
|
||||
|
||||
func Close() {
|
||||
C.endwin()
|
||||
C.swapOutput()
|
||||
C.delscreen(_screen)
|
||||
}
|
||||
|
||||
func GetBytes() []byte {
|
||||
@@ -356,19 +393,19 @@ func escSequence(sz *int) Event {
|
||||
*sz = 3
|
||||
switch _buf[2] {
|
||||
case 68:
|
||||
return Event{CtrlB, 0, nil}
|
||||
return Event{Left, 0, nil}
|
||||
case 67:
|
||||
return Event{CtrlF, 0, nil}
|
||||
return Event{Right, 0, nil}
|
||||
case 66:
|
||||
return Event{CtrlJ, 0, nil}
|
||||
return Event{Down, 0, nil}
|
||||
case 65:
|
||||
return Event{CtrlK, 0, nil}
|
||||
return Event{Up, 0, nil}
|
||||
case 90:
|
||||
return Event{BTab, 0, nil}
|
||||
case 72:
|
||||
return Event{CtrlA, 0, nil}
|
||||
return Event{Home, 0, nil}
|
||||
case 70:
|
||||
return Event{CtrlE, 0, nil}
|
||||
return Event{End, 0, nil}
|
||||
case 77:
|
||||
return mouseSequence(sz)
|
||||
case 80:
|
||||
@@ -390,7 +427,7 @@ func escSequence(sz *int) Event {
|
||||
case 51:
|
||||
return Event{Del, 0, nil}
|
||||
case 52:
|
||||
return Event{CtrlE, 0, nil}
|
||||
return Event{End, 0, nil}
|
||||
case 53:
|
||||
return Event{PgUp, 0, nil}
|
||||
case 54:
|
||||
@@ -398,7 +435,7 @@ func escSequence(sz *int) Event {
|
||||
case 49:
|
||||
switch _buf[3] {
|
||||
case 126:
|
||||
return Event{CtrlA, 0, nil}
|
||||
return Event{Home, 0, nil}
|
||||
case 59:
|
||||
if len(_buf) != 6 {
|
||||
return Event{Invalid, 0, nil}
|
||||
@@ -408,16 +445,16 @@ func escSequence(sz *int) Event {
|
||||
case 50:
|
||||
switch _buf[5] {
|
||||
case 68:
|
||||
return Event{CtrlA, 0, nil}
|
||||
return Event{Home, 0, nil}
|
||||
case 67:
|
||||
return Event{CtrlE, 0, nil}
|
||||
return Event{End, 0, nil}
|
||||
}
|
||||
case 53:
|
||||
switch _buf[5] {
|
||||
case 68:
|
||||
return Event{AltB, 0, nil}
|
||||
return Event{SLeft, 0, nil}
|
||||
case 67:
|
||||
return Event{AltF, 0, nil}
|
||||
return Event{SRight, 0, nil}
|
||||
}
|
||||
} // _buf[4]
|
||||
} // _buf[3]
|
||||
@@ -444,10 +481,14 @@ func GetChar() Event {
|
||||
}()
|
||||
|
||||
switch _buf[0] {
|
||||
case CtrlC, CtrlG, CtrlQ:
|
||||
case CtrlC:
|
||||
return Event{CtrlC, 0, nil}
|
||||
case CtrlG:
|
||||
return Event{CtrlG, 0, nil}
|
||||
case CtrlQ:
|
||||
return Event{CtrlQ, 0, nil}
|
||||
case 127:
|
||||
return Event{CtrlH, 0, nil}
|
||||
return Event{BSpace, 0, nil}
|
||||
case ESC:
|
||||
return escSequence(&sz)
|
||||
}
|
||||
@@ -474,7 +515,12 @@ func MoveAndClear(y int, x int) {
|
||||
}
|
||||
|
||||
func Print(text string) {
|
||||
C.addstr(C.CString(text))
|
||||
C.addstr(C.CString(strings.Map(func(r rune) rune {
|
||||
if r < 32 {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, text)))
|
||||
}
|
||||
|
||||
func CPrint(pair int, bold bool, text string) {
|
||||
|
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")
|
||||
}
|
||||
}
|
84
src/item.go
84
src/item.go
@@ -6,8 +6,8 @@ import (
|
||||
"github.com/junegunn/fzf/src/curses"
|
||||
)
|
||||
|
||||
// Offset holds two 32-bit integers denoting the offsets of a matched substring
|
||||
type Offset [2]int32
|
||||
// Offset holds three 32-bit integers denoting the offsets of a matched substring
|
||||
type Offset [3]int32
|
||||
|
||||
type colorOffset struct {
|
||||
offset [2]int32
|
||||
@@ -17,9 +17,9 @@ type colorOffset struct {
|
||||
|
||||
// Item represents each input line
|
||||
type Item struct {
|
||||
text *string
|
||||
origText *string
|
||||
transformed *[]Token
|
||||
text []rune
|
||||
origText *[]rune
|
||||
transformed []Token
|
||||
index uint32
|
||||
offsets []Offset
|
||||
colors []ansiOffset
|
||||
@@ -37,16 +37,19 @@ type Rank struct {
|
||||
var rankTiebreak tiebreak
|
||||
|
||||
// Rank calculates rank of the Item
|
||||
func (i *Item) Rank(cache bool) Rank {
|
||||
if cache && (i.rank.matchlen > 0 || i.rank.tiebreak > 0) {
|
||||
return i.rank
|
||||
func (item *Item) Rank(cache bool) Rank {
|
||||
if cache && (item.rank.matchlen > 0 || item.rank.tiebreak > 0) {
|
||||
return item.rank
|
||||
}
|
||||
matchlen := 0
|
||||
prevEnd := 0
|
||||
lenSum := 0
|
||||
minBegin := math.MaxUint16
|
||||
for _, offset := range i.offsets {
|
||||
for _, offset := range item.offsets {
|
||||
begin := int(offset[0])
|
||||
end := int(offset[1])
|
||||
trimLen := int(offset[2])
|
||||
lenSum += trimLen
|
||||
if prevEnd > begin {
|
||||
begin = prevEnd
|
||||
}
|
||||
@@ -60,16 +63,25 @@ func (i *Item) Rank(cache bool) Rank {
|
||||
matchlen += end - begin
|
||||
}
|
||||
}
|
||||
if matchlen == 0 {
|
||||
matchlen = math.MaxUint16
|
||||
}
|
||||
var tiebreak uint16
|
||||
switch rankTiebreak {
|
||||
case byLength:
|
||||
tiebreak = uint16(len(*i.text))
|
||||
// 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
|
||||
tiebreak = uint16(lenSum)
|
||||
} else {
|
||||
tiebreak = uint16(len(item.text))
|
||||
}
|
||||
case byBegin:
|
||||
// We can't just look at i.offsets[0][0] because it can be an inverse term
|
||||
// We can't just look at item.offsets[0][0] because it can be an inverse term
|
||||
tiebreak = uint16(minBegin)
|
||||
case byEnd:
|
||||
if prevEnd > 0 {
|
||||
tiebreak = uint16(1 + len(*i.text) - prevEnd)
|
||||
tiebreak = uint16(1 + len(item.text) - prevEnd)
|
||||
} else {
|
||||
// Empty offsets due to inverse terms.
|
||||
tiebreak = 1
|
||||
@@ -77,26 +89,38 @@ func (i *Item) Rank(cache bool) Rank {
|
||||
case byIndex:
|
||||
tiebreak = 1
|
||||
}
|
||||
rank := Rank{uint16(matchlen), tiebreak, i.index}
|
||||
rank := Rank{uint16(matchlen), tiebreak, item.index}
|
||||
if cache {
|
||||
i.rank = rank
|
||||
item.rank = rank
|
||||
}
|
||||
return rank
|
||||
}
|
||||
|
||||
// AsString returns the original string
|
||||
func (i *Item) AsString() string {
|
||||
if i.origText != nil {
|
||||
return *i.origText
|
||||
func (item *Item) AsString(stripAnsi bool) string {
|
||||
return *item.StringPtr(stripAnsi)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if len(item.colors) == 0 {
|
||||
var offsets []colorOffset
|
||||
for _, off := range item.offsets {
|
||||
offsets = append(offsets, colorOffset{offset: off, color: color, bold: bold})
|
||||
|
||||
offsets = append(offsets, colorOffset{offset: [2]int32{off[0], off[1]}, color: color, bold: bold})
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
@@ -140,16 +164,28 @@ func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset
|
||||
if curr != 0 && idx > start {
|
||||
if curr == -1 {
|
||||
offsets = append(offsets, colorOffset{
|
||||
offset: Offset{int32(start), int32(idx)}, color: color, bold: bold})
|
||||
offset: [2]int32{int32(start), int32(idx)}, color: color, bold: bold})
|
||||
} else {
|
||||
ansi := item.colors[curr-1]
|
||||
fg := ansi.color.fg
|
||||
if fg == -1 {
|
||||
if current {
|
||||
fg = curses.CurrentFG
|
||||
} else {
|
||||
fg = curses.FG
|
||||
}
|
||||
}
|
||||
bg := ansi.color.bg
|
||||
if current && bg == -1 {
|
||||
bg = int(curses.DarkBG)
|
||||
if bg == -1 {
|
||||
if current {
|
||||
bg = curses.DarkBG
|
||||
} else {
|
||||
bg = curses.BG
|
||||
}
|
||||
}
|
||||
offsets = append(offsets, colorOffset{
|
||||
offset: Offset{int32(start), int32(idx)},
|
||||
color: curses.PairFor(ansi.color.fg, bg),
|
||||
offset: [2]int32{int32(start), int32(idx)},
|
||||
color: curses.PairFor(fg, bg),
|
||||
bold: ansi.color.bold || bold})
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
@@ -39,14 +40,14 @@ func TestRankComparison(t *testing.T) {
|
||||
|
||||
// Match length, string length, index
|
||||
func TestItemRank(t *testing.T) {
|
||||
strs := []string{"foo", "foobar", "bar", "baz"}
|
||||
item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}
|
||||
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
||||
item1 := Item{text: strs[0], index: 1, offsets: []Offset{}}
|
||||
rank1 := item1.Rank(true)
|
||||
if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {
|
||||
if rank1.matchlen != math.MaxUint16 || rank1.tiebreak != 3 || rank1.index != 1 {
|
||||
t.Error(item1.Rank(true))
|
||||
}
|
||||
// Only differ in index
|
||||
item2 := Item{text: &strs[0], index: 0, offsets: []Offset{}}
|
||||
item2 := Item{text: strs[0], index: 0, offsets: []Offset{}}
|
||||
|
||||
items := []*Item{&item1, &item2}
|
||||
sort.Sort(ByRelevance(items))
|
||||
@@ -62,15 +63,15 @@ func TestItemRank(t *testing.T) {
|
||||
}
|
||||
|
||||
// Sort by relevance
|
||||
item3 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item4 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
item5 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item6 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
item3 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item4 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
item5 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}
|
||||
item6 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}
|
||||
items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}
|
||||
sort.Sort(ByRelevance(items))
|
||||
if items[0] != &item2 || items[1] != &item1 ||
|
||||
items[2] != &item6 || items[3] != &item4 ||
|
||||
items[4] != &item5 || items[5] != &item3 {
|
||||
if items[0] != &item6 || items[1] != &item4 ||
|
||||
items[2] != &item5 || items[3] != &item3 ||
|
||||
items[4] != &item2 || items[5] != &item1 {
|
||||
t.Error(items)
|
||||
}
|
||||
}
|
||||
|
@@ -96,7 +96,7 @@ func (m *Matcher) Loop() {
|
||||
}
|
||||
|
||||
if !cancelled {
|
||||
if merger.Cacheable() {
|
||||
if merger.cacheable() {
|
||||
m.mergerCache[patternString] = merger
|
||||
}
|
||||
merger.final = request.final
|
||||
|
@@ -82,7 +82,7 @@ func (mg *Merger) Get(idx int) *Item {
|
||||
panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))
|
||||
}
|
||||
|
||||
func (mg *Merger) Cacheable() bool {
|
||||
func (mg *Merger) cacheable() bool {
|
||||
return mg.count < mergerCacheMax
|
||||
}
|
||||
|
||||
|
@@ -22,7 +22,7 @@ func randItem() *Item {
|
||||
offsets[idx] = Offset{sidx, eidx}
|
||||
}
|
||||
return &Item{
|
||||
text: &str,
|
||||
text: []rune(str),
|
||||
index: rand.Uint32(),
|
||||
offsets: offsets}
|
||||
}
|
||||
|
760
src/options.go
760
src/options.go
@@ -1,9 +1,9 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -14,61 +14,55 @@ import (
|
||||
|
||||
const usage = `usage: fzf [options]
|
||||
|
||||
Search mode
|
||||
Search
|
||||
-x, --extended Extended-search mode
|
||||
-e, --extended-exact Extended-search mode (exact match)
|
||||
(enabled by default; +x or --no-extended to disable)
|
||||
-e, --exact Enable Exact-match
|
||||
-i Case-insensitive match (default: smart-case match)
|
||||
+i Case-sensitive match
|
||||
-n, --nth=N[,..] Comma-separated list of field index expressions
|
||||
for limiting search scope. Each can be a non-zero
|
||||
integer or a range expression ([BEGIN]..[END])
|
||||
--with-nth=N[,..] Transform the item using index expressions for search
|
||||
--with-nth=N[,..] Transform item using index expressions within finder
|
||||
-d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)
|
||||
|
||||
Search result
|
||||
+s, --no-sort Do not sort the result
|
||||
--tac Reverse the order of the input
|
||||
--tiebreak=CRI Sort criterion when the scores are tied;
|
||||
--tac Reverse the order of the input
|
||||
--tiebreak=CRITERION Sort criterion when the scores are tied;
|
||||
[length|begin|end|index] (default: length)
|
||||
|
||||
Interface
|
||||
-m, --multi Enable multi-select with tab/shift-tab
|
||||
--ansi Enable processing of ANSI color codes
|
||||
--no-mouse Disable mouse
|
||||
--color=COL Color scheme; [dark|light|16|bw]
|
||||
(default: dark on 256-color terminal, otherwise 16)
|
||||
--black Use black background
|
||||
--reverse Reverse orientation
|
||||
--no-hscroll Disable horizontal scroll
|
||||
--inline-info Display finder info inline with the query
|
||||
--prompt=STR Input prompt (default: '> ')
|
||||
--ansi Enable processing of ANSI color codes
|
||||
--no-mouse Disable mouse
|
||||
--color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors
|
||||
--black Use black background
|
||||
--reverse Reverse orientation
|
||||
--margin=MARGIN Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)
|
||||
--cycle Enable cyclic scroll
|
||||
--no-hscroll Disable horizontal scroll
|
||||
--inline-info Display finder info inline with the query
|
||||
--prompt=STR Input prompt (default: '> ')
|
||||
--bind=KEYBINDS Custom key bindings. Refer to the man page.
|
||||
--history=FILE History file
|
||||
--history-size=N Maximum number of history entries (default: 1000)
|
||||
--header=STR String to print as header
|
||||
--header-lines=N The first N lines of the input are treated as header
|
||||
|
||||
Scripting
|
||||
-q, --query=STR Start the finder with the given query
|
||||
-1, --select-1 Automatically select the only match
|
||||
-0, --exit-0 Exit immediately when there's no match
|
||||
-f, --filter=STR Filter mode. Do not start interactive finder.
|
||||
--print-query Print query as the first line
|
||||
--expect=KEYS Comma-separated list of keys to complete fzf
|
||||
--toggle-sort=KEY Key to toggle sort
|
||||
--sync Synchronous search for multi-staged filtering
|
||||
--print-query Print query as the first line
|
||||
--expect=KEYS Comma-separated list of keys to complete fzf
|
||||
--sync Synchronous search for multi-staged filtering
|
||||
|
||||
Environment variables
|
||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||
FZF_DEFAULT_OPTS Defaults options. (e.g. '-x -m')
|
||||
FZF_DEFAULT_OPTS Defaults options. (e.g. '--reverse --inline-info')
|
||||
|
||||
`
|
||||
|
||||
// Mode denotes the current search mode
|
||||
type Mode int
|
||||
|
||||
// Search modes
|
||||
const (
|
||||
ModeFuzzy Mode = iota
|
||||
ModeExtended
|
||||
ModeExtendedExact
|
||||
)
|
||||
|
||||
// Case denotes case-sensitivity of search
|
||||
type Case int
|
||||
|
||||
@@ -89,88 +83,110 @@ const (
|
||||
byIndex
|
||||
)
|
||||
|
||||
func defaultMargin() [4]string {
|
||||
return [4]string{"0", "0", "0", "0"}
|
||||
}
|
||||
|
||||
// Options stores the values of command-line options
|
||||
type Options struct {
|
||||
Mode Mode
|
||||
Case Case
|
||||
Nth []Range
|
||||
WithNth []Range
|
||||
Delimiter *regexp.Regexp
|
||||
Sort int
|
||||
Tac bool
|
||||
Tiebreak tiebreak
|
||||
Multi bool
|
||||
Ansi bool
|
||||
Mouse bool
|
||||
Theme *curses.ColorTheme
|
||||
Black bool
|
||||
Reverse bool
|
||||
Hscroll bool
|
||||
InlineInfo bool
|
||||
Prompt string
|
||||
Query string
|
||||
Select1 bool
|
||||
Exit0 bool
|
||||
Filter *string
|
||||
ToggleSort int
|
||||
Expect []int
|
||||
PrintQuery bool
|
||||
Sync bool
|
||||
Version bool
|
||||
Fuzzy bool
|
||||
Extended bool
|
||||
Case Case
|
||||
Nth []Range
|
||||
WithNth []Range
|
||||
Delimiter Delimiter
|
||||
Sort int
|
||||
Tac bool
|
||||
Tiebreak tiebreak
|
||||
Multi bool
|
||||
Ansi bool
|
||||
Mouse bool
|
||||
Theme *curses.ColorTheme
|
||||
Black bool
|
||||
Reverse bool
|
||||
Cycle bool
|
||||
Hscroll bool
|
||||
InlineInfo bool
|
||||
Prompt string
|
||||
Query string
|
||||
Select1 bool
|
||||
Exit0 bool
|
||||
Filter *string
|
||||
ToggleSort bool
|
||||
Expect map[int]string
|
||||
Keymap map[int]actionType
|
||||
Execmap map[int]string
|
||||
PrintQuery bool
|
||||
ReadZero bool
|
||||
Sync bool
|
||||
History *History
|
||||
Header []string
|
||||
HeaderLines int
|
||||
Margin [4]string
|
||||
Version bool
|
||||
}
|
||||
|
||||
func defaultTheme() *curses.ColorTheme {
|
||||
if strings.Contains(os.Getenv("TERM"), "256") {
|
||||
return curses.Dark256
|
||||
}
|
||||
return curses.Default16
|
||||
}
|
||||
|
||||
func defaultOptions() *Options {
|
||||
var defaultTheme *curses.ColorTheme
|
||||
if strings.Contains(os.Getenv("TERM"), "256") {
|
||||
defaultTheme = curses.Dark256
|
||||
} else {
|
||||
defaultTheme = curses.Default16
|
||||
}
|
||||
|
||||
return &Options{
|
||||
Mode: ModeFuzzy,
|
||||
Case: CaseSmart,
|
||||
Nth: make([]Range, 0),
|
||||
WithNth: make([]Range, 0),
|
||||
Delimiter: nil,
|
||||
Sort: 1000,
|
||||
Tac: false,
|
||||
Tiebreak: byLength,
|
||||
Multi: false,
|
||||
Ansi: false,
|
||||
Mouse: true,
|
||||
Theme: defaultTheme,
|
||||
Black: false,
|
||||
Reverse: false,
|
||||
Hscroll: true,
|
||||
InlineInfo: false,
|
||||
Prompt: "> ",
|
||||
Query: "",
|
||||
Select1: false,
|
||||
Exit0: false,
|
||||
Filter: nil,
|
||||
ToggleSort: 0,
|
||||
Expect: []int{},
|
||||
PrintQuery: false,
|
||||
Sync: false,
|
||||
Version: false}
|
||||
Fuzzy: true,
|
||||
Extended: true,
|
||||
Case: CaseSmart,
|
||||
Nth: make([]Range, 0),
|
||||
WithNth: make([]Range, 0),
|
||||
Delimiter: Delimiter{},
|
||||
Sort: 1000,
|
||||
Tac: false,
|
||||
Tiebreak: byLength,
|
||||
Multi: false,
|
||||
Ansi: false,
|
||||
Mouse: true,
|
||||
Theme: defaultTheme(),
|
||||
Black: false,
|
||||
Reverse: false,
|
||||
Cycle: false,
|
||||
Hscroll: true,
|
||||
InlineInfo: false,
|
||||
Prompt: "> ",
|
||||
Query: "",
|
||||
Select1: false,
|
||||
Exit0: false,
|
||||
Filter: nil,
|
||||
ToggleSort: false,
|
||||
Expect: make(map[int]string),
|
||||
Keymap: defaultKeymap(),
|
||||
Execmap: make(map[int]string),
|
||||
PrintQuery: false,
|
||||
ReadZero: false,
|
||||
Sync: false,
|
||||
History: nil,
|
||||
Header: make([]string, 0),
|
||||
HeaderLines: 0,
|
||||
Margin: defaultMargin(),
|
||||
Version: false}
|
||||
}
|
||||
|
||||
func help(ok int) {
|
||||
func help(code int) {
|
||||
os.Stderr.WriteString(usage)
|
||||
os.Exit(ok)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func errorExit(msg string) {
|
||||
os.Stderr.WriteString(msg + "\n")
|
||||
help(1)
|
||||
os.Exit(exitError)
|
||||
}
|
||||
|
||||
func optString(arg string, prefix string) (bool, string) {
|
||||
rx, _ := regexp.Compile(fmt.Sprintf("^(?:%s)(.*)$", prefix))
|
||||
matches := rx.FindStringSubmatch(arg)
|
||||
if len(matches) > 1 {
|
||||
return true, matches[1]
|
||||
func optString(arg string, prefixes ...string) (bool, string) {
|
||||
for _, prefix := range prefixes {
|
||||
if strings.HasPrefix(arg, prefix) {
|
||||
return true, arg[len(prefix):]
|
||||
}
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
@@ -184,6 +200,39 @@ func nextString(args []string, i *int, message string) string {
|
||||
return args[*i]
|
||||
}
|
||||
|
||||
func optionalNextString(args []string, i *int) string {
|
||||
if len(args) > *i+1 {
|
||||
*i++
|
||||
return args[*i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func atoi(str string) int {
|
||||
num, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
errorExit("not a valid integer: " + str)
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
func atof(str string) float64 {
|
||||
num, err := strconv.ParseFloat(str, 64)
|
||||
if err != nil {
|
||||
errorExit("not a valid number: " + str)
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
func nextInt(args []string, i *int, message string) int {
|
||||
if len(args) > *i+1 {
|
||||
*i++
|
||||
} else {
|
||||
errorExit(message)
|
||||
}
|
||||
return atoi(args[*i])
|
||||
}
|
||||
|
||||
func optionalNumeric(args []string, i *int) int {
|
||||
if len(args) > *i+1 {
|
||||
if strings.IndexAny(args[*i+1], "0123456789") == 0 {
|
||||
@@ -210,24 +259,30 @@ func splitNth(str string) []Range {
|
||||
return ranges
|
||||
}
|
||||
|
||||
func delimiterRegexp(str string) *regexp.Regexp {
|
||||
rx, e := regexp.Compile(str)
|
||||
if e != nil {
|
||||
str = regexp.QuoteMeta(str)
|
||||
func delimiterRegexp(str string) Delimiter {
|
||||
// Special handling of \t
|
||||
str = strings.Replace(str, "\\t", "\t", -1)
|
||||
|
||||
// 1. Pattern does not contain any special character
|
||||
if regexp.QuoteMeta(str) == str {
|
||||
return Delimiter{str: &str}
|
||||
}
|
||||
|
||||
rx, e = regexp.Compile(fmt.Sprintf("(?:.*?%s)|(?:.+?$)", str))
|
||||
rx, e := regexp.Compile(str)
|
||||
// 2. Pattern is not a valid regular expression
|
||||
if e != nil {
|
||||
errorExit("invalid regular expression: " + e.Error())
|
||||
return Delimiter{str: &str}
|
||||
}
|
||||
return rx
|
||||
|
||||
// 3. Pattern as regular expression. Slow.
|
||||
return Delimiter{regex: rx}
|
||||
}
|
||||
|
||||
func isAlphabet(char uint8) bool {
|
||||
return char >= 'a' && char <= 'z'
|
||||
}
|
||||
|
||||
func parseKeyChords(str string, message string) []int {
|
||||
func parseKeyChords(str string, message string) map[int]string {
|
||||
if len(str) == 0 {
|
||||
errorExit(message)
|
||||
}
|
||||
@@ -237,22 +292,67 @@ func parseKeyChords(str string, message string) []int {
|
||||
tokens = append(tokens, ",")
|
||||
}
|
||||
|
||||
var chords []int
|
||||
chords := make(map[int]string)
|
||||
for _, key := range tokens {
|
||||
if len(key) == 0 {
|
||||
continue // ignore
|
||||
}
|
||||
lkey := strings.ToLower(key)
|
||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||
chords = append(chords, curses.CtrlA+int(lkey[5])-'a')
|
||||
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||
chords = append(chords, curses.AltA+int(lkey[4])-'a')
|
||||
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
||||
chords = append(chords, curses.F1+int(key[1])-'1')
|
||||
} else if utf8.RuneCountInString(key) == 1 {
|
||||
chords = append(chords, curses.AltZ+int([]rune(key)[0]))
|
||||
} else {
|
||||
errorExit("unsupported key: " + key)
|
||||
chord := 0
|
||||
switch lkey {
|
||||
case "up":
|
||||
chord = curses.Up
|
||||
case "down":
|
||||
chord = curses.Down
|
||||
case "left":
|
||||
chord = curses.Left
|
||||
case "right":
|
||||
chord = curses.Right
|
||||
case "enter", "return":
|
||||
chord = curses.CtrlM
|
||||
case "space":
|
||||
chord = curses.AltZ + int(' ')
|
||||
case "bspace", "bs":
|
||||
chord = curses.BSpace
|
||||
case "alt-bs", "alt-bspace":
|
||||
chord = curses.AltBS
|
||||
case "tab":
|
||||
chord = curses.Tab
|
||||
case "btab", "shift-tab":
|
||||
chord = curses.BTab
|
||||
case "esc":
|
||||
chord = curses.ESC
|
||||
case "del":
|
||||
chord = curses.Del
|
||||
case "home":
|
||||
chord = curses.Home
|
||||
case "end":
|
||||
chord = curses.End
|
||||
case "pgup", "page-up":
|
||||
chord = curses.PgUp
|
||||
case "pgdn", "page-down":
|
||||
chord = curses.PgDn
|
||||
case "shift-left":
|
||||
chord = curses.SLeft
|
||||
case "shift-right":
|
||||
chord = curses.SRight
|
||||
case "double-click":
|
||||
chord = curses.DoubleClick
|
||||
default:
|
||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||
chord = curses.CtrlA + int(lkey[5]) - 'a'
|
||||
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||
chord = curses.AltA + int(lkey[4]) - 'a'
|
||||
} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '4' {
|
||||
chord = curses.F1 + int(key[1]) - '1'
|
||||
} else if utf8.RuneCountInString(key) == 1 {
|
||||
chord = curses.AltZ + int([]rune(key)[0])
|
||||
} else {
|
||||
errorExit("unsupported key: " + key)
|
||||
}
|
||||
}
|
||||
if chord > 0 {
|
||||
chords[chord] = key
|
||||
}
|
||||
}
|
||||
return chords
|
||||
@@ -274,42 +374,336 @@ func parseTiebreak(str string) tiebreak {
|
||||
return byLength
|
||||
}
|
||||
|
||||
func parseTheme(str string) *curses.ColorTheme {
|
||||
switch strings.ToLower(str) {
|
||||
case "dark":
|
||||
return curses.Dark256
|
||||
case "light":
|
||||
return curses.Light256
|
||||
case "16":
|
||||
return curses.Default16
|
||||
case "bw", "no":
|
||||
return nil
|
||||
default:
|
||||
errorExit("invalid color scheme: " + str)
|
||||
func dupeTheme(theme *curses.ColorTheme) *curses.ColorTheme {
|
||||
if theme != nil {
|
||||
dupe := *theme
|
||||
return &dupe
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkToggleSort(str string) int {
|
||||
func parseTheme(defaultTheme *curses.ColorTheme, str string) *curses.ColorTheme {
|
||||
theme := dupeTheme(defaultTheme)
|
||||
for _, str := range strings.Split(strings.ToLower(str), ",") {
|
||||
switch str {
|
||||
case "dark":
|
||||
theme = dupeTheme(curses.Dark256)
|
||||
case "light":
|
||||
theme = dupeTheme(curses.Light256)
|
||||
case "16":
|
||||
theme = dupeTheme(curses.Default16)
|
||||
case "bw", "no":
|
||||
theme = nil
|
||||
default:
|
||||
fail := func() {
|
||||
errorExit("invalid color specification: " + str)
|
||||
}
|
||||
// Color is disabled
|
||||
if theme == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
pair := strings.Split(str, ":")
|
||||
if len(pair) != 2 {
|
||||
fail()
|
||||
}
|
||||
ansi32, err := strconv.Atoi(pair[1])
|
||||
if err != nil || ansi32 < -1 || ansi32 > 255 {
|
||||
fail()
|
||||
}
|
||||
ansi := int16(ansi32)
|
||||
switch pair[0] {
|
||||
case "fg":
|
||||
theme.Fg = ansi
|
||||
theme.UseDefault = theme.UseDefault && ansi < 0
|
||||
case "bg":
|
||||
theme.Bg = ansi
|
||||
theme.UseDefault = theme.UseDefault && ansi < 0
|
||||
case "fg+":
|
||||
theme.Current = ansi
|
||||
case "bg+":
|
||||
theme.DarkBg = ansi
|
||||
case "hl":
|
||||
theme.Match = ansi
|
||||
case "hl+":
|
||||
theme.CurrentMatch = ansi
|
||||
case "prompt":
|
||||
theme.Prompt = ansi
|
||||
case "spinner":
|
||||
theme.Spinner = ansi
|
||||
case "info":
|
||||
theme.Info = ansi
|
||||
case "pointer":
|
||||
theme.Cursor = ansi
|
||||
case "marker":
|
||||
theme.Selected = ansi
|
||||
case "header":
|
||||
theme.Header = ansi
|
||||
default:
|
||||
fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
return theme
|
||||
}
|
||||
|
||||
var executeRegexp *regexp.Regexp
|
||||
|
||||
func firstKey(keymap map[int]string) int {
|
||||
for k := range keymap {
|
||||
return k
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const (
|
||||
escapedColon = 0
|
||||
escapedComma = 1
|
||||
)
|
||||
|
||||
func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {
|
||||
if executeRegexp == nil {
|
||||
// Backreferences are not supported.
|
||||
// "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')
|
||||
executeRegexp = regexp.MustCompile(
|
||||
"(?s):execute(-multi)?:.*|:execute(-multi)?(\\([^)]*\\)|\\[[^\\]]*\\]|~[^~]*~|![^!]*!|@[^@]*@|\\#[^\\#]*\\#|\\$[^\\$]*\\$|%[^%]*%|\\^[^\\^]*\\^|&[^&]*&|\\*[^\\*]*\\*|;[^;]*;|/[^/]*/|\\|[^\\|]*\\|)")
|
||||
}
|
||||
masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {
|
||||
if strings.HasPrefix(src, ":execute-multi") {
|
||||
return ":execute-multi(" + strings.Repeat(" ", len(src)-len(":execute-multi()")) + ")"
|
||||
}
|
||||
return ":execute(" + strings.Repeat(" ", len(src)-len(":execute()")) + ")"
|
||||
})
|
||||
masked = strings.Replace(masked, "::", string([]rune{escapedColon, ':'}), -1)
|
||||
masked = strings.Replace(masked, ",:", string([]rune{escapedComma, ':'}), -1)
|
||||
|
||||
idx := 0
|
||||
for _, pairStr := range strings.Split(masked, ",") {
|
||||
origPairStr := str[idx : idx+len(pairStr)]
|
||||
idx += len(pairStr) + 1
|
||||
|
||||
pair := strings.SplitN(pairStr, ":", 2)
|
||||
if len(pair) < 2 {
|
||||
errorExit("bind action not specified: " + origPairStr)
|
||||
}
|
||||
var key int
|
||||
if len(pair[0]) == 1 && pair[0][0] == escapedColon {
|
||||
key = ':' + curses.AltZ
|
||||
} else if len(pair[0]) == 1 && pair[0][0] == escapedComma {
|
||||
key = ',' + curses.AltZ
|
||||
} else {
|
||||
keys := parseKeyChords(pair[0], "key name required")
|
||||
key = firstKey(keys)
|
||||
}
|
||||
|
||||
act := origPairStr[len(pair[0])+1 : len(origPairStr)]
|
||||
actLower := strings.ToLower(act)
|
||||
switch actLower {
|
||||
case "ignore":
|
||||
keymap[key] = actIgnore
|
||||
case "beginning-of-line":
|
||||
keymap[key] = actBeginningOfLine
|
||||
case "abort":
|
||||
keymap[key] = actAbort
|
||||
case "accept":
|
||||
keymap[key] = actAccept
|
||||
case "backward-char":
|
||||
keymap[key] = actBackwardChar
|
||||
case "backward-delete-char":
|
||||
keymap[key] = actBackwardDeleteChar
|
||||
case "backward-word":
|
||||
keymap[key] = actBackwardWord
|
||||
case "clear-screen":
|
||||
keymap[key] = actClearScreen
|
||||
case "delete-char":
|
||||
keymap[key] = actDeleteChar
|
||||
case "delete-char/eof":
|
||||
keymap[key] = actDeleteCharEOF
|
||||
case "end-of-line":
|
||||
keymap[key] = actEndOfLine
|
||||
case "cancel":
|
||||
keymap[key] = actCancel
|
||||
case "forward-char":
|
||||
keymap[key] = actForwardChar
|
||||
case "forward-word":
|
||||
keymap[key] = actForwardWord
|
||||
case "kill-line":
|
||||
keymap[key] = actKillLine
|
||||
case "kill-word":
|
||||
keymap[key] = actKillWord
|
||||
case "unix-line-discard", "line-discard":
|
||||
keymap[key] = actUnixLineDiscard
|
||||
case "unix-word-rubout", "word-rubout":
|
||||
keymap[key] = actUnixWordRubout
|
||||
case "yank":
|
||||
keymap[key] = actYank
|
||||
case "backward-kill-word":
|
||||
keymap[key] = actBackwardKillWord
|
||||
case "toggle-down":
|
||||
keymap[key] = actToggleDown
|
||||
case "toggle-up":
|
||||
keymap[key] = actToggleUp
|
||||
case "toggle-all":
|
||||
keymap[key] = actToggleAll
|
||||
case "select-all":
|
||||
keymap[key] = actSelectAll
|
||||
case "deselect-all":
|
||||
keymap[key] = actDeselectAll
|
||||
case "toggle":
|
||||
keymap[key] = actToggle
|
||||
case "down":
|
||||
keymap[key] = actDown
|
||||
case "up":
|
||||
keymap[key] = actUp
|
||||
case "page-up":
|
||||
keymap[key] = actPageUp
|
||||
case "page-down":
|
||||
keymap[key] = actPageDown
|
||||
case "previous-history":
|
||||
keymap[key] = actPreviousHistory
|
||||
case "next-history":
|
||||
keymap[key] = actNextHistory
|
||||
case "toggle-sort":
|
||||
keymap[key] = actToggleSort
|
||||
toggleSort = true
|
||||
default:
|
||||
if isExecuteAction(actLower) {
|
||||
var offset int
|
||||
if strings.HasPrefix(actLower, "execute-multi") {
|
||||
keymap[key] = actExecuteMulti
|
||||
offset = len("execute-multi")
|
||||
} else {
|
||||
keymap[key] = actExecute
|
||||
offset = len("execute")
|
||||
}
|
||||
if act[offset] == ':' {
|
||||
execmap[key] = act[offset+1:]
|
||||
} else {
|
||||
execmap[key] = act[offset+1 : len(act)-1]
|
||||
}
|
||||
} else {
|
||||
errorExit("unknown action: " + act)
|
||||
}
|
||||
}
|
||||
}
|
||||
return keymap, execmap, toggleSort
|
||||
}
|
||||
|
||||
func isExecuteAction(str string) bool {
|
||||
if !strings.HasPrefix(str, "execute") || len(str) < len("execute()") {
|
||||
return false
|
||||
}
|
||||
b := str[len("execute")]
|
||||
if strings.HasPrefix(str, "execute-multi") {
|
||||
if len(str) < len("execute-multi()") {
|
||||
return false
|
||||
}
|
||||
b = str[len("execute-multi")]
|
||||
}
|
||||
e := str[len(str)-1]
|
||||
if b == ':' || b == '(' && e == ')' || b == '[' && e == ']' ||
|
||||
b == e && strings.ContainsAny(string(b), "~!@#$%^&*;/|") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {
|
||||
keys := parseKeyChords(str, "key name required")
|
||||
if len(keys) != 1 {
|
||||
errorExit("multiple keys specified")
|
||||
}
|
||||
return keys[0]
|
||||
keymap[firstKey(keys)] = actToggleSort
|
||||
return keymap
|
||||
}
|
||||
|
||||
func strLines(str string) []string {
|
||||
return strings.Split(strings.TrimSuffix(str, "\n"), "\n")
|
||||
}
|
||||
|
||||
func parseMargin(margin string) [4]string {
|
||||
margins := strings.Split(margin, ",")
|
||||
checked := func(str string) string {
|
||||
if strings.HasSuffix(str, "%") {
|
||||
val := atof(str[:len(str)-1])
|
||||
if val < 0 {
|
||||
errorExit("margin must be non-negative")
|
||||
}
|
||||
if val > 100 {
|
||||
errorExit("margin too large")
|
||||
}
|
||||
} else {
|
||||
val := atoi(str)
|
||||
if val < 0 {
|
||||
errorExit("margin must be non-negative")
|
||||
}
|
||||
}
|
||||
return str
|
||||
}
|
||||
switch len(margins) {
|
||||
case 1:
|
||||
m := checked(margins[0])
|
||||
return [4]string{m, m, m, m}
|
||||
case 2:
|
||||
tb := checked(margins[0])
|
||||
rl := checked(margins[1])
|
||||
return [4]string{tb, rl, tb, rl}
|
||||
case 3:
|
||||
t := checked(margins[0])
|
||||
rl := checked(margins[1])
|
||||
b := checked(margins[2])
|
||||
return [4]string{t, rl, b, rl}
|
||||
case 4:
|
||||
return [4]string{
|
||||
checked(margins[0]), checked(margins[1]),
|
||||
checked(margins[2]), checked(margins[3])}
|
||||
default:
|
||||
errorExit("invalid margin: " + margin)
|
||||
}
|
||||
return defaultMargin()
|
||||
}
|
||||
|
||||
func parseOptions(opts *Options, allArgs []string) {
|
||||
keymap := make(map[int]actionType)
|
||||
var historyMax int
|
||||
if opts.History == nil {
|
||||
historyMax = defaultHistoryMax
|
||||
} else {
|
||||
historyMax = opts.History.maxSize
|
||||
}
|
||||
setHistory := func(path string) {
|
||||
h, e := NewHistory(path, historyMax)
|
||||
if e != nil {
|
||||
errorExit(e.Error())
|
||||
}
|
||||
opts.History = h
|
||||
}
|
||||
setHistoryMax := func(max int) {
|
||||
historyMax = max
|
||||
if historyMax < 1 {
|
||||
errorExit("history max must be a positive integer")
|
||||
}
|
||||
if opts.History != nil {
|
||||
opts.History.maxSize = historyMax
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(allArgs); i++ {
|
||||
arg := allArgs[i]
|
||||
switch arg {
|
||||
case "-h", "--help":
|
||||
help(0)
|
||||
help(exitOk)
|
||||
case "-x", "--extended":
|
||||
opts.Mode = ModeExtended
|
||||
case "-e", "--extended-exact":
|
||||
opts.Mode = ModeExtendedExact
|
||||
case "+x", "--no-extended", "+e", "--no-extended-exact":
|
||||
opts.Mode = ModeFuzzy
|
||||
opts.Extended = true
|
||||
case "-e", "--exact":
|
||||
opts.Fuzzy = false
|
||||
case "--extended-exact":
|
||||
// Note that we now don't have --no-extended-exact
|
||||
opts.Fuzzy = false
|
||||
opts.Extended = true
|
||||
case "+x", "--no-extended":
|
||||
opts.Extended = false
|
||||
case "+e", "--no-exact":
|
||||
opts.Fuzzy = true
|
||||
case "-q", "--query":
|
||||
opts.Query = nextString(allArgs, &i, "query string required")
|
||||
case "-f", "--filter":
|
||||
@@ -319,10 +713,19 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
||||
case "--tiebreak":
|
||||
opts.Tiebreak = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||
case "--bind":
|
||||
keymap, opts.Execmap, opts.ToggleSort =
|
||||
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))
|
||||
case "--color":
|
||||
opts.Theme = parseTheme(nextString(allArgs, &i, "color scheme name required"))
|
||||
spec := optionalNextString(allArgs, &i)
|
||||
if len(spec) == 0 {
|
||||
opts.Theme = defaultTheme()
|
||||
} else {
|
||||
opts.Theme = parseTheme(opts.Theme, spec)
|
||||
}
|
||||
case "--toggle-sort":
|
||||
opts.ToggleSort = checkToggleSort(nextString(allArgs, &i, "key name required"))
|
||||
keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))
|
||||
opts.ToggleSort = true
|
||||
case "-d", "--delimiter":
|
||||
opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))
|
||||
case "-n", "--nth":
|
||||
@@ -363,6 +766,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Reverse = true
|
||||
case "--no-reverse":
|
||||
opts.Reverse = false
|
||||
case "--cycle":
|
||||
opts.Cycle = true
|
||||
case "--no-cycle":
|
||||
opts.Cycle = false
|
||||
case "--hscroll":
|
||||
opts.Hscroll = true
|
||||
case "--no-hscroll":
|
||||
@@ -379,6 +786,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Exit0 = true
|
||||
case "+0", "--no-exit-0":
|
||||
opts.Exit0 = false
|
||||
case "--read0":
|
||||
opts.ReadZero = true
|
||||
case "--no-read0":
|
||||
opts.ReadZero = false
|
||||
case "--print-query":
|
||||
opts.PrintQuery = true
|
||||
case "--no-print-query":
|
||||
@@ -391,40 +802,93 @@ func parseOptions(opts *Options, allArgs []string) {
|
||||
opts.Sync = false
|
||||
case "--async":
|
||||
opts.Sync = false
|
||||
case "--no-history":
|
||||
opts.History = nil
|
||||
case "--history":
|
||||
setHistory(nextString(allArgs, &i, "history file path required"))
|
||||
case "--history-size":
|
||||
setHistoryMax(nextInt(allArgs, &i, "history max size required"))
|
||||
case "--no-header":
|
||||
opts.Header = []string{}
|
||||
case "--no-header-lines":
|
||||
opts.HeaderLines = 0
|
||||
case "--header":
|
||||
opts.Header = strLines(nextString(allArgs, &i, "header string required"))
|
||||
case "--header-lines":
|
||||
opts.HeaderLines = atoi(
|
||||
nextString(allArgs, &i, "number of header lines required"))
|
||||
case "--no-margin":
|
||||
opts.Margin = defaultMargin()
|
||||
case "--margin":
|
||||
opts.Margin = parseMargin(
|
||||
nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))
|
||||
case "--version":
|
||||
opts.Version = true
|
||||
default:
|
||||
if match, value := optString(arg, "-q|--query="); match {
|
||||
if match, value := optString(arg, "-q", "--query="); match {
|
||||
opts.Query = value
|
||||
} else if match, value := optString(arg, "-f|--filter="); match {
|
||||
} else if match, value := optString(arg, "-f", "--filter="); match {
|
||||
opts.Filter = &value
|
||||
} else if match, value := optString(arg, "-d|--delimiter="); match {
|
||||
} else if match, value := optString(arg, "-d", "--delimiter="); match {
|
||||
opts.Delimiter = delimiterRegexp(value)
|
||||
} else if match, value := optString(arg, "--prompt="); match {
|
||||
opts.Prompt = value
|
||||
} else if match, value := optString(arg, "-n|--nth="); match {
|
||||
} else if match, value := optString(arg, "-n", "--nth="); match {
|
||||
opts.Nth = splitNth(value)
|
||||
} else if match, value := optString(arg, "--with-nth="); match {
|
||||
opts.WithNth = splitNth(value)
|
||||
} else if match, _ := optString(arg, "-s|--sort="); match {
|
||||
} else if match, _ := optString(arg, "-s", "--sort="); match {
|
||||
opts.Sort = 1 // Don't care
|
||||
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||
opts.ToggleSort = checkToggleSort(value)
|
||||
keymap = checkToggleSort(keymap, value)
|
||||
opts.ToggleSort = true
|
||||
} else if match, value := optString(arg, "--expect="); match {
|
||||
opts.Expect = parseKeyChords(value, "key names required")
|
||||
} else if match, value := optString(arg, "--tiebreak="); match {
|
||||
opts.Tiebreak = parseTiebreak(value)
|
||||
} else if match, value := optString(arg, "--color="); match {
|
||||
opts.Theme = parseTheme(value)
|
||||
opts.Theme = parseTheme(opts.Theme, value)
|
||||
} else if match, value := optString(arg, "--bind="); match {
|
||||
keymap, opts.Execmap, opts.ToggleSort =
|
||||
parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)
|
||||
} else if match, value := optString(arg, "--history="); match {
|
||||
setHistory(value)
|
||||
} else if match, value := optString(arg, "--history-size="); match {
|
||||
setHistoryMax(atoi(value))
|
||||
} else if match, value := optString(arg, "--header="); match {
|
||||
opts.Header = strLines(value)
|
||||
} else if match, value := optString(arg, "--header-lines="); match {
|
||||
opts.HeaderLines = atoi(value)
|
||||
} else if match, value := optString(arg, "--margin="); match {
|
||||
opts.Margin = parseMargin(value)
|
||||
} else {
|
||||
errorExit("unknown option: " + arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if opts.HeaderLines < 0 {
|
||||
errorExit("header lines must be a non-negative integer")
|
||||
}
|
||||
|
||||
// Change default actions for CTRL-N / CTRL-P when --history is used
|
||||
if opts.History != nil {
|
||||
if _, prs := keymap[curses.CtrlP]; !prs {
|
||||
keymap[curses.CtrlP] = actPreviousHistory
|
||||
}
|
||||
if _, prs := keymap[curses.CtrlN]; !prs {
|
||||
keymap[curses.CtrlN] = actNextHistory
|
||||
}
|
||||
}
|
||||
|
||||
// Override default key bindings
|
||||
for key, act := range keymap {
|
||||
opts.Keymap[key] = act
|
||||
}
|
||||
|
||||
// If we're not using extended search mode, --nth option becomes irrelevant
|
||||
// if it contains the whole range
|
||||
if opts.Mode == ModeFuzzy || len(opts.Nth) == 1 {
|
||||
if !opts.Extended || len(opts.Nth) == 1 {
|
||||
for _, r := range opts.Nth {
|
||||
if r.begin == rangeEllipsis && r.end == rangeEllipsis {
|
||||
opts.Nth = make([]Range, 0)
|
||||
|
@@ -1,17 +1,66 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/junegunn/fzf/src/curses"
|
||||
)
|
||||
|
||||
func TestDelimiterRegex(t *testing.T) {
|
||||
rx := delimiterRegexp("*")
|
||||
tokens := rx.FindAllString("-*--*---**---", -1)
|
||||
if tokens[0] != "-*" || tokens[1] != "--*" || tokens[2] != "---*" ||
|
||||
tokens[3] != "*" || tokens[4] != "---" {
|
||||
t.Errorf("%s %s %d", rx, tokens, len(tokens))
|
||||
// Valid regex
|
||||
delim := delimiterRegexp(".")
|
||||
if delim.regex == nil || delim.str != nil {
|
||||
t.Error(delim)
|
||||
}
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +100,7 @@ func TestIrrelevantNth(t *testing.T) {
|
||||
t.Errorf("nth should be empty: %s", opts.Nth)
|
||||
}
|
||||
}
|
||||
for _, words := range [][]string{[]string{"--nth", "..,3"}, []string{"--nth", "3,1.."}, []string{"--nth", "..-1,1"}} {
|
||||
for _, words := range [][]string{[]string{"--nth", "..,3", "+x"}, []string{"--nth", "3,1..", "+x"}, []string{"--nth", "..-1,1", "+x"}} {
|
||||
{
|
||||
opts := defaultOptions()
|
||||
parseOptions(opts, words)
|
||||
@@ -71,61 +120,211 @@ func TestIrrelevantNth(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseKeys(t *testing.T) {
|
||||
keys := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
||||
check := func(key int, expected int) {
|
||||
if key != expected {
|
||||
t.Errorf("%d != %d", key, expected)
|
||||
pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g", "")
|
||||
check := func(i int, s string) {
|
||||
if pairs[i] != s {
|
||||
t.Errorf("%s != %s", pairs[i], s)
|
||||
}
|
||||
}
|
||||
check(len(keys), 9)
|
||||
check(keys[0], curses.CtrlZ)
|
||||
check(keys[1], curses.AltZ)
|
||||
check(keys[2], curses.F2)
|
||||
check(keys[3], curses.AltZ+'@')
|
||||
check(keys[4], curses.AltA)
|
||||
check(keys[5], curses.AltZ+'!')
|
||||
check(keys[6], curses.CtrlA+'g'-'a')
|
||||
check(keys[7], curses.AltZ+'J')
|
||||
check(keys[8], curses.AltZ+'g')
|
||||
if len(pairs) != 9 {
|
||||
t.Error(9)
|
||||
}
|
||||
check(curses.CtrlZ, "ctrl-z")
|
||||
check(curses.AltZ, "alt-z")
|
||||
check(curses.F2, "f2")
|
||||
check(curses.AltZ+'@', "@")
|
||||
check(curses.AltA, "Alt-a")
|
||||
check(curses.AltZ+'!', "!")
|
||||
check(curses.CtrlA+'g'-'a', "ctrl-G")
|
||||
check(curses.AltZ+'J', "J")
|
||||
check(curses.AltZ+'g', "g")
|
||||
|
||||
// Synonyms
|
||||
pairs = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")
|
||||
if len(pairs) != 9 {
|
||||
t.Error(9)
|
||||
}
|
||||
check(curses.CtrlM, "Return")
|
||||
check(curses.AltZ+' ', "space")
|
||||
check(curses.Tab, "tab")
|
||||
check(curses.BTab, "btab")
|
||||
check(curses.ESC, "esc")
|
||||
check(curses.Up, "up")
|
||||
check(curses.Down, "down")
|
||||
check(curses.Left, "left")
|
||||
check(curses.Right, "right")
|
||||
|
||||
pairs = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")
|
||||
if len(pairs) != 11 {
|
||||
t.Error(11)
|
||||
}
|
||||
check(curses.Tab, "Ctrl-I")
|
||||
check(curses.PgUp, "page-up")
|
||||
check(curses.PgDn, "Page-Down")
|
||||
check(curses.Home, "Home")
|
||||
check(curses.End, "End")
|
||||
check(curses.AltBS, "Alt-BSpace")
|
||||
check(curses.SLeft, "shift-left")
|
||||
check(curses.SRight, "shift-right")
|
||||
check(curses.BTab, "shift-tab")
|
||||
check(curses.CtrlM, "Enter")
|
||||
check(curses.BSpace, "bspace")
|
||||
}
|
||||
|
||||
func TestParseKeysWithComma(t *testing.T) {
|
||||
check := func(key int, expected int) {
|
||||
if key != expected {
|
||||
t.Errorf("%d != %d", key, expected)
|
||||
checkN := func(a int, b int) {
|
||||
if a != b {
|
||||
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(",", "")
|
||||
check(len(keys), 1)
|
||||
check(keys[0], curses.AltZ+',')
|
||||
pairs := parseKeyChords(",", "")
|
||||
checkN(len(pairs), 1)
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
|
||||
keys = parseKeyChords(",,a,b", "")
|
||||
check(len(keys), 3)
|
||||
check(keys[0], curses.AltZ+'a')
|
||||
check(keys[1], curses.AltZ+'b')
|
||||
check(keys[2], curses.AltZ+',')
|
||||
pairs = parseKeyChords(",,a,b", "")
|
||||
checkN(len(pairs), 3)
|
||||
check(pairs, curses.AltZ+'a', "a")
|
||||
check(pairs, curses.AltZ+'b', "b")
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
|
||||
keys = parseKeyChords("a,b,,", "")
|
||||
check(len(keys), 3)
|
||||
check(keys[0], curses.AltZ+'a')
|
||||
check(keys[1], curses.AltZ+'b')
|
||||
check(keys[2], curses.AltZ+',')
|
||||
pairs = parseKeyChords("a,b,,", "")
|
||||
checkN(len(pairs), 3)
|
||||
check(pairs, curses.AltZ+'a', "a")
|
||||
check(pairs, curses.AltZ+'b', "b")
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
|
||||
keys = parseKeyChords("a,,,b", "")
|
||||
check(len(keys), 3)
|
||||
check(keys[0], curses.AltZ+'a')
|
||||
check(keys[1], curses.AltZ+'b')
|
||||
check(keys[2], curses.AltZ+',')
|
||||
pairs = parseKeyChords("a,,,b", "")
|
||||
checkN(len(pairs), 3)
|
||||
check(pairs, curses.AltZ+'a', "a")
|
||||
check(pairs, curses.AltZ+'b', "b")
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
|
||||
keys = parseKeyChords("a,,,b,c", "")
|
||||
check(len(keys), 4)
|
||||
check(keys[0], curses.AltZ+'a')
|
||||
check(keys[1], curses.AltZ+'b')
|
||||
check(keys[2], curses.AltZ+'c')
|
||||
check(keys[3], curses.AltZ+',')
|
||||
pairs = parseKeyChords("a,,,b,c", "")
|
||||
checkN(len(pairs), 4)
|
||||
check(pairs, curses.AltZ+'a', "a")
|
||||
check(pairs, curses.AltZ+'b', "b")
|
||||
check(pairs, curses.AltZ+'c', "c")
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
|
||||
keys = parseKeyChords(",,,", "")
|
||||
check(len(keys), 1)
|
||||
check(keys[0], curses.AltZ+',')
|
||||
pairs = parseKeyChords(",,,", "")
|
||||
checkN(len(pairs), 1)
|
||||
check(pairs, curses.AltZ+',', ",")
|
||||
}
|
||||
|
||||
func TestBind(t *testing.T) {
|
||||
check := func(action actionType, expected actionType) {
|
||||
if action != expected {
|
||||
t.Errorf("%d != %d", action, expected)
|
||||
}
|
||||
}
|
||||
checkString := func(action string, expected string) {
|
||||
if action != expected {
|
||||
t.Errorf("%d != %d", action, expected)
|
||||
}
|
||||
}
|
||||
keymap := defaultKeymap()
|
||||
execmap := make(map[int]string)
|
||||
check(actBeginningOfLine, keymap[curses.CtrlA])
|
||||
keymap, execmap, toggleSort :=
|
||||
parseKeymap(keymap, execmap, false,
|
||||
"ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+
|
||||
"f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+
|
||||
"alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+
|
||||
",,:abort,::accept,X:execute:\nfoobar,Y:execute(baz)")
|
||||
if !toggleSort {
|
||||
t.Errorf("toggleSort not set")
|
||||
}
|
||||
check(actKillLine, keymap[curses.CtrlA])
|
||||
check(actToggleSort, keymap[curses.CtrlB])
|
||||
check(actPageUp, keymap[curses.AltZ+'c'])
|
||||
check(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{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {
|
||||
keymap, execmap, toggleSort =
|
||||
parseKeymap(keymap, execmap, false, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))
|
||||
checkString("foobar", execmap[curses.AltZ+int([]rune(fmt.Sprintf("%d", idx%10))[0])])
|
||||
}
|
||||
|
||||
keymap, execmap, toggleSort = parseKeymap(keymap, execmap, false, "f1:abort")
|
||||
if toggleSort {
|
||||
t.Errorf("toggleSort set")
|
||||
}
|
||||
check(actAbort, keymap[curses.F1])
|
||||
}
|
||||
|
||||
func TestColorSpec(t *testing.T) {
|
||||
theme := curses.Dark256
|
||||
dark := parseTheme(theme, "dark")
|
||||
if *dark != *theme {
|
||||
t.Errorf("colors should be equivalent")
|
||||
}
|
||||
if dark == theme {
|
||||
t.Errorf("point should not be equivalent")
|
||||
}
|
||||
|
||||
light := parseTheme(theme, "dark,light")
|
||||
if *light == *theme {
|
||||
t.Errorf("should not be equivalent")
|
||||
}
|
||||
if *light != *curses.Light256 {
|
||||
t.Errorf("colors should be equivalent")
|
||||
}
|
||||
if light == theme {
|
||||
t.Errorf("point should not be equivalent")
|
||||
}
|
||||
|
||||
customized := parseTheme(theme, "fg:231,bg:232")
|
||||
if customized.Fg != 231 || customized.Bg != 232 {
|
||||
t.Errorf("color not customized")
|
||||
}
|
||||
if *curses.Dark256 == *customized {
|
||||
t.Errorf("colors should not be equivalent")
|
||||
}
|
||||
customized.Fg = curses.Dark256.Fg
|
||||
customized.Bg = curses.Dark256.Bg
|
||||
if *curses.Dark256 == *customized {
|
||||
t.Errorf("colors should now be equivalent")
|
||||
}
|
||||
|
||||
customized = parseTheme(theme, "fg:231,dark,bg:232")
|
||||
if customized.Fg != curses.Dark256.Fg || customized.Bg == curses.Dark256.Bg {
|
||||
t.Errorf("color not customized")
|
||||
}
|
||||
if customized.UseDefault {
|
||||
t.Errorf("not using default colors")
|
||||
}
|
||||
if !curses.Dark256.UseDefault {
|
||||
t.Errorf("using default colors")
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
181
src/pattern.go
181
src/pattern.go
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/junegunn/fzf/src/algo"
|
||||
"github.com/junegunn/fzf/src/util"
|
||||
)
|
||||
|
||||
// fuzzy
|
||||
@@ -24,6 +25,7 @@ const (
|
||||
termExact
|
||||
termPrefix
|
||||
termSuffix
|
||||
termEqual
|
||||
)
|
||||
|
||||
type term struct {
|
||||
@@ -34,16 +36,20 @@ type term struct {
|
||||
origText []rune
|
||||
}
|
||||
|
||||
type termSet []term
|
||||
|
||||
// Pattern represents search pattern
|
||||
type Pattern struct {
|
||||
mode Mode
|
||||
fuzzy bool
|
||||
extended bool
|
||||
caseSensitive bool
|
||||
forward bool
|
||||
text []rune
|
||||
terms []term
|
||||
hasInvTerm bool
|
||||
delimiter *regexp.Regexp
|
||||
termSets []termSet
|
||||
cacheable bool
|
||||
delimiter Delimiter
|
||||
nth []Range
|
||||
procFun map[termType]func(bool, *[]rune, []rune) (int, int)
|
||||
procFun map[termType]func(bool, bool, []rune, []rune) (int, int)
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -60,7 +66,7 @@ func init() {
|
||||
|
||||
func clearPatternCache() {
|
||||
// We can uniquely identify the pattern for a given string since
|
||||
// mode and caseMode do not change while the program is running
|
||||
// search mode and caseMode do not change while the program is running
|
||||
_patternCache = make(map[string]*Pattern)
|
||||
}
|
||||
|
||||
@@ -69,14 +75,13 @@ func clearChunkCache() {
|
||||
}
|
||||
|
||||
// BuildPattern builds Pattern object from the given arguments
|
||||
func BuildPattern(mode Mode, caseMode Case,
|
||||
nth []Range, delimiter *regexp.Regexp, runes []rune) *Pattern {
|
||||
func BuildPattern(fuzzy bool, extended bool, caseMode Case, forward bool,
|
||||
nth []Range, delimiter Delimiter, runes []rune) *Pattern {
|
||||
|
||||
var asString string
|
||||
switch mode {
|
||||
case ModeExtended, ModeExtendedExact:
|
||||
if extended {
|
||||
asString = strings.Trim(string(runes), " ")
|
||||
default:
|
||||
} else {
|
||||
asString = string(runes)
|
||||
}
|
||||
|
||||
@@ -85,18 +90,23 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
return cached
|
||||
}
|
||||
|
||||
caseSensitive, hasInvTerm := true, false
|
||||
terms := []term{}
|
||||
caseSensitive, cacheable := true, true
|
||||
termSets := []termSet{}
|
||||
|
||||
switch mode {
|
||||
case ModeExtended, ModeExtendedExact:
|
||||
terms = parseTerms(mode, caseMode, asString)
|
||||
for _, term := range terms {
|
||||
if term.inv {
|
||||
hasInvTerm = true
|
||||
if extended {
|
||||
termSets = parseTerms(fuzzy, caseMode, asString)
|
||||
Loop:
|
||||
for _, termSet := range termSets {
|
||||
for idx, term := range termSet {
|
||||
// If the query contains inverse search terms or OR operators,
|
||||
// we cannot cache the search scope
|
||||
if idx > 0 || term.inv {
|
||||
cacheable = false
|
||||
break Loop
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
} else {
|
||||
lowerString := strings.ToLower(asString)
|
||||
caseSensitive = caseMode == CaseRespect ||
|
||||
caseMode == CaseSmart && lowerString != asString
|
||||
@@ -106,16 +116,19 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
}
|
||||
|
||||
ptr := &Pattern{
|
||||
mode: mode,
|
||||
fuzzy: fuzzy,
|
||||
extended: extended,
|
||||
caseSensitive: caseSensitive,
|
||||
forward: forward,
|
||||
text: []rune(asString),
|
||||
terms: terms,
|
||||
hasInvTerm: hasInvTerm,
|
||||
termSets: termSets,
|
||||
cacheable: cacheable,
|
||||
nth: nth,
|
||||
delimiter: delimiter,
|
||||
procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}
|
||||
procFun: make(map[termType]func(bool, bool, []rune, []rune) (int, int))}
|
||||
|
||||
ptr.procFun[termFuzzy] = algo.FuzzyMatch
|
||||
ptr.procFun[termEqual] = algo.EqualMatch
|
||||
ptr.procFun[termExact] = algo.ExactMatchNaive
|
||||
ptr.procFun[termPrefix] = algo.PrefixMatch
|
||||
ptr.procFun[termSuffix] = algo.SuffixMatch
|
||||
@@ -124,9 +137,11 @@ func BuildPattern(mode Mode, caseMode Case,
|
||||
return ptr
|
||||
}
|
||||
|
||||
func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||
func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {
|
||||
tokens := _splitRegex.Split(str, -1)
|
||||
terms := []term{}
|
||||
sets := []termSet{}
|
||||
set := termSet{}
|
||||
switchSet := false
|
||||
for _, token := range tokens {
|
||||
typ, inv, text := termFuzzy, false, token
|
||||
lowerText := strings.ToLower(text)
|
||||
@@ -136,46 +151,68 @@ func parseTerms(mode Mode, caseMode Case, str string) []term {
|
||||
text = lowerText
|
||||
}
|
||||
origText := []rune(text)
|
||||
if mode == ModeExtendedExact {
|
||||
if !fuzzy {
|
||||
typ = termExact
|
||||
}
|
||||
|
||||
if text == "|" {
|
||||
switchSet = false
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(text, "!") {
|
||||
inv = true
|
||||
text = text[1:]
|
||||
}
|
||||
|
||||
if strings.HasPrefix(text, "'") {
|
||||
if mode == ModeExtended {
|
||||
// Flip exactness
|
||||
if fuzzy {
|
||||
typ = termExact
|
||||
text = text[1:]
|
||||
} else {
|
||||
typ = termFuzzy
|
||||
text = text[1:]
|
||||
}
|
||||
} else if strings.HasPrefix(text, "^") {
|
||||
typ = termPrefix
|
||||
text = text[1:]
|
||||
if strings.HasSuffix(text, "$") {
|
||||
typ = termEqual
|
||||
text = text[1 : len(text)-1]
|
||||
} else {
|
||||
typ = termPrefix
|
||||
text = text[1:]
|
||||
}
|
||||
} else if strings.HasSuffix(text, "$") {
|
||||
typ = termSuffix
|
||||
text = text[:len(text)-1]
|
||||
}
|
||||
|
||||
if len(text) > 0 {
|
||||
terms = append(terms, term{
|
||||
if switchSet {
|
||||
sets = append(sets, set)
|
||||
set = termSet{}
|
||||
}
|
||||
set = append(set, term{
|
||||
typ: typ,
|
||||
inv: inv,
|
||||
text: []rune(text),
|
||||
caseSensitive: caseSensitive,
|
||||
origText: origText})
|
||||
switchSet = true
|
||||
}
|
||||
}
|
||||
return terms
|
||||
if len(set) > 0 {
|
||||
sets = append(sets, set)
|
||||
}
|
||||
return sets
|
||||
}
|
||||
|
||||
// IsEmpty returns true if the pattern is effectively empty
|
||||
func (p *Pattern) IsEmpty() bool {
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
return len(p.text) == 0
|
||||
}
|
||||
return len(p.terms) == 0
|
||||
return len(p.termSets) == 0
|
||||
}
|
||||
|
||||
// AsString returns the search query in string type
|
||||
@@ -185,15 +222,14 @@ func (p *Pattern) AsString() string {
|
||||
|
||||
// CacheKey is used to build string to be used as the key of result cache
|
||||
func (p *Pattern) CacheKey() string {
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
return p.AsString()
|
||||
}
|
||||
cacheableTerms := []string{}
|
||||
for _, term := range p.terms {
|
||||
if term.inv {
|
||||
continue
|
||||
for _, termSet := range p.termSets {
|
||||
if len(termSet) == 1 && !termSet[0].inv {
|
||||
cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
|
||||
}
|
||||
cacheableTerms = append(cacheableTerms, string(term.origText))
|
||||
}
|
||||
return strings.Join(cacheableTerms, " ")
|
||||
}
|
||||
@@ -204,7 +240,7 @@ func (p *Pattern) Match(chunk *Chunk) []*Item {
|
||||
|
||||
// ChunkCache: Exact match
|
||||
cacheKey := p.CacheKey()
|
||||
if !p.hasInvTerm { // Because we're excluding Inv-term from cache key
|
||||
if p.cacheable {
|
||||
if cached, found := _cache.Find(chunk, cacheKey); found {
|
||||
return cached
|
||||
}
|
||||
@@ -229,7 +265,7 @@ Loop:
|
||||
|
||||
matches := p.matchChunk(space)
|
||||
|
||||
if !p.hasInvTerm {
|
||||
if p.cacheable {
|
||||
_cache.Add(chunk, cacheKey, matches)
|
||||
}
|
||||
return matches
|
||||
@@ -237,16 +273,16 @@ Loop:
|
||||
|
||||
func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||
matches := []*Item{}
|
||||
if p.mode == ModeFuzzy {
|
||||
if !p.extended {
|
||||
for _, item := range *chunk {
|
||||
if sidx, eidx := p.fuzzyMatch(item); sidx >= 0 {
|
||||
if sidx, eidx, tlen := p.basicMatch(item); sidx >= 0 {
|
||||
matches = append(matches,
|
||||
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx)}}))
|
||||
dupItem(item, []Offset{Offset{int32(sidx), int32(eidx), int32(tlen)}}))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, item := range *chunk {
|
||||
if offsets := p.extendedMatch(item); len(offsets) == len(p.terms) {
|
||||
if offsets := p.extendedMatch(item); len(offsets) == len(p.termSets) {
|
||||
matches = append(matches, dupItem(item, offsets))
|
||||
}
|
||||
}
|
||||
@@ -256,12 +292,12 @@ func (p *Pattern) matchChunk(chunk *Chunk) []*Item {
|
||||
|
||||
// MatchItem returns true if the Item is a match
|
||||
func (p *Pattern) MatchItem(item *Item) bool {
|
||||
if p.mode == ModeFuzzy {
|
||||
sidx, _ := p.fuzzyMatch(item)
|
||||
if !p.extended {
|
||||
sidx, _, _ := p.basicMatch(item)
|
||||
return sidx >= 0
|
||||
}
|
||||
offsets := p.extendedMatch(item)
|
||||
return len(offsets) == len(p.terms)
|
||||
return len(offsets) == len(p.termSets)
|
||||
}
|
||||
|
||||
func dupItem(item *Item, offsets []Offset) *Item {
|
||||
@@ -276,53 +312,62 @@ func dupItem(item *Item, offsets []Offset) *Item {
|
||||
rank: Rank{0, 0, item.index}}
|
||||
}
|
||||
|
||||
func (p *Pattern) fuzzyMatch(item *Item) (int, int) {
|
||||
func (p *Pattern) basicMatch(item *Item) (int, int, int) {
|
||||
input := p.prepareInput(item)
|
||||
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.text)
|
||||
if p.fuzzy {
|
||||
return p.iter(algo.FuzzyMatch, input, p.caseSensitive, p.forward, p.text)
|
||||
}
|
||||
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text)
|
||||
}
|
||||
|
||||
func (p *Pattern) extendedMatch(item *Item) []Offset {
|
||||
input := p.prepareInput(item)
|
||||
offsets := []Offset{}
|
||||
for _, term := range p.terms {
|
||||
pfun := p.procFun[term.typ]
|
||||
if sidx, eidx := p.iter(pfun, input, term.caseSensitive, term.text); sidx >= 0 {
|
||||
if term.inv {
|
||||
for _, termSet := range p.termSets {
|
||||
var offset *Offset
|
||||
for _, term := range termSet {
|
||||
pfun := p.procFun[term.typ]
|
||||
if sidx, eidx, tlen := p.iter(pfun, input, term.caseSensitive, p.forward, term.text); sidx >= 0 {
|
||||
if term.inv {
|
||||
continue
|
||||
}
|
||||
offset = &Offset{int32(sidx), int32(eidx), int32(tlen)}
|
||||
break
|
||||
} else if term.inv {
|
||||
offset = &Offset{0, 0, 0}
|
||||
continue
|
||||
}
|
||||
offsets = append(offsets, Offset{int32(sidx), int32(eidx)})
|
||||
} else if term.inv {
|
||||
offsets = append(offsets, Offset{0, 0})
|
||||
}
|
||||
if offset != nil {
|
||||
offsets = append(offsets, *offset)
|
||||
}
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
|
||||
func (p *Pattern) prepareInput(item *Item) *[]Token {
|
||||
func (p *Pattern) prepareInput(item *Item) []Token {
|
||||
if item.transformed != nil {
|
||||
return item.transformed
|
||||
}
|
||||
|
||||
var ret *[]Token
|
||||
var ret []Token
|
||||
if len(p.nth) > 0 {
|
||||
tokens := Tokenize(item.text, p.delimiter)
|
||||
ret = Transform(tokens, p.nth)
|
||||
} else {
|
||||
runes := []rune(*item.text)
|
||||
trans := []Token{Token{text: &runes, prefixLength: 0}}
|
||||
ret = &trans
|
||||
ret = []Token{Token{text: item.text, prefixLength: 0, trimLength: util.TrimLen(item.text)}}
|
||||
}
|
||||
item.transformed = ret
|
||||
return ret
|
||||
}
|
||||
|
||||
func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),
|
||||
tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {
|
||||
for _, part := range *tokens {
|
||||
func (p *Pattern) iter(pfun func(bool, bool, []rune, []rune) (int, int),
|
||||
tokens []Token, caseSensitive bool, forward bool, pattern []rune) (int, int, int) {
|
||||
for _, part := range tokens {
|
||||
prefixLength := part.prefixLength
|
||||
if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {
|
||||
return sidx + prefixLength, eidx + prefixLength
|
||||
if sidx, eidx := pfun(caseSensitive, forward, part.text, pattern); sidx >= 0 {
|
||||
return sidx + prefixLength, eidx + prefixLength, part.trimLength
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
return -1, -1, -1 // math.MaxUint16
|
||||
}
|
||||
|
@@ -1,26 +1,33 @@
|
||||
package fzf
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/junegunn/fzf/src/algo"
|
||||
)
|
||||
|
||||
func TestParseTermsExtended(t *testing.T) {
|
||||
terms := parseTerms(ModeExtended, CaseSmart,
|
||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
||||
if len(terms) != 8 ||
|
||||
terms[0].typ != termFuzzy || terms[0].inv ||
|
||||
terms[1].typ != termExact || terms[1].inv ||
|
||||
terms[2].typ != termPrefix || terms[2].inv ||
|
||||
terms[3].typ != termSuffix || terms[3].inv ||
|
||||
terms[4].typ != termFuzzy || !terms[4].inv ||
|
||||
terms[5].typ != termExact || !terms[5].inv ||
|
||||
terms[6].typ != termPrefix || !terms[6].inv ||
|
||||
terms[7].typ != termSuffix || !terms[7].inv {
|
||||
terms := parseTerms(true, CaseSmart,
|
||||
"| aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | | zzz$ | !ZZZ |")
|
||||
if len(terms) != 9 ||
|
||||
terms[0][0].typ != termFuzzy || terms[0][0].inv ||
|
||||
terms[1][0].typ != termExact || terms[1][0].inv ||
|
||||
terms[2][0].typ != termPrefix || terms[2][0].inv ||
|
||||
terms[3][0].typ != termSuffix || terms[3][0].inv ||
|
||||
terms[4][0].typ != termFuzzy || !terms[4][0].inv ||
|
||||
terms[5][0].typ != termExact || !terms[5][0].inv ||
|
||||
terms[6][0].typ != termPrefix || !terms[6][0].inv ||
|
||||
terms[7][0].typ != termSuffix || !terms[7][0].inv ||
|
||||
terms[7][1].typ != termEqual || terms[7][1].inv ||
|
||||
terms[8][0].typ != termPrefix || terms[8][0].inv ||
|
||||
terms[8][1].typ != termExact || terms[8][1].inv ||
|
||||
terms[8][2].typ != termSuffix || terms[8][2].inv ||
|
||||
terms[8][3].typ != termFuzzy || !terms[8][3].inv {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
for idx, term := range terms {
|
||||
for idx, termSet := range terms[:8] {
|
||||
term := termSet[0]
|
||||
if len(term.text) != 3 {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
@@ -28,26 +35,31 @@ func TestParseTermsExtended(t *testing.T) {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
}
|
||||
for _, term := range terms[8] {
|
||||
if len(term.origText) != 4 {
|
||||
t.Errorf("%s", term)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTermsExtendedExact(t *testing.T) {
|
||||
terms := parseTerms(ModeExtendedExact, CaseSmart,
|
||||
terms := parseTerms(false, CaseSmart,
|
||||
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$")
|
||||
if len(terms) != 8 ||
|
||||
terms[0].typ != termExact || terms[0].inv || len(terms[0].text) != 3 ||
|
||||
terms[1].typ != termExact || terms[1].inv || len(terms[1].text) != 4 ||
|
||||
terms[2].typ != termPrefix || terms[2].inv || len(terms[2].text) != 3 ||
|
||||
terms[3].typ != termSuffix || terms[3].inv || len(terms[3].text) != 3 ||
|
||||
terms[4].typ != termExact || !terms[4].inv || len(terms[4].text) != 3 ||
|
||||
terms[5].typ != termExact || !terms[5].inv || len(terms[5].text) != 4 ||
|
||||
terms[6].typ != termPrefix || !terms[6].inv || len(terms[6].text) != 3 ||
|
||||
terms[7].typ != termSuffix || !terms[7].inv || len(terms[7].text) != 3 {
|
||||
terms[0][0].typ != termExact || terms[0][0].inv || len(terms[0][0].text) != 3 ||
|
||||
terms[1][0].typ != termFuzzy || terms[1][0].inv || len(terms[1][0].text) != 3 ||
|
||||
terms[2][0].typ != termPrefix || terms[2][0].inv || len(terms[2][0].text) != 3 ||
|
||||
terms[3][0].typ != termSuffix || terms[3][0].inv || len(terms[3][0].text) != 3 ||
|
||||
terms[4][0].typ != termExact || !terms[4][0].inv || len(terms[4][0].text) != 3 ||
|
||||
terms[5][0].typ != termFuzzy || !terms[5][0].inv || len(terms[5][0].text) != 3 ||
|
||||
terms[6][0].typ != termPrefix || !terms[6][0].inv || len(terms[6][0].text) != 3 ||
|
||||
terms[7][0].typ != termSuffix || !terms[7][0].inv || len(terms[7][0].text) != 3 {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTermsEmpty(t *testing.T) {
|
||||
terms := parseTerms(ModeExtended, CaseSmart, "' $ ^ !' !^ !$")
|
||||
terms := parseTerms(true, CaseSmart, "' $ ^ !' !^ !$")
|
||||
if len(terms) != 0 {
|
||||
t.Errorf("%s", terms)
|
||||
}
|
||||
@@ -56,29 +68,45 @@ func TestParseTermsEmpty(t *testing.T) {
|
||||
func TestExact(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pattern := BuildPattern(ModeExtended, CaseSmart,
|
||||
[]Range{}, nil, []rune("'abc"))
|
||||
runes := []rune("aabbcc abc")
|
||||
sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)
|
||||
pattern := BuildPattern(true, true, CaseSmart, true,
|
||||
[]Range{}, Delimiter{}, []rune("'abc"))
|
||||
sidx, eidx := algo.ExactMatchNaive(
|
||||
pattern.caseSensitive, pattern.forward, []rune("aabbcc abc"), pattern.termSets[0][0].text)
|
||||
if sidx != 7 || eidx != 10 {
|
||||
t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)
|
||||
t.Errorf("%s / %d / %d", pattern.termSets, sidx, eidx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEqual(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("^AbC$"))
|
||||
|
||||
match := func(str string, sidxExpected int, eidxExpected int) {
|
||||
sidx, eidx := algo.EqualMatch(
|
||||
pattern.caseSensitive, pattern.forward, []rune(str), pattern.termSets[0][0].text)
|
||||
if sidx != sidxExpected || eidx != eidxExpected {
|
||||
t.Errorf("%s / %d / %d", pattern.termSets, sidx, eidx)
|
||||
}
|
||||
}
|
||||
match("ABC", -1, -1)
|
||||
match("AbC", 0, 3)
|
||||
}
|
||||
|
||||
func TestCaseSensitivity(t *testing.T) {
|
||||
defer clearPatternCache()
|
||||
clearPatternCache()
|
||||
pat1 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("abc"))
|
||||
pat1 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
clearPatternCache()
|
||||
pat2 := BuildPattern(ModeFuzzy, CaseSmart, []Range{}, nil, []rune("Abc"))
|
||||
pat2 := BuildPattern(true, false, CaseSmart, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
clearPatternCache()
|
||||
pat3 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("abc"))
|
||||
pat3 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
clearPatternCache()
|
||||
pat4 := BuildPattern(ModeFuzzy, CaseIgnore, []Range{}, nil, []rune("Abc"))
|
||||
pat4 := BuildPattern(true, false, CaseIgnore, true, []Range{}, Delimiter{}, []rune("Abc"))
|
||||
clearPatternCache()
|
||||
pat5 := BuildPattern(ModeFuzzy, CaseRespect, []Range{}, nil, []rune("abc"))
|
||||
pat5 := BuildPattern(true, false, CaseRespect, true, []Range{}, Delimiter{}, []rune("abc"))
|
||||
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 ||
|
||||
string(pat2.text) != "Abc" || pat2.caseSensitive != true ||
|
||||
@@ -91,26 +119,46 @@ func TestCaseSensitivity(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestOrigTextAndTransformed(t *testing.T) {
|
||||
strptr := func(str string) *string {
|
||||
return &str
|
||||
}
|
||||
pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))
|
||||
tokens := Tokenize(strptr("junegunn"), nil)
|
||||
pattern := BuildPattern(true, true, CaseSmart, true, []Range{}, Delimiter{}, []rune("jg"))
|
||||
tokens := Tokenize([]rune("junegunn"), Delimiter{})
|
||||
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{
|
||||
&Item{
|
||||
text: strptr("junegunn"),
|
||||
origText: strptr("junegunn.choi"),
|
||||
text: []rune("junegunn"),
|
||||
origText: &origRunes,
|
||||
transformed: trans},
|
||||
}
|
||||
pattern.mode = mode
|
||||
pattern.extended = extended
|
||||
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].transformed != trans {
|
||||
!reflect.DeepEqual(matches[0].transformed, trans) {
|
||||
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)
|
||||
}
|
||||
|
@@ -11,8 +11,9 @@ import (
|
||||
|
||||
// Reader reads from command or standard input
|
||||
type Reader struct {
|
||||
pusher func(string)
|
||||
pusher func([]byte) bool
|
||||
eventBox *util.EventBox
|
||||
delimNil bool
|
||||
}
|
||||
|
||||
// ReadSource reads data from the default command or from standard input
|
||||
@@ -30,10 +31,25 @@ func (r *Reader) ReadSource() {
|
||||
}
|
||||
|
||||
func (r *Reader) feed(src io.Reader) {
|
||||
if scanner := bufio.NewScanner(src); scanner != nil {
|
||||
for scanner.Scan() {
|
||||
r.pusher(scanner.Text())
|
||||
r.eventBox.Set(EvtReadNew, nil)
|
||||
delim := byte('\n')
|
||||
if r.delimNil {
|
||||
delim = '\000'
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ func TestReadFromCommand(t *testing.T) {
|
||||
strs := []string{}
|
||||
eb := util.NewEventBox()
|
||||
reader := Reader{
|
||||
pusher: func(s string) { strs = append(strs, s) },
|
||||
pusher: func(s []byte) bool { strs = append(strs, string(s)); return true },
|
||||
eventBox: eb}
|
||||
|
||||
// Check EventBox
|
||||
|
745
src/terminal.go
745
src/terminal.go
@@ -4,9 +4,11 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
@@ -31,10 +33,19 @@ type Terminal struct {
|
||||
input []rune
|
||||
multi bool
|
||||
sort bool
|
||||
toggleSort int
|
||||
expect []int
|
||||
pressed int
|
||||
toggleSort bool
|
||||
expect map[int]string
|
||||
keymap map[int]actionType
|
||||
execmap map[int]string
|
||||
pressed string
|
||||
printQuery bool
|
||||
history *History
|
||||
cycle bool
|
||||
header []string
|
||||
header0 []string
|
||||
ansi bool
|
||||
margin [4]string
|
||||
marginInt [4]int
|
||||
count int
|
||||
progress int
|
||||
reading bool
|
||||
@@ -73,6 +84,7 @@ var _runeWidths = make(map[rune]int)
|
||||
const (
|
||||
reqPrompt util.EventType = iota
|
||||
reqInfo
|
||||
reqHeader
|
||||
reqList
|
||||
reqRefresh
|
||||
reqRedraw
|
||||
@@ -80,9 +92,108 @@ const (
|
||||
reqQuit
|
||||
)
|
||||
|
||||
type actionType int
|
||||
|
||||
const (
|
||||
actIgnore actionType = iota
|
||||
actInvalid
|
||||
actRune
|
||||
actMouse
|
||||
actBeginningOfLine
|
||||
actAbort
|
||||
actAccept
|
||||
actBackwardChar
|
||||
actBackwardDeleteChar
|
||||
actBackwardWord
|
||||
actCancel
|
||||
actClearScreen
|
||||
actDeleteChar
|
||||
actDeleteCharEOF
|
||||
actEndOfLine
|
||||
actForwardChar
|
||||
actForwardWord
|
||||
actKillLine
|
||||
actKillWord
|
||||
actUnixLineDiscard
|
||||
actUnixWordRubout
|
||||
actYank
|
||||
actBackwardKillWord
|
||||
actSelectAll
|
||||
actDeselectAll
|
||||
actToggle
|
||||
actToggleAll
|
||||
actToggleDown
|
||||
actToggleUp
|
||||
actDown
|
||||
actUp
|
||||
actPageUp
|
||||
actPageDown
|
||||
actToggleSort
|
||||
actPreviousHistory
|
||||
actNextHistory
|
||||
actExecute
|
||||
actExecuteMulti
|
||||
)
|
||||
|
||||
func defaultKeymap() map[int]actionType {
|
||||
keymap := make(map[int]actionType)
|
||||
keymap[C.Invalid] = actInvalid
|
||||
keymap[C.CtrlA] = actBeginningOfLine
|
||||
keymap[C.CtrlB] = actBackwardChar
|
||||
keymap[C.CtrlC] = actAbort
|
||||
keymap[C.CtrlG] = actAbort
|
||||
keymap[C.CtrlQ] = actAbort
|
||||
keymap[C.ESC] = actAbort
|
||||
keymap[C.CtrlD] = actDeleteCharEOF
|
||||
keymap[C.CtrlE] = actEndOfLine
|
||||
keymap[C.CtrlF] = actForwardChar
|
||||
keymap[C.CtrlH] = actBackwardDeleteChar
|
||||
keymap[C.BSpace] = actBackwardDeleteChar
|
||||
keymap[C.Tab] = actToggleDown
|
||||
keymap[C.BTab] = actToggleUp
|
||||
keymap[C.CtrlJ] = actDown
|
||||
keymap[C.CtrlK] = actUp
|
||||
keymap[C.CtrlL] = actClearScreen
|
||||
keymap[C.CtrlM] = actAccept
|
||||
keymap[C.CtrlN] = actDown
|
||||
keymap[C.CtrlP] = actUp
|
||||
keymap[C.CtrlU] = actUnixLineDiscard
|
||||
keymap[C.CtrlW] = actUnixWordRubout
|
||||
keymap[C.CtrlY] = actYank
|
||||
|
||||
keymap[C.AltB] = actBackwardWord
|
||||
keymap[C.SLeft] = actBackwardWord
|
||||
keymap[C.AltF] = actForwardWord
|
||||
keymap[C.SRight] = actForwardWord
|
||||
keymap[C.AltD] = actKillWord
|
||||
keymap[C.AltBS] = actBackwardKillWord
|
||||
|
||||
keymap[C.Up] = actUp
|
||||
keymap[C.Down] = actDown
|
||||
keymap[C.Left] = actBackwardChar
|
||||
keymap[C.Right] = actForwardChar
|
||||
|
||||
keymap[C.Home] = actBeginningOfLine
|
||||
keymap[C.End] = actEndOfLine
|
||||
keymap[C.Del] = actDeleteChar
|
||||
keymap[C.PgUp] = actPageUp
|
||||
keymap[C.PgDn] = actPageDown
|
||||
|
||||
keymap[C.Rune] = actRune
|
||||
keymap[C.Mouse] = actMouse
|
||||
keymap[C.DoubleClick] = actAccept
|
||||
return keymap
|
||||
}
|
||||
|
||||
// NewTerminal returns new Terminal object
|
||||
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||
input := []rune(opts.Query)
|
||||
var header []string
|
||||
if opts.Reverse {
|
||||
header = opts.Header
|
||||
} else {
|
||||
header = reverseStringArray(opts.Header)
|
||||
}
|
||||
return &Terminal{
|
||||
inlineInfo: opts.InlineInfo,
|
||||
prompt: opts.Prompt,
|
||||
@@ -97,8 +208,18 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||
sort: opts.Sort > 0,
|
||||
toggleSort: opts.ToggleSort,
|
||||
expect: opts.Expect,
|
||||
pressed: 0,
|
||||
keymap: opts.Keymap,
|
||||
execmap: opts.Execmap,
|
||||
pressed: "",
|
||||
printQuery: opts.PrintQuery,
|
||||
history: opts.History,
|
||||
margin: opts.Margin,
|
||||
marginInt: [4]int{0, 0, 0, 0},
|
||||
cycle: opts.Cycle,
|
||||
header: header,
|
||||
header0: header,
|
||||
ansi: opts.Ansi,
|
||||
reading: true,
|
||||
merger: EmptyMerger,
|
||||
selected: make(map[uint32]selectedItem),
|
||||
reqBox: util.NewEventBox(),
|
||||
@@ -130,6 +251,23 @@ func (t *Terminal) UpdateCount(cnt int, final bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func reverseStringArray(input []string) []string {
|
||||
size := len(input)
|
||||
reversed := make([]string, size)
|
||||
for idx, str := range input {
|
||||
reversed[size-idx-1] = str
|
||||
}
|
||||
return reversed
|
||||
}
|
||||
|
||||
// UpdateHeader updates the header
|
||||
func (t *Terminal) UpdateHeader(header []string) {
|
||||
t.mutex.Lock()
|
||||
t.header = append(append([]string{}, t.header0...), header...)
|
||||
t.mutex.Unlock()
|
||||
t.reqBox.Set(reqHeader, nil)
|
||||
}
|
||||
|
||||
// UpdateProgress updates the search progress
|
||||
func (t *Terminal) UpdateProgress(progress float32) {
|
||||
t.mutex.Lock()
|
||||
@@ -153,38 +291,35 @@ func (t *Terminal) UpdateList(merger *Merger) {
|
||||
t.reqBox.Set(reqList, nil)
|
||||
}
|
||||
|
||||
func (t *Terminal) output() {
|
||||
func (t *Terminal) output() bool {
|
||||
if t.printQuery {
|
||||
fmt.Println(string(t.input))
|
||||
}
|
||||
if len(t.expect) > 0 {
|
||||
if t.pressed == 0 {
|
||||
fmt.Println()
|
||||
} else if util.Between(t.pressed, C.AltA, C.AltZ) {
|
||||
fmt.Printf("alt-%c\n", t.pressed+'a'-C.AltA)
|
||||
} else if util.Between(t.pressed, C.F1, C.F4) {
|
||||
fmt.Printf("f%c\n", t.pressed+'1'-C.F1)
|
||||
} else if util.Between(t.pressed, C.CtrlA, C.CtrlZ) {
|
||||
fmt.Printf("ctrl-%c\n", t.pressed+'a'-C.CtrlA)
|
||||
} else {
|
||||
fmt.Printf("%c\n", t.pressed-C.AltZ)
|
||||
}
|
||||
fmt.Println(t.pressed)
|
||||
}
|
||||
if len(t.selected) == 0 {
|
||||
found := len(t.selected) > 0
|
||||
if !found {
|
||||
cnt := t.merger.Length()
|
||||
if cnt > 0 && cnt > t.cy {
|
||||
fmt.Println(t.merger.Get(t.cy).AsString())
|
||||
fmt.Println(t.merger.Get(t.cy).AsString(t.ansi))
|
||||
found = true
|
||||
}
|
||||
} else {
|
||||
sels := make([]selectedItem, 0, len(t.selected))
|
||||
for _, sel := range t.selected {
|
||||
sels = append(sels, sel)
|
||||
}
|
||||
sort.Sort(byTimeOrder(sels))
|
||||
for _, sel := range sels {
|
||||
for _, sel := range t.sortSelected() {
|
||||
fmt.Println(*sel.text)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (t *Terminal) sortSelected() []selectedItem {
|
||||
sels := make([]selectedItem, 0, len(t.selected))
|
||||
for _, sel := range t.selected {
|
||||
sels = append(sels, sel)
|
||||
}
|
||||
sort.Sort(byTimeOrder(sels))
|
||||
return sels
|
||||
}
|
||||
|
||||
func runeWidth(r rune, prefixWidth int) int {
|
||||
@@ -207,10 +342,50 @@ func displayWidth(runes []rune) int {
|
||||
return l
|
||||
}
|
||||
|
||||
const minWidth = 16
|
||||
const minHeight = 4
|
||||
|
||||
func (t *Terminal) calculateMargins() {
|
||||
screenWidth := C.MaxX()
|
||||
screenHeight := C.MaxY()
|
||||
for idx, str := range t.margin {
|
||||
if str == "0" {
|
||||
t.marginInt[idx] = 0
|
||||
} else if strings.HasSuffix(str, "%") {
|
||||
num, _ := strconv.ParseFloat(str[:len(str)-1], 64)
|
||||
var val float64
|
||||
if idx%2 == 0 {
|
||||
val = float64(screenHeight)
|
||||
} else {
|
||||
val = float64(screenWidth)
|
||||
}
|
||||
t.marginInt[idx] = int(val * num * 0.01)
|
||||
} else {
|
||||
num, _ := strconv.Atoi(str)
|
||||
t.marginInt[idx] = num
|
||||
}
|
||||
}
|
||||
adjust := func(idx1 int, idx2 int, max int, min int) {
|
||||
if max >= min {
|
||||
margin := t.marginInt[idx1] + t.marginInt[idx2]
|
||||
if max-margin < min {
|
||||
desired := max - min
|
||||
t.marginInt[idx1] = desired * t.marginInt[idx1] / margin
|
||||
t.marginInt[idx2] = desired * t.marginInt[idx2] / margin
|
||||
}
|
||||
}
|
||||
}
|
||||
adjust(1, 3, screenWidth, minWidth)
|
||||
adjust(0, 2, screenHeight, minHeight)
|
||||
}
|
||||
|
||||
func (t *Terminal) move(y int, x int, clear bool) {
|
||||
x += t.marginInt[3]
|
||||
maxy := C.MaxY()
|
||||
if !t.reverse {
|
||||
y = maxy - y - 1
|
||||
y = maxy - y - 1 - t.marginInt[2]
|
||||
} else {
|
||||
y += t.marginInt[0]
|
||||
}
|
||||
|
||||
if clear {
|
||||
@@ -221,7 +396,7 @@ func (t *Terminal) move(y int, x int, clear bool) {
|
||||
}
|
||||
|
||||
func (t *Terminal) placeCursor() {
|
||||
t.move(0, len(t.prompt)+displayWidth(t.input[:t.cx]), false)
|
||||
t.move(0, displayWidth([]rune(t.prompt))+displayWidth(t.input[:t.cx]), false)
|
||||
}
|
||||
|
||||
func (t *Terminal) printPrompt() {
|
||||
@@ -232,7 +407,7 @@ func (t *Terminal) printPrompt() {
|
||||
|
||||
func (t *Terminal) printInfo() {
|
||||
if t.inlineInfo {
|
||||
t.move(0, len(t.prompt)+displayWidth(t.input)+1, true)
|
||||
t.move(0, displayWidth([]rune(t.prompt))+displayWidth(t.input)+1, true)
|
||||
if t.reading {
|
||||
C.CPrint(C.ColSpinner, true, " < ")
|
||||
} else {
|
||||
@@ -249,7 +424,7 @@ func (t *Terminal) printInfo() {
|
||||
}
|
||||
|
||||
output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)
|
||||
if t.toggleSort > 0 {
|
||||
if t.toggleSort {
|
||||
if t.sort {
|
||||
output += "/S"
|
||||
} else {
|
||||
@@ -265,17 +440,46 @@ func (t *Terminal) printInfo() {
|
||||
C.CPrint(C.ColInfo, false, output)
|
||||
}
|
||||
|
||||
func (t *Terminal) maxHeight() int {
|
||||
return C.MaxY() - t.marginInt[0] - t.marginInt[2]
|
||||
}
|
||||
|
||||
func (t *Terminal) printHeader() {
|
||||
if len(t.header) == 0 {
|
||||
return
|
||||
}
|
||||
max := t.maxHeight()
|
||||
var state *ansiState
|
||||
for idx, lineStr := range t.header {
|
||||
line := idx + 2
|
||||
if t.inlineInfo {
|
||||
line--
|
||||
}
|
||||
if line >= max {
|
||||
continue
|
||||
}
|
||||
trimmed, colors, newState := extractColor(lineStr, state)
|
||||
state = newState
|
||||
item := &Item{
|
||||
text: []rune(trimmed),
|
||||
index: 0,
|
||||
colors: colors,
|
||||
rank: Rank{0, 0, 0}}
|
||||
|
||||
t.move(line, 2, true)
|
||||
t.printHighlighted(item, false, C.ColHeader, 0, false)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Terminal) printList() {
|
||||
t.constrain()
|
||||
|
||||
maxy := t.maxItems()
|
||||
count := t.merger.Length() - t.offset
|
||||
for i := 0; i < maxy; i++ {
|
||||
var line int
|
||||
line := i + 2 + len(t.header)
|
||||
if t.inlineInfo {
|
||||
line = i + 1
|
||||
} else {
|
||||
line = i + 2
|
||||
line--
|
||||
}
|
||||
t.move(line, 0, true)
|
||||
if i < count {
|
||||
@@ -289,7 +493,7 @@ func (t *Terminal) printItem(item *Item, current bool) {
|
||||
if current {
|
||||
C.CPrint(C.ColCursor, true, ">")
|
||||
if selected {
|
||||
C.CPrint(C.ColCurrent, true, ">")
|
||||
C.CPrint(C.ColSelected, true, ">")
|
||||
} else {
|
||||
C.CPrint(C.ColCurrent, true, " ")
|
||||
}
|
||||
@@ -350,9 +554,10 @@ func (t *Terminal) printHighlighted(item *Item, bold bool, col1 int, col2 int, c
|
||||
}
|
||||
|
||||
// Overflow
|
||||
text := []rune(*item.text)
|
||||
text := make([]rune, len(item.text))
|
||||
copy(text, item.text)
|
||||
offsets := item.colorOffsets(col2, bold, current)
|
||||
maxWidth := C.MaxX() - 3
|
||||
maxWidth := C.MaxX() - 3 - t.marginInt[1] - t.marginInt[3]
|
||||
fullWidth := displayWidth(text)
|
||||
if fullWidth > maxWidth {
|
||||
if t.hscroll {
|
||||
@@ -435,9 +640,11 @@ func processTabs(runes []rune, prefixWidth int) (string, int) {
|
||||
}
|
||||
|
||||
func (t *Terminal) printAll() {
|
||||
t.calculateMargins()
|
||||
t.printList()
|
||||
t.printInfo()
|
||||
t.printPrompt()
|
||||
t.printInfo()
|
||||
t.printHeader()
|
||||
}
|
||||
|
||||
func (t *Terminal) refresh() {
|
||||
@@ -496,21 +703,30 @@ func keyMatch(key int, event C.Event) bool {
|
||||
return event.Type == key || event.Type == C.Rune && int(event.Char) == key-C.AltZ
|
||||
}
|
||||
|
||||
func quoteEntry(entry string) string {
|
||||
return fmt.Sprintf("%q", entry)
|
||||
}
|
||||
|
||||
func executeCommand(template string, replacement string) {
|
||||
command := strings.Replace(template, "{}", replacement, -1)
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
C.Endwin()
|
||||
cmd.Run()
|
||||
C.Refresh()
|
||||
}
|
||||
|
||||
// Loop is called to start Terminal I/O
|
||||
func (t *Terminal) Loop() {
|
||||
<-t.startChan
|
||||
{ // Late initialization
|
||||
t.mutex.Lock()
|
||||
t.initFunc()
|
||||
t.printPrompt()
|
||||
t.placeCursor()
|
||||
C.Refresh()
|
||||
t.printInfo()
|
||||
t.mutex.Unlock()
|
||||
intChan := make(chan os.Signal, 1)
|
||||
signal.Notify(intChan, os.Interrupt, os.Kill)
|
||||
go func() {
|
||||
timer := time.NewTimer(initialDelay)
|
||||
<-timer.C
|
||||
t.reqBox.Set(reqRefresh, nil)
|
||||
<-intChan
|
||||
t.reqBox.Set(reqQuit, nil)
|
||||
}()
|
||||
|
||||
resizeChan := make(chan os.Signal, 1)
|
||||
@@ -521,6 +737,42 @@ func (t *Terminal) Loop() {
|
||||
t.reqBox.Set(reqRedraw, nil)
|
||||
}
|
||||
}()
|
||||
|
||||
t.mutex.Lock()
|
||||
t.initFunc()
|
||||
t.calculateMargins()
|
||||
t.printPrompt()
|
||||
t.placeCursor()
|
||||
C.Refresh()
|
||||
t.printInfo()
|
||||
t.printHeader()
|
||||
t.mutex.Unlock()
|
||||
go func() {
|
||||
timer := time.NewTimer(initialDelay)
|
||||
<-timer.C
|
||||
t.reqBox.Set(reqRefresh, nil)
|
||||
}()
|
||||
|
||||
// Keep the spinner spinning
|
||||
go func() {
|
||||
for {
|
||||
t.mutex.Lock()
|
||||
reading := t.reading
|
||||
t.mutex.Unlock()
|
||||
if !reading {
|
||||
break
|
||||
}
|
||||
time.Sleep(spinnerDuration)
|
||||
t.reqBox.Set(reqInfo, nil)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
exit := func(code int) {
|
||||
if code <= exitNoMatch && t.history != nil {
|
||||
t.history.append(string(t.input))
|
||||
}
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
go func() {
|
||||
@@ -539,6 +791,8 @@ func (t *Terminal) Loop() {
|
||||
t.printInfo()
|
||||
case reqList:
|
||||
t.printList()
|
||||
case reqHeader:
|
||||
t.printHeader()
|
||||
case reqRefresh:
|
||||
t.suppress = false
|
||||
case reqRedraw:
|
||||
@@ -548,11 +802,13 @@ func (t *Terminal) Loop() {
|
||||
t.printAll()
|
||||
case reqClose:
|
||||
C.Close()
|
||||
t.output()
|
||||
os.Exit(0)
|
||||
if t.output() {
|
||||
exit(exitOk)
|
||||
}
|
||||
exit(exitNoMatch)
|
||||
case reqQuit:
|
||||
C.Close()
|
||||
os.Exit(1)
|
||||
exit(exitInterrupt)
|
||||
}
|
||||
}
|
||||
t.placeCursor()
|
||||
@@ -577,166 +833,256 @@ func (t *Terminal) Loop() {
|
||||
}
|
||||
}
|
||||
}
|
||||
selectItem := func(item *Item) bool {
|
||||
if _, found := t.selected[item.index]; !found {
|
||||
t.selected[item.index] = selectedItem{time.Now(), item.StringPtr(t.ansi)}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
toggleY := func(y int) {
|
||||
item := t.merger.Get(y)
|
||||
if !selectItem(item) {
|
||||
delete(t.selected, item.index)
|
||||
}
|
||||
}
|
||||
toggle := func() {
|
||||
if t.cy < t.merger.Length() {
|
||||
item := t.merger.Get(t.cy)
|
||||
if _, found := t.selected[item.index]; !found {
|
||||
var strptr *string
|
||||
if item.origText != nil {
|
||||
strptr = item.origText
|
||||
} else {
|
||||
strptr = item.text
|
||||
}
|
||||
t.selected[item.index] = selectedItem{time.Now(), strptr}
|
||||
} else {
|
||||
delete(t.selected, item.index)
|
||||
}
|
||||
toggleY(t.cy)
|
||||
req(reqInfo)
|
||||
}
|
||||
}
|
||||
for _, key := range t.expect {
|
||||
for key, ret := range t.expect {
|
||||
if keyMatch(key, event) {
|
||||
t.pressed = key
|
||||
t.pressed = ret
|
||||
req(reqClose)
|
||||
break
|
||||
}
|
||||
}
|
||||
if t.toggleSort > 0 {
|
||||
if keyMatch(t.toggleSort, event) {
|
||||
|
||||
var doAction func(actionType, int) bool
|
||||
doAction = func(action actionType, mapkey int) bool {
|
||||
switch action {
|
||||
case actIgnore:
|
||||
case actExecute:
|
||||
if t.cy >= 0 && t.cy < t.merger.Length() {
|
||||
item := t.merger.Get(t.cy)
|
||||
executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))
|
||||
}
|
||||
case actExecuteMulti:
|
||||
if len(t.selected) > 0 {
|
||||
sels := make([]string, len(t.selected))
|
||||
for i, sel := range t.sortSelected() {
|
||||
sels[i] = quoteEntry(*sel.text)
|
||||
}
|
||||
executeCommand(t.execmap[mapkey], strings.Join(sels, " "))
|
||||
} else {
|
||||
return doAction(actExecute, mapkey)
|
||||
}
|
||||
case actInvalid:
|
||||
t.mutex.Unlock()
|
||||
return false
|
||||
case actToggleSort:
|
||||
t.sort = !t.sort
|
||||
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||
t.mutex.Unlock()
|
||||
continue
|
||||
}
|
||||
}
|
||||
switch event.Type {
|
||||
case C.Invalid:
|
||||
t.mutex.Unlock()
|
||||
continue
|
||||
case C.CtrlA:
|
||||
t.cx = 0
|
||||
case C.CtrlB:
|
||||
if t.cx > 0 {
|
||||
t.cx--
|
||||
}
|
||||
case C.CtrlC, C.CtrlG, C.CtrlQ, C.ESC:
|
||||
req(reqQuit)
|
||||
case C.CtrlD:
|
||||
if !t.delChar() && t.cx == 0 {
|
||||
return false
|
||||
case actBeginningOfLine:
|
||||
t.cx = 0
|
||||
case actBackwardChar:
|
||||
if t.cx > 0 {
|
||||
t.cx--
|
||||
}
|
||||
case actAbort:
|
||||
req(reqQuit)
|
||||
}
|
||||
case C.CtrlE:
|
||||
t.cx = len(t.input)
|
||||
case C.CtrlF:
|
||||
if t.cx < len(t.input) {
|
||||
t.cx++
|
||||
}
|
||||
case C.CtrlH:
|
||||
if t.cx > 0 {
|
||||
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
||||
t.cx--
|
||||
}
|
||||
case C.Tab:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
case actDeleteChar:
|
||||
t.delChar()
|
||||
case actDeleteCharEOF:
|
||||
if !t.delChar() && t.cx == 0 {
|
||||
req(reqQuit)
|
||||
}
|
||||
case actEndOfLine:
|
||||
t.cx = len(t.input)
|
||||
case actCancel:
|
||||
if len(t.input) == 0 {
|
||||
req(reqQuit)
|
||||
} else {
|
||||
t.yanked = t.input
|
||||
t.input = []rune{}
|
||||
t.cx = 0
|
||||
}
|
||||
case actForwardChar:
|
||||
if t.cx < len(t.input) {
|
||||
t.cx++
|
||||
}
|
||||
case actBackwardDeleteChar:
|
||||
if t.cx > 0 {
|
||||
t.input = append(t.input[:t.cx-1], t.input[t.cx:]...)
|
||||
t.cx--
|
||||
}
|
||||
case actSelectAll:
|
||||
if t.multi {
|
||||
for i := 0; i < t.merger.Length(); i++ {
|
||||
item := t.merger.Get(i)
|
||||
selectItem(item)
|
||||
}
|
||||
req(reqList, reqInfo)
|
||||
}
|
||||
case actDeselectAll:
|
||||
if t.multi {
|
||||
for i := 0; i < t.merger.Length(); i++ {
|
||||
item := t.merger.Get(i)
|
||||
delete(t.selected, item.index)
|
||||
}
|
||||
req(reqList, reqInfo)
|
||||
}
|
||||
case actToggle:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleAll:
|
||||
if t.multi {
|
||||
for i := 0; i < t.merger.Length(); i++ {
|
||||
toggleY(i)
|
||||
}
|
||||
req(reqList, reqInfo)
|
||||
}
|
||||
case actToggleDown:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
}
|
||||
case actToggleUp:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
}
|
||||
case actDown:
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
}
|
||||
case C.BTab:
|
||||
if t.multi && t.merger.Length() > 0 {
|
||||
toggle()
|
||||
case actUp:
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
}
|
||||
case C.CtrlJ, C.CtrlN:
|
||||
t.vmove(-1)
|
||||
req(reqList)
|
||||
case C.CtrlK, C.CtrlP:
|
||||
t.vmove(1)
|
||||
req(reqList)
|
||||
case C.CtrlM:
|
||||
req(reqClose)
|
||||
case C.CtrlL:
|
||||
req(reqRedraw)
|
||||
case C.CtrlU:
|
||||
if t.cx > 0 {
|
||||
t.yanked = copySlice(t.input[:t.cx])
|
||||
t.input = t.input[t.cx:]
|
||||
t.cx = 0
|
||||
}
|
||||
case C.CtrlW:
|
||||
if t.cx > 0 {
|
||||
t.rubout("\\s\\S")
|
||||
}
|
||||
case C.AltBS:
|
||||
if t.cx > 0 {
|
||||
t.rubout("[^[:alnum:]][[:alnum:]]")
|
||||
}
|
||||
case C.CtrlY:
|
||||
suffix := copySlice(t.input[t.cx:])
|
||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||
t.cx += len(t.yanked)
|
||||
case C.Del:
|
||||
t.delChar()
|
||||
case C.PgUp:
|
||||
t.vmove(t.maxItems() - 1)
|
||||
req(reqList)
|
||||
case C.PgDn:
|
||||
t.vmove(-(t.maxItems() - 1))
|
||||
req(reqList)
|
||||
case C.AltB:
|
||||
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
||||
case C.AltF:
|
||||
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
case C.AltD:
|
||||
ncx := t.cx +
|
||||
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
if ncx > t.cx {
|
||||
t.yanked = copySlice(t.input[t.cx:ncx])
|
||||
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
||||
}
|
||||
case C.Rune:
|
||||
prefix := copySlice(t.input[:t.cx])
|
||||
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
||||
t.cx++
|
||||
case C.Mouse:
|
||||
me := event.MouseEvent
|
||||
mx, my := util.Constrain(me.X-len(t.prompt), 0, len(t.input)), me.Y
|
||||
if !t.reverse {
|
||||
my = C.MaxY() - my - 1
|
||||
}
|
||||
min := 2
|
||||
if t.inlineInfo {
|
||||
min = 1
|
||||
}
|
||||
if me.S != 0 {
|
||||
// Scroll
|
||||
if t.merger.Length() > 0 {
|
||||
if t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
t.vmove(me.S)
|
||||
req(reqList)
|
||||
case actAccept:
|
||||
req(reqClose)
|
||||
case actClearScreen:
|
||||
req(reqRedraw)
|
||||
case actUnixLineDiscard:
|
||||
if t.cx > 0 {
|
||||
t.yanked = copySlice(t.input[:t.cx])
|
||||
t.input = t.input[t.cx:]
|
||||
t.cx = 0
|
||||
}
|
||||
} else if me.Double {
|
||||
// Double-click
|
||||
if my >= min {
|
||||
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
||||
req(reqClose)
|
||||
case actUnixWordRubout:
|
||||
if t.cx > 0 {
|
||||
t.rubout("\\s\\S")
|
||||
}
|
||||
case actBackwardKillWord:
|
||||
if t.cx > 0 {
|
||||
t.rubout("[^[:alnum:]][[:alnum:]]")
|
||||
}
|
||||
case actYank:
|
||||
suffix := copySlice(t.input[t.cx:])
|
||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||
t.cx += len(t.yanked)
|
||||
case actPageUp:
|
||||
t.vmove(t.maxItems() - 1)
|
||||
req(reqList)
|
||||
case actPageDown:
|
||||
t.vmove(-(t.maxItems() - 1))
|
||||
req(reqList)
|
||||
case actBackwardWord:
|
||||
t.cx = findLastMatch("[^[:alnum:]][[:alnum:]]", string(t.input[:t.cx])) + 1
|
||||
case actForwardWord:
|
||||
t.cx += findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
case actKillWord:
|
||||
ncx := t.cx +
|
||||
findFirstMatch("[[:alnum:]][^[:alnum:]]|(.$)", string(t.input[t.cx:])) + 1
|
||||
if ncx > t.cx {
|
||||
t.yanked = copySlice(t.input[t.cx:ncx])
|
||||
t.input = append(t.input[:t.cx], t.input[ncx:]...)
|
||||
}
|
||||
case actKillLine:
|
||||
if t.cx < len(t.input) {
|
||||
t.yanked = copySlice(t.input[t.cx:])
|
||||
t.input = t.input[:t.cx]
|
||||
}
|
||||
case actRune:
|
||||
prefix := copySlice(t.input[:t.cx])
|
||||
t.input = append(append(prefix, event.Char), t.input[t.cx:]...)
|
||||
t.cx++
|
||||
case actPreviousHistory:
|
||||
if t.history != nil {
|
||||
t.history.override(string(t.input))
|
||||
t.input = []rune(t.history.previous())
|
||||
t.cx = len(t.input)
|
||||
}
|
||||
case actNextHistory:
|
||||
if t.history != nil {
|
||||
t.history.override(string(t.input))
|
||||
t.input = []rune(t.history.next())
|
||||
t.cx = len(t.input)
|
||||
}
|
||||
case actMouse:
|
||||
me := event.MouseEvent
|
||||
mx, my := me.X, me.Y
|
||||
if me.S != 0 {
|
||||
// Scroll
|
||||
if t.merger.Length() > 0 {
|
||||
if t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
t.vmove(me.S)
|
||||
req(reqList)
|
||||
}
|
||||
} else if mx >= t.marginInt[3] && mx < C.MaxX()-t.marginInt[1] &&
|
||||
my >= t.marginInt[0] && my < C.MaxY()-t.marginInt[2] {
|
||||
mx -= t.marginInt[3]
|
||||
my -= t.marginInt[0]
|
||||
mx = util.Constrain(mx-displayWidth([]rune(t.prompt)), 0, len(t.input))
|
||||
if !t.reverse {
|
||||
my = t.maxHeight() - my - 1
|
||||
}
|
||||
min := 2 + len(t.header)
|
||||
if t.inlineInfo {
|
||||
min--
|
||||
}
|
||||
if me.Double {
|
||||
// Double-click
|
||||
if my >= min {
|
||||
if t.vset(t.offset+my-min) && t.cy < t.merger.Length() {
|
||||
return doAction(t.keymap[C.DoubleClick], C.DoubleClick)
|
||||
}
|
||||
}
|
||||
} else if me.Down {
|
||||
if my == 0 && mx >= 0 {
|
||||
// Prompt
|
||||
t.cx = mx
|
||||
} else if my >= min {
|
||||
// List
|
||||
if t.vset(t.offset+my-min) && t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
req(reqList)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if me.Down {
|
||||
if my == 0 && mx >= 0 {
|
||||
// Prompt
|
||||
t.cx = mx
|
||||
} else if my >= min {
|
||||
// List
|
||||
if t.vset(t.offset+my-min) && t.multi && me.Mod {
|
||||
toggle()
|
||||
}
|
||||
req(reqList)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
action := t.keymap[event.Type]
|
||||
mapkey := event.Type
|
||||
if event.Type == C.Rune {
|
||||
mapkey = int(event.Char) + int(C.AltZ)
|
||||
if act, prs := t.keymap[mapkey]; prs {
|
||||
action = act
|
||||
}
|
||||
}
|
||||
if !doAction(action, mapkey) {
|
||||
continue
|
||||
}
|
||||
changed := string(previousInput) != string(t.input)
|
||||
t.mutex.Unlock() // Must be unlocked before touching reqBox
|
||||
@@ -770,14 +1116,27 @@ func (t *Terminal) constrain() {
|
||||
t.offset = util.Max(0, count-height)
|
||||
t.cy = util.Constrain(t.offset+diffpos, 0, count-1)
|
||||
}
|
||||
t.offset = util.Max(0, t.offset)
|
||||
}
|
||||
|
||||
func (t *Terminal) vmove(o int) {
|
||||
if t.reverse {
|
||||
t.vset(t.cy - o)
|
||||
} else {
|
||||
t.vset(t.cy + o)
|
||||
o *= -1
|
||||
}
|
||||
dest := t.cy + o
|
||||
if t.cycle {
|
||||
max := t.merger.Length() - 1
|
||||
if dest > max {
|
||||
if t.cy == max {
|
||||
dest = 0
|
||||
}
|
||||
} else if dest < 0 {
|
||||
if t.cy == 0 {
|
||||
dest = max
|
||||
}
|
||||
}
|
||||
}
|
||||
t.vset(dest)
|
||||
}
|
||||
|
||||
func (t *Terminal) vset(o int) bool {
|
||||
@@ -786,9 +1145,9 @@ func (t *Terminal) vset(o int) bool {
|
||||
}
|
||||
|
||||
func (t *Terminal) maxItems() int {
|
||||
max := t.maxHeight() - 2 - len(t.header)
|
||||
if t.inlineInfo {
|
||||
return C.MaxY() - 1
|
||||
} else {
|
||||
return C.MaxY() - 2
|
||||
max++
|
||||
}
|
||||
return util.Max(max, 0)
|
||||
}
|
||||
|
@@ -18,8 +18,15 @@ type Range struct {
|
||||
|
||||
// Token contains the tokenized part of the strings and its prefix length
|
||||
type Token struct {
|
||||
text *[]rune
|
||||
text []rune
|
||||
prefixLength int
|
||||
trimLength int
|
||||
}
|
||||
|
||||
// Delimiter for tokenizing the input
|
||||
type Delimiter struct {
|
||||
regex *regexp.Regexp
|
||||
str *string
|
||||
}
|
||||
|
||||
func newRange(begin int, end int) Range {
|
||||
@@ -68,16 +75,15 @@ func ParseRange(str *string) (Range, bool) {
|
||||
return newRange(n, n), true
|
||||
}
|
||||
|
||||
func withPrefixLengths(tokens []string, begin int) []Token {
|
||||
func withPrefixLengths(tokens [][]rune, begin int) []Token {
|
||||
ret := make([]Token, len(tokens))
|
||||
|
||||
prefixLength := begin
|
||||
for idx, token := range tokens {
|
||||
// Need to define a new local variable instead of the reused token to take
|
||||
// the pointer to it
|
||||
runes := []rune(token)
|
||||
ret[idx] = Token{text: &runes, prefixLength: prefixLength}
|
||||
prefixLength += len([]rune(token))
|
||||
ret[idx] = Token{token, prefixLength, util.TrimLen(token)}
|
||||
prefixLength += len(token)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
@@ -88,13 +94,13 @@ const (
|
||||
awkWhite
|
||||
)
|
||||
|
||||
func awkTokenizer(input *string) ([]string, int) {
|
||||
func awkTokenizer(input []rune) ([][]rune, int) {
|
||||
// 9, 32
|
||||
ret := []string{}
|
||||
ret := [][]rune{}
|
||||
str := []rune{}
|
||||
prefixLength := 0
|
||||
state := awkNil
|
||||
for _, r := range []rune(*input) {
|
||||
for _, r := range input {
|
||||
white := r == 9 || r == 32
|
||||
switch state {
|
||||
case awkNil:
|
||||
@@ -113,47 +119,69 @@ func awkTokenizer(input *string) ([]string, int) {
|
||||
if white {
|
||||
str = append(str, r)
|
||||
} else {
|
||||
ret = append(ret, string(str))
|
||||
ret = append(ret, str)
|
||||
state = awkBlack
|
||||
str = []rune{r}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(str) > 0 {
|
||||
ret = append(ret, string(str))
|
||||
ret = append(ret, str)
|
||||
}
|
||||
return ret, prefixLength
|
||||
}
|
||||
|
||||
// Tokenize tokenizes the given string with the delimiter
|
||||
func Tokenize(str *string, delimiter *regexp.Regexp) []Token {
|
||||
if delimiter == nil {
|
||||
func Tokenize(runes []rune, delimiter Delimiter) []Token {
|
||||
if delimiter.str == nil && delimiter.regex == nil {
|
||||
// AWK-style (\S+\s*)
|
||||
tokens, prefixLength := awkTokenizer(str)
|
||||
tokens, prefixLength := awkTokenizer(runes)
|
||||
return withPrefixLengths(tokens, prefixLength)
|
||||
}
|
||||
tokens := delimiter.FindAllString(*str, -1)
|
||||
return withPrefixLengths(tokens, 0)
|
||||
}
|
||||
|
||||
func joinTokens(tokens *[]Token) *string {
|
||||
ret := ""
|
||||
for _, token := range *tokens {
|
||||
ret += string(*token.text)
|
||||
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:]
|
||||
}
|
||||
}
|
||||
return &ret
|
||||
asRunes := make([][]rune, len(tokens))
|
||||
for i, token := range tokens {
|
||||
asRunes[i] = []rune(token)
|
||||
}
|
||||
return withPrefixLengths(asRunes, 0)
|
||||
}
|
||||
|
||||
func joinTokensAsRunes(tokens *[]Token) *[]rune {
|
||||
func joinTokens(tokens []Token) []rune {
|
||||
ret := []rune{}
|
||||
for _, token := range *tokens {
|
||||
ret = append(ret, *token.text...)
|
||||
for _, token := range tokens {
|
||||
ret = append(ret, token.text...)
|
||||
}
|
||||
return &ret
|
||||
return ret
|
||||
}
|
||||
|
||||
func joinTokensAsRunes(tokens []Token) []rune {
|
||||
ret := []rune{}
|
||||
for _, token := range tokens {
|
||||
ret = append(ret, token.text...)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// Transform is used to transform the input when --with-nth option is given
|
||||
func Transform(tokens []Token, withNth []Range) *[]Token {
|
||||
func Transform(tokens []Token, withNth []Range) []Token {
|
||||
transTokens := make([]Token, len(withNth))
|
||||
numTokens := len(tokens)
|
||||
for idx, r := range withNth {
|
||||
@@ -162,14 +190,14 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
||||
if r.begin == r.end {
|
||||
idx := r.begin
|
||||
if idx == rangeEllipsis {
|
||||
part = append(part, *joinTokensAsRunes(&tokens)...)
|
||||
part = append(part, joinTokensAsRunes(tokens)...)
|
||||
} else {
|
||||
if idx < 0 {
|
||||
idx += numTokens + 1
|
||||
}
|
||||
if idx >= 1 && idx <= numTokens {
|
||||
minIdx = idx - 1
|
||||
part = append(part, *tokens[idx-1].text...)
|
||||
part = append(part, tokens[idx-1].text...)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -196,7 +224,7 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
||||
minIdx = util.Max(0, begin-1)
|
||||
for idx := begin; idx <= end; idx++ {
|
||||
if idx >= 1 && idx <= numTokens {
|
||||
part = append(part, *tokens[idx-1].text...)
|
||||
part = append(part, tokens[idx-1].text...)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,7 +234,7 @@ func Transform(tokens []Token, withNth []Range) *[]Token {
|
||||
} else {
|
||||
prefixLength = 0
|
||||
}
|
||||
transTokens[idx] = Token{&part, prefixLength}
|
||||
transTokens[idx] = Token{part, prefixLength, util.TrimLen(part)}
|
||||
}
|
||||
return &transTokens
|
||||
return transTokens
|
||||
}
|
||||
|
@@ -43,14 +43,23 @@ func TestParseRange(t *testing.T) {
|
||||
func TestTokenize(t *testing.T) {
|
||||
// AWK-style
|
||||
input := " abc: def: ghi "
|
||||
tokens := Tokenize(&input, nil)
|
||||
if string(*tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {
|
||||
tokens := Tokenize([]rune(input), Delimiter{})
|
||||
if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 || tokens[0].trimLength != 4 {
|
||||
t.Errorf("%s", tokens)
|
||||
}
|
||||
|
||||
// With delimiter
|
||||
tokens = Tokenize(&input, delimiterRegexp(":"))
|
||||
if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {
|
||||
tokens = Tokenize([]rune(input), delimiterRegexp(":"))
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -58,39 +67,39 @@ func TestTokenize(t *testing.T) {
|
||||
func TestTransform(t *testing.T) {
|
||||
input := " abc: def: ghi: jkl"
|
||||
{
|
||||
tokens := Tokenize(&input, nil)
|
||||
tokens := Tokenize([]rune(input), Delimiter{})
|
||||
{
|
||||
ranges := splitNth("1,2,3")
|
||||
tx := Transform(tokens, ranges)
|
||||
if *joinTokens(tx) != "abc: def: ghi: " {
|
||||
t.Errorf("%s", *tx)
|
||||
if string(joinTokens(tx)) != "abc: def: ghi: " {
|
||||
t.Errorf("%s", tx)
|
||||
}
|
||||
}
|
||||
{
|
||||
ranges := splitNth("1..2,3,2..,1")
|
||||
tx := Transform(tokens, ranges)
|
||||
if *joinTokens(tx) != "abc: def: ghi: def: ghi: jklabc: " ||
|
||||
len(*tx) != 4 ||
|
||||
string(*(*tx)[0].text) != "abc: def: " || (*tx)[0].prefixLength != 2 ||
|
||||
string(*(*tx)[1].text) != "ghi: " || (*tx)[1].prefixLength != 14 ||
|
||||
string(*(*tx)[2].text) != "def: ghi: jkl" || (*tx)[2].prefixLength != 8 ||
|
||||
string(*(*tx)[3].text) != "abc: " || (*tx)[3].prefixLength != 2 {
|
||||
t.Errorf("%s", *tx)
|
||||
if string(joinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||
|
||||
len(tx) != 4 ||
|
||||
string(tx[0].text) != "abc: def: " || tx[0].prefixLength != 2 ||
|
||||
string(tx[1].text) != "ghi: " || tx[1].prefixLength != 14 ||
|
||||
string(tx[2].text) != "def: ghi: jkl" || tx[2].prefixLength != 8 ||
|
||||
string(tx[3].text) != "abc: " || tx[3].prefixLength != 2 {
|
||||
t.Errorf("%s", tx)
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
tokens := Tokenize(&input, delimiterRegexp(":"))
|
||||
tokens := Tokenize([]rune(input), delimiterRegexp(":"))
|
||||
{
|
||||
ranges := splitNth("1..2,3,2..,1")
|
||||
tx := Transform(tokens, ranges)
|
||||
if *joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||
|
||||
len(*tx) != 4 ||
|
||||
string(*(*tx)[0].text) != " abc: def:" || (*tx)[0].prefixLength != 0 ||
|
||||
string(*(*tx)[1].text) != " ghi:" || (*tx)[1].prefixLength != 12 ||
|
||||
string(*(*tx)[2].text) != " def: ghi: jkl" || (*tx)[2].prefixLength != 6 ||
|
||||
string(*(*tx)[3].text) != " abc:" || (*tx)[3].prefixLength != 0 {
|
||||
t.Errorf("%s", *tx)
|
||||
if string(joinTokens(tx)) != " abc: def: ghi: def: ghi: jkl abc:" ||
|
||||
len(tx) != 4 ||
|
||||
string(tx[0].text) != " abc: def:" || tx[0].prefixLength != 0 ||
|
||||
string(tx[1].text) != " ghi:" || tx[1].prefixLength != 12 ||
|
||||
string(tx[2].text) != " def: ghi: jkl" || tx[2].prefixLength != 6 ||
|
||||
string(tx[3].text) != " abc:" || tx[3].prefixLength != 0 {
|
||||
t.Errorf("%s", tx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -6,6 +6,7 @@ import "C"
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Max returns the largest integer
|
||||
@@ -19,7 +20,7 @@ func Max(first int, items ...int) int {
|
||||
return max
|
||||
}
|
||||
|
||||
// Max32 returns the smallest 32-bit integer
|
||||
// Min32 returns the smallest 32-bit integer
|
||||
func Min32(first int32, second int32) int32 {
|
||||
if first <= second {
|
||||
return first
|
||||
@@ -69,22 +70,59 @@ func DurWithin(
|
||||
return val
|
||||
}
|
||||
|
||||
func Between(val int, min int, max int) bool {
|
||||
return val >= min && val <= max
|
||||
}
|
||||
|
||||
// IsTty returns true is stdin is a terminal
|
||||
func IsTty() bool {
|
||||
return int(C.isatty(C.int(os.Stdin.Fd()))) != 0
|
||||
}
|
||||
|
||||
func TrimRight(runes *[]rune) []rune {
|
||||
// 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]
|
||||
for i = len(runes) - 1; i >= 0; i-- {
|
||||
char := runes[i]
|
||||
if char != ' ' && char != '\t' {
|
||||
break
|
||||
}
|
||||
}
|
||||
return (*runes)[0 : i+1]
|
||||
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
|
||||
}
|
||||
|
@@ -20,3 +20,23 @@ func TestContrain(t *testing.T) {
|
||||
t.Error("Expected", 3)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrimLen(t *testing.T) {
|
||||
check := func(str string, exp int) {
|
||||
trimmed := TrimLen([]rune(str))
|
||||
if trimmed != exp {
|
||||
t.Errorf("Invalid TrimLen result for '%s': %d (expected %d)",
|
||||
str, trimmed, exp)
|
||||
}
|
||||
}
|
||||
check("hello", 5)
|
||||
check("hello ", 5)
|
||||
check("hello ", 5)
|
||||
check(" hello", 5)
|
||||
check(" hello", 5)
|
||||
check(" hello ", 5)
|
||||
check(" hello ", 5)
|
||||
check("h o", 5)
|
||||
check(" h o ", 5)
|
||||
check(" ", 0)
|
||||
}
|
||||
|
803
test/test_go.rb
803
test/test_go.rb
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user