mirror of
https://github.com/junegunn/fzf.git
synced 2025-11-14 06:13:47 -05:00
Compare commits
182 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e89eebb7ba | ||
|
|
fee404399a | ||
|
|
6b4805ca1a | ||
|
|
159699b5d7 | ||
|
|
af809c9661 | ||
|
|
329de8f416 | ||
|
|
e825b07e85 | ||
|
|
71fdb99a07 | ||
|
|
55ee4186aa | ||
|
|
941b0a0ff7 | ||
|
|
6aae12288e | ||
|
|
302cc552ef | ||
|
|
a2a4df0886 | ||
|
|
3399e39968 | ||
|
|
87874bba88 | ||
|
|
c304fc4333 | ||
|
|
6977cf268f | ||
|
|
931c78a70c | ||
|
|
8d23646fe6 | ||
|
|
656963e018 | ||
|
|
644277faf1 | ||
|
|
0558dfee79 | ||
|
|
487c8fe88f | ||
|
|
0d171ba1d8 | ||
|
|
2069bbc8b5 | ||
|
|
053d628b53 | ||
|
|
6bc592e6c9 | ||
|
|
6c76d8cd1c | ||
|
|
a09e411936 | ||
|
|
02a7b96f33 | ||
|
|
e55e029ae8 | ||
|
|
6b18b144cf | ||
|
|
6d53089cc1 | ||
|
|
e85a8a68d0 | ||
|
|
dc55e68524 | ||
|
|
462c68b625 | ||
|
|
999d374f0c | ||
|
|
b208aa675e | ||
|
|
2b98fee136 | ||
|
|
e5e75efebc | ||
|
|
4a4fef2daf | ||
|
|
ecb6b234cc | ||
|
|
39dbc8acdb | ||
|
|
a56489bc7f | ||
|
|
99927c7071 | ||
|
|
3e28403978 | ||
|
|
37370f057f | ||
|
|
f4b46fad27 | ||
|
|
9d2c6a95f4 | ||
|
|
376a76d1d3 | ||
|
|
1fcc07e54e | ||
|
|
8db3345c2f | ||
|
|
69aa2fea68 | ||
|
|
298749bfcd | ||
|
|
f1f31baae1 | ||
|
|
e1c8f19e8f | ||
|
|
5e302c70e9 | ||
|
|
4c5a679066 | ||
|
|
41f0b2c354 | ||
|
|
a0a3c349c9 | ||
|
|
bc3983181d | ||
|
|
980b58ef5a | ||
|
|
a2604c0963 | ||
|
|
6dbc108da2 | ||
|
|
bd98f988f0 | ||
|
|
06301c7847 | ||
|
|
18a1aeaa91 | ||
|
|
c9f16b6430 | ||
|
|
bc9d2abdb6 | ||
|
|
28810c178f | ||
|
|
a9e64efe45 | ||
|
|
6b5886c034 | ||
|
|
7727ad43af | ||
|
|
bbe10f4f77 | ||
|
|
5e72709613 | ||
|
|
9e85cba0d0 | ||
|
|
4b59ced08f | ||
|
|
8dbdd55730 | ||
|
|
6725151a99 | ||
|
|
d4f3d5a164 | ||
|
|
7b5ccc45bc | ||
|
|
940214a1a2 | ||
|
|
68bd410159 | ||
|
|
b13fcfd831 | ||
|
|
07ef2b051c | ||
|
|
3fc795340d | ||
|
|
70cfa6af13 | ||
|
|
dbcaec59ae | ||
|
|
faedae708e | ||
|
|
0c66521b23 | ||
|
|
bf92862459 | ||
|
|
1a68698d76 | ||
|
|
842a73357c | ||
|
|
5efdeccdbb | ||
|
|
050777b8c4 | ||
|
|
a4d78e2200 | ||
|
|
b49f22cdf9 | ||
|
|
7e483b0c25 | ||
|
|
3cf9ae04c7 | ||
|
|
bf0cb4bfe2 | ||
|
|
773133c4ce | ||
|
|
ca0b3b6fd7 | ||
|
|
f4731c0514 | ||
|
|
34f16e5b7d | ||
|
|
83e9af6601 | ||
|
|
8bbf9335e1 | ||
|
|
159f30b37f | ||
|
|
2e3dc75425 | ||
|
|
7d3575b362 | ||
|
|
35d407021c | ||
|
|
076f49d447 | ||
|
|
0665fe0413 | ||
|
|
669a6fee40 | ||
|
|
8aab0fc189 | ||
|
|
5d6eb5bfd6 | ||
|
|
cf4711d878 | ||
|
|
21d664d670 | ||
|
|
ab182e276b | ||
|
|
96a3250152 | ||
|
|
f5746002fd | ||
|
|
e1e3339770 | ||
|
|
3a5086796d | ||
|
|
11300913a4 | ||
|
|
e65f14cbed | ||
|
|
6898849e3e | ||
|
|
2d61691bb2 | ||
|
|
eba9e04e2e | ||
|
|
33f32de690 | ||
|
|
93b8f61551 | ||
|
|
7f17a9d1b4 | ||
|
|
d34e4cf698 | ||
|
|
6b592137b9 | ||
|
|
d5e72bf55d | ||
|
|
5677e5e133 | ||
|
|
7a11a06cbd | ||
|
|
a5862d4b9c | ||
|
|
a50909e806 | ||
|
|
7c8f7d3f20 | ||
|
|
9078197446 | ||
|
|
0fe07cf9fe | ||
|
|
2216169ca1 | ||
|
|
50e989ca85 | ||
|
|
fa1fc3d855 | ||
|
|
bbe696e925 | ||
|
|
5d12f523a3 | ||
|
|
d295d20dc4 | ||
|
|
2ba10071c9 | ||
|
|
505dc0491b | ||
|
|
54a4ab0f26 | ||
|
|
e03e91477b | ||
|
|
88ac397158 | ||
|
|
6fd4be580b | ||
|
|
53348feb89 | ||
|
|
337cdbb37c | ||
|
|
05fdf91fc5 | ||
|
|
c387689d1c | ||
|
|
cb9238dc4e | ||
|
|
a484811f78 | ||
|
|
111d1934c4 | ||
|
|
972fb1a29d | ||
|
|
3a6af27586 | ||
|
|
c89ac341e4 | ||
|
|
cd59e5d07b | ||
|
|
0b940e4b2b | ||
|
|
b29375c844 | ||
|
|
76d3f6d248 | ||
|
|
e87a85a179 | ||
|
|
11407bf656 | ||
|
|
c82fb3c9b9 | ||
|
|
309e1d8619 | ||
|
|
c2db67c1c0 | ||
|
|
9526594905 | ||
|
|
3d74d277aa | ||
|
|
fc274c2ba4 | ||
|
|
ce43ea9f42 | ||
|
|
21da02fac2 | ||
|
|
19569bd5c5 | ||
|
|
afa25d8c57 | ||
|
|
1ba7acf4bd | ||
|
|
a847fe8754 | ||
|
|
5bb18b6441 | ||
|
|
876c233a26 |
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,6 +1,8 @@
|
|||||||
bin
|
bin/fzf
|
||||||
src/fzf/fzf-*
|
target
|
||||||
gopath
|
|
||||||
pkg
|
pkg
|
||||||
Gemfile.lock
|
Gemfile.lock
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
doc/tags
|
||||||
|
vendor
|
||||||
|
gopath
|
||||||
|
|||||||
20
.travis.yml
20
.travis.yml
@@ -1,28 +1,20 @@
|
|||||||
language: ruby
|
language: ruby
|
||||||
|
dist: trusty
|
||||||
|
sudo: required
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- env: TAGS=
|
- env: TAGS=
|
||||||
rvm: 2.3.3
|
rvm: 2.3.3
|
||||||
# - env: TAGS=tcell
|
# - env: TAGS=tcell
|
||||||
# rvm: 2.2.0
|
# rvm: 2.3.3
|
||||||
|
|
||||||
install:
|
install:
|
||||||
- sudo apt-get update
|
|
||||||
- sudo apt-get install -y libncurses-dev lib32ncurses5-dev libgpm-dev
|
|
||||||
- sudo add-apt-repository -y ppa:pi-rho/dev
|
- sudo add-apt-repository -y ppa:pi-rho/dev
|
||||||
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
- sudo apt-add-repository -y ppa:fish-shell/release-2
|
||||||
- sudo apt-get update
|
- sudo apt-get update
|
||||||
- sudo apt-get install -y tmux=1.9a-1~ppa1~p
|
- sudo apt-get install -y tmux zsh fish
|
||||||
- sudo apt-get install -y zsh fish
|
|
||||||
|
|
||||||
script: |
|
script: |
|
||||||
export GOPATH=~/go
|
make test install &&
|
||||||
export FZF_BASE=$GOPATH/src/github.com/junegunn/fzf
|
./install --all &&
|
||||||
|
|
||||||
mkdir -p $GOPATH/src/github.com/junegunn
|
|
||||||
ln -s $(pwd) $FZF_BASE
|
|
||||||
|
|
||||||
cd $FZF_BASE/src && make test fzf/fzf-linux_amd64 install &&
|
|
||||||
cd $FZF_BASE/bin && ln -sf fzf-linux_amd64 fzf-$(./fzf --version)-linux_amd64 &&
|
|
||||||
cd $FZF_BASE && yes | ./install && rm -f fzf &&
|
|
||||||
tmux new "ruby test/test_go.rb > out && touch ok" && cat out && [ -e ok ]
|
tmux new "ruby test/test_go.rb > out && touch ok" && cat out && [ -e ok ]
|
||||||
|
|||||||
11
BUILD.md
11
BUILD.md
@@ -13,19 +13,16 @@ Build instructions
|
|||||||
Makefile will set up and use its own `$GOPATH` under the project root.
|
Makefile will set up and use its own `$GOPATH` under the project root.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Source files are located in src directory
|
# Build fzf binary for your platform in target
|
||||||
cd src
|
|
||||||
|
|
||||||
# Build fzf binary for your platform in src/fzf
|
|
||||||
make
|
make
|
||||||
|
|
||||||
# Build fzf binary and copy it to bin directory
|
# Build fzf binary and copy it to bin directory
|
||||||
make install
|
make install
|
||||||
|
|
||||||
# Build 32-bit and 64-bit executables and tarballs
|
# Build 32-bit and 64-bit executables and tarballs in target
|
||||||
make release
|
make release
|
||||||
|
|
||||||
# Make release archives for all supported platforms
|
# Make release archives for all supported platforms in target
|
||||||
make release-all
|
make release-all
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -35,7 +32,7 @@ Alternatively, you can build fzf directly with `go get` command without
|
|||||||
manually cloning the repository.
|
manually cloning the repository.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go get -u github.com/junegunn/fzf/src/fzf
|
go get -u github.com/junegunn/fzf
|
||||||
```
|
```
|
||||||
|
|
||||||
Third-party libraries used
|
Third-party libraries used
|
||||||
|
|||||||
61
CHANGELOG.md
61
CHANGELOG.md
@@ -1,6 +1,67 @@
|
|||||||
CHANGELOG
|
CHANGELOG
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
0.17.0
|
||||||
|
------
|
||||||
|
- Performance optimization
|
||||||
|
- One can match literal spaces in extended-search mode with a space prepended
|
||||||
|
by a backslash.
|
||||||
|
- `--expect` is now additive and can be specified multiple times.
|
||||||
|
|
||||||
|
0.16.11
|
||||||
|
-------
|
||||||
|
- Performance optimization
|
||||||
|
- Fixed missing preview update
|
||||||
|
|
||||||
|
0.16.10
|
||||||
|
-------
|
||||||
|
- Fixed invalid handling of ANSI colors in preview window
|
||||||
|
- Further improved `--ansi` performance
|
||||||
|
|
||||||
|
0.16.9
|
||||||
|
------
|
||||||
|
- Memory and performance optimization
|
||||||
|
- Around 20% performance improvement for general use cases
|
||||||
|
- Up to 5x faster processing of `--ansi`
|
||||||
|
- Up to 50% reduction of memory usage
|
||||||
|
- Bug fixes and usability improvements
|
||||||
|
- Fixed handling of bracketed paste mode
|
||||||
|
- [ERROR] on info line when the default command failed
|
||||||
|
- More efficient rendering of preview window
|
||||||
|
- `--no-clear` updated for repetitive relaunching scenarios
|
||||||
|
|
||||||
|
0.16.8
|
||||||
|
------
|
||||||
|
- New `change` event and `top` action for `--bind`
|
||||||
|
- `fzf --bind change:top`
|
||||||
|
- Move cursor to the top result whenever the query string is changed
|
||||||
|
- `fzf --bind 'ctrl-w:unix-word-rubout+top,ctrl-u:unix-line-discard+top'`
|
||||||
|
- `top` combined with `unix-word-rubout` and `unix-line-discard`
|
||||||
|
- Fixed inconsistent tiebreak scores when `--nth` is used
|
||||||
|
- Proper display of tab characters in `--prompt`
|
||||||
|
- Fixed not to `--cycle` on page-up/page-down to prevent overshoot
|
||||||
|
- Git revision in `--version` output
|
||||||
|
- Basic support for Cygwin environment
|
||||||
|
- Many fixes in Vim plugin on Windows/Cygwin (thanks to @janlazo)
|
||||||
|
|
||||||
|
0.16.7
|
||||||
|
------
|
||||||
|
- Added support for `ctrl-alt-[a-z]` key chords
|
||||||
|
- CTRL-Z (SIGSTOP) now works with fzf
|
||||||
|
- fzf will export `$FZF_PREVIEW_WINDOW` so that the scripts can use it
|
||||||
|
- Bug fixes and improvements in Vim plugin and shell extensions
|
||||||
|
|
||||||
|
0.16.6
|
||||||
|
------
|
||||||
|
- Minor bug fixes and improvements
|
||||||
|
- Added `--no-clear` option for scripting purposes
|
||||||
|
|
||||||
|
0.16.5
|
||||||
|
------
|
||||||
|
- Minor bug fixes
|
||||||
|
- Added `toggle-preview-wrap` action
|
||||||
|
- Built with Go 1.8
|
||||||
|
|
||||||
0.16.4
|
0.16.4
|
||||||
------
|
------
|
||||||
- Added `--border` option to draw border above and below the finder
|
- Added `--border` option to draw border above and below the finder
|
||||||
|
|||||||
138
Makefile
Normal file
138
Makefile
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
ifndef GOOS
|
||||||
|
UNAME_S := $(shell uname -s)
|
||||||
|
ifeq ($(UNAME_S),Darwin)
|
||||||
|
GOOS := darwin
|
||||||
|
else ifeq ($(UNAME_S),Linux)
|
||||||
|
GOOS := linux
|
||||||
|
else
|
||||||
|
$(error "$$GOOS is not defined.")
|
||||||
|
endif
|
||||||
|
endif
|
||||||
|
|
||||||
|
MAKEFILE := $(realpath $(lastword $(MAKEFILE_LIST)))
|
||||||
|
ROOT_DIR := $(shell dirname $(MAKEFILE))
|
||||||
|
GOPATH := $(ROOT_DIR)/gopath
|
||||||
|
SRC_LINK := $(GOPATH)/src/github.com/junegunn/fzf/src
|
||||||
|
VENDOR_LINK := $(GOPATH)/src/github.com/junegunn/fzf/vendor
|
||||||
|
export GOPATH
|
||||||
|
|
||||||
|
GLIDE_YAML := glide.yaml
|
||||||
|
GLIDE_LOCK := glide.lock
|
||||||
|
SOURCES := $(wildcard *.go src/*.go src/*/*.go) $(SRC_LINK) $(VENDOR_LINK) $(GLIDE_LOCK) $(MAKEFILE)
|
||||||
|
|
||||||
|
REVISION := $(shell git log -n 1 --pretty=format:%h -- $(SOURCES))
|
||||||
|
BUILD_FLAGS := -a -ldflags "-X main.revision=$(REVISION) -w -extldflags=$(LDFLAGS)" -tags "$(TAGS)"
|
||||||
|
|
||||||
|
BINARY32 := fzf-$(GOOS)_386
|
||||||
|
BINARY64 := fzf-$(GOOS)_amd64
|
||||||
|
BINARYARM5 := fzf-$(GOOS)_arm5
|
||||||
|
BINARYARM6 := fzf-$(GOOS)_arm6
|
||||||
|
BINARYARM7 := fzf-$(GOOS)_arm7
|
||||||
|
BINARYARM8 := fzf-$(GOOS)_arm8
|
||||||
|
VERSION := $(shell awk -F= '/version =/ {print $$2}' src/constants.go | tr -d "\" ")
|
||||||
|
RELEASE32 := fzf-$(VERSION)-$(GOOS)_386
|
||||||
|
RELEASE64 := fzf-$(VERSION)-$(GOOS)_amd64
|
||||||
|
RELEASEARM5 := fzf-$(VERSION)-$(GOOS)_arm5
|
||||||
|
RELEASEARM6 := fzf-$(VERSION)-$(GOOS)_arm6
|
||||||
|
RELEASEARM7 := fzf-$(VERSION)-$(GOOS)_arm7
|
||||||
|
RELEASEARM8 := fzf-$(VERSION)-$(GOOS)_arm8
|
||||||
|
|
||||||
|
# https://en.wikipedia.org/wiki/Uname
|
||||||
|
UNAME_M := $(shell uname -m)
|
||||||
|
ifeq ($(UNAME_M),x86_64)
|
||||||
|
BINARY := $(BINARY64)
|
||||||
|
else ifeq ($(UNAME_M),amd64)
|
||||||
|
BINARY := $(BINARY64)
|
||||||
|
else ifeq ($(UNAME_M),i686)
|
||||||
|
BINARY := $(BINARY32)
|
||||||
|
else ifeq ($(UNAME_M),i386)
|
||||||
|
BINARY := $(BINARY32)
|
||||||
|
else ifeq ($(UNAME_M),armv5l)
|
||||||
|
BINARY := $(BINARYARM5)
|
||||||
|
else ifeq ($(UNAME_M),armv6l)
|
||||||
|
BINARY := $(BINARYARM6)
|
||||||
|
else ifeq ($(UNAME_M),armv7l)
|
||||||
|
BINARY := $(BINARYARM7)
|
||||||
|
else
|
||||||
|
$(error "Build on $(UNAME_M) is not supported, yet.")
|
||||||
|
endif
|
||||||
|
|
||||||
|
all: target/$(BINARY)
|
||||||
|
|
||||||
|
target:
|
||||||
|
mkdir -p $@
|
||||||
|
|
||||||
|
ifeq ($(GOOS),windows)
|
||||||
|
release: target/$(BINARY32) target/$(BINARY64)
|
||||||
|
cd target && cp -f $(BINARY32) fzf.exe && zip $(RELEASE32).zip fzf.exe
|
||||||
|
cd target && cp -f $(BINARY64) fzf.exe && zip $(RELEASE64).zip fzf.exe
|
||||||
|
cd target && rm -f fzf.exe
|
||||||
|
else ifeq ($(GOOS),linux)
|
||||||
|
release: target/$(BINARY32) target/$(BINARY64) target/$(BINARYARM5) target/$(BINARYARM6) target/$(BINARYARM7) target/$(BINARYARM8)
|
||||||
|
cd target && cp -f $(BINARY32) fzf && tar -czf $(RELEASE32).tgz fzf
|
||||||
|
cd target && cp -f $(BINARY64) fzf && tar -czf $(RELEASE64).tgz fzf
|
||||||
|
cd target && cp -f $(BINARYARM5) fzf && tar -czf $(RELEASEARM5).tgz fzf
|
||||||
|
cd target && cp -f $(BINARYARM6) fzf && tar -czf $(RELEASEARM6).tgz fzf
|
||||||
|
cd target && cp -f $(BINARYARM7) fzf && tar -czf $(RELEASEARM7).tgz fzf
|
||||||
|
cd target && cp -f $(BINARYARM8) fzf && tar -czf $(RELEASEARM8).tgz fzf
|
||||||
|
cd target && rm -f fzf
|
||||||
|
else
|
||||||
|
release: target/$(BINARY32) target/$(BINARY64)
|
||||||
|
cd target && cp -f $(BINARY32) fzf && tar -czf $(RELEASE32).tgz fzf
|
||||||
|
cd target && cp -f $(BINARY64) fzf && tar -czf $(RELEASE64).tgz fzf
|
||||||
|
cd target && rm -f fzf
|
||||||
|
endif
|
||||||
|
|
||||||
|
release-all: clean test
|
||||||
|
GOOS=darwin make release
|
||||||
|
GOOS=linux make release
|
||||||
|
GOOS=freebsd make release
|
||||||
|
GOOS=openbsd make release
|
||||||
|
GOOS=windows make release
|
||||||
|
|
||||||
|
$(SRC_LINK):
|
||||||
|
mkdir -p $(shell dirname $(SRC_LINK))
|
||||||
|
ln -sf $(ROOT_DIR)/src $(SRC_LINK)
|
||||||
|
|
||||||
|
$(VENDOR_LINK):
|
||||||
|
mkdir -p $(shell dirname $(VENDOR_LINK))
|
||||||
|
ln -sf $(ROOT_DIR)/vendor $(VENDOR_LINK)
|
||||||
|
|
||||||
|
vendor: $(GLIDE_YAML)
|
||||||
|
go get -u github.com/Masterminds/glide && $(GOPATH)/bin/glide install && touch $@
|
||||||
|
|
||||||
|
test: $(SOURCES) vendor
|
||||||
|
SHELL=/bin/sh GOOS= go test -v -tags "$(TAGS)" \
|
||||||
|
github.com/junegunn/fzf/src \
|
||||||
|
github.com/junegunn/fzf/src/algo \
|
||||||
|
github.com/junegunn/fzf/src/tui \
|
||||||
|
github.com/junegunn/fzf/src/util
|
||||||
|
|
||||||
|
install: bin/fzf
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf target
|
||||||
|
|
||||||
|
target/$(BINARY32): $(SOURCES) vendor
|
||||||
|
GOARCH=386 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
target/$(BINARY64): $(SOURCES) vendor
|
||||||
|
GOARCH=amd64 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
# https://github.com/golang/go/wiki/GoArm
|
||||||
|
target/$(BINARYARM5): $(SOURCES) vendor
|
||||||
|
GOARCH=arm GOARM=5 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
target/$(BINARYARM6): $(SOURCES) vendor
|
||||||
|
GOARCH=arm GOARM=6 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
target/$(BINARYARM7): $(SOURCES) vendor
|
||||||
|
GOARCH=arm GOARM=7 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
target/$(BINARYARM8): $(SOURCES) vendor
|
||||||
|
GOARCH=arm64 go build $(BUILD_FLAGS) -o $@
|
||||||
|
|
||||||
|
bin/fzf: target/$(BINARY) | bin
|
||||||
|
cp -f target/$(BINARY) bin/fzf
|
||||||
|
|
||||||
|
.PHONY: all release release-all test install clean
|
||||||
168
README-VIM.md
Normal file
168
README-VIM.md
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
FZF Vim integration
|
||||||
|
===================
|
||||||
|
|
||||||
|
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[!]`
|
||||||
|
---------
|
||||||
|
|
||||||
|
If you have set up fzf for Vim, `:FZF` command will be added.
|
||||||
|
|
||||||
|
```vim
|
||||||
|
" Look for files under current directory
|
||||||
|
:FZF
|
||||||
|
|
||||||
|
" Look for files under your home directory
|
||||||
|
:FZF ~
|
||||||
|
|
||||||
|
" With options
|
||||||
|
:FZF --no-sort --reverse --inline-info /tmp
|
||||||
|
|
||||||
|
" Bang version starts fzf in fullscreen mode
|
||||||
|
:FZF!
|
||||||
|
```
|
||||||
|
|
||||||
|
Similarly to [ctrlp.vim](https://github.com/kien/ctrlp.vim), use enter key,
|
||||||
|
`CTRL-T`, `CTRL-X` or `CTRL-V` to open selected files in the current window,
|
||||||
|
in new tabs, in horizontal splits, or in vertical splits respectively.
|
||||||
|
|
||||||
|
Note that the environment variables `FZF_DEFAULT_COMMAND` and
|
||||||
|
`FZF_DEFAULT_OPTS` also apply here.
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
- `g:fzf_action`
|
||||||
|
- Customizable extra key bindings for opening selected files in different ways
|
||||||
|
- `g:fzf_layout`
|
||||||
|
- Determines the size and position of fzf window (tmux pane or Neovim split)
|
||||||
|
- `g:fzf_colors`
|
||||||
|
- Customizes fzf colors to match the current color scheme
|
||||||
|
- `g:fzf_history_dir`
|
||||||
|
- Enables history feature
|
||||||
|
- `g:fzf_launcher`
|
||||||
|
- (Only in GVim) Terminal emulator to open fzf with
|
||||||
|
- `g:Fzf_launcher` for function reference
|
||||||
|
|
||||||
|
#### Examples
|
||||||
|
|
||||||
|
```vim
|
||||||
|
" This is the default extra key bindings
|
||||||
|
let g:fzf_action = {
|
||||||
|
\ 'ctrl-t': 'tab split',
|
||||||
|
\ 'ctrl-x': 'split',
|
||||||
|
\ 'ctrl-v': 'vsplit' }
|
||||||
|
|
||||||
|
" An action can be a reference to a function that processes selected lines
|
||||||
|
function! s:build_quickfix_list(lines)
|
||||||
|
call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
|
||||||
|
copen
|
||||||
|
cc
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
let g:fzf_action = {
|
||||||
|
\ 'ctrl-q': function('s:build_quickfix_list'),
|
||||||
|
\ 'ctrl-t': 'tab split',
|
||||||
|
\ 'ctrl-x': 'split',
|
||||||
|
\ 'ctrl-v': 'vsplit' }
|
||||||
|
|
||||||
|
" Default fzf layout
|
||||||
|
" - down / up / left / right
|
||||||
|
let g:fzf_layout = { 'down': '~40%' }
|
||||||
|
|
||||||
|
" In Neovim, you can set up fzf window using a Vim command
|
||||||
|
let g:fzf_layout = { 'window': 'enew' }
|
||||||
|
let g:fzf_layout = { 'window': '-tabnew' }
|
||||||
|
let g:fzf_layout = { 'window': '10split enew' }
|
||||||
|
|
||||||
|
" Customize fzf colors to match your color scheme
|
||||||
|
let g:fzf_colors =
|
||||||
|
\ { 'fg': ['fg', 'Normal'],
|
||||||
|
\ 'bg': ['bg', 'Normal'],
|
||||||
|
\ 'hl': ['fg', 'Comment'],
|
||||||
|
\ 'fg+': ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
|
||||||
|
\ 'bg+': ['bg', 'CursorLine', 'CursorColumn'],
|
||||||
|
\ 'hl+': ['fg', 'Statement'],
|
||||||
|
\ 'info': ['fg', 'PreProc'],
|
||||||
|
\ 'prompt': ['fg', 'Conditional'],
|
||||||
|
\ 'pointer': ['fg', 'Exception'],
|
||||||
|
\ 'marker': ['fg', 'Keyword'],
|
||||||
|
\ 'spinner': ['fg', 'Label'],
|
||||||
|
\ 'header': ['fg', 'Comment'] }
|
||||||
|
|
||||||
|
" Enable per-command history.
|
||||||
|
" CTRL-N and CTRL-P will be automatically bound to next-history and
|
||||||
|
" previous-history instead of down and up. If you don't like the change,
|
||||||
|
" explicitly bind the keys to down and up in your $FZF_DEFAULT_OPTS.
|
||||||
|
let g:fzf_history_dir = '~/.local/share/fzf-history'
|
||||||
|
```
|
||||||
|
|
||||||
|
`fzf#run`
|
||||||
|
---------
|
||||||
|
|
||||||
|
For more advanced uses, you can use `fzf#run([options])` function with the
|
||||||
|
following options.
|
||||||
|
|
||||||
|
| Option name | Type | Description |
|
||||||
|
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
||||||
|
| `source` | string | External command to generate input to fzf (e.g. `find .`) |
|
||||||
|
| `source` | list | Vim list as input to fzf |
|
||||||
|
| `sink` | string | Vim command to handle the selected item (e.g. `e`, `tabe`) |
|
||||||
|
| `sink` | funcref | Reference to function to process each selected item |
|
||||||
|
| `sink*` | funcref | Similar to `sink`, but takes the list of output lines at once |
|
||||||
|
| `options` | string/list | Options to fzf |
|
||||||
|
| `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 (GVim only) |
|
||||||
|
| `launcher` | funcref | Function for generating `launcher` string (GVim only) |
|
||||||
|
|
||||||
|
`options` entry can be either a string or a list. For simple cases, string
|
||||||
|
should suffice, but prefer to use list type if you're concerned about escaping
|
||||||
|
issues on different platforms.
|
||||||
|
|
||||||
|
```vim
|
||||||
|
call fzf#run({'options': '--reverse --prompt "C:\\Program Files\\"'})
|
||||||
|
call fzf#run({'options': ['--reverse', '--prompt', 'C:\Program Files\']})
|
||||||
|
```
|
||||||
|
|
||||||
|
`fzf#wrap`
|
||||||
|
----------
|
||||||
|
|
||||||
|
`fzf#wrap([name string,] [opts dict,] [fullscreen boolean])` is a helper
|
||||||
|
function that decorates the options dictionary so that it understands
|
||||||
|
`g:fzf_layout`, `g:fzf_action`, `g:fzf_colors`, and `g:fzf_history_dir` like
|
||||||
|
`:FZF`.
|
||||||
|
|
||||||
|
```vim
|
||||||
|
command! -bang MyStuff
|
||||||
|
\ call fzf#run(fzf#wrap('my-stuff', {'dir': '~/my-stuff'}, <bang>0))
|
||||||
|
```
|
||||||
|
|
||||||
|
GVim
|
||||||
|
----
|
||||||
|
|
||||||
|
In GVim, you need an external terminal emulator to start fzf with. `xterm`
|
||||||
|
command is used by default, but you can customize it with `g:fzf_launcher`.
|
||||||
|
|
||||||
|
```vim
|
||||||
|
" This is the default. %s is replaced with fzf command
|
||||||
|
let g:fzf_launcher = 'xterm -e bash -ic %s'
|
||||||
|
|
||||||
|
" Use urxvt instead
|
||||||
|
let g:fzf_launcher = 'urxvt -geometry 120x30 -e sh -c %s'
|
||||||
|
```
|
||||||
|
|
||||||
|
If you're running MacVim on OSX, I recommend you to use iTerm2 as the
|
||||||
|
launcher. Refer to the [this wiki page][macvim-iterm2] to see how to set up.
|
||||||
|
|
||||||
|
[macvim-iterm2]: https://github.com/junegunn/fzf/wiki/On-MacVim-with-iTerm2
|
||||||
|
|
||||||
|
[License](LICENSE)
|
||||||
|
------------------
|
||||||
|
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2017 Junegunn Choi
|
||||||
221
README.md
221
README.md
@@ -1,20 +1,61 @@
|
|||||||
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf)
|
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf.png" height="170" alt="fzf - a command-line fuzzy finder"> [](https://travis-ci.org/junegunn/fzf) [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EKYAW9PGKPD2N)
|
||||||
===
|
===
|
||||||
|
|
||||||
fzf is a general-purpose command-line fuzzy finder.
|
fzf is a general-purpose command-line fuzzy finder.
|
||||||
|
|
||||||

|
<img src="https://raw.githubusercontent.com/junegunn/i/master/fzf-preview.png" width=640>
|
||||||
|
|
||||||
|
It's an interactive Unix filter for command-line that can be used with any
|
||||||
|
list; files, command history, processes, hostnames, bookmarks, git commits,
|
||||||
|
etc.
|
||||||
|
|
||||||
Pros
|
Pros
|
||||||
----
|
----
|
||||||
|
|
||||||
- No dependencies
|
- Portable, no dependencies
|
||||||
- Blazingly fast
|
- Blazingly fast
|
||||||
- The most comprehensive feature set
|
- The most comprehensive feature set
|
||||||
- Flexible layout using tmux panes
|
- Flexible layout
|
||||||
- Batteries included
|
- Batteries included
|
||||||
- Vim/Neovim plugin, key bindings and fuzzy auto-completion
|
- Vim/Neovim plugin, key bindings and fuzzy auto-completion
|
||||||
|
|
||||||
|
Table of Contents
|
||||||
|
-----------------
|
||||||
|
|
||||||
|
* [Installation](#installation)
|
||||||
|
* [Using git](#using-git)
|
||||||
|
* [Using Homebrew or Linuxbrew](#using-homebrew-or-linuxbrew)
|
||||||
|
* [As Vim plugin](#as-vim-plugin)
|
||||||
|
* [Windows](#windows)
|
||||||
|
* [Upgrading fzf](#upgrading-fzf)
|
||||||
|
* [Building fzf](#building-fzf)
|
||||||
|
* [Usage](#usage)
|
||||||
|
* [Using the finder](#using-the-finder)
|
||||||
|
* [Layout](#layout)
|
||||||
|
* [Search syntax](#search-syntax)
|
||||||
|
* [Environment variables](#environment-variables)
|
||||||
|
* [Options](#options)
|
||||||
|
* [Examples](#examples)
|
||||||
|
* [fzf-tmux script](#fzf-tmux-script)
|
||||||
|
* [Key bindings for command line](#key-bindings-for-command-line)
|
||||||
|
* [Fuzzy completion for bash and zsh](#fuzzy-completion-for-bash-and-zsh)
|
||||||
|
* [Files and directories](#files-and-directories)
|
||||||
|
* [Process IDs](#process-ids)
|
||||||
|
* [Host names](#host-names)
|
||||||
|
* [Environment variables / Aliases](#environment-variables--aliases)
|
||||||
|
* [Settings](#settings)
|
||||||
|
* [Supported commands](#supported-commands)
|
||||||
|
* [Vim plugin](#vim-plugin)
|
||||||
|
* [Advanced topics](#advanced-topics)
|
||||||
|
* [Performance](#performance)
|
||||||
|
* [Executing external programs](#executing-external-programs)
|
||||||
|
* [Preview window](#preview-window)
|
||||||
|
* [Tips](#tips)
|
||||||
|
* [Respecting .gitignore, <code>.hgignore</code>, and <code>svn:ignore</code>](#respecting-gitignore-hgignore-and-svnignore)
|
||||||
|
* [git ls-tree for fast traversal](#git-ls-tree-for-fast-traversal)
|
||||||
|
* [Fish shell](#fish-shell)
|
||||||
|
* [<a href="LICENSE">License</a>](#license)
|
||||||
|
|
||||||
Installation
|
Installation
|
||||||
------------
|
------------
|
||||||
|
|
||||||
@@ -42,9 +83,10 @@ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
|
|||||||
~/.fzf/install
|
~/.fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
### Using Homebrew
|
### Using Homebrew or Linuxbrew
|
||||||
|
|
||||||
On OS X, you can use [Homebrew](http://brew.sh/) to install fzf.
|
Alternatively, you can use [Homebrew](http://brew.sh/) or
|
||||||
|
[Linuxbrew](http://linuxbrew.sh/) to install fzf.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
brew install fzf
|
brew install fzf
|
||||||
@@ -53,7 +95,7 @@ brew install fzf
|
|||||||
/usr/local/opt/fzf/install
|
/usr/local/opt/fzf/install
|
||||||
```
|
```
|
||||||
|
|
||||||
### Vim plugin
|
### As Vim plugin
|
||||||
|
|
||||||
You can manually add the directory to `&runtimepath` as follows,
|
You can manually add the directory to `&runtimepath` as follows,
|
||||||
|
|
||||||
@@ -74,10 +116,18 @@ Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
|
|||||||
|
|
||||||
### Windows
|
### Windows
|
||||||
|
|
||||||
Pre-built binaries for Windows can be downloaded [here][bin]. However, other
|
Pre-built binaries for Windows can be downloaded [here][bin]. fzf is also
|
||||||
components of the project may not work on Windows. You might want to consider
|
available as a [Chocolatey package][choco].
|
||||||
installing fzf on [Windows Subsystem for Linux][wsl] where everything runs
|
|
||||||
flawlessly.
|
[choco]: https://chocolatey.org/packages/fzf
|
||||||
|
|
||||||
|
```sh
|
||||||
|
choco install fzf
|
||||||
|
```
|
||||||
|
|
||||||
|
However, other components of the project may not work on Windows. You might
|
||||||
|
want to consider installing fzf on [Windows Subsystem for Linux][wsl] where
|
||||||
|
everything runs flawlessly.
|
||||||
|
|
||||||
[wsl]: https://blogs.msdn.microsoft.com/wsl/
|
[wsl]: https://blogs.msdn.microsoft.com/wsl/
|
||||||
|
|
||||||
@@ -90,6 +140,7 @@ method used.
|
|||||||
|
|
||||||
- git: `cd ~/.fzf && git pull && ./install`
|
- git: `cd ~/.fzf && git pull && ./install`
|
||||||
- brew: `brew update; brew reinstall fzf`
|
- brew: `brew update; brew reinstall fzf`
|
||||||
|
- chocolatey: `choco upgrade fzf`
|
||||||
- vim-plug: `:PlugUpdate fzf`
|
- vim-plug: `:PlugUpdate fzf`
|
||||||
|
|
||||||
Building fzf
|
Building fzf
|
||||||
@@ -100,7 +151,7 @@ See [BUILD.md](BUILD.md).
|
|||||||
Usage
|
Usage
|
||||||
-----
|
-----
|
||||||
|
|
||||||
fzf will launch curses-based finder, read the list from STDIN, and write the
|
fzf will launch interactive finder, read the list from STDIN, and write the
|
||||||
selected item to STDOUT.
|
selected item to STDOUT.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -230,8 +281,8 @@ fish.
|
|||||||
- Set `FZF_CTRL_T_COMMAND` to override the default command
|
- Set `FZF_CTRL_T_COMMAND` to override the default command
|
||||||
- Set `FZF_CTRL_T_OPTS` to pass additional options
|
- Set `FZF_CTRL_T_OPTS` to pass additional options
|
||||||
- `CTRL-R` - Paste the selected command from history onto the command line
|
- `CTRL-R` - Paste the selected command from history onto the command line
|
||||||
- Sort is disabled by default to respect chronological ordering
|
- If you want to see the commands in chronological order, press `CTRL-R`
|
||||||
- Press `CTRL-R` again to toggle sort
|
again which toggles sorting by relevance
|
||||||
- Set `FZF_CTRL_R_OPTS` to pass additional options
|
- Set `FZF_CTRL_R_OPTS` to pass additional options
|
||||||
- `ALT-C` - cd into the selected directory
|
- `ALT-C` - cd into the selected directory
|
||||||
- Set `FZF_ALT_C_COMMAND` to override the default command
|
- Set `FZF_ALT_C_COMMAND` to override the default command
|
||||||
@@ -332,87 +383,103 @@ On bash, fuzzy completion is enabled only for a predefined set of commands
|
|||||||
commands as well like follows.
|
commands as well like follows.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# There are also _fzf_path_completion and _fzf_dir_completion
|
complete -F _fzf_path_completion -o default -o bashdefault ag
|
||||||
complete -F _fzf_file_completion -o default -o bashdefault doge
|
complete -F _fzf_dir_completion -o default -o bashdefault tree
|
||||||
```
|
```
|
||||||
|
|
||||||
Usage as Vim plugin
|
Vim plugin
|
||||||
-------------------
|
----------
|
||||||
|
|
||||||
This repository only enables basic integration with Vim. If you're looking for
|
See [README-VIM.md](README-VIM.md).
|
||||||
more, check out [fzf.vim](https://github.com/junegunn/fzf.vim) project.
|
|
||||||
|
|
||||||
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
Advanced topics
|
||||||
|
---------------
|
||||||
|
|
||||||
#### `:FZF[!]`
|
### Performance
|
||||||
|
|
||||||
If you have set up fzf for Vim, `:FZF` command will be added.
|
fzf is fast, and is [getting even faster][perf]. Performance should not be
|
||||||
|
a problem in most use cases. However, you might want to be aware of the
|
||||||
|
options that affect the performance.
|
||||||
|
|
||||||
```vim
|
- `--ansi` tells fzf to extract and parse ANSI color codes in the input and it
|
||||||
" Look for files under current directory
|
makes the initial scanning slower. So it's not recommended that you add it
|
||||||
:FZF
|
to your `$FZF_DEFAULT_OPTS`.
|
||||||
|
- `--nth` makes fzf slower as fzf has to tokenize each line.
|
||||||
|
- `--with-nth` makes fzf slower as fzf has to tokenize and reassemble each
|
||||||
|
line.
|
||||||
|
- If you absolutely need better performance, you can consider using
|
||||||
|
`--algo=v1` (the default being `v2`) to make fzf use faster greedy
|
||||||
|
algorithm. However, this algorithm is not guaranteed to find the optimal
|
||||||
|
ordering of the matches and is not recommended.
|
||||||
|
|
||||||
" Look for files under your home directory
|
[perf]: https://junegunn.kr/images/fzf-0.16.11.png
|
||||||
:FZF ~
|
|
||||||
|
|
||||||
" With options
|
### Executing external programs
|
||||||
:FZF --no-sort --reverse --inline-info /tmp
|
|
||||||
|
|
||||||
" Bang version starts fzf in fullscreen mode
|
You can set up key bindings for starting external processes without leaving
|
||||||
:FZF!
|
fzf (`execute`, `execute-silent`).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Press F1 to open the file with less without leaving fzf
|
||||||
|
# Press CTRL-Y to copy the line to clipboard and aborts fzf (requires pbcopy)
|
||||||
|
fzf --bind 'f1:execute(less -f {}),ctrl-y:execute-silent(echo {} | pbcopy)+abort'
|
||||||
```
|
```
|
||||||
|
|
||||||
Similarly to [ctrlp.vim](https://github.com/kien/ctrlp.vim), use enter key,
|
See *KEY BINDINGS* section of the man page for details.
|
||||||
`CTRL-T`, `CTRL-X` or `CTRL-V` to open selected files in the current window,
|
|
||||||
in new tabs, in horizontal splits, or in vertical splits respectively.
|
|
||||||
|
|
||||||
Note that the environment variables `FZF_DEFAULT_COMMAND` and
|
### Preview window
|
||||||
`FZF_DEFAULT_OPTS` also apply here. Refer to [the wiki page][fzf-config] for
|
|
||||||
customization.
|
|
||||||
|
|
||||||
[fzf-config]: https://github.com/junegunn/fzf/wiki/Configuring-Vim-plugin
|
When `--preview` option is set, fzf automatically starts external process with
|
||||||
|
the current line as the argument and shows the result in the split window.
|
||||||
|
|
||||||
#### `fzf#run`
|
```bash
|
||||||
|
# {} is replaced to the single-quoted string of the focused line
|
||||||
For more advanced uses, you can use `fzf#run([options])` function with the
|
fzf --preview 'cat {}'
|
||||||
following options.
|
|
||||||
|
|
||||||
| Option name | Type | Description |
|
|
||||||
| -------------------------- | ------------- | ---------------------------------------------------------------- |
|
|
||||||
| `source` | string | External command to generate input to fzf (e.g. `find .`) |
|
|
||||||
| `source` | list | Vim list as input to fzf |
|
|
||||||
| `sink` | string | Vim command to handle the selected item (e.g. `e`, `tabe`) |
|
|
||||||
| `sink` | funcref | Reference to function to process each selected item |
|
|
||||||
| `sink*` | funcref | Similar to `sink`, but takes the list of output lines at once |
|
|
||||||
| `options` | string | Options to fzf |
|
|
||||||
| `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 (GVim only) |
|
|
||||||
| `launcher` | funcref | Function for generating `launcher` string (GVim only) |
|
|
||||||
|
|
||||||
Examples can be found on [the wiki
|
|
||||||
page](https://github.com/junegunn/fzf/wiki/Examples-(vim)).
|
|
||||||
|
|
||||||
#### `fzf#wrap`
|
|
||||||
|
|
||||||
`fzf#wrap([name string,] [opts dict,] [fullscreen boolean])` is a helper
|
|
||||||
function that decorates the options dictionary so that it understands
|
|
||||||
`g:fzf_layout`, `g:fzf_action`, `g:fzf_colors`, and `g:fzf_history_dir` like
|
|
||||||
`:FZF`.
|
|
||||||
|
|
||||||
```vim
|
|
||||||
command! -bang MyStuff
|
|
||||||
\ call fzf#run(fzf#wrap('my-stuff', {'dir': '~/my-stuff'}, <bang>0))
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Since preview window is updated only after the process is complete, it's
|
||||||
|
important that the command finishes quickly.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Use head instead of cat so that the command doesn't take too long to finish
|
||||||
|
fzf --preview 'head -100 {}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Preview window supports ANSI colors, so you can use programs that
|
||||||
|
syntax-highlights the content of a file.
|
||||||
|
|
||||||
|
- Highlight: http://www.andre-simon.de/doku/highlight/en/highlight.php
|
||||||
|
- CodeRay: http://coderay.rubychan.de/
|
||||||
|
- Rouge: https://github.com/jneen/rouge
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Try highlight, coderay, rougify in turn, then fall back to cat
|
||||||
|
fzf --preview '[[ $(file --mime {}) =~ binary ]] &&
|
||||||
|
echo {} is a binary file ||
|
||||||
|
(highlight -O ansi -l {} ||
|
||||||
|
coderay {} ||
|
||||||
|
rougify {} ||
|
||||||
|
cat {}) 2> /dev/null | head -500'
|
||||||
|
```
|
||||||
|
|
||||||
|
You can customize the size and position of the preview window using
|
||||||
|
`--preview-window` option. For example,
|
||||||
|
|
||||||
|
```bash
|
||||||
|
fzf --height 40% --reverse --preview 'file {}' --preview-window down:1
|
||||||
|
```
|
||||||
|
|
||||||
|
For more advanced examples, see [Key bindings for git with fzf][fzf-git].
|
||||||
|
|
||||||
|
[fzf-git]: https://junegunn.kr/2016/07/fzf-git/
|
||||||
|
|
||||||
Tips
|
Tips
|
||||||
----
|
----
|
||||||
|
|
||||||
#### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`
|
#### Respecting `.gitignore`, `.hgignore`, and `svn:ignore`
|
||||||
|
|
||||||
[ag](https://github.com/ggreer/the_silver_searcher) or
|
[ag](https://github.com/ggreer/the_silver_searcher) or
|
||||||
[pt](https://github.com/monochromegane/the_platinum_searcher) will do the
|
[rg](https://github.com/BurntSushi/ripgrep) will do the
|
||||||
filtering:
|
filtering:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -449,10 +516,10 @@ export FZF_DEFAULT_COMMAND='
|
|||||||
|
|
||||||
#### Fish shell
|
#### Fish shell
|
||||||
|
|
||||||
It's [a known bug of fish](https://github.com/fish-shell/fish-shell/issues/1362)
|
Fish shell before version 2.6.0 [doesn't allow](https://github.com/fish-shell/fish-shell/issues/1362)
|
||||||
that it doesn't allow reading from STDIN in command substitution, which means
|
reading from STDIN in command substitution, which means simple `vim (fzf)`
|
||||||
simple `vim (fzf)` won't work as expected. The workaround is to use the `read`
|
doesn't work as expected. The workaround for fish 2.5.0 and earlier is to use
|
||||||
fish command:
|
the `read` fish command:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
fzf | read -l result; and vim $result
|
fzf | read -l result; and vim $result
|
||||||
@@ -480,7 +547,7 @@ make use of this feature. `$dir` defaults to `.` when the last token is not a
|
|||||||
valid directory. Example:
|
valid directory. Example:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
set -l FZF_CTRL_T_COMMAND "command find -L \$dir -type f 2> /dev/null | sed '1d; s#^\./##'"
|
set -g FZF_CTRL_T_COMMAND "command find -L \$dir -type f 2> /dev/null | sed '1d; s#^\./##'"
|
||||||
```
|
```
|
||||||
|
|
||||||
[License](LICENSE)
|
[License](LICENSE)
|
||||||
|
|||||||
22
bin/fzf-tmux
22
bin/fzf-tmux
@@ -121,7 +121,7 @@ args+=("--no-height")
|
|||||||
if tmux list-panes -F '#F' | grep -q Z; then
|
if tmux list-panes -F '#F' | grep -q Z; then
|
||||||
zoomed=1
|
zoomed=1
|
||||||
original_window=$(tmux display-message -p "#{window_id}")
|
original_window=$(tmux display-message -p "#{window_id}")
|
||||||
tmp_window=$(tmux new-window -d -P -F "#{window_id}" "bash -c 'while :; do for c in \\| / - \\\\; do sleep 0.2; printf \"\\r\$c fzf-tmux is running\\r\"; done; done'")
|
tmp_window=$(tmux new-window -d -P -F "#{window_id}" "bash -c 'while :; do for c in \\| / - '\\;' do sleep 0.2; printf \"\\r\$c fzf-tmux is running\\r\"; done; done'")
|
||||||
tmux swap-pane -t $tmp_window \; select-window -t $tmp_window
|
tmux swap-pane -t $tmp_window \; select-window -t $tmp_window
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -134,17 +134,24 @@ fifo1="${TMPDIR:-/tmp}/fzf-fifo1-$id"
|
|||||||
fifo2="${TMPDIR:-/tmp}/fzf-fifo2-$id"
|
fifo2="${TMPDIR:-/tmp}/fzf-fifo2-$id"
|
||||||
fifo3="${TMPDIR:-/tmp}/fzf-fifo3-$id"
|
fifo3="${TMPDIR:-/tmp}/fzf-fifo3-$id"
|
||||||
cleanup() {
|
cleanup() {
|
||||||
rm -f $argsf $fifo1 $fifo2 $fifo3
|
\rm -f $argsf $fifo1 $fifo2 $fifo3
|
||||||
|
|
||||||
# Remove temp window if we were zoomed
|
# Remove temp window if we were zoomed
|
||||||
if [[ -n "$zoomed" ]]; then
|
if [[ -n "$zoomed" ]]; then
|
||||||
|
tmux display-message -p "#{window_id}" > /dev/null
|
||||||
tmux swap-pane -t $original_window \; \
|
tmux swap-pane -t $original_window \; \
|
||||||
select-window -t $original_window \; \
|
select-window -t $original_window \; \
|
||||||
kill-window -t $tmp_window \; \
|
kill-window -t $tmp_window \; \
|
||||||
resize-pane -Z
|
resize-pane -Z
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ $# -gt 0 ]; then
|
||||||
|
trap - EXIT
|
||||||
|
exit 130
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
trap cleanup EXIT SIGINT SIGTERM
|
trap 'cleanup 1' SIGUSR1
|
||||||
|
trap 'cleanup' EXIT
|
||||||
|
|
||||||
envs="env TERM=$TERM "
|
envs="env TERM=$TERM "
|
||||||
[[ -n "$FZF_DEFAULT_OPTS" ]] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
[[ -n "$FZF_DEFAULT_OPTS" ]] && envs="$envs FZF_DEFAULT_OPTS=$(printf %q "$FZF_DEFAULT_OPTS")"
|
||||||
@@ -163,15 +170,20 @@ for arg in "${args[@]}"; do
|
|||||||
opts="$opts \"$arg\""
|
opts="$opts \"$arg\""
|
||||||
done
|
done
|
||||||
|
|
||||||
|
pppid=$$
|
||||||
|
echo -n "trap 'kill -SIGUSR1 -$pppid' EXIT SIGINT SIGTERM;" > $argsf
|
||||||
|
close="; trap - EXIT SIGINT SIGTERM $close"
|
||||||
|
|
||||||
if [[ -n "$term" ]] || [[ -t 0 ]]; then
|
if [[ -n "$term" ]] || [[ -t 0 ]]; then
|
||||||
cat <<< "\"$fzf\" $opts > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
cat <<< "\"$fzf\" $opts > $fifo2; echo \$? > $fifo3 $close" >> $argsf
|
||||||
|
cat $argsf
|
||||||
TMUX=$(echo $TMUX | cut -d , -f 1,2) tmux set-window-option synchronize-panes off \;\
|
TMUX=$(echo $TMUX | cut -d , -f 1,2) tmux set-window-option synchronize-panes off \;\
|
||||||
set-window-option remain-on-exit off \;\
|
set-window-option remain-on-exit off \;\
|
||||||
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap \
|
split-window $opt "cd $(printf %q "$PWD");$envs bash $argsf" $swap \
|
||||||
> /dev/null 2>&1
|
> /dev/null 2>&1
|
||||||
else
|
else
|
||||||
mkfifo $fifo1
|
mkfifo $fifo1
|
||||||
cat <<< "\"$fzf\" $opts < $fifo1 > $fifo2; echo \$? > $fifo3 $close" > $argsf
|
cat <<< "\"$fzf\" $opts < $fifo1 > $fifo2; echo \$? > $fifo3 $close" >> $argsf
|
||||||
TMUX=$(echo $TMUX | cut -d , -f 1,2) tmux set-window-option synchronize-panes off \;\
|
TMUX=$(echo $TMUX | cut -d , -f 1,2) tmux set-window-option synchronize-panes off \;\
|
||||||
set-window-option remain-on-exit off \;\
|
set-window-option remain-on-exit off \;\
|
||||||
split-window $opt "$envs bash $argsf" $swap \
|
split-window $opt "$envs bash $argsf" $swap \
|
||||||
|
|||||||
195
doc/fzf.txt
Normal file
195
doc/fzf.txt
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
fzf.txt fzf Last change: August 14 2017
|
||||||
|
FZF - TABLE OF CONTENTS *fzf* *fzf-toc*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
FZF Vim integration
|
||||||
|
:FZF[!]
|
||||||
|
Configuration
|
||||||
|
Examples
|
||||||
|
fzf#run
|
||||||
|
fzf#wrap
|
||||||
|
GVim
|
||||||
|
License
|
||||||
|
|
||||||
|
FZF VIM INTEGRATION *fzf-vim-integration*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
This repository only enables basic integration with Vim. If you're looking for
|
||||||
|
more, check out {fzf.vim}{1} project.
|
||||||
|
|
||||||
|
(Note: To use fzf in GVim, an external terminal emulator is required.)
|
||||||
|
|
||||||
|
{1} https://github.com/junegunn/fzf.vim
|
||||||
|
|
||||||
|
|
||||||
|
:FZF[!]
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
*:FZF*
|
||||||
|
|
||||||
|
If you have set up fzf for Vim, `:FZF` command will be added.
|
||||||
|
>
|
||||||
|
" Look for files under current directory
|
||||||
|
:FZF
|
||||||
|
|
||||||
|
" Look for files under your home directory
|
||||||
|
:FZF ~
|
||||||
|
|
||||||
|
" With options
|
||||||
|
:FZF --no-sort --reverse --inline-info /tmp
|
||||||
|
|
||||||
|
" Bang version starts fzf in fullscreen mode
|
||||||
|
:FZF!
|
||||||
|
<
|
||||||
|
Similarly to {ctrlp.vim}{2}, use enter key, CTRL-T, CTRL-X or CTRL-V to open
|
||||||
|
selected files in the current window, in new tabs, in horizontal splits, or in
|
||||||
|
vertical splits respectively.
|
||||||
|
|
||||||
|
Note that the environment variables `FZF_DEFAULT_COMMAND` and
|
||||||
|
`FZF_DEFAULT_OPTS` also apply here.
|
||||||
|
|
||||||
|
{2} https://github.com/kien/ctrlp.vim
|
||||||
|
|
||||||
|
|
||||||
|
< Configuration >_____________________________________________________________~
|
||||||
|
*fzf-configuration*
|
||||||
|
|
||||||
|
*g:fzf_action* *g:fzf_layout* *g:fzf_colors* *g:fzf_history_dir* *g:fzf_launcher*
|
||||||
|
*g:Fzf_launcher*
|
||||||
|
|
||||||
|
- `g:fzf_action`
|
||||||
|
- Customizable extra key bindings for opening selected files in different
|
||||||
|
ways
|
||||||
|
- `g:fzf_layout`
|
||||||
|
- Determines the size and position of fzf window (tmux pane or Neovim split)
|
||||||
|
- `g:fzf_colors`
|
||||||
|
- Customizes fzf colors to match the current color scheme
|
||||||
|
- `g:fzf_history_dir`
|
||||||
|
- Enables history feature
|
||||||
|
- `g:fzf_launcher`
|
||||||
|
- (Only in GVim) Terminal emulator to open fzf with
|
||||||
|
- `g:Fzf_launcher` for function reference
|
||||||
|
|
||||||
|
|
||||||
|
Examples~
|
||||||
|
*fzf-examples*
|
||||||
|
>
|
||||||
|
" This is the default extra key bindings
|
||||||
|
let g:fzf_action = {
|
||||||
|
\ 'ctrl-t': 'tab split',
|
||||||
|
\ 'ctrl-x': 'split',
|
||||||
|
\ 'ctrl-v': 'vsplit' }
|
||||||
|
|
||||||
|
" An action can be a reference to a function that processes selected lines
|
||||||
|
function! s:build_quickfix_list(lines)
|
||||||
|
call setqflist(map(copy(a:lines), '{ "filename": v:val }'))
|
||||||
|
copen
|
||||||
|
cc
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
let g:fzf_action = {
|
||||||
|
\ 'ctrl-q': function('s:build_quickfix_list'),
|
||||||
|
\ 'ctrl-t': 'tab split',
|
||||||
|
\ 'ctrl-x': 'split',
|
||||||
|
\ 'ctrl-v': 'vsplit' }
|
||||||
|
|
||||||
|
" Default fzf layout
|
||||||
|
" - down / up / left / right
|
||||||
|
let g:fzf_layout = { 'down': '~40%' }
|
||||||
|
|
||||||
|
" In Neovim, you can set up fzf window using a Vim command
|
||||||
|
let g:fzf_layout = { 'window': 'enew' }
|
||||||
|
let g:fzf_layout = { 'window': '-tabnew' }
|
||||||
|
let g:fzf_layout = { 'window': '10split enew' }
|
||||||
|
|
||||||
|
" Customize fzf colors to match your color scheme
|
||||||
|
let g:fzf_colors =
|
||||||
|
\ { 'fg': ['fg', 'Normal'],
|
||||||
|
\ 'bg': ['bg', 'Normal'],
|
||||||
|
\ 'hl': ['fg', 'Comment'],
|
||||||
|
\ 'fg+': ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
|
||||||
|
\ 'bg+': ['bg', 'CursorLine', 'CursorColumn'],
|
||||||
|
\ 'hl+': ['fg', 'Statement'],
|
||||||
|
\ 'info': ['fg', 'PreProc'],
|
||||||
|
\ 'prompt': ['fg', 'Conditional'],
|
||||||
|
\ 'pointer': ['fg', 'Exception'],
|
||||||
|
\ 'marker': ['fg', 'Keyword'],
|
||||||
|
\ 'spinner': ['fg', 'Label'],
|
||||||
|
\ 'header': ['fg', 'Comment'] }
|
||||||
|
|
||||||
|
" Enable per-command history.
|
||||||
|
" CTRL-N and CTRL-P will be automatically bound to next-history and
|
||||||
|
" previous-history instead of down and up. If you don't like the change,
|
||||||
|
" explicitly bind the keys to down and up in your $FZF_DEFAULT_OPTS.
|
||||||
|
let g:fzf_history_dir = '~/.local/share/fzf-history'
|
||||||
|
<
|
||||||
|
|
||||||
|
FZF#RUN *fzf#run*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
For more advanced uses, you can use `fzf#run([options])` function with the
|
||||||
|
following options.
|
||||||
|
|
||||||
|
---------------------------+---------------+--------------------------------------------------------------
|
||||||
|
Option name | Type | Description ~
|
||||||
|
---------------------------+---------------+--------------------------------------------------------------
|
||||||
|
`source` | string | External command to generate input to fzf (e.g. `find .` )
|
||||||
|
`source` | list | Vim list as input to fzf
|
||||||
|
`sink` | string | Vim command to handle the selected item (e.g. `e` , `tabe` )
|
||||||
|
`sink` | funcref | Reference to function to process each selected item
|
||||||
|
`sink*` | funcref | Similar to `sink` , but takes the list of output lines at once
|
||||||
|
`options` | string/list | Options to fzf
|
||||||
|
`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 (GVim only)
|
||||||
|
`launcher` | funcref | Function for generating `launcher` string (GVim only)
|
||||||
|
---------------------------+---------------+--------------------------------------------------------------
|
||||||
|
|
||||||
|
`options` entry can be either a string or a list. For simple cases, string
|
||||||
|
should suffice, but prefer to use list type if you're concerned about escaping
|
||||||
|
issues on different platforms.
|
||||||
|
>
|
||||||
|
call fzf#run({'options': '--reverse --prompt "C:\\Program Files\\"'})
|
||||||
|
call fzf#run({'options': ['--reverse', '--prompt', 'C:\Program Files\']})
|
||||||
|
<
|
||||||
|
|
||||||
|
FZF#WRAP *fzf#wrap*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
`fzf#wrap([name string,] [opts dict,] [fullscreen boolean])` is a helper
|
||||||
|
function that decorates the options dictionary so that it understands
|
||||||
|
`g:fzf_layout`, `g:fzf_action`, `g:fzf_colors`, and `g:fzf_history_dir` like
|
||||||
|
`:FZF`.
|
||||||
|
>
|
||||||
|
command! -bang MyStuff
|
||||||
|
\ call fzf#run(fzf#wrap('my-stuff', {'dir': '~/my-stuff'}, <bang>0))
|
||||||
|
<
|
||||||
|
|
||||||
|
GVIM *fzf-gvim*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
In GVim, you need an external terminal emulator to start fzf with. `xterm`
|
||||||
|
command is used by default, but you can customize it with `g:fzf_launcher`.
|
||||||
|
>
|
||||||
|
" This is the default. %s is replaced with fzf command
|
||||||
|
let g:fzf_launcher = 'xterm -e bash -ic %s'
|
||||||
|
|
||||||
|
" Use urxvt instead
|
||||||
|
let g:fzf_launcher = 'urxvt -geometry 120x30 -e sh -c %s'
|
||||||
|
<
|
||||||
|
If you're running MacVim on OSX, I recommend you to use iTerm2 as the
|
||||||
|
launcher. Refer to the {this wiki page}{3} to see how to set up.
|
||||||
|
|
||||||
|
{3} https://github.com/junegunn/fzf/wiki/On-MacVim-with-iTerm2
|
||||||
|
|
||||||
|
|
||||||
|
LICENSE *fzf-license*
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2017 Junegunn Choi
|
||||||
|
|
||||||
|
==============================================================================
|
||||||
|
vim:tw=78:sw=2:ts=2:ft=help:norl:nowrap:
|
||||||
38
glide.lock
generated
Normal file
38
glide.lock
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
hash: d68dd0bd779ac4ffca1e0c49ca38d85f90d5d68fa8e2d5d7db70a8ce8c662ec1
|
||||||
|
updated: 2017-06-01T15:48:41.653745249-07:00
|
||||||
|
imports:
|
||||||
|
- name: github.com/gdamore/encoding
|
||||||
|
version: b23993cbb6353f0e6aa98d0ee318a34728f628b9
|
||||||
|
- name: github.com/gdamore/tcell
|
||||||
|
version: 44772c121bb7838819d3ba4a7e84c0c2d617328e
|
||||||
|
subpackages:
|
||||||
|
- encoding
|
||||||
|
- name: github.com/lucasb-eyer/go-colorful
|
||||||
|
version: c900de9dbbc73129068f5af6a823068fc5f2308c
|
||||||
|
- name: github.com/mattn/go-isatty
|
||||||
|
version: 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8
|
||||||
|
- name: github.com/mattn/go-runewidth
|
||||||
|
version: 14207d285c6c197daabb5c9793d63e7af9ab2d50
|
||||||
|
- name: github.com/mattn/go-shellwords
|
||||||
|
version: 02e3cf038dcea8290e44424da473dd12be796a8a
|
||||||
|
- name: golang.org/x/crypto
|
||||||
|
version: e1a4589e7d3ea14a3352255d04b6f1a418845e5e
|
||||||
|
subpackages:
|
||||||
|
- ssh/terminal
|
||||||
|
- name: golang.org/x/sys
|
||||||
|
version: b90f89a1e7a9c1f6b918820b3daa7f08488c8594
|
||||||
|
subpackages:
|
||||||
|
- unix
|
||||||
|
- name: golang.org/x/text
|
||||||
|
version: 4ee4af566555f5fbe026368b75596286a312663a
|
||||||
|
subpackages:
|
||||||
|
- encoding
|
||||||
|
- encoding/charmap
|
||||||
|
- encoding/internal
|
||||||
|
- encoding/internal/identifier
|
||||||
|
- encoding/japanese
|
||||||
|
- encoding/korean
|
||||||
|
- encoding/simplifiedchinese
|
||||||
|
- encoding/traditionalchinese
|
||||||
|
- transform
|
||||||
|
testImports: []
|
||||||
16
glide.yaml
Normal file
16
glide.yaml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package: github.com/junegunn/fzf
|
||||||
|
import:
|
||||||
|
- package: github.com/mattn/go-isatty
|
||||||
|
version: 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8
|
||||||
|
- package: github.com/mattn/go-runewidth
|
||||||
|
version: 14207d285c6c197daabb5c9793d63e7af9ab2d50
|
||||||
|
- package: github.com/mattn/go-shellwords
|
||||||
|
version: 02e3cf038dcea8290e44424da473dd12be796a8a
|
||||||
|
- package: github.com/gdamore/tcell
|
||||||
|
version: 44772c121bb7838819d3ba4a7e84c0c2d617328e
|
||||||
|
subpackages:
|
||||||
|
- encoding
|
||||||
|
- package: golang.org/x/crypto
|
||||||
|
version: e1a4589e7d3ea14a3352255d04b6f1a418845e5e
|
||||||
|
subpackages:
|
||||||
|
- ssh/terminal
|
||||||
157
install
157
install
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
set -u
|
set -u
|
||||||
|
|
||||||
version=0.16.4
|
version=0.17.0
|
||||||
auto_completion=
|
auto_completion=
|
||||||
key_bindings=
|
key_bindings=
|
||||||
update_config=2
|
update_config=2
|
||||||
@@ -72,7 +72,7 @@ ask() {
|
|||||||
check_binary() {
|
check_binary() {
|
||||||
echo -n " - Checking fzf executable ... "
|
echo -n " - Checking fzf executable ... "
|
||||||
local output
|
local output
|
||||||
output=$("$fzf_base"/bin/fzf --version 2>&1)
|
output=$("$fzf_base"/bin/fzf --version 2>&1 | awk '{print $1}')
|
||||||
if [ $? -ne 0 ]; then
|
if [ $? -ne 0 ]; then
|
||||||
echo "Error: $output"
|
echo "Error: $output"
|
||||||
binary_error="Invalid binary"
|
binary_error="Invalid binary"
|
||||||
@@ -99,11 +99,23 @@ link_fzf_in_path() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try_curl() {
|
try_curl() {
|
||||||
command -v curl > /dev/null && curl -fL $1 | tar -xz
|
command -v curl > /dev/null &&
|
||||||
|
if [[ $1 =~ tgz$ ]]; then
|
||||||
|
curl -fL $1 | tar -xzf -
|
||||||
|
else
|
||||||
|
local temp=${TMPDIR:-/tmp}/fzf.zip
|
||||||
|
curl -fLo "$temp" $1 && unzip -o "$temp" && rm -f "$temp"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
try_wget() {
|
try_wget() {
|
||||||
command -v wget > /dev/null && wget -O - $1 | tar -xz
|
command -v wget > /dev/null &&
|
||||||
|
if [[ $1 =~ tgz$ ]]; then
|
||||||
|
wget -O - $1 | tar -xzf -
|
||||||
|
else
|
||||||
|
local temp=${TMPDIR:-/tmp}/fzf.zip
|
||||||
|
wget -O "$temp" $1 && unzip -o "$temp" && rm -f "$temp"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
download() {
|
download() {
|
||||||
@@ -123,8 +135,8 @@ download() {
|
|||||||
|
|
||||||
local url
|
local url
|
||||||
[[ "$version" =~ alpha ]] &&
|
[[ "$version" =~ alpha ]] &&
|
||||||
url=https://github.com/junegunn/fzf-bin/releases/download/alpha/${1}.tgz ||
|
url=https://github.com/junegunn/fzf-bin/releases/download/alpha/${1} ||
|
||||||
url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}.tgz
|
url=https://github.com/junegunn/fzf-bin/releases/download/$version/${1}
|
||||||
set -o pipefail
|
set -o pipefail
|
||||||
if ! (try_curl $url || try_wget $url); then
|
if ! (try_curl $url || try_wget $url); then
|
||||||
set +o pipefail
|
set +o pipefail
|
||||||
@@ -146,92 +158,24 @@ archi=$(uname -sm)
|
|||||||
binary_available=1
|
binary_available=1
|
||||||
binary_error=""
|
binary_error=""
|
||||||
case "$archi" in
|
case "$archi" in
|
||||||
Darwin\ *64) download fzf-$version-darwin_${binary_arch:-amd64} ;;
|
Darwin\ *64) download fzf-$version-darwin_${binary_arch:-amd64}.tgz ;;
|
||||||
Darwin\ *86) download fzf-$version-darwin_${binary_arch:-386} ;;
|
Darwin\ *86) download fzf-$version-darwin_${binary_arch:-386}.tgz ;;
|
||||||
Linux\ *64) download fzf-$version-linux_${binary_arch:-amd64} ;;
|
Linux\ *64) download fzf-$version-linux_${binary_arch:-amd64}.tgz ;;
|
||||||
Linux\ *86) download fzf-$version-linux_${binary_arch:-386} ;;
|
Linux\ *86) download fzf-$version-linux_${binary_arch:-386}.tgz ;;
|
||||||
Linux\ armv5*) download fzf-$version-linux_${binary_arch:-arm5} ;;
|
Linux\ armv5*) download fzf-$version-linux_${binary_arch:-arm5}.tgz ;;
|
||||||
Linux\ armv6*) download fzf-$version-linux_${binary_arch:-arm6} ;;
|
Linux\ armv6*) download fzf-$version-linux_${binary_arch:-arm6}.tgz ;;
|
||||||
Linux\ armv7*) download fzf-$version-linux_${binary_arch:-arm7} ;;
|
Linux\ armv7*) download fzf-$version-linux_${binary_arch:-arm7}.tgz ;;
|
||||||
Linux\ armv8*) download fzf-$version-linux_${binary_arch:-arm8} ;;
|
Linux\ armv8*) download fzf-$version-linux_${binary_arch:-arm8}.tgz ;;
|
||||||
FreeBSD\ *64) download fzf-$version-freebsd_${binary_arch:-amd64} ;;
|
FreeBSD\ *64) download fzf-$version-freebsd_${binary_arch:-amd64}.tgz ;;
|
||||||
FreeBSD\ *86) download fzf-$version-freebsd_${binary_arch:-386} ;;
|
FreeBSD\ *86) download fzf-$version-freebsd_${binary_arch:-386}.tgz ;;
|
||||||
OpenBSD\ *64) download fzf-$version-openbsd_${binary_arch:-amd64} ;;
|
OpenBSD\ *64) download fzf-$version-openbsd_${binary_arch:-amd64}.tgz ;;
|
||||||
OpenBSD\ *86) download fzf-$version-openbsd_${binary_arch:-386} ;;
|
OpenBSD\ *86) download fzf-$version-openbsd_${binary_arch:-386}.tgz ;;
|
||||||
*) binary_available=0 binary_error=1 ;;
|
CYGWIN*\ *64) download fzf-$version-windows_${binary_arch:-amd64}.zip ;;
|
||||||
|
MINGW*\ *86) download fzf-$version-windows_${binary_arch:-386}.zip ;;
|
||||||
|
MINGW*\ *64) download fzf-$version-windows_${binary_arch:-amd64}.zip ;;
|
||||||
|
*) binary_available=0 binary_error=1 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
install_ruby_fzf() {
|
|
||||||
if [ -z "$allow_legacy" ]; then
|
|
||||||
ask "Do you want to install legacy Ruby version instead?" && exit 1
|
|
||||||
fi
|
|
||||||
echo "Installing legacy Ruby version ..."
|
|
||||||
|
|
||||||
# ruby executable
|
|
||||||
echo -n "Checking Ruby executable ... "
|
|
||||||
ruby=$(command -v ruby)
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "ruby executable not found !!!"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# System ruby is preferred
|
|
||||||
system_ruby=/usr/bin/ruby
|
|
||||||
if [ -x $system_ruby ] && [ $system_ruby != "$ruby" ]; then
|
|
||||||
$system_ruby --disable-gems -rcurses -e0 2> /dev/null
|
|
||||||
[ $? -eq 0 ] && ruby=$system_ruby
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "OK ($ruby)"
|
|
||||||
|
|
||||||
# Curses-support
|
|
||||||
echo -n "Checking Curses support ... "
|
|
||||||
"$ruby" -rcurses -e0 2> /dev/null
|
|
||||||
if [ $? -eq 0 ]; then
|
|
||||||
echo "OK"
|
|
||||||
else
|
|
||||||
echo "Not found"
|
|
||||||
echo "Installing 'curses' gem ... "
|
|
||||||
if (( EUID )); then
|
|
||||||
/usr/bin/env gem install curses --user-install
|
|
||||||
else
|
|
||||||
/usr/bin/env gem install curses
|
|
||||||
fi
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo
|
|
||||||
echo "Failed to install 'curses' gem."
|
|
||||||
if [[ $(uname -r) =~ 'ARCH' ]]; then
|
|
||||||
echo "Make sure that base-devel package group is installed."
|
|
||||||
fi
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Ruby version
|
|
||||||
echo -n "Checking Ruby version ... "
|
|
||||||
"$ruby" -e 'exit RUBY_VERSION >= "1.9"'
|
|
||||||
if [ $? -eq 0 ]; then
|
|
||||||
echo ">= 1.9"
|
|
||||||
"$ruby" --disable-gems -rcurses -e0 2> /dev/null
|
|
||||||
if [ $? -eq 0 ]; then
|
|
||||||
fzf_cmd="$ruby --disable-gems $fzf_base/fzf"
|
|
||||||
else
|
|
||||||
fzf_cmd="$ruby $fzf_base/fzf"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "< 1.9"
|
|
||||||
fzf_cmd="$ruby $fzf_base/fzf"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Create fzf script
|
|
||||||
echo -n "Creating wrapper script for fzf ... "
|
|
||||||
rm -f "$fzf_base"/bin/fzf
|
|
||||||
echo "#!/bin/sh" > "$fzf_base"/bin/fzf
|
|
||||||
echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf
|
|
||||||
chmod +x "$fzf_base"/bin/fzf
|
|
||||||
echo "OK"
|
|
||||||
}
|
|
||||||
|
|
||||||
cd "$fzf_base"
|
cd "$fzf_base"
|
||||||
if [ -n "$binary_error" ]; then
|
if [ -n "$binary_error" ]; then
|
||||||
if [ $binary_available -eq 0 ]; then
|
if [ $binary_available -eq 0 ]; then
|
||||||
@@ -240,21 +184,21 @@ if [ -n "$binary_error" ]; then
|
|||||||
echo " - $binary_error !!!"
|
echo " - $binary_error !!!"
|
||||||
fi
|
fi
|
||||||
if command -v go > /dev/null; then
|
if command -v go > /dev/null; then
|
||||||
echo -n "Building binary (go get -u github.com/junegunn/fzf/src/fzf) ... "
|
echo -n "Building binary (go get -u github.com/junegunn/fzf) ... "
|
||||||
if [ -z "${GOPATH-}" ]; then
|
if [ -z "${GOPATH-}" ]; then
|
||||||
export GOPATH="${TMPDIR:-/tmp}/fzf-gopath"
|
export GOPATH="${TMPDIR:-/tmp}/fzf-gopath"
|
||||||
mkdir -p "$GOPATH"
|
mkdir -p "$GOPATH"
|
||||||
fi
|
fi
|
||||||
if go get -u github.com/junegunn/fzf/src/fzf; then
|
if go get -u github.com/junegunn/fzf; then
|
||||||
echo "OK"
|
echo "OK"
|
||||||
cp "$GOPATH/bin/fzf" "$fzf_base/bin/"
|
cp "$GOPATH/bin/fzf" "$fzf_base/bin/"
|
||||||
else
|
else
|
||||||
echo "Failed to build binary ..."
|
echo "Failed to build binary. Installation failed."
|
||||||
install_ruby_fzf
|
exit 1
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo "go executable not found. Cannot build binary ..."
|
echo "go executable not found. Installation failed."
|
||||||
install_ruby_fzf
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -368,6 +312,17 @@ append_line() {
|
|||||||
set +e
|
set +e
|
||||||
}
|
}
|
||||||
|
|
||||||
|
create_file() {
|
||||||
|
local file="$1"
|
||||||
|
shift
|
||||||
|
echo "Create $file:"
|
||||||
|
for line in "$@"; do
|
||||||
|
echo " $line"
|
||||||
|
echo "$line" >> "$file"
|
||||||
|
done
|
||||||
|
echo
|
||||||
|
}
|
||||||
|
|
||||||
if [ $update_config -eq 2 ]; then
|
if [ $update_config -eq 2 ]; then
|
||||||
echo
|
echo
|
||||||
ask "Do you want to update your shell configuration files?"
|
ask "Do you want to update your shell configuration files?"
|
||||||
@@ -381,7 +336,14 @@ done
|
|||||||
|
|
||||||
if [ $key_bindings -eq 1 ] && [ $has_fish -eq 1 ]; then
|
if [ $key_bindings -eq 1 ] && [ $has_fish -eq 1 ]; then
|
||||||
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
bind_file=~/.config/fish/functions/fish_user_key_bindings.fish
|
||||||
append_line $update_config "fzf_key_bindings" "$bind_file"
|
if [ ! -e "$bind_file" ]; then
|
||||||
|
create_file "$bind_file" \
|
||||||
|
'function fish_user_key_bindings' \
|
||||||
|
' fzf_key_bindings' \
|
||||||
|
'end'
|
||||||
|
else
|
||||||
|
append_line $update_config "fzf_key_bindings" "$bind_file"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ $update_config -eq 1 ]; then
|
if [ $update_config -eq 1 ]; then
|
||||||
@@ -394,4 +356,3 @@ if [ $update_config -eq 1 ]; then
|
|||||||
echo
|
echo
|
||||||
fi
|
fi
|
||||||
echo 'For more information, see: https://github.com/junegunn/fzf'
|
echo 'For more information, see: https://github.com/junegunn/fzf'
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package main
|
|||||||
|
|
||||||
import "github.com/junegunn/fzf/src"
|
import "github.com/junegunn/fzf/src"
|
||||||
|
|
||||||
|
var revision string
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fzf.Run(fzf.ParseOptions())
|
fzf.Run(fzf.ParseOptions(), revision)
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
..
|
..
|
||||||
.TH fzf-tmux 1 "Feb 2017" "fzf 0.16.4" "fzf-tmux - open fzf in tmux split pane"
|
.TH fzf-tmux 1 "Aug 2017" "fzf 0.17.0" "fzf-tmux - open fzf in tmux split pane"
|
||||||
|
|
||||||
.SH NAME
|
.SH NAME
|
||||||
fzf-tmux - open fzf in tmux split pane
|
fzf-tmux - open fzf in tmux split pane
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
..
|
..
|
||||||
.TH fzf 1 "Feb 2017" "fzf 0.16.4" "fzf - a command-line fuzzy finder"
|
.TH fzf 1 "Aug 2017" "fzf 0.17.0" "fzf - a command-line fuzzy finder"
|
||||||
|
|
||||||
.SH NAME
|
.SH NAME
|
||||||
fzf - a command-line fuzzy finder
|
fzf - a command-line fuzzy finder
|
||||||
@@ -111,6 +111,9 @@ Comma-separated list of sort criteria to apply when the scores are tied.
|
|||||||
.B "-m, --multi"
|
.B "-m, --multi"
|
||||||
Enable multi-select with tab/shift-tab
|
Enable multi-select with tab/shift-tab
|
||||||
.TP
|
.TP
|
||||||
|
.B "+m, --no-multi"
|
||||||
|
Disable multi-select
|
||||||
|
.TP
|
||||||
.B "--no-mouse"
|
.B "--no-mouse"
|
||||||
Disable mouse
|
Disable mouse
|
||||||
.TP
|
.TP
|
||||||
@@ -236,6 +239,7 @@ e.g. \fBfzf --color=bg+:24\fR
|
|||||||
\fBbg+ \fRBackground (current line)
|
\fBbg+ \fRBackground (current line)
|
||||||
\fBhl+ \fRHighlighted substrings (current line)
|
\fBhl+ \fRHighlighted substrings (current line)
|
||||||
\fBinfo \fRInfo
|
\fBinfo \fRInfo
|
||||||
|
\fBborder \fRBorder of the preview window and horizontal separators (\fB--border\fR)
|
||||||
\fBprompt \fRPrompt
|
\fBprompt \fRPrompt
|
||||||
\fBpointer \fRPointer to the current line
|
\fBpointer \fRPointer to the current line
|
||||||
\fBmarker \fRMulti-select marker
|
\fBmarker \fRMulti-select marker
|
||||||
@@ -327,10 +331,12 @@ 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
|
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
|
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
|
\fB--print-query\fR is also used). The line will be empty if fzf is completed
|
||||||
with the default enter key.
|
with the default enter key. If \fB--expect\fR option is specified multiple
|
||||||
|
times, fzf will expect the union of the keys. \fB--no-expect\fR will clear the
|
||||||
|
list.
|
||||||
|
|
||||||
.RS
|
.RS
|
||||||
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s,f1,f2,~,@\fR
|
e.g. \fBfzf --expect=ctrl-v,ctrl-t,alt-s --expect=f1,f2,~,@\fR
|
||||||
.RE
|
.RE
|
||||||
.TP
|
.TP
|
||||||
.B "--read0"
|
.B "--read0"
|
||||||
@@ -339,6 +345,12 @@ Read input delimited by ASCII NUL characters instead of newline characters
|
|||||||
.B "--print0"
|
.B "--print0"
|
||||||
Print output delimited by ASCII NUL characters instead of newline characters
|
Print output delimited by ASCII NUL characters instead of newline characters
|
||||||
.TP
|
.TP
|
||||||
|
.B "--no-clear"
|
||||||
|
Do not clear finder interface on exit. If fzf was started in full screen mode,
|
||||||
|
it will not switch back to the original screen, so you'll have to manually run
|
||||||
|
\fBtput rmcup\fR to return. This option can be used to avoid flickering of the
|
||||||
|
screen when your application needs to start fzf multiple times in order.
|
||||||
|
.TP
|
||||||
.B "--sync"
|
.B "--sync"
|
||||||
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
Synchronous search for multi-staged filtering. If specified, fzf will launch
|
||||||
ncurses finder only after the input stream is complete.
|
ncurses finder only after the input stream is complete.
|
||||||
@@ -346,6 +358,12 @@ ncurses finder only after the input stream is complete.
|
|||||||
.RS
|
.RS
|
||||||
e.g. \fBfzf --multi | fzf --sync\fR
|
e.g. \fBfzf --multi | fzf --sync\fR
|
||||||
.RE
|
.RE
|
||||||
|
.TP
|
||||||
|
.B "--version"
|
||||||
|
Display version information and exit
|
||||||
|
|
||||||
|
.TP
|
||||||
|
Note that most options have the opposite versions with \fB--no-\fR prefix.
|
||||||
|
|
||||||
.SH ENVIRONMENT VARIABLES
|
.SH ENVIRONMENT VARIABLES
|
||||||
.TP
|
.TP
|
||||||
@@ -394,6 +412,9 @@ 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
|
mode, you can specify multiple patterns delimited by spaces, such as: \fB'wild
|
||||||
^music .mp3$ sbtrkt !rmx\fR
|
^music .mp3$ sbtrkt !rmx\fR
|
||||||
|
|
||||||
|
You can prepend a backslash to a space (\fB\\ \fR) to match a literal space
|
||||||
|
character.
|
||||||
|
|
||||||
.SS Exact-match (quoted)
|
.SS Exact-match (quoted)
|
||||||
A term that is prefixed by a single-quote character (\fB'\fR) is interpreted as
|
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
|
an "exact-match" (or "non-fuzzy") term. fzf will search for the exact
|
||||||
@@ -430,6 +451,7 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
|||||||
.B AVAILABLE KEYS: (SYNONYMS)
|
.B AVAILABLE KEYS: (SYNONYMS)
|
||||||
\fIctrl-[a-z]\fR
|
\fIctrl-[a-z]\fR
|
||||||
\fIctrl-space\fR
|
\fIctrl-space\fR
|
||||||
|
\fIctrl-alt-[a-z]\fR
|
||||||
\fIalt-[a-z]\fR
|
\fIalt-[a-z]\fR
|
||||||
\fIalt-[0-9]\fR
|
\fIalt-[0-9]\fR
|
||||||
\fIf[1-12]\fR
|
\fIf[1-12]\fR
|
||||||
@@ -457,6 +479,11 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
|||||||
\fIdouble-click\fR
|
\fIdouble-click\fR
|
||||||
or any single character
|
or any single character
|
||||||
|
|
||||||
|
Additionally, a special event named \fIchange\fR is available which is
|
||||||
|
triggered whenever the query string is changed.
|
||||||
|
|
||||||
|
e.g. \fBfzf --bind change:top\fR
|
||||||
|
|
||||||
\fBACTION: DEFAULT BINDINGS (NOTES):
|
\fBACTION: DEFAULT BINDINGS (NOTES):
|
||||||
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
\fBabort\fR \fIctrl-c ctrl-g ctrl-q esc\fR
|
||||||
\fBaccept\fR \fIenter double-click\fR
|
\fBaccept\fR \fIenter double-click\fR
|
||||||
@@ -500,8 +527,10 @@ e.g. \fBfzf --bind=ctrl-j:accept,ctrl-k:kill-line\fR
|
|||||||
\fBtoggle-in\fR (\fB--reverse\fR ? \fBtoggle+up\fR : \fBtoggle+down\fR)
|
\fBtoggle-in\fR (\fB--reverse\fR ? \fBtoggle+up\fR : \fBtoggle+down\fR)
|
||||||
\fBtoggle-out\fR (\fB--reverse\fR ? \fBtoggle+down\fR : \fBtoggle+up\fR)
|
\fBtoggle-out\fR (\fB--reverse\fR ? \fBtoggle+down\fR : \fBtoggle+up\fR)
|
||||||
\fBtoggle-preview\fR
|
\fBtoggle-preview\fR
|
||||||
|
\fBtoggle-preview-wrap\fR
|
||||||
\fBtoggle-sort\fR
|
\fBtoggle-sort\fR
|
||||||
\fBtoggle+up\fR \fIbtab (shift-tab)\fR
|
\fBtoggle+up\fR \fIbtab (shift-tab)\fR
|
||||||
|
\fBtop\fR (move to the top result)
|
||||||
\fBunix-line-discard\fR \fIctrl-u\fR
|
\fBunix-line-discard\fR \fIctrl-u\fR
|
||||||
\fBunix-word-rubout\fR \fIctrl-w\fR
|
\fBunix-word-rubout\fR \fIctrl-w\fR
|
||||||
\fBup\fR \fIctrl-k ctrl-p up\fR
|
\fBup\fR \fIctrl-k ctrl-p up\fR
|
||||||
|
|||||||
242
plugin/fzf.vim
242
plugin/fzf.vim
@@ -26,10 +26,76 @@ if exists('g:loaded_fzf')
|
|||||||
endif
|
endif
|
||||||
let g:loaded_fzf = 1
|
let g:loaded_fzf = 1
|
||||||
|
|
||||||
|
let s:is_win = has('win32') || has('win64')
|
||||||
|
if s:is_win && &shellslash
|
||||||
|
set noshellslash
|
||||||
|
let s:base_dir = expand('<sfile>:h:h')
|
||||||
|
set shellslash
|
||||||
|
else
|
||||||
|
let s:base_dir = expand('<sfile>:h:h')
|
||||||
|
endif
|
||||||
|
if s:is_win
|
||||||
|
function! s:fzf_call(fn, ...)
|
||||||
|
let shellslash = &shellslash
|
||||||
|
try
|
||||||
|
set noshellslash
|
||||||
|
return call(a:fn, a:000)
|
||||||
|
finally
|
||||||
|
let &shellslash = shellslash
|
||||||
|
endtry
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
" Use utf-8 for fzf.vim commands
|
||||||
|
" Return array of shell commands for cmd.exe
|
||||||
|
function! s:wrap_cmds(cmds)
|
||||||
|
return ['@echo off', 'for /f "tokens=4" %%a in (''chcp'') do set origchcp=%%a', 'chcp 65001 > nul'] +
|
||||||
|
\ (type(a:cmds) == type([]) ? a:cmds : [a:cmds]) +
|
||||||
|
\ ['chcp %origchcp% > nul']
|
||||||
|
endfunction
|
||||||
|
else
|
||||||
|
function! s:fzf_call(fn, ...)
|
||||||
|
return call(a:fn, a:000)
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:wrap_cmds(cmds)
|
||||||
|
return a:cmds
|
||||||
|
endfunction
|
||||||
|
endif
|
||||||
|
|
||||||
|
function! s:shellesc_cmd(arg)
|
||||||
|
let escaped = substitute(a:arg, '[&|<>()@^]', '^&', 'g')
|
||||||
|
let escaped = substitute(escaped, '%', '%%', 'g')
|
||||||
|
let escaped = substitute(escaped, '"', '\\^&', 'g')
|
||||||
|
let escaped = substitute(escaped, '\(\\\+\)\(\\^\)', '\1\1\2', 'g')
|
||||||
|
return '^"'.substitute(escaped, '\(\\\+\)$', '\1\1', '').'^"'
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! fzf#shellescape(arg, ...)
|
||||||
|
let shell = get(a:000, 0, &shell)
|
||||||
|
if shell =~# 'cmd.exe$'
|
||||||
|
return s:shellesc_cmd(a:arg)
|
||||||
|
endif
|
||||||
|
return s:fzf_call('shellescape', a:arg)
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:fzf_getcwd()
|
||||||
|
return s:fzf_call('getcwd')
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:fzf_fnamemodify(fname, mods)
|
||||||
|
return s:fzf_call('fnamemodify', a:fname, a:mods)
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:fzf_expand(fmt)
|
||||||
|
return s:fzf_call('expand', a:fmt, 1)
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:fzf_tempname()
|
||||||
|
return s:fzf_call('tempname')
|
||||||
|
endfunction
|
||||||
|
|
||||||
let s:default_layout = { 'down': '~40%' }
|
let s:default_layout = { 'down': '~40%' }
|
||||||
let s:layout_keys = ['window', 'up', 'down', 'left', 'right']
|
let s:layout_keys = ['window', 'up', 'down', 'left', 'right']
|
||||||
let s:is_win = has('win32') || has('win64')
|
|
||||||
let s:base_dir = expand('<sfile>:h:h')
|
|
||||||
let s:fzf_go = s:base_dir.'/bin/fzf'
|
let s:fzf_go = s:base_dir.'/bin/fzf'
|
||||||
let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'
|
let s:fzf_tmux = s:base_dir.'/bin/fzf-tmux'
|
||||||
let s:install = s:base_dir.'/install'
|
let s:install = s:base_dir.'/install'
|
||||||
@@ -44,7 +110,7 @@ function! s:fzf_exec()
|
|||||||
let s:exec = s:fzf_go
|
let s:exec = s:fzf_go
|
||||||
elseif executable('fzf')
|
elseif executable('fzf')
|
||||||
let s:exec = 'fzf'
|
let s:exec = 'fzf'
|
||||||
elseif s:is_win
|
elseif s:is_win && !has('win32unix')
|
||||||
call s:warn('fzf executable not found.')
|
call s:warn('fzf executable not found.')
|
||||||
call s:warn('Download fzf binary for Windows from https://github.com/junegunn/fzf-bin/releases/')
|
call s:warn('Download fzf binary for Windows from https://github.com/junegunn/fzf-bin/releases/')
|
||||||
call s:warn('and place it as '.s:base_dir.'\bin\fzf.exe')
|
call s:warn('and place it as '.s:base_dir.'\bin\fzf.exe')
|
||||||
@@ -62,7 +128,7 @@ function! s:fzf_exec()
|
|||||||
throw 'fzf executable not found'
|
throw 'fzf executable not found'
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
return s:shellesc(s:exec)
|
return fzf#shellescape(s:exec)
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:tmux_enabled()
|
function! s:tmux_enabled()
|
||||||
@@ -82,18 +148,9 @@ function! s:tmux_enabled()
|
|||||||
return s:tmux
|
return s:tmux
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:shellesc(arg)
|
|
||||||
return '"'.substitute(a:arg, '"', '\\"', 'g').'"'
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
function! s:escape(path)
|
function! s:escape(path)
|
||||||
let escaped_chars = '$%#''"'
|
let path = fnameescape(a:path)
|
||||||
|
return s:is_win ? escape(path, '$') : path
|
||||||
if has('unix')
|
|
||||||
let escaped_chars .= ' \'
|
|
||||||
endif
|
|
||||||
|
|
||||||
return escape(a:path, escaped_chars)
|
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
" Upgrade legacy options
|
" Upgrade legacy options
|
||||||
@@ -133,7 +190,7 @@ function! s:has_any(dict, keys)
|
|||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:open(cmd, target)
|
function! s:open(cmd, target)
|
||||||
if stridx('edit', a:cmd) == 0 && fnamemodify(a:target, ':p') ==# expand('%:p')
|
if stridx('edit', a:cmd) == 0 && s:fzf_fnamemodify(a:target, ':p') ==# s:fzf_expand('%:p')
|
||||||
return
|
return
|
||||||
endif
|
endif
|
||||||
execute a:cmd s:escape(a:target)
|
execute a:cmd s:escape(a:target)
|
||||||
@@ -144,15 +201,18 @@ function! s:common_sink(action, lines) abort
|
|||||||
return
|
return
|
||||||
endif
|
endif
|
||||||
let key = remove(a:lines, 0)
|
let key = remove(a:lines, 0)
|
||||||
let cmd = get(a:action, key, 'e')
|
let Cmd = get(a:action, key, 'e')
|
||||||
|
if type(Cmd) == type(function('call'))
|
||||||
|
return Cmd(a:lines)
|
||||||
|
endif
|
||||||
if len(a:lines) > 1
|
if len(a:lines) > 1
|
||||||
augroup fzf_swap
|
augroup fzf_swap
|
||||||
autocmd SwapExists * let v:swapchoice='o'
|
autocmd SwapExists * let v:swapchoice='o'
|
||||||
\| call s:warn('fzf: E325: swap file exists: '.expand('<afile>'))
|
\| call s:warn('fzf: E325: swap file exists: '.s:fzf_expand('<afile>'))
|
||||||
augroup END
|
augroup END
|
||||||
endif
|
endif
|
||||||
try
|
try
|
||||||
let empty = empty(expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified
|
let empty = empty(s:fzf_expand('%')) && line('$') == 1 && empty(getline(1)) && !&modified
|
||||||
let autochdir = &autochdir
|
let autochdir = &autochdir
|
||||||
set noautochdir
|
set noautochdir
|
||||||
for item in a:lines
|
for item in a:lines
|
||||||
@@ -160,7 +220,7 @@ function! s:common_sink(action, lines) abort
|
|||||||
execute 'e' s:escape(item)
|
execute 'e' s:escape(item)
|
||||||
let empty = 0
|
let empty = 0
|
||||||
else
|
else
|
||||||
call s:open(cmd, item)
|
call s:open(Cmd, item)
|
||||||
endif
|
endif
|
||||||
if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')
|
if !has('patch-8.0.0177') && !has('nvim-0.2') && exists('#BufEnter')
|
||||||
\ && isdirectory(item)
|
\ && isdirectory(item)
|
||||||
@@ -192,6 +252,21 @@ function! s:defaults()
|
|||||||
return empty(colors) ? '' : ('--color='.colors)
|
return empty(colors) ? '' : ('--color='.colors)
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
function! s:validate_layout(layout)
|
||||||
|
for key in keys(a:layout)
|
||||||
|
if index(s:layout_keys, key) < 0
|
||||||
|
throw printf('Invalid entry in g:fzf_layout: %s (allowed: %s)%s',
|
||||||
|
\ key, join(s:layout_keys, ', '), key == 'options' ? '. Use $FZF_DEFAULT_OPTS.' : '')
|
||||||
|
endif
|
||||||
|
endfor
|
||||||
|
return a:layout
|
||||||
|
endfunction
|
||||||
|
|
||||||
|
function! s:evaluate_opts(options)
|
||||||
|
return type(a:options) == type([]) ?
|
||||||
|
\ join(map(copy(a:options), 'fzf#shellescape(v:val)')) : a:options
|
||||||
|
endfunction
|
||||||
|
|
||||||
" [name string,] [opts dict,] [fullscreen boolean]
|
" [name string,] [opts dict,] [fullscreen boolean]
|
||||||
function! fzf#wrap(...)
|
function! fzf#wrap(...)
|
||||||
let args = ['', {}, 0]
|
let args = ['', {}, 0]
|
||||||
@@ -200,7 +275,7 @@ function! fzf#wrap(...)
|
|||||||
for arg in copy(a:000)
|
for arg in copy(a:000)
|
||||||
let tidx = index(expects, type(arg), tidx)
|
let tidx = index(expects, type(arg), tidx)
|
||||||
if tidx < 0
|
if tidx < 0
|
||||||
throw 'invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'
|
throw 'Invalid arguments (expected: [name string] [opts dict] [fullscreen boolean])'
|
||||||
endif
|
endif
|
||||||
let args[tidx] = arg
|
let args[tidx] = arg
|
||||||
let tidx += 1
|
let tidx += 1
|
||||||
@@ -223,20 +298,21 @@ function! fzf#wrap(...)
|
|||||||
if !exists('g:fzf_layout') && exists('g:fzf_height')
|
if !exists('g:fzf_layout') && exists('g:fzf_height')
|
||||||
let opts.down = g:fzf_height
|
let opts.down = g:fzf_height
|
||||||
else
|
else
|
||||||
let opts = extend(opts, get(g:, 'fzf_layout', s:default_layout))
|
let opts = extend(opts, s:validate_layout(get(g:, 'fzf_layout', s:default_layout)))
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
" Colors: g:fzf_colors
|
" Colors: g:fzf_colors
|
||||||
let opts.options = s:defaults() .' '. get(opts, 'options', '')
|
let opts.options = s:defaults() .' '. s:evaluate_opts(get(opts, 'options', ''))
|
||||||
|
|
||||||
" History: g:fzf_history_dir
|
" History: g:fzf_history_dir
|
||||||
if len(name) && len(get(g:, 'fzf_history_dir', ''))
|
if len(name) && len(get(g:, 'fzf_history_dir', ''))
|
||||||
let dir = expand(g:fzf_history_dir)
|
let dir = s:fzf_expand(g:fzf_history_dir)
|
||||||
if !isdirectory(dir)
|
if !isdirectory(dir)
|
||||||
call mkdir(dir, 'p')
|
call mkdir(dir, 'p')
|
||||||
endif
|
endif
|
||||||
let opts.options = join(['--history', s:escape(dir.'/'.name), opts.options])
|
let history = fzf#shellescape(dir.'/'.name)
|
||||||
|
let opts.options = join(['--history', history, opts.options])
|
||||||
endif
|
endif
|
||||||
|
|
||||||
" Action: g:fzf_action
|
" Action: g:fzf_action
|
||||||
@@ -252,19 +328,6 @@ function! fzf#wrap(...)
|
|||||||
return opts
|
return opts
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! fzf#shellescape(path)
|
|
||||||
if s:is_win
|
|
||||||
let shellslash = &shellslash
|
|
||||||
try
|
|
||||||
set noshellslash
|
|
||||||
return shellescape(a:path)
|
|
||||||
finally
|
|
||||||
let &shellslash = shellslash
|
|
||||||
endtry
|
|
||||||
endif
|
|
||||||
return shellescape(a:path)
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
function! fzf#run(...) abort
|
function! fzf#run(...) abort
|
||||||
try
|
try
|
||||||
let oshell = &shell
|
let oshell = &shell
|
||||||
@@ -277,23 +340,26 @@ try
|
|||||||
set shell=sh
|
set shell=sh
|
||||||
endif
|
endif
|
||||||
|
|
||||||
if has('nvim') && len(filter(range(1, bufnr('$')), 'bufname(v:val) =~# ";#FZF"'))
|
|
||||||
call s:warn('FZF is already running!')
|
|
||||||
return []
|
|
||||||
endif
|
|
||||||
let dict = exists('a:1') ? s:upgrade(a:1) : {}
|
let dict = exists('a:1') ? s:upgrade(a:1) : {}
|
||||||
let temps = { 'result': tempname() }
|
let temps = { 'result': s:fzf_tempname() }
|
||||||
let optstr = get(dict, 'options', '')
|
let optstr = s:evaluate_opts(get(dict, 'options', ''))
|
||||||
try
|
try
|
||||||
let fzf_exec = s:fzf_exec()
|
let fzf_exec = s:fzf_exec()
|
||||||
catch
|
catch
|
||||||
throw v:exception
|
throw v:exception
|
||||||
endtry
|
endtry
|
||||||
|
|
||||||
if !has_key(dict, 'source') && !empty($FZF_DEFAULT_COMMAND)
|
if has('nvim') && !has_key(dict, 'dir')
|
||||||
let temps.source = tempname()
|
let dict.dir = s:fzf_getcwd()
|
||||||
call writefile(split($FZF_DEFAULT_COMMAND, "\n"), temps.source)
|
endif
|
||||||
let dict.source = (empty($SHELL) ? &shell : $SHELL) . ' ' . s:shellesc(temps.source)
|
if has('win32unix') && has_key(dict, 'dir')
|
||||||
|
let dict.dir = fnamemodify(dict.dir, ':p')
|
||||||
|
endif
|
||||||
|
|
||||||
|
if !has_key(dict, 'source') && !empty($FZF_DEFAULT_COMMAND) && !s:is_win
|
||||||
|
let temps.source = s:fzf_tempname()
|
||||||
|
call writefile(s:wrap_cmds(split($FZF_DEFAULT_COMMAND, "\n")), temps.source)
|
||||||
|
let dict.source = (empty($SHELL) ? &shell : $SHELL).' '.fzf#shellescape(temps.source)
|
||||||
endif
|
endif
|
||||||
|
|
||||||
if has_key(dict, 'source')
|
if has_key(dict, 'source')
|
||||||
@@ -302,11 +368,11 @@ try
|
|||||||
if type == 1
|
if type == 1
|
||||||
let prefix = source.'|'
|
let prefix = source.'|'
|
||||||
elseif type == 3
|
elseif type == 3
|
||||||
let temps.input = tempname()
|
let temps.input = s:fzf_tempname()
|
||||||
call writefile(source, temps.input)
|
call writefile(source, temps.input)
|
||||||
let prefix = 'cat '.s:shellesc(temps.input).'|'
|
let prefix = (s:is_win ? 'type ' : 'cat ').fzf#shellescape(temps.input).'|'
|
||||||
else
|
else
|
||||||
throw 'invalid source type'
|
throw 'Invalid source type'
|
||||||
endif
|
endif
|
||||||
else
|
else
|
||||||
let prefix = ''
|
let prefix = ''
|
||||||
@@ -314,16 +380,17 @@ try
|
|||||||
|
|
||||||
let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0)
|
let prefer_tmux = get(g:, 'fzf_prefer_tmux', 0)
|
||||||
let use_height = has_key(dict, 'down') &&
|
let use_height = has_key(dict, 'down') &&
|
||||||
\ !(has('nvim') || s:is_win || s:present(dict, 'up', 'left', 'right')) &&
|
\ !(has('nvim') || s:is_win || has('win32unix') || s:present(dict, 'up', 'left', 'right')) &&
|
||||||
\ executable('tput') && filereadable('/dev/tty')
|
\ executable('tput') && filereadable('/dev/tty')
|
||||||
let use_term = has('nvim')
|
let use_term = has('nvim') && !s:is_win
|
||||||
let use_tmux = (!use_height && !use_term || prefer_tmux) && s:tmux_enabled() && s:splittable(dict)
|
let use_tmux = (!use_height && !use_term || prefer_tmux) && !has('win32unix') && s:tmux_enabled() && s:splittable(dict)
|
||||||
if prefer_tmux && use_tmux
|
if prefer_tmux && use_tmux
|
||||||
let use_height = 0
|
let use_height = 0
|
||||||
let use_term = 0
|
let use_term = 0
|
||||||
endif
|
endif
|
||||||
if use_height
|
if use_height
|
||||||
let optstr .= ' --height='.s:calc_size(&lines, dict.down, dict)
|
let height = s:calc_size(&lines, dict.down, dict)
|
||||||
|
let optstr .= ' --height='.height
|
||||||
elseif use_term
|
elseif use_term
|
||||||
let optstr .= ' --no-height'
|
let optstr .= ' --no-height'
|
||||||
endif
|
endif
|
||||||
@@ -367,7 +434,7 @@ function! s:fzf_tmux(dict)
|
|||||||
endif
|
endif
|
||||||
endfor
|
endfor
|
||||||
return printf('LINES=%d COLUMNS=%d %s %s %s --',
|
return printf('LINES=%d COLUMNS=%d %s %s %s --',
|
||||||
\ &lines, &columns, s:shellesc(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))
|
\ &lines, &columns, fzf#shellescape(s:fzf_tmux), size, (has_key(a:dict, 'source') ? '' : '-'))
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:splittable(dict)
|
function! s:splittable(dict)
|
||||||
@@ -377,13 +444,13 @@ endfunction
|
|||||||
|
|
||||||
function! s:pushd(dict)
|
function! s:pushd(dict)
|
||||||
if s:present(a:dict, 'dir')
|
if s:present(a:dict, 'dir')
|
||||||
let cwd = getcwd()
|
let cwd = s:fzf_getcwd()
|
||||||
if get(a:dict, 'prev_dir', '') ==# cwd
|
if get(a:dict, 'prev_dir', '') ==# cwd
|
||||||
return 1
|
return 1
|
||||||
endif
|
endif
|
||||||
let a:dict.prev_dir = cwd
|
let a:dict.prev_dir = cwd
|
||||||
execute 'lcd' s:escape(a:dict.dir)
|
execute 'lcd' s:escape(a:dict.dir)
|
||||||
let a:dict.dir = getcwd()
|
let a:dict.dir = s:fzf_getcwd()
|
||||||
return 1
|
return 1
|
||||||
endif
|
endif
|
||||||
return 0
|
return 0
|
||||||
@@ -395,11 +462,11 @@ augroup fzf_popd
|
|||||||
augroup END
|
augroup END
|
||||||
|
|
||||||
function! s:dopopd()
|
function! s:dopopd()
|
||||||
if !exists('w:fzf_prev_dir') || exists('*haslocaldir') && !haslocaldir()
|
if !exists('w:fzf_dir') || s:fzf_getcwd() != w:fzf_dir[1]
|
||||||
return
|
return
|
||||||
endif
|
endif
|
||||||
execute 'lcd' s:escape(w:fzf_prev_dir)
|
execute 'lcd' s:escape(w:fzf_dir[0])
|
||||||
unlet w:fzf_prev_dir
|
unlet w:fzf_dir
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:xterm_launcher()
|
function! s:xterm_launcher()
|
||||||
@@ -412,7 +479,7 @@ function! s:xterm_launcher()
|
|||||||
\ &columns, &lines/2, getwinposx(), getwinposy())
|
\ &columns, &lines/2, getwinposx(), getwinposy())
|
||||||
endfunction
|
endfunction
|
||||||
unlet! s:launcher
|
unlet! s:launcher
|
||||||
if s:is_win
|
if s:is_win || has('win32unix')
|
||||||
let s:launcher = '%s'
|
let s:launcher = '%s'
|
||||||
else
|
else
|
||||||
let s:launcher = function('s:xterm_launcher')
|
let s:launcher = function('s:xterm_launcher')
|
||||||
@@ -436,7 +503,7 @@ function! s:execute(dict, command, use_height, temps) abort
|
|||||||
if has('unix') && !a:use_height
|
if has('unix') && !a:use_height
|
||||||
silent! !clear 2> /dev/null
|
silent! !clear 2> /dev/null
|
||||||
endif
|
endif
|
||||||
let escaped = escape(substitute(a:command, '\n', '\\n', 'g'), '%#')
|
let escaped = (a:use_height || s:is_win) ? a:command : escape(substitute(a:command, '\n', '\\n', 'g'), '%#!')
|
||||||
if has('gui_running')
|
if has('gui_running')
|
||||||
let Launcher = get(a:dict, 'launcher', get(g:, 'Fzf_launcher', get(g:, 'fzf_launcher', s:launcher)))
|
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 fmt = type(Launcher) == 2 ? call(Launcher, []) : Launcher
|
||||||
@@ -447,6 +514,32 @@ function! s:execute(dict, command, use_height, temps) abort
|
|||||||
else
|
else
|
||||||
let command = escaped
|
let command = escaped
|
||||||
endif
|
endif
|
||||||
|
if s:is_win
|
||||||
|
let batchfile = s:fzf_tempname().'.bat'
|
||||||
|
call writefile(s:wrap_cmds(command), batchfile)
|
||||||
|
let command = batchfile
|
||||||
|
let a:temps.batchfile = batchfile
|
||||||
|
if has('nvim')
|
||||||
|
let fzf = {}
|
||||||
|
let fzf.dict = a:dict
|
||||||
|
let fzf.temps = a:temps
|
||||||
|
function! fzf.on_exit(job_id, exit_status, event) dict
|
||||||
|
if s:present(self.dict, 'dir')
|
||||||
|
execute 'lcd' s:escape(self.dict.dir)
|
||||||
|
endif
|
||||||
|
let lines = s:collect(self.temps)
|
||||||
|
call s:callback(self.dict, lines)
|
||||||
|
endfunction
|
||||||
|
let cmd = 'start /wait cmd /c '.command
|
||||||
|
call jobstart(cmd, fzf)
|
||||||
|
return []
|
||||||
|
endif
|
||||||
|
elseif has('win32unix') && $TERM !=# 'cygwin'
|
||||||
|
let shellscript = s:fzf_tempname()
|
||||||
|
call writefile([command], shellscript)
|
||||||
|
let command = 'cmd.exe /C '.fzf#shellescape('set "TERM=" & start /WAIT sh -c '.shellscript)
|
||||||
|
let a:temps.shellscript = shellscript
|
||||||
|
endif
|
||||||
if a:use_height
|
if a:use_height
|
||||||
let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'
|
let stdin = has_key(a:dict, 'source') ? '' : '< /dev/tty'
|
||||||
call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))
|
call system(printf('tput cup %d > /dev/tty; tput cnorm > /dev/tty; %s %s 2> /dev/tty', &lines, command, stdin))
|
||||||
@@ -462,7 +555,7 @@ function! s:execute_tmux(dict, command, temps) abort
|
|||||||
let command = a:command
|
let command = a:command
|
||||||
if s:pushd(a:dict)
|
if s:pushd(a:dict)
|
||||||
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
" -c '#{pane_current_path}' is only available on tmux 1.9 or above
|
||||||
let command = 'cd '.s:escape(a:dict.dir).' && '.command
|
let command = join(['cd', fzf#shellescape(a:dict.dir), '&&', command])
|
||||||
endif
|
endif
|
||||||
|
|
||||||
call system(command)
|
call system(command)
|
||||||
@@ -591,7 +684,7 @@ function! s:execute_term(dict, command, temps) abort
|
|||||||
lcd -
|
lcd -
|
||||||
endif
|
endif
|
||||||
endtry
|
endtry
|
||||||
setlocal nospell bufhidden=wipe nobuflisted
|
setlocal nospell bufhidden=wipe nobuflisted nonumber
|
||||||
setf fzf
|
setf fzf
|
||||||
startinsert
|
startinsert
|
||||||
return []
|
return []
|
||||||
@@ -622,7 +715,7 @@ function! s:callback(dict, lines) abort
|
|||||||
let popd = has_key(a:dict, 'prev_dir') &&
|
let popd = has_key(a:dict, 'prev_dir') &&
|
||||||
\ (!&autochdir || (empty(a:lines) || len(a:lines) == 1 && empty(a:lines[0])))
|
\ (!&autochdir || (empty(a:lines) || len(a:lines) == 1 && empty(a:lines[0])))
|
||||||
if popd
|
if popd
|
||||||
let w:fzf_prev_dir = a:dict.prev_dir
|
let w:fzf_dir = [a:dict.prev_dir, a:dict.dir]
|
||||||
endif
|
endif
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -646,7 +739,7 @@ function! s:callback(dict, lines) abort
|
|||||||
|
|
||||||
" We may have opened a new window or tab
|
" We may have opened a new window or tab
|
||||||
if popd
|
if popd
|
||||||
let w:fzf_prev_dir = a:dict.prev_dir
|
let w:fzf_dir = [a:dict.prev_dir, a:dict.dir]
|
||||||
call s:dopopd()
|
call s:dopopd()
|
||||||
endif
|
endif
|
||||||
endfunction
|
endfunction
|
||||||
@@ -658,19 +751,24 @@ let s:default_action = {
|
|||||||
|
|
||||||
function! s:shortpath()
|
function! s:shortpath()
|
||||||
let short = pathshorten(fnamemodify(getcwd(), ':~:.'))
|
let short = pathshorten(fnamemodify(getcwd(), ':~:.'))
|
||||||
return empty(short) ? '~/' : short . (short =~ '/$' ? '' : '/')
|
let slash = (s:is_win && !&shellslash) ? '\' : '/'
|
||||||
|
return empty(short) ? '~'.slash : short . (short =~ escape(slash, '\').'$' ? '' : slash)
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
function! s:cmd(bang, ...) abort
|
function! s:cmd(bang, ...) abort
|
||||||
let args = copy(a:000)
|
let args = copy(a:000)
|
||||||
let opts = { 'options': '--multi ' }
|
let opts = { 'options': ['--multi'] }
|
||||||
if len(args) && isdirectory(expand(args[-1]))
|
if len(args) && isdirectory(expand(args[-1]))
|
||||||
let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')
|
let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')
|
||||||
let opts.options .= ' --prompt '.fzf#shellescape(opts.dir)
|
if s:is_win && !&shellslash
|
||||||
|
let opts.dir = substitute(opts.dir, '/', '\\', 'g')
|
||||||
|
endif
|
||||||
|
let prompt = opts.dir
|
||||||
else
|
else
|
||||||
let opts.options .= ' --prompt '.fzf#shellescape(s:shortpath())
|
let prompt = s:shortpath()
|
||||||
endif
|
endif
|
||||||
let opts.options .= ' '.join(args)
|
call extend(opts.options, ['--prompt', prompt])
|
||||||
|
call extend(opts.options, args)
|
||||||
call fzf#run(fzf#wrap('FZF', opts, a:bang))
|
call fzf#run(fzf#wrap('FZF', opts, a:bang))
|
||||||
endfunction
|
endfunction
|
||||||
|
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ _fzf_complete_telnet() {
|
|||||||
_fzf_complete_ssh() {
|
_fzf_complete_ssh() {
|
||||||
_fzf_complete '+m' "$@" < <(
|
_fzf_complete '+m' "$@" < <(
|
||||||
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | command grep -i '^host' | command grep -v '*') \
|
cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | command grep -i '^host' | command grep -v '*') \
|
||||||
<(command grep -oE '^[a-z0-9.,-]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
<(command grep -oE '^[a-z0-9.,:-]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
||||||
<(command grep -v '^\s*\(#\|$\)' /etc/hosts | command grep -Fv '0.0.0.0') |
|
<(command grep -v '^\s*\(#\|$\)' /etc/hosts | command grep -Fv '0.0.0.0') |
|
||||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
)
|
)
|
||||||
@@ -304,7 +304,7 @@ done
|
|||||||
|
|
||||||
# Directory
|
# Directory
|
||||||
for cmd in $d_cmds; do
|
for cmd in $d_cmds; do
|
||||||
_fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o plusdirs"
|
_fzf_defc "$cmd" _fzf_dir_completion "-o nospace -o dirnames"
|
||||||
done
|
done
|
||||||
|
|
||||||
unset _fzf_defc
|
unset _fzf_defc
|
||||||
|
|||||||
@@ -117,7 +117,7 @@ _fzf_complete_telnet() {
|
|||||||
_fzf_complete_ssh() {
|
_fzf_complete_ssh() {
|
||||||
_fzf_complete '+m' "$@" < <(
|
_fzf_complete '+m' "$@" < <(
|
||||||
command cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | command grep -i '^host' | command grep -v '*') \
|
command cat <(cat ~/.ssh/config /etc/ssh/ssh_config 2> /dev/null | command grep -i '^host' | command grep -v '*') \
|
||||||
<(command grep -oE '^[a-z0-9.,-]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
<(command grep -oE '^[a-z0-9.,:-]+' ~/.ssh/known_hosts | tr ',' '\n' | awk '{ print $1 " " $1 }') \
|
||||||
<(command grep -v '^\s*\(#\|$\)' /etc/hosts | command grep -Fv '0.0.0.0') |
|
<(command grep -v '^\s*\(#\|$\)' /etc/hosts | command grep -Fv '0.0.0.0') |
|
||||||
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
awk '{if (length($2) > 0) {print $2}}' | sort -u
|
||||||
)
|
)
|
||||||
@@ -143,7 +143,7 @@ _fzf_complete_unalias() {
|
|||||||
|
|
||||||
fzf-completion() {
|
fzf-completion() {
|
||||||
local tokens cmd prefix trigger tail fzf matches lbuf d_cmds
|
local tokens cmd prefix trigger tail fzf matches lbuf d_cmds
|
||||||
setopt localoptions noshwordsplit noksh_arrays
|
setopt localoptions noshwordsplit noksh_arrays noposixbuiltins
|
||||||
|
|
||||||
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
# http://zsh.sourceforge.net/FAQ/zshfaq03.html
|
||||||
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
# http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Key bindings
|
# Key bindings
|
||||||
# ------------
|
# ------------
|
||||||
__fzf_select__() {
|
__fzf_select__() {
|
||||||
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | cut -b3-"}"
|
-o -type l -print 2> /dev/null | cut -b3-"}"
|
||||||
@@ -46,8 +46,8 @@ fzf-file-widget() {
|
|||||||
|
|
||||||
__fzf_cd__() {
|
__fzf_cd__() {
|
||||||
local cmd dir
|
local cmd dir
|
||||||
cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
cmd="${FZF_ALT_C_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
-o -type d -print 2> /dev/null | cut -b3-"}"
|
||||||
dir=$(eval "$cmd" | FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS" $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
dir=$(eval "$cmd" | FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS" $(__fzfcmd) +m) && printf 'cd %q' "$dir"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ __fzf_history__() (
|
|||||||
shopt -u nocaseglob nocasematch
|
shopt -u nocaseglob nocasematch
|
||||||
line=$(
|
line=$(
|
||||||
HISTTIMEFORMAT= history |
|
HISTTIMEFORMAT= history |
|
||||||
FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} $FZF_DEFAULT_OPTS +s --tac -n2..,.. --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS +m" $(__fzfcmd) |
|
FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} $FZF_DEFAULT_OPTS --tac -n2..,.. --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS +m" $(__fzfcmd) |
|
||||||
command grep '^ *[0-9]') &&
|
command grep '^ *[0-9]') &&
|
||||||
if [[ $- =~ H ]]; then
|
if [[ $- =~ H ]]; then
|
||||||
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
sed 's/^ *\([0-9]*\)\** .*/!\1/' <<< "$line"
|
||||||
|
|||||||
@@ -2,36 +2,29 @@
|
|||||||
# ------------
|
# ------------
|
||||||
function fzf_key_bindings
|
function fzf_key_bindings
|
||||||
|
|
||||||
# Store last token in $dir as root for the 'find' command
|
# Store current token in $dir as root for the 'find' command
|
||||||
function fzf-file-widget -d "List files and folders"
|
function fzf-file-widget -d "List files and folders"
|
||||||
set -l dir (commandline -t)
|
set -l commandline (__fzf_parse_commandline)
|
||||||
# The commandline token might be escaped, we need to unescape it.
|
set -l dir $commandline[1]
|
||||||
set dir (eval "printf '%s' $dir")
|
set -l fzf_query $commandline[2]
|
||||||
if [ ! -d "$dir" ]
|
|
||||||
set dir .
|
|
||||||
end
|
|
||||||
# Some 'find' versions print undesired duplicated slashes if the path ends with slashes.
|
|
||||||
set dir (string replace --regex '(.)/+$' '$1' "$dir")
|
|
||||||
|
|
||||||
# "-path \$dir'*/\\.*'" matches hidden files/folders inside $dir but not
|
# "-path \$dir'*/\\.*'" matches hidden files/folders inside $dir but not
|
||||||
# $dir itself, even if hidden.
|
# $dir itself, even if hidden.
|
||||||
set -q FZF_CTRL_T_COMMAND; or set -l FZF_CTRL_T_COMMAND "
|
set -q FZF_CTRL_T_COMMAND; or set -l FZF_CTRL_T_COMMAND "
|
||||||
command find -L \$dir -mindepth 1 \\( -path \$dir'*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' \\) -prune \
|
command find -L \$dir -mindepth 1 \\( -path \$dir'*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | sed 's#^\./##'"
|
-o -type l -print 2> /dev/null | sed 's@^\./@@'"
|
||||||
|
|
||||||
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
||||||
begin
|
begin
|
||||||
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT --reverse $FZF_DEFAULT_OPTS $FZF_CTRL_T_OPTS"
|
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT --reverse $FZF_DEFAULT_OPTS $FZF_CTRL_T_OPTS"
|
||||||
eval "$FZF_CTRL_T_COMMAND | "(__fzfcmd)" -m" | while read -l r; set result $result $r; end
|
eval "$FZF_CTRL_T_COMMAND | "(__fzfcmd)' -m --query "'$fzf_query'"' | while read -l r; set result $result $r; end
|
||||||
end
|
end
|
||||||
if [ -z "$result" ]
|
if [ -z "$result" ]
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
return
|
return
|
||||||
end
|
else
|
||||||
|
|
||||||
if [ "$dir" != . ]
|
|
||||||
# Remove last token from commandline.
|
# Remove last token from commandline.
|
||||||
commandline -t ""
|
commandline -t ""
|
||||||
end
|
end
|
||||||
@@ -45,23 +38,46 @@ function fzf_key_bindings
|
|||||||
function fzf-history-widget -d "Show command history"
|
function fzf-history-widget -d "Show command history"
|
||||||
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
||||||
begin
|
begin
|
||||||
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT $FZF_DEFAULT_OPTS +s --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS +m"
|
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT $FZF_DEFAULT_OPTS --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS +m"
|
||||||
history | eval (__fzfcmd) -q '(commandline)' | read -l result
|
|
||||||
and commandline -- $result
|
set -l FISH_MAJOR (echo $FISH_VERSION | cut -f1 -d.)
|
||||||
|
set -l FISH_MINOR (echo $FISH_VERSION | cut -f2 -d.)
|
||||||
|
|
||||||
|
# history's -z flag is needed for multi-line support.
|
||||||
|
# history's -z flag was added in fish 2.4.0, so don't use it for versions
|
||||||
|
# before 2.4.0.
|
||||||
|
if [ "$FISH_MAJOR" -gt 2 -o \( "$FISH_MAJOR" -eq 2 -a "$FISH_MINOR" -ge 4 \) ];
|
||||||
|
history -z | eval (__fzfcmd) --read0 -q '(commandline)' | perl -pe 'chomp if eof' | read -lz result
|
||||||
|
and commandline -- $result
|
||||||
|
else
|
||||||
|
history | eval (__fzfcmd) -q '(commandline)' | read -l result
|
||||||
|
and commandline -- $result
|
||||||
|
end
|
||||||
end
|
end
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
end
|
end
|
||||||
|
|
||||||
function fzf-cd-widget -d "Change directory"
|
function fzf-cd-widget -d "Change directory"
|
||||||
|
set -l commandline (__fzf_parse_commandline)
|
||||||
|
set -l dir $commandline[1]
|
||||||
|
set -l fzf_query $commandline[2]
|
||||||
|
|
||||||
set -q FZF_ALT_C_COMMAND; or set -l FZF_ALT_C_COMMAND "
|
set -q FZF_ALT_C_COMMAND; or set -l FZF_ALT_C_COMMAND "
|
||||||
command find -L . \\( -path '*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' \\) -prune \
|
command find -L \$dir -mindepth 1 \\( -path \$dir'*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' \\) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"
|
-o -type d -print 2> /dev/null | sed 's@^\./@@'"
|
||||||
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
set -q FZF_TMUX_HEIGHT; or set FZF_TMUX_HEIGHT 40%
|
||||||
begin
|
begin
|
||||||
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS"
|
set -lx FZF_DEFAULT_OPTS "--height $FZF_TMUX_HEIGHT --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS"
|
||||||
eval "$FZF_ALT_C_COMMAND | "(__fzfcmd)" +m" | read -l result
|
eval "$FZF_ALT_C_COMMAND | "(__fzfcmd)' +m --query "'$fzf_query'"' | read -l result
|
||||||
[ "$result" ]; and cd $result
|
|
||||||
|
if [ -n "$result" ]
|
||||||
|
cd $result
|
||||||
|
|
||||||
|
# Remove last token from commandline.
|
||||||
|
commandline -t ""
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
commandline -f repaint
|
commandline -f repaint
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -84,4 +100,47 @@ function fzf_key_bindings
|
|||||||
bind -M insert \cr fzf-history-widget
|
bind -M insert \cr fzf-history-widget
|
||||||
bind -M insert \ec fzf-cd-widget
|
bind -M insert \ec fzf-cd-widget
|
||||||
end
|
end
|
||||||
|
|
||||||
|
function __fzf_parse_commandline -d 'Parse the current command line token and return split of existing filepath and rest of token'
|
||||||
|
# eval is used to do shell expansion on paths
|
||||||
|
set -l commandline (eval "printf '%s' "(commandline -t))
|
||||||
|
|
||||||
|
if [ -z $commandline ]
|
||||||
|
# Default to current directory with no --query
|
||||||
|
set dir '.'
|
||||||
|
set fzf_query ''
|
||||||
|
else
|
||||||
|
set dir (__fzf_get_dir $commandline)
|
||||||
|
|
||||||
|
if [ "$dir" = "." -a (string sub -l 1 $commandline) != '.' ]
|
||||||
|
# if $dir is "." but commandline is not a relative path, this means no file path found
|
||||||
|
set fzf_query $commandline
|
||||||
|
else
|
||||||
|
# Also remove trailing slash after dir, to "split" input properly
|
||||||
|
set fzf_query (string replace -r "^$dir/?" '' "$commandline")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
echo $dir
|
||||||
|
echo $fzf_query
|
||||||
|
end
|
||||||
|
|
||||||
|
function __fzf_get_dir -d 'Find the longest existing filepath from input string'
|
||||||
|
set dir $argv
|
||||||
|
|
||||||
|
# Strip all trailing slashes. Ignore if $dir is root dir (/)
|
||||||
|
if [ (string length $dir) -gt 1 ]
|
||||||
|
set dir (string replace -r '/*$' '' $dir)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Iteratively check if dir exists and strip tail end of path
|
||||||
|
while [ ! -d "$dir" ]
|
||||||
|
# If path is absolute, this can keep going until ends up at /
|
||||||
|
# If path is relative, this can keep going until entire input is consumed, dirname returns "."
|
||||||
|
set dir (dirname "$dir")
|
||||||
|
end
|
||||||
|
|
||||||
|
echo $dir
|
||||||
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ if [[ $- == *i* ]]; then
|
|||||||
|
|
||||||
# CTRL-T - Paste the selected file path(s) into the command line
|
# CTRL-T - Paste the selected file path(s) into the command line
|
||||||
__fsel() {
|
__fsel() {
|
||||||
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
local cmd="${FZF_CTRL_T_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type f -print \
|
-o -type f -print \
|
||||||
-o -type d -print \
|
-o -type d -print \
|
||||||
-o -type l -print 2> /dev/null | cut -b3-"}"
|
-o -type l -print 2> /dev/null | cut -b3-"}"
|
||||||
@@ -38,10 +38,15 @@ bindkey '^T' fzf-file-widget
|
|||||||
|
|
||||||
# ALT-C - cd into the selected directory
|
# ALT-C - cd into the selected directory
|
||||||
fzf-cd-widget() {
|
fzf-cd-widget() {
|
||||||
local cmd="${FZF_ALT_C_COMMAND:-"command find -L . \\( -path '*/\\.*' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
local cmd="${FZF_ALT_C_COMMAND:-"command find -L . -mindepth 1 \\( -path '*/\\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \\) -prune \
|
||||||
-o -type d -print 2> /dev/null | sed 1d | cut -b3-"}"
|
-o -type d -print 2> /dev/null | cut -b3-"}"
|
||||||
setopt localoptions pipefail 2> /dev/null
|
setopt localoptions pipefail 2> /dev/null
|
||||||
cd "${$(eval "$cmd" | FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS" $(__fzfcmd) +m):-.}"
|
local dir="$(eval "$cmd" | FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse $FZF_DEFAULT_OPTS $FZF_ALT_C_OPTS" $(__fzfcmd) +m)"
|
||||||
|
if [[ -z "$dir" ]]; then
|
||||||
|
zle redisplay
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
cd "$dir"
|
||||||
local ret=$?
|
local ret=$?
|
||||||
zle reset-prompt
|
zle reset-prompt
|
||||||
typeset -f zle-line-init >/dev/null && zle zle-line-init
|
typeset -f zle-line-init >/dev/null && zle zle-line-init
|
||||||
@@ -53,9 +58,9 @@ bindkey '\ec' fzf-cd-widget
|
|||||||
# CTRL-R - Paste the selected command from history into the command line
|
# CTRL-R - Paste the selected command from history into the command line
|
||||||
fzf-history-widget() {
|
fzf-history-widget() {
|
||||||
local selected num
|
local selected num
|
||||||
setopt localoptions noglobsubst pipefail 2> /dev/null
|
setopt localoptions noglobsubst noposixbuiltins pipefail 2> /dev/null
|
||||||
selected=( $(fc -l 1 |
|
selected=( $(fc -l 1 |
|
||||||
FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} $FZF_DEFAULT_OPTS +s --tac -n2..,.. --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS --query=${(q)LBUFFER} +m" $(__fzfcmd)) )
|
FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} $FZF_DEFAULT_OPTS --tac -n2..,.. --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS --query=${(q)LBUFFER} +m" $(__fzfcmd)) )
|
||||||
local ret=$?
|
local ret=$?
|
||||||
if [ -n "$selected" ]; then
|
if [ -n "$selected" ]; then
|
||||||
num=$selected[1]
|
num=$selected[1]
|
||||||
@@ -71,4 +76,3 @@ zle -N fzf-history-widget
|
|||||||
bindkey '^R' fzf-history-widget
|
bindkey '^R' fzf-history-widget
|
||||||
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
@@ -1,40 +0,0 @@
|
|||||||
FROM ubuntu:14.04
|
|
||||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
|
||||||
|
|
||||||
# apt-get
|
|
||||||
RUN apt-get update && apt-get -y upgrade && \
|
|
||||||
apt-get install -y --force-yes git curl build-essential
|
|
||||||
|
|
||||||
# Install Go 1.4
|
|
||||||
RUN cd / && curl \
|
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
|
||||||
tar -xz && mv go go1.4 && \
|
|
||||||
sed -i 's@#define PTHREAD_KEYS_MAX 128@@' /go1.4/src/runtime/cgo/gcc_android_arm.c
|
|
||||||
|
|
||||||
ENV GOROOT /go1.4
|
|
||||||
ENV PATH /go1.4/bin:$PATH
|
|
||||||
|
|
||||||
RUN cd / && \
|
|
||||||
curl -O http://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin && \
|
|
||||||
chmod 755 /android-ndk* && /android-ndk-r10e-linux-x86_64.bin && \
|
|
||||||
mv android-ndk-r10e /android-ndk
|
|
||||||
|
|
||||||
RUN cd /android-ndk && bash ./build/tools/make-standalone-toolchain.sh --platform=android-21 --install-dir=/ndk --arch=arm
|
|
||||||
|
|
||||||
ENV NDK_CC /ndk/bin/arm-linux-androideabi-gcc
|
|
||||||
|
|
||||||
RUN cd $GOROOT/src && \
|
|
||||||
CC_FOR_TARGET=$NDK_CC GOOS=android GOARCH=arm GOARM=7 ./make.bash
|
|
||||||
|
|
||||||
RUN cd / && curl \
|
|
||||||
http://ftp.gnu.org/gnu/ncurses/ncurses-5.9.tar.gz | \
|
|
||||||
tar -xz && cd /ncurses-5.9 && \
|
|
||||||
./configure CC=$NDK_CC CFLAGS="-fPIE -march=armv7-a -mfpu=neon -mhard-float -Wl,--no-warn-mismatch" LDFLAGS="-march=armv7-a -Wl,--no-warn-mismatch" --host=arm-linux --enable-overwrite --enable-const --without-cxx-binding --without-shared --without-debug --enable-widec --enable-ext-colors --enable-ext-mouse --enable-pc-files --with-pkg-config-libdir=$PKG_CONFIG_LIBDIR --without-manpages --without-ada --disable-shared --without-tests --prefix=/ndk/sysroot/usr --with-default-terminfo-dirs=/usr/share/terminfo --with-terminfo-dirs=/usr/share/terminfo ac_cv_header_locale_h=n ac_cv_func_getpwent=no ac_cv_func_getpwnam=no ac_cv_func_getpwuid=no && \
|
|
||||||
sed -i 's@#define HAVE_LOCALE_H 1@/* #undef HAVE_LOCALE_H */@' include/ncurses_cfg.h && \
|
|
||||||
make && \
|
|
||||||
sed -i '0,/echo.*/{s/echo.*/exit 0/}' misc/run_tic.sh && \
|
|
||||||
make install && \
|
|
||||||
mv /ndk/sysroot/usr/lib/libncursesw.a /ndk/sysroot/usr/lib/libncurses.a
|
|
||||||
|
|
||||||
# Default CMD
|
|
||||||
CMD cd /fzf/src && /bin/bash
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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
|
|
||||||
RUN cd / && curl \
|
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
|
||||||
tar -xz && mv go go1.4
|
|
||||||
|
|
||||||
ENV GOROOT /go1.4
|
|
||||||
ENV PATH /go1.4/bin:$PATH
|
|
||||||
|
|
||||||
# For i386 build
|
|
||||||
RUN echo '[multilib]' >> /etc/pacman.conf && \
|
|
||||||
echo 'Include = /etc/pacman.d/mirrorlist' >> /etc/pacman.conf && \
|
|
||||||
pacman-db-upgrade && yes | pacman -Sy gcc-multilib lib32-ncurses && \
|
|
||||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
|
||||||
|
|
||||||
# Default CMD
|
|
||||||
CMD cd /fzf/src && /bin/bash
|
|
||||||
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
FROM centos:centos6
|
|
||||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
|
||||||
|
|
||||||
# yum
|
|
||||||
RUN yum install -y git gcc make tar glibc-devel glibc-devel.i686 \
|
|
||||||
ncurses-devel ncurses-static ncurses-devel.i686 \
|
|
||||||
gpm-devel gpm-static libgcc.i686
|
|
||||||
|
|
||||||
# Install Go 1.4
|
|
||||||
RUN cd / && curl \
|
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
|
||||||
tar -xz && mv go go1.4
|
|
||||||
|
|
||||||
# Install Go 1.7
|
|
||||||
RUN cd / && curl \
|
|
||||||
https://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gz | \
|
|
||||||
tar -xz && mv go go1.7
|
|
||||||
|
|
||||||
# Install RPMs for building static 32-bit binary
|
|
||||||
RUN curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.8/os/i386/Packages/ncurses-static-5.7-4.20090207.el6.i686.rpm -o rpm && rpm -i rpm && \
|
|
||||||
curl ftp://ftp.pbone.net/mirror/ftp.centos.org/6.8/os/i386/Packages/gpm-static-1.20.6-12.el6.i686.rpm -o rpm && rpm -i rpm
|
|
||||||
|
|
||||||
ENV GOROOT_BOOTSTRAP /go1.4
|
|
||||||
ENV GOROOT /go1.7
|
|
||||||
ENV PATH /go1.7/bin:$PATH
|
|
||||||
|
|
||||||
# For i386 build
|
|
||||||
RUN cd $GOROOT/src && GOARCH=386 ./make.bash
|
|
||||||
|
|
||||||
# Default CMD
|
|
||||||
CMD cd /fzf/src && /bin/bash
|
|
||||||
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
FROM ubuntu:14.04
|
|
||||||
MAINTAINER Junegunn Choi <junegunn.c@gmail.com>
|
|
||||||
|
|
||||||
# apt-get
|
|
||||||
RUN apt-get update && apt-get -y upgrade && \
|
|
||||||
apt-get install -y --force-yes git curl build-essential libncurses-dev libgpm-dev
|
|
||||||
|
|
||||||
# Install Go 1.4
|
|
||||||
RUN cd / && curl \
|
|
||||||
https://storage.googleapis.com/golang/go1.4.2.linux-amd64.tar.gz | \
|
|
||||||
tar -xz && mv go go1.4
|
|
||||||
|
|
||||||
ENV GOROOT /go1.4
|
|
||||||
ENV PATH /go1.4/bin:$PATH
|
|
||||||
|
|
||||||
# For i386 build
|
|
||||||
RUN apt-get install -y lib32ncurses5-dev && \
|
|
||||||
cd $GOROOT/src && GOARCH=386 ./make.bash
|
|
||||||
|
|
||||||
# Default CMD
|
|
||||||
CMD cd /fzf/src && /bin/bash
|
|
||||||
|
|
||||||
170
src/Makefile
170
src/Makefile
@@ -1,170 +0,0 @@
|
|||||||
ifndef GOOS
|
|
||||||
UNAME_S := $(shell uname -s)
|
|
||||||
ifeq ($(UNAME_S),Darwin)
|
|
||||||
GOOS := darwin
|
|
||||||
else ifeq ($(UNAME_S),Linux)
|
|
||||||
GOOS := linux
|
|
||||||
endif
|
|
||||||
endif
|
|
||||||
|
|
||||||
SOURCES := $(wildcard *.go */*.go)
|
|
||||||
ROOTDIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
|
|
||||||
BINDIR := $(shell dirname $(ROOTDIR))/bin
|
|
||||||
GOPATH := $(shell dirname $(ROOTDIR))/gopath
|
|
||||||
SRCDIR := $(GOPATH)/src/github.com/junegunn/fzf/src
|
|
||||||
DOCKEROPTS := -i -t -v $(ROOTDIR):/fzf/src
|
|
||||||
BINARY32 := fzf-$(GOOS)_386
|
|
||||||
BINARY64 := fzf-$(GOOS)_amd64
|
|
||||||
BINARYARM5 := fzf-$(GOOS)_arm5
|
|
||||||
BINARYARM6 := fzf-$(GOOS)_arm6
|
|
||||||
BINARYARM7 := fzf-$(GOOS)_arm7
|
|
||||||
BINARYARM8 := fzf-$(GOOS)_arm8
|
|
||||||
VERSION := $(shell awk -F= '/version =/ {print $$2}' constants.go | tr -d "\" ")
|
|
||||||
RELEASE32 := fzf-$(VERSION)-$(GOOS)_386
|
|
||||||
RELEASE64 := fzf-$(VERSION)-$(GOOS)_amd64
|
|
||||||
RELEASEARM5 := fzf-$(VERSION)-$(GOOS)_arm5
|
|
||||||
RELEASEARM6 := fzf-$(VERSION)-$(GOOS)_arm6
|
|
||||||
RELEASEARM7 := fzf-$(VERSION)-$(GOOS)_arm7
|
|
||||||
RELEASEARM8 := fzf-$(VERSION)-$(GOOS)_arm8
|
|
||||||
export GOPATH
|
|
||||||
|
|
||||||
# https://en.wikipedia.org/wiki/Uname
|
|
||||||
UNAME_M := $(shell uname -m)
|
|
||||||
ifeq ($(UNAME_M),x86_64)
|
|
||||||
BINARY := $(BINARY64)
|
|
||||||
else ifeq ($(UNAME_M),amd64)
|
|
||||||
BINARY := $(BINARY64)
|
|
||||||
else ifeq ($(UNAME_M),i686)
|
|
||||||
BINARY := $(BINARY32)
|
|
||||||
else ifeq ($(UNAME_M),i386)
|
|
||||||
BINARY := $(BINARY32)
|
|
||||||
else ifeq ($(UNAME_M),armv5l)
|
|
||||||
BINARY := $(BINARYARM5)
|
|
||||||
else ifeq ($(UNAME_M),armv6l)
|
|
||||||
BINARY := $(BINARYARM6)
|
|
||||||
else ifeq ($(UNAME_M),armv7l)
|
|
||||||
BINARY := $(BINARYARM7)
|
|
||||||
else
|
|
||||||
$(error "Build on $(UNAME_M) is not supported, yet.")
|
|
||||||
endif
|
|
||||||
|
|
||||||
all: fzf/$(BINARY)
|
|
||||||
|
|
||||||
ifeq ($(GOOS),windows)
|
|
||||||
release: fzf/$(BINARY32) fzf/$(BINARY64)
|
|
||||||
cd fzf && cp -f $(BINARY32) fzf.exe && zip $(RELEASE32).zip fzf.exe
|
|
||||||
cd fzf && cp -f $(BINARY64) fzf.exe && zip $(RELEASE64).zip fzf.exe
|
|
||||||
cd fzf && rm -f fzf.exe
|
|
||||||
else ifeq ($(GOOS),linux)
|
|
||||||
release: fzf/$(BINARY32) fzf/$(BINARY64) fzf/$(BINARYARM5) fzf/$(BINARYARM6) fzf/$(BINARYARM7) fzf/$(BINARYARM8)
|
|
||||||
cd fzf && cp -f $(BINARY32) fzf && tar -czf $(RELEASE32).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARY64) fzf && tar -czf $(RELEASE64).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARYARM5) fzf && tar -czf $(RELEASEARM5).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARYARM6) fzf && tar -czf $(RELEASEARM6).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARYARM7) fzf && tar -czf $(RELEASEARM7).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARYARM8) fzf && tar -czf $(RELEASEARM8).tgz fzf
|
|
||||||
cd fzf && rm -f fzf
|
|
||||||
else
|
|
||||||
release: fzf/$(BINARY32) fzf/$(BINARY64)
|
|
||||||
cd fzf && cp -f $(BINARY32) fzf && tar -czf $(RELEASE32).tgz fzf
|
|
||||||
cd fzf && cp -f $(BINARY64) fzf && tar -czf $(RELEASE64).tgz fzf
|
|
||||||
cd fzf && rm -f fzf
|
|
||||||
endif
|
|
||||||
|
|
||||||
release-all: clean test
|
|
||||||
GOOS=darwin make release
|
|
||||||
GOOS=linux make release
|
|
||||||
GOOS=freebsd make release
|
|
||||||
GOOS=openbsd make release
|
|
||||||
GOOS=windows make release
|
|
||||||
|
|
||||||
$(SRCDIR):
|
|
||||||
mkdir -p $(shell dirname $(SRCDIR))
|
|
||||||
ln -s $(ROOTDIR) $(SRCDIR)
|
|
||||||
|
|
||||||
deps: $(SRCDIR) $(SOURCES)
|
|
||||||
cd $(SRCDIR) && go get -tags "$(TAGS)"
|
|
||||||
./deps
|
|
||||||
|
|
||||||
android-build: $(SRCDIR)
|
|
||||||
cd $(SRCDIR) && GOARCH=arm GOARM=7 CGO_ENABLED=1 go get
|
|
||||||
cd $(SRCDIR)/fzf && GOARCH=arm GOARM=7 CGO_ENABLED=1 go build -a -ldflags="-w -extldflags=-pie" -o $(BINARYARM7)
|
|
||||||
cd $(SRCDIR)/fzf && cp $(BINARYARM7) $(RELEASEARM7) && tar -czf $(RELEASEARM7).tgz $(RELEASEARM7) && \
|
|
||||||
rm -f $(RELEASEARM7)
|
|
||||||
|
|
||||||
test: deps
|
|
||||||
SHELL=/bin/sh GOOS= go test -v -tags "$(TAGS)" ./...
|
|
||||||
|
|
||||||
install: $(BINDIR)/fzf
|
|
||||||
|
|
||||||
uninstall:
|
|
||||||
rm -f $(BINDIR)/fzf $(BINDIR)/$(BINARY)
|
|
||||||
|
|
||||||
clean:
|
|
||||||
cd fzf && rm -f fzf-*
|
|
||||||
|
|
||||||
fzf/$(BINARY32): deps
|
|
||||||
cd fzf && GOARCH=386 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARY32)
|
|
||||||
|
|
||||||
fzf/$(BINARY64): deps
|
|
||||||
cd fzf && GOARCH=amd64 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARY64)
|
|
||||||
|
|
||||||
# https://github.com/golang/go/wiki/GoArm
|
|
||||||
fzf/$(BINARYARM5): deps
|
|
||||||
cd fzf && GOARCH=arm GOARM=5 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARYARM5)
|
|
||||||
|
|
||||||
fzf/$(BINARYARM6): deps
|
|
||||||
cd fzf && GOARCH=arm GOARM=6 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARYARM6)
|
|
||||||
|
|
||||||
fzf/$(BINARYARM7): deps
|
|
||||||
cd fzf && GOARCH=arm GOARM=7 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARYARM7)
|
|
||||||
|
|
||||||
fzf/$(BINARYARM8): deps
|
|
||||||
cd fzf && GOARCH=arm64 go build -a -ldflags "-w -extldflags=$(LDFLAGS)" -tags "$(TAGS)" -o $(BINARYARM8)
|
|
||||||
|
|
||||||
$(BINDIR)/fzf: fzf/$(BINARY) | $(BINDIR)
|
|
||||||
cp -f fzf/$(BINARY) $(BINDIR)
|
|
||||||
cd $(BINDIR) && ln -sf $(BINARY) fzf
|
|
||||||
|
|
||||||
$(BINDIR):
|
|
||||||
mkdir -p $@
|
|
||||||
|
|
||||||
docker-arch:
|
|
||||||
docker build -t junegunn/arch-sandbox - < Dockerfile.arch
|
|
||||||
|
|
||||||
docker-ubuntu:
|
|
||||||
docker build -t junegunn/ubuntu-sandbox - < Dockerfile.ubuntu
|
|
||||||
|
|
||||||
docker-centos:
|
|
||||||
docker build -t junegunn/centos-sandbox - < Dockerfile.centos
|
|
||||||
|
|
||||||
docker-android:
|
|
||||||
docker build -t junegunn/android-sandbox - < Dockerfile.android
|
|
||||||
|
|
||||||
arch: docker-arch
|
|
||||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
|
||||||
sh -c 'cd /fzf/src; /bin/bash'
|
|
||||||
|
|
||||||
ubuntu: docker-ubuntu
|
|
||||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
|
||||||
sh -c 'cd /fzf/src; /bin/bash'
|
|
||||||
|
|
||||||
centos: docker-centos
|
|
||||||
docker run $(DOCKEROPTS) junegunn/$@-sandbox \
|
|
||||||
sh -c 'cd /fzf/src; /bin/bash'
|
|
||||||
|
|
||||||
linux: docker-centos
|
|
||||||
docker run $(DOCKEROPTS) junegunn/centos-sandbox \
|
|
||||||
/bin/bash -ci 'cd /fzf/src; make TAGS=static release'
|
|
||||||
|
|
||||||
ubuntu-android: docker-android
|
|
||||||
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
|
||||||
sh -c 'cd /fzf/src; /bin/bash'
|
|
||||||
|
|
||||||
android: docker-android
|
|
||||||
docker run $(DOCKEROPTS) junegunn/android-sandbox \
|
|
||||||
/bin/bash -ci 'cd /fzf/src; GOOS=android make android-build'
|
|
||||||
|
|
||||||
.PHONY: all deps release test install uninstall clean \
|
|
||||||
linux arch ubuntu centos docker-arch docker-ubuntu docker-centos \
|
|
||||||
android-build docker-android ubuntu-android android
|
|
||||||
106
src/README.md
106
src/README.md
@@ -1,106 +0,0 @@
|
|||||||
fzf in Go
|
|
||||||
=========
|
|
||||||
|
|
||||||
<img src="https://cloud.githubusercontent.com/assets/700826/5725028/028ea834-9b93-11e4-9198-43088c3f295d.gif" height="463" alt="fzf in go">
|
|
||||||
|
|
||||||
This directory contains the source code for the new fzf implementation in
|
|
||||||
[Go][go].
|
|
||||||
|
|
||||||
Upgrade from Ruby version
|
|
||||||
-------------------------
|
|
||||||
|
|
||||||
The install script has been updated to download the right binary for your
|
|
||||||
system. If you already have installed fzf, simply git-pull the repository and
|
|
||||||
rerun the install script.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cd ~/.fzf
|
|
||||||
git pull
|
|
||||||
./install
|
|
||||||
```
|
|
||||||
|
|
||||||
Otherwise, follow [the instruction][install] as before. You can also install
|
|
||||||
fzf using Homebrew if you prefer that way.
|
|
||||||
|
|
||||||
Motivations
|
|
||||||
-----------
|
|
||||||
|
|
||||||
### No Ruby dependency
|
|
||||||
|
|
||||||
There have always been complaints about fzf being a Ruby script. To make
|
|
||||||
matters worse, Ruby 2.1 removed ncurses binding from its standard libary.
|
|
||||||
Because of the change, users running Ruby 2.1 or above are forced to build C
|
|
||||||
extensions of curses gem to meet the requirement of fzf. The new Go version
|
|
||||||
will be distributed as an executable binary so it will be much more accessible
|
|
||||||
and should be easier to setup.
|
|
||||||
|
|
||||||
### Performance
|
|
||||||
|
|
||||||
Many people have been surprised to see how fast fzf is even when it was
|
|
||||||
written in Ruby. It stays quite responsive even for 100k+ lines, which is
|
|
||||||
well above the size of the usual input.
|
|
||||||
|
|
||||||
The new Go version, of course, is significantly faster than that. It has all
|
|
||||||
the performance optimization techniques used in Ruby implementation and more.
|
|
||||||
It also doesn't suffer from [GIL][gil], so the search performance scales
|
|
||||||
proportional to the number of CPU cores. On my MacBook Pro (Mid 2012), the new
|
|
||||||
version was shown to be an order of magnitude faster on certain cases. It also
|
|
||||||
starts much faster though the difference may not be noticeable.
|
|
||||||
|
|
||||||
Build
|
|
||||||
-----
|
|
||||||
|
|
||||||
See [BUILD.md](../BUILD.md)
|
|
||||||
|
|
||||||
Test
|
|
||||||
----
|
|
||||||
|
|
||||||
Unit tests can be run with `make test`. Integration tests are written in Ruby
|
|
||||||
script that should be run on tmux.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cd src
|
|
||||||
|
|
||||||
# Unit tests
|
|
||||||
make test
|
|
||||||
|
|
||||||
# Integration tests
|
|
||||||
ruby ../test/test_go.rb
|
|
||||||
|
|
||||||
# Build binary for the platform
|
|
||||||
make
|
|
||||||
|
|
||||||
# Install the executable to ../bin directory
|
|
||||||
make install
|
|
||||||
|
|
||||||
# Make release archives
|
|
||||||
make release
|
|
||||||
|
|
||||||
# Make release archives for all supported platforms
|
|
||||||
make release-all
|
|
||||||
```
|
|
||||||
|
|
||||||
Third-party libraries used
|
|
||||||
--------------------------
|
|
||||||
|
|
||||||
- ~[ncurses][ncurses]~
|
|
||||||
- [mattn/go-runewidth](https://github.com/mattn/go-runewidth)
|
|
||||||
- Licensed under [MIT](http://mattn.mit-license.org)
|
|
||||||
- [mattn/go-shellwords](https://github.com/mattn/go-shellwords)
|
|
||||||
- Licensed under [MIT](http://mattn.mit-license.org)
|
|
||||||
- [mattn/go-isatty](https://github.com/mattn/go-isatty)
|
|
||||||
- Licensed under [MIT](http://mattn.mit-license.org)
|
|
||||||
- [tcell](https://github.com/gdamore/tcell)
|
|
||||||
- Licensed under [Apache License 2.0](https://github.com/gdamore/tcell/blob/master/LICENSE)
|
|
||||||
|
|
||||||
License
|
|
||||||
-------
|
|
||||||
|
|
||||||
[MIT](LICENSE)
|
|
||||||
|
|
||||||
[install]: https://github.com/junegunn/fzf#installation
|
|
||||||
[go]: https://golang.org/
|
|
||||||
[gil]: http://en.wikipedia.org/wiki/Global_Interpreter_Lock
|
|
||||||
[ncurses]: https://www.gnu.org/software/ncurses/
|
|
||||||
[req]: http://golang.org/doc/install
|
|
||||||
[tcell]: https://github.com/gdamore/tcell
|
|
||||||
350
src/algo/algo.go
350
src/algo/algo.go
@@ -78,9 +78,11 @@ Scoring criteria
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
@@ -156,27 +158,17 @@ func posArray(withPos bool, len int) *[]int {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func alloc16(offset int, slab *util.Slab, size int, clear bool) (int, []int16) {
|
func alloc16(offset int, slab *util.Slab, size int) (int, []int16) {
|
||||||
if slab != nil && cap(slab.I16) > offset+size {
|
if slab != nil && cap(slab.I16) > offset+size {
|
||||||
slice := slab.I16[offset : offset+size]
|
slice := slab.I16[offset : offset+size]
|
||||||
if clear {
|
|
||||||
for idx := range slice {
|
|
||||||
slice[idx] = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return offset + size, slice
|
return offset + size, slice
|
||||||
}
|
}
|
||||||
return offset, make([]int16, size)
|
return offset, make([]int16, size)
|
||||||
}
|
}
|
||||||
|
|
||||||
func alloc32(offset int, slab *util.Slab, size int, clear bool) (int, []int32) {
|
func alloc32(offset int, slab *util.Slab, size int) (int, []int32) {
|
||||||
if slab != nil && cap(slab.I32) > offset+size {
|
if slab != nil && cap(slab.I32) > offset+size {
|
||||||
slice := slab.I32[offset : offset+size]
|
slice := slab.I32[offset : offset+size]
|
||||||
if clear {
|
|
||||||
for idx := range slice {
|
|
||||||
slice[idx] = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return offset + size, slice
|
return offset + size, slice
|
||||||
}
|
}
|
||||||
return offset, make([]int32, size)
|
return offset, make([]int32, size)
|
||||||
@@ -227,7 +219,7 @@ func bonusFor(prevClass charClass, class charClass) int16 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func bonusAt(input util.Chars, idx int) int16 {
|
func bonusAt(input *util.Chars, idx int) int16 {
|
||||||
if idx == 0 {
|
if idx == 0 {
|
||||||
return bonusBoundary
|
return bonusBoundary
|
||||||
}
|
}
|
||||||
@@ -249,21 +241,113 @@ func normalizeRune(r rune) rune {
|
|||||||
// Algo functions make two assumptions
|
// Algo functions make two assumptions
|
||||||
// 1. "pattern" is given in lowercase if "caseSensitive" is false
|
// 1. "pattern" is given in lowercase if "caseSensitive" is false
|
||||||
// 2. "pattern" is already normalized if "normalize" is true
|
// 2. "pattern" is already normalized if "normalize" is true
|
||||||
type Algo func(caseSensitive bool, normalize bool, forward bool, input util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)
|
type Algo func(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int)
|
||||||
|
|
||||||
func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func trySkip(input *util.Chars, caseSensitive bool, b byte, from int) int {
|
||||||
|
byteArray := input.Bytes()[from:]
|
||||||
|
idx := bytes.IndexByte(byteArray, b)
|
||||||
|
if idx == 0 {
|
||||||
|
// Can't skip any further
|
||||||
|
return from
|
||||||
|
}
|
||||||
|
// We may need to search for the uppercase letter again. We don't have to
|
||||||
|
// consider normalization as we can be sure that this is an ASCII string.
|
||||||
|
if !caseSensitive && b >= 'a' && b <= 'z' {
|
||||||
|
if idx > 0 {
|
||||||
|
byteArray = byteArray[:idx]
|
||||||
|
}
|
||||||
|
uidx := bytes.IndexByte(byteArray, b-32)
|
||||||
|
if uidx >= 0 {
|
||||||
|
idx = uidx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx < 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
return from + idx
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAscii(runes []rune) bool {
|
||||||
|
for _, r := range runes {
|
||||||
|
if r >= utf8.RuneSelf {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) int {
|
||||||
|
// Can't determine
|
||||||
|
if !input.IsBytes() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not possible
|
||||||
|
if !isAscii(pattern) {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
firstIdx, idx := 0, 0
|
||||||
|
for pidx := 0; pidx < len(pattern); pidx++ {
|
||||||
|
idx = trySkip(input, caseSensitive, byte(pattern[pidx]), idx)
|
||||||
|
if idx < 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if pidx == 0 && idx > 0 {
|
||||||
|
// Step back to find the right bonus point
|
||||||
|
firstIdx = idx - 1
|
||||||
|
}
|
||||||
|
idx++
|
||||||
|
}
|
||||||
|
return firstIdx
|
||||||
|
}
|
||||||
|
|
||||||
|
func debugV2(T []rune, pattern []rune, F []int32, lastIdx int, H []int16, C []int16) {
|
||||||
|
width := lastIdx - int(F[0]) + 1
|
||||||
|
|
||||||
|
for i, f := range F {
|
||||||
|
I := i * width
|
||||||
|
if i == 0 {
|
||||||
|
fmt.Print(" ")
|
||||||
|
for j := int(f); j <= lastIdx; j++ {
|
||||||
|
fmt.Printf(" " + string(T[j]) + " ")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
|
fmt.Print(string(pattern[i]) + " ")
|
||||||
|
for idx := int(F[0]); idx < int(f); idx++ {
|
||||||
|
fmt.Print(" 0 ")
|
||||||
|
}
|
||||||
|
for idx := int(f); idx <= lastIdx; idx++ {
|
||||||
|
fmt.Printf("%2d ", H[i*width+idx-int(F[0])])
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
fmt.Print(" ")
|
||||||
|
for idx, p := range C[I : I+width] {
|
||||||
|
if idx+int(F[0]) < int(F[i]) {
|
||||||
|
p = 0
|
||||||
|
}
|
||||||
|
if p > 0 {
|
||||||
|
fmt.Printf("%2d ", p)
|
||||||
|
} else {
|
||||||
|
fmt.Print(" ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
// Assume that pattern is given in lowercase if case-insensitive.
|
// Assume that pattern is given in lowercase if case-insensitive.
|
||||||
// First check if there's a match and calculate bonus for each position.
|
// First check if there's a match and calculate bonus for each position.
|
||||||
// If the input string is too long, consider finding the matching chars in
|
// If the input string is too long, consider finding the matching chars in
|
||||||
// this phase as well (non-optimal alignment).
|
// this phase as well (non-optimal alignment).
|
||||||
N := input.Length()
|
|
||||||
M := len(pattern)
|
M := len(pattern)
|
||||||
switch M {
|
if M == 0 {
|
||||||
case 0:
|
|
||||||
return Result{0, 0, 0}, posArray(withPos, M)
|
return Result{0, 0, 0}, posArray(withPos, M)
|
||||||
case 1:
|
|
||||||
return ExactMatchNaive(caseSensitive, normalize, forward, input, pattern[0:1], withPos, slab)
|
|
||||||
}
|
}
|
||||||
|
N := input.Length()
|
||||||
|
|
||||||
// Since O(nm) algorithm can be prohibitively expensive for large input,
|
// Since O(nm) algorithm can be prohibitively expensive for large input,
|
||||||
// we fall back to the greedy algorithm.
|
// we fall back to the greedy algorithm.
|
||||||
@@ -271,158 +355,175 @@ func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input util.C
|
|||||||
return FuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos, slab)
|
return FuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos, slab)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Phase 1. Optimized search for ASCII string
|
||||||
|
idx := asciiFuzzyIndex(input, pattern, caseSensitive)
|
||||||
|
if idx < 0 {
|
||||||
|
return Result{-1, -1, 0}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages
|
// Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages
|
||||||
offset16 := 0
|
offset16 := 0
|
||||||
offset32 := 0
|
offset32 := 0
|
||||||
|
offset16, H0 := alloc16(offset16, slab, N)
|
||||||
|
offset16, C0 := alloc16(offset16, slab, N)
|
||||||
// Bonus point for each position
|
// Bonus point for each position
|
||||||
offset16, B := alloc16(offset16, slab, N, false)
|
offset16, B := alloc16(offset16, slab, N)
|
||||||
// The first occurrence of each character in the pattern
|
// The first occurrence of each character in the pattern
|
||||||
offset32, F := alloc32(offset32, slab, M, false)
|
offset32, F := alloc32(offset32, slab, M)
|
||||||
// Rune array
|
// Rune array
|
||||||
offset32, T := alloc32(offset32, slab, N, false)
|
offset32, T := alloc32(offset32, slab, N)
|
||||||
|
input.CopyRunes(T)
|
||||||
|
|
||||||
// Phase 1. Check if there's a match and calculate bonus for each point
|
// Phase 2. Calculate bonus for each point
|
||||||
pidx, lastIdx, prevClass := 0, 0, charNonWord
|
maxScore, maxScorePos := int16(0), 0
|
||||||
for idx := 0; idx < N; idx++ {
|
pidx, lastIdx := 0, 0
|
||||||
char := input.Get(idx)
|
pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), charNonWord, false
|
||||||
|
Tsub := T[idx:]
|
||||||
|
H0sub, C0sub, Bsub := H0[idx:][:len(Tsub)], C0[idx:][:len(Tsub)], B[idx:][:len(Tsub)]
|
||||||
|
for off, char := range Tsub {
|
||||||
var class charClass
|
var class charClass
|
||||||
if char <= unicode.MaxASCII {
|
if char <= unicode.MaxASCII {
|
||||||
class = charClassOfAscii(char)
|
class = charClassOfAscii(char)
|
||||||
|
if !caseSensitive && class == charUpper {
|
||||||
|
char += 32
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
class = charClassOfNonAscii(char)
|
class = charClassOfNonAscii(char)
|
||||||
}
|
if !caseSensitive && class == charUpper {
|
||||||
|
|
||||||
if !caseSensitive && class == charUpper {
|
|
||||||
if char <= unicode.MaxASCII {
|
|
||||||
char += 32
|
|
||||||
} else {
|
|
||||||
char = unicode.To(unicode.LowerCase, char)
|
char = unicode.To(unicode.LowerCase, char)
|
||||||
}
|
}
|
||||||
|
if normalize {
|
||||||
|
char = normalizeRune(char)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if normalize {
|
Tsub[off] = char
|
||||||
char = normalizeRune(char)
|
bonus := bonusFor(prevClass, class)
|
||||||
}
|
Bsub[off] = bonus
|
||||||
|
|
||||||
T[idx] = char
|
|
||||||
B[idx] = bonusFor(prevClass, class)
|
|
||||||
prevClass = class
|
prevClass = class
|
||||||
|
|
||||||
if pidx < M {
|
if char == pchar {
|
||||||
if char == pattern[pidx] {
|
if pidx < M {
|
||||||
lastIdx = idx
|
F[pidx] = int32(idx + off)
|
||||||
F[pidx] = int32(idx)
|
|
||||||
pidx++
|
pidx++
|
||||||
|
pchar = pattern[util.Min(pidx, M-1)]
|
||||||
}
|
}
|
||||||
} else {
|
lastIdx = idx + off
|
||||||
if char == pattern[M-1] {
|
|
||||||
lastIdx = idx
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if char == pchar0 {
|
||||||
|
score := scoreMatch + bonus*bonusFirstCharMultiplier
|
||||||
|
H0sub[off] = score
|
||||||
|
C0sub[off] = 1
|
||||||
|
if M == 1 && (forward && score > maxScore || !forward && score >= maxScore) {
|
||||||
|
maxScore, maxScorePos = score, idx+off
|
||||||
|
if forward && bonus == bonusBoundary {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inGap = false
|
||||||
|
} else {
|
||||||
|
if inGap {
|
||||||
|
H0sub[off] = util.Max16(prevH0+scoreGapExtention, 0)
|
||||||
|
} else {
|
||||||
|
H0sub[off] = util.Max16(prevH0+scoreGapStart, 0)
|
||||||
|
}
|
||||||
|
C0sub[off] = 0
|
||||||
|
inGap = true
|
||||||
|
}
|
||||||
|
prevH0 = H0sub[off]
|
||||||
}
|
}
|
||||||
if pidx != M {
|
if pidx != M {
|
||||||
return Result{-1, -1, 0}, nil
|
return Result{-1, -1, 0}, nil
|
||||||
}
|
}
|
||||||
|
if M == 1 {
|
||||||
|
result := Result{maxScorePos, maxScorePos + 1, int(maxScore)}
|
||||||
|
if !withPos {
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
pos := []int{maxScorePos}
|
||||||
|
return result, &pos
|
||||||
|
}
|
||||||
|
|
||||||
// Phase 2. Fill in score matrix (H)
|
// Phase 3. Fill in score matrix (H)
|
||||||
// Unlike the original algorithm, we do not allow omission.
|
// Unlike the original algorithm, we do not allow omission.
|
||||||
width := lastIdx - int(F[0]) + 1
|
f0 := int(F[0])
|
||||||
offset16, H := alloc16(offset16, slab, width*M, false)
|
width := lastIdx - f0 + 1
|
||||||
|
offset16, H := alloc16(offset16, slab, width*M)
|
||||||
|
copy(H, H0[f0:lastIdx+1])
|
||||||
|
|
||||||
// Possible length of consecutive chunk at each position.
|
// Possible length of consecutive chunk at each position.
|
||||||
offset16, C := alloc16(offset16, slab, width*M, false)
|
offset16, C := alloc16(offset16, slab, width*M)
|
||||||
|
copy(C, C0[f0:lastIdx+1])
|
||||||
|
|
||||||
maxScore, maxScorePos := int16(0), 0
|
Fsub := F[1:]
|
||||||
for i := 0; i < M; i++ {
|
Psub := pattern[1:][:len(Fsub)]
|
||||||
I := i * width
|
for off, f := range Fsub {
|
||||||
|
f := int(f)
|
||||||
|
pchar := Psub[off]
|
||||||
|
pidx := off + 1
|
||||||
|
row := pidx * width
|
||||||
inGap := false
|
inGap := false
|
||||||
for j := int(F[i]); j <= lastIdx; j++ {
|
Tsub := T[f : lastIdx+1]
|
||||||
j0 := j - int(F[0])
|
Bsub := B[f:][:len(Tsub)]
|
||||||
|
Csub := C[row+f-f0:][:len(Tsub)]
|
||||||
|
Cdiag := C[row+f-f0-1-width:][:len(Tsub)]
|
||||||
|
Hsub := H[row+f-f0:][:len(Tsub)]
|
||||||
|
Hdiag := H[row+f-f0-1-width:][:len(Tsub)]
|
||||||
|
Hleft := H[row+f-f0-1:][:len(Tsub)]
|
||||||
|
Hleft[0] = 0
|
||||||
|
for off, char := range Tsub {
|
||||||
|
col := off + f
|
||||||
var s1, s2, consecutive int16
|
var s1, s2, consecutive int16
|
||||||
|
|
||||||
if j > int(F[i]) {
|
if inGap {
|
||||||
if inGap {
|
s2 = Hleft[off] + scoreGapExtention
|
||||||
s2 = H[I+j0-1] + scoreGapExtention
|
} else {
|
||||||
} else {
|
s2 = Hleft[off] + scoreGapStart
|
||||||
s2 = H[I+j0-1] + scoreGapStart
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if pattern[i] == T[j] {
|
if pchar == char {
|
||||||
var diag int16
|
s1 = Hdiag[off] + scoreMatch
|
||||||
if i > 0 && j0 > 0 {
|
b := Bsub[off]
|
||||||
diag = H[I-width+j0-1]
|
consecutive = Cdiag[off] + 1
|
||||||
}
|
// Break consecutive chunk
|
||||||
s1 = diag + scoreMatch
|
if b == bonusBoundary {
|
||||||
b := B[j]
|
|
||||||
if i > 0 {
|
|
||||||
// j > 0 if i > 0
|
|
||||||
consecutive = C[I-width+j0-1] + 1
|
|
||||||
// Break consecutive chunk
|
|
||||||
if b == bonusBoundary {
|
|
||||||
consecutive = 1
|
|
||||||
} else if consecutive > 1 {
|
|
||||||
b = util.Max16(b, util.Max16(bonusConsecutive, B[j-int(consecutive)+1]))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
consecutive = 1
|
consecutive = 1
|
||||||
b *= bonusFirstCharMultiplier
|
} else if consecutive > 1 {
|
||||||
|
b = util.Max16(b, util.Max16(bonusConsecutive, B[col-int(consecutive)+1]))
|
||||||
}
|
}
|
||||||
if s1+b < s2 {
|
if s1+b < s2 {
|
||||||
s1 += B[j]
|
s1 += Bsub[off]
|
||||||
consecutive = 0
|
consecutive = 0
|
||||||
} else {
|
} else {
|
||||||
s1 += b
|
s1 += b
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
C[I+j0] = consecutive
|
Csub[off] = consecutive
|
||||||
|
|
||||||
inGap = s1 < s2
|
inGap = s1 < s2
|
||||||
score := util.Max16(util.Max16(s1, s2), 0)
|
score := util.Max16(util.Max16(s1, s2), 0)
|
||||||
if i == M-1 && (forward && score > maxScore || !forward && score >= maxScore) {
|
if pidx == M-1 && (forward && score > maxScore || !forward && score >= maxScore) {
|
||||||
maxScore, maxScorePos = score, j
|
maxScore, maxScorePos = score, col
|
||||||
}
|
}
|
||||||
H[I+j0] = score
|
Hsub[off] = score
|
||||||
}
|
|
||||||
|
|
||||||
if DEBUG {
|
|
||||||
if i == 0 {
|
|
||||||
fmt.Print(" ")
|
|
||||||
for j := int(F[i]); j <= lastIdx; j++ {
|
|
||||||
fmt.Printf(" " + string(input.Get(j)) + " ")
|
|
||||||
}
|
|
||||||
fmt.Println()
|
|
||||||
}
|
|
||||||
fmt.Print(string(pattern[i]) + " ")
|
|
||||||
for idx := int(F[0]); idx < int(F[i]); idx++ {
|
|
||||||
fmt.Print(" 0 ")
|
|
||||||
}
|
|
||||||
for idx := int(F[i]); idx <= lastIdx; idx++ {
|
|
||||||
fmt.Printf("%2d ", H[i*width+idx-int(F[0])])
|
|
||||||
}
|
|
||||||
fmt.Println()
|
|
||||||
|
|
||||||
fmt.Print(" ")
|
|
||||||
for idx, p := range C[I : I+width] {
|
|
||||||
if idx+int(F[0]) < int(F[i]) {
|
|
||||||
p = 0
|
|
||||||
}
|
|
||||||
fmt.Printf("%2d ", p)
|
|
||||||
}
|
|
||||||
fmt.Println()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Phase 3. (Optional) Backtrace to find character positions
|
if DEBUG {
|
||||||
|
debugV2(T, pattern, F, lastIdx, H, C)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 4. (Optional) Backtrace to find character positions
|
||||||
pos := posArray(withPos, M)
|
pos := posArray(withPos, M)
|
||||||
j := int(F[0])
|
j := f0
|
||||||
if withPos {
|
if withPos {
|
||||||
i := M - 1
|
i := M - 1
|
||||||
j = maxScorePos
|
j = maxScorePos
|
||||||
preferMatch := true
|
preferMatch := true
|
||||||
for {
|
for {
|
||||||
I := i * width
|
I := i * width
|
||||||
j0 := j - int(F[0])
|
j0 := j - f0
|
||||||
s := H[I+j0]
|
s := H[I+j0]
|
||||||
|
|
||||||
var s1, s2 int16
|
var s1, s2 int16
|
||||||
@@ -451,7 +552,7 @@ func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input util.C
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Implement the same sorting criteria as V2
|
// Implement the same sorting criteria as V2
|
||||||
func calculateScore(caseSensitive bool, normalize bool, text util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) {
|
func calculateScore(caseSensitive bool, normalize bool, text *util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) {
|
||||||
pidx, score, inGap, consecutive, firstBonus := 0, 0, false, 0, int16(0)
|
pidx, score, inGap, consecutive, firstBonus := 0, 0, false, 0, int16(0)
|
||||||
pos := posArray(withPos, len(pattern))
|
pos := posArray(withPos, len(pattern))
|
||||||
prevClass := charNonWord
|
prevClass := charNonWord
|
||||||
@@ -511,10 +612,13 @@ func calculateScore(caseSensitive bool, normalize bool, text util.Chars, pattern
|
|||||||
}
|
}
|
||||||
|
|
||||||
// FuzzyMatchV1 performs fuzzy-match
|
// FuzzyMatchV1 performs fuzzy-match
|
||||||
func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return Result{0, 0, 0}, nil
|
return Result{0, 0, 0}, nil
|
||||||
}
|
}
|
||||||
|
if asciiFuzzyIndex(text, pattern, caseSensitive) < 0 {
|
||||||
|
return Result{-1, -1, 0}, nil
|
||||||
|
}
|
||||||
|
|
||||||
pidx := 0
|
pidx := 0
|
||||||
sidx := -1
|
sidx := -1
|
||||||
@@ -594,7 +698,7 @@ func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text util.Ch
|
|||||||
// bonus point, instead of stopping immediately after finding the first match.
|
// bonus point, instead of stopping immediately after finding the first match.
|
||||||
// The solution is much cheaper since there is only one possible alignment of
|
// The solution is much cheaper since there is only one possible alignment of
|
||||||
// the pattern.
|
// the pattern.
|
||||||
func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return Result{0, 0, 0}, nil
|
return Result{0, 0, 0}, nil
|
||||||
}
|
}
|
||||||
@@ -606,6 +710,10 @@ func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text util
|
|||||||
return Result{-1, -1, 0}, nil
|
return Result{-1, -1, 0}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if asciiFuzzyIndex(text, pattern, caseSensitive) < 0 {
|
||||||
|
return Result{-1, -1, 0}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// For simplicity, only look at the bonus at the first character position
|
// For simplicity, only look at the bonus at the first character position
|
||||||
pidx := 0
|
pidx := 0
|
||||||
bestPos, bonus, bestBonus := -1, int16(0), int16(-1)
|
bestPos, bonus, bestBonus := -1, int16(0), int16(-1)
|
||||||
@@ -660,7 +768,7 @@ func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text util
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PrefixMatch performs prefix-match
|
// PrefixMatch performs prefix-match
|
||||||
func PrefixMatch(caseSensitive bool, normalize bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func PrefixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
return Result{0, 0, 0}, nil
|
return Result{0, 0, 0}, nil
|
||||||
}
|
}
|
||||||
@@ -687,7 +795,7 @@ func PrefixMatch(caseSensitive bool, normalize bool, forward bool, text util.Cha
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SuffixMatch performs suffix-match
|
// SuffixMatch performs suffix-match
|
||||||
func SuffixMatch(caseSensitive bool, normalize bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func SuffixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
lenRunes := text.Length()
|
lenRunes := text.Length()
|
||||||
trimmedLen := lenRunes - text.TrailingWhitespaces()
|
trimmedLen := lenRunes - text.TrailingWhitespaces()
|
||||||
if len(pattern) == 0 {
|
if len(pattern) == 0 {
|
||||||
@@ -718,7 +826,7 @@ func SuffixMatch(caseSensitive bool, normalize bool, forward bool, text util.Cha
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EqualMatch performs equal-match
|
// EqualMatch performs equal-match
|
||||||
func EqualMatch(caseSensitive bool, normalize bool, forward bool, text util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
func EqualMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
|
||||||
lenPattern := len(pattern)
|
lenPattern := len(pattern)
|
||||||
if text.Length() != lenPattern {
|
if text.Length() != lenPattern {
|
||||||
return Result{-1, -1, 0}, nil
|
return Result{-1, -1, 0}, nil
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ func assertMatch2(t *testing.T, fun Algo, caseSensitive, normalize, forward bool
|
|||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
pattern = strings.ToLower(pattern)
|
pattern = strings.ToLower(pattern)
|
||||||
}
|
}
|
||||||
res, pos := fun(caseSensitive, normalize, forward, util.RunesToChars([]rune(input)), []rune(pattern), true, nil)
|
chars := util.ToChars([]byte(input))
|
||||||
|
res, pos := fun(caseSensitive, normalize, forward, &chars, []rune(pattern), true, nil)
|
||||||
var start, end int
|
var start, end int
|
||||||
if pos == nil || len(*pos) == 0 {
|
if pos == nil || len(*pos) == 0 {
|
||||||
start = res.Start
|
start = res.Start
|
||||||
|
|||||||
78
src/ansi.go
78
src/ansi.go
@@ -44,7 +44,21 @@ func init() {
|
|||||||
*/
|
*/
|
||||||
// The following regular expression will include not all but most of the
|
// The following regular expression will include not all but most of the
|
||||||
// frequently used ANSI sequences
|
// frequently used ANSI sequences
|
||||||
ansiRegex = regexp.MustCompile("\x1b[\\[()][0-9;]*[a-zA-Z@]|\x1b.|[\x0e\x0f]|.\x08")
|
ansiRegex = regexp.MustCompile("(?:\x1b[\\[()][0-9;]*[a-zA-Z@]|\x1b.|[\x0e\x0f]|.\x08)")
|
||||||
|
}
|
||||||
|
|
||||||
|
func findAnsiStart(str string) int {
|
||||||
|
idx := 0
|
||||||
|
for ; idx < len(str); idx++ {
|
||||||
|
b := str[idx]
|
||||||
|
if b == 0x1b || b == 0x0e || b == 0x0f {
|
||||||
|
return idx
|
||||||
|
}
|
||||||
|
if b == 0x08 && idx > 0 {
|
||||||
|
return idx - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return idx
|
||||||
}
|
}
|
||||||
|
|
||||||
func extractColor(str string, state *ansiState, proc func(string, *ansiState) bool) (string, *[]ansiOffset, *ansiState) {
|
func extractColor(str string, state *ansiState, proc func(string, *ansiState) bool) (string, *[]ansiOffset, *ansiState) {
|
||||||
@@ -55,50 +69,76 @@ func extractColor(str string, state *ansiState, proc func(string, *ansiState) bo
|
|||||||
offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})
|
offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})
|
||||||
}
|
}
|
||||||
|
|
||||||
idx := 0
|
prevIdx := 0
|
||||||
for _, offset := range ansiRegex.FindAllStringIndex(str, -1) {
|
runeCount := 0
|
||||||
prev := str[idx:offset[0]]
|
for idx := 0; idx < len(str); {
|
||||||
output.WriteString(prev)
|
idx += findAnsiStart(str[idx:])
|
||||||
|
if idx == len(str) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure that we found an ANSI code
|
||||||
|
offset := ansiRegex.FindStringIndex(str[idx:])
|
||||||
|
if len(offset) < 2 {
|
||||||
|
idx++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offset[0] += idx
|
||||||
|
offset[1] += idx
|
||||||
|
idx = offset[1]
|
||||||
|
|
||||||
|
// Check if we should continue
|
||||||
|
prev := str[prevIdx:offset[0]]
|
||||||
if proc != nil && !proc(prev, state) {
|
if proc != nil && !proc(prev, state) {
|
||||||
return "", nil, nil
|
return "", nil, nil
|
||||||
}
|
}
|
||||||
newState := interpretCode(str[offset[0]:offset[1]], state)
|
|
||||||
|
|
||||||
|
prevIdx = offset[1]
|
||||||
|
runeCount += utf8.RuneCountInString(prev)
|
||||||
|
output.WriteString(prev)
|
||||||
|
|
||||||
|
newState := interpretCode(str[offset[0]:offset[1]], state)
|
||||||
if !newState.equals(state) {
|
if !newState.equals(state) {
|
||||||
if state != nil {
|
if state != nil {
|
||||||
// Update last offset
|
// Update last offset
|
||||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
(&offsets[len(offsets)-1]).offset[1] = int32(runeCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
if newState.colored() {
|
if newState.colored() {
|
||||||
// Append new offset
|
// Append new offset
|
||||||
state = newState
|
state = newState
|
||||||
newLen := int32(utf8.RuneCount(output.Bytes()))
|
offsets = append(offsets, ansiOffset{[2]int32{int32(runeCount), int32(runeCount)}, *state})
|
||||||
offsets = append(offsets, ansiOffset{[2]int32{newLen, newLen}, *state})
|
|
||||||
} else {
|
} else {
|
||||||
// Discard state
|
// Discard state
|
||||||
state = nil
|
state = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
idx = offset[1]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rest := str[idx:]
|
var rest string
|
||||||
if len(rest) > 0 {
|
var trimmed string
|
||||||
|
|
||||||
|
if prevIdx == 0 {
|
||||||
|
// No ANSI code found
|
||||||
|
rest = str
|
||||||
|
trimmed = str
|
||||||
|
} else {
|
||||||
|
rest = str[prevIdx:]
|
||||||
output.WriteString(rest)
|
output.WriteString(rest)
|
||||||
if state != nil {
|
trimmed = output.String()
|
||||||
// Update last offset
|
}
|
||||||
(&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))
|
if len(rest) > 0 && state != nil {
|
||||||
}
|
// Update last offset
|
||||||
|
runeCount += utf8.RuneCountInString(rest)
|
||||||
|
(&offsets[len(offsets)-1]).offset[1] = int32(runeCount)
|
||||||
}
|
}
|
||||||
if proc != nil {
|
if proc != nil {
|
||||||
proc(rest, state)
|
proc(rest, state)
|
||||||
}
|
}
|
||||||
if len(offsets) == 0 {
|
if len(offsets) == 0 {
|
||||||
return output.String(), nil, state
|
return trimmed, nil, state
|
||||||
}
|
}
|
||||||
return output.String(), &offsets, state
|
return trimmed, &offsets, state
|
||||||
}
|
}
|
||||||
|
|
||||||
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
func interpretCode(ansiCode string, prevState *ansiState) *ansiState {
|
||||||
|
|||||||
42
src/cache.go
42
src/cache.go
@@ -3,7 +3,7 @@ package fzf
|
|||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
// queryCache associates strings to lists of items
|
// queryCache associates strings to lists of items
|
||||||
type queryCache map[string][]*Result
|
type queryCache map[string][]Result
|
||||||
|
|
||||||
// ChunkCache associates Chunk and query string to lists of items
|
// ChunkCache associates Chunk and query string to lists of items
|
||||||
type ChunkCache struct {
|
type ChunkCache struct {
|
||||||
@@ -17,7 +17,7 @@ func NewChunkCache() ChunkCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add adds the list to the cache
|
// Add adds the list to the cache
|
||||||
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {
|
func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {
|
||||||
if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {
|
if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -33,10 +33,10 @@ func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {
|
|||||||
(*qc)[key] = list
|
(*qc)[key] = list
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find is called to lookup ChunkCache
|
// Lookup is called to lookup ChunkCache
|
||||||
func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Result, bool) {
|
func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {
|
||||||
if len(key) == 0 || !chunk.IsFull() {
|
if len(key) == 0 || !chunk.IsFull() {
|
||||||
return nil, false
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
cc.mutex.Lock()
|
cc.mutex.Lock()
|
||||||
@@ -46,8 +46,36 @@ func (cc *ChunkCache) Find(chunk *Chunk, key string) ([]*Result, bool) {
|
|||||||
if ok {
|
if ok {
|
||||||
list, ok := (*qc)[key]
|
list, ok := (*qc)[key]
|
||||||
if ok {
|
if ok {
|
||||||
return list, true
|
return list
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, false
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {
|
||||||
|
if len(key) == 0 || !chunk.IsFull() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cc.mutex.Lock()
|
||||||
|
defer cc.mutex.Unlock()
|
||||||
|
|
||||||
|
qc, ok := cc.cache[chunk]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for idx := 1; idx < len(key); idx++ {
|
||||||
|
// [---------| ] | [ |---------]
|
||||||
|
// [--------| ] | [ |--------]
|
||||||
|
// [-------| ] | [ |-------]
|
||||||
|
prefix := key[:len(key)-idx]
|
||||||
|
suffix := key[idx:]
|
||||||
|
for _, substr := range [2]string{prefix, suffix} {
|
||||||
|
if cached, found := (*qc)[substr]; found {
|
||||||
|
return cached
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,37 +4,36 @@ import "testing"
|
|||||||
|
|
||||||
func TestChunkCache(t *testing.T) {
|
func TestChunkCache(t *testing.T) {
|
||||||
cache := NewChunkCache()
|
cache := NewChunkCache()
|
||||||
chunk2 := make(Chunk, chunkSize)
|
|
||||||
chunk1p := &Chunk{}
|
chunk1p := &Chunk{}
|
||||||
chunk2p := &chunk2
|
chunk2p := &Chunk{count: chunkSize}
|
||||||
items1 := []*Result{&Result{}}
|
items1 := []Result{Result{}}
|
||||||
items2 := []*Result{&Result{}, &Result{}}
|
items2 := []Result{Result{}, Result{}}
|
||||||
cache.Add(chunk1p, "foo", items1)
|
cache.Add(chunk1p, "foo", items1)
|
||||||
cache.Add(chunk2p, "foo", items1)
|
cache.Add(chunk2p, "foo", items1)
|
||||||
cache.Add(chunk2p, "bar", items2)
|
cache.Add(chunk2p, "bar", items2)
|
||||||
|
|
||||||
{ // chunk1 is not full
|
{ // chunk1 is not full
|
||||||
cached, found := cache.Find(chunk1p, "foo")
|
cached := cache.Lookup(chunk1p, "foo")
|
||||||
if found {
|
if cached != nil {
|
||||||
t.Error("Cached disabled for non-empty chunks", found, cached)
|
t.Error("Cached disabled for non-empty chunks", cached)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
cached, found := cache.Find(chunk2p, "foo")
|
cached := cache.Lookup(chunk2p, "foo")
|
||||||
if !found || len(cached) != 1 {
|
if cached == nil || len(cached) != 1 {
|
||||||
t.Error("Expected 1 item cached", found, cached)
|
t.Error("Expected 1 item cached", cached)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
cached, found := cache.Find(chunk2p, "bar")
|
cached := cache.Lookup(chunk2p, "bar")
|
||||||
if !found || len(cached) != 2 {
|
if cached == nil || len(cached) != 2 {
|
||||||
t.Error("Expected 2 items cached", found, cached)
|
t.Error("Expected 2 items cached", cached)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
cached, found := cache.Find(chunk1p, "foobar")
|
cached := cache.Lookup(chunk1p, "foobar")
|
||||||
if found {
|
if cached != nil {
|
||||||
t.Error("Expected 0 item cached", found, cached)
|
t.Error("Expected 0 item cached", cached)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,18 @@ package fzf
|
|||||||
|
|
||||||
import "sync"
|
import "sync"
|
||||||
|
|
||||||
// Chunk is a list of Item pointers whose size has the upper limit of chunkSize
|
// Chunk is a list of Items whose size has the upper limit of chunkSize
|
||||||
type Chunk []*Item // >>> []Item
|
type Chunk struct {
|
||||||
|
items [chunkSize]Item
|
||||||
|
count int
|
||||||
|
}
|
||||||
|
|
||||||
// ItemBuilder is a closure type that builds Item object from a pointer to a
|
// ItemBuilder is a closure type that builds Item object from byte array
|
||||||
// string and an integer
|
type ItemBuilder func(*Item, []byte) bool
|
||||||
type ItemBuilder func([]byte, int) *Item
|
|
||||||
|
|
||||||
// ChunkList is a list of Chunks
|
// ChunkList is a list of Chunks
|
||||||
type ChunkList struct {
|
type ChunkList struct {
|
||||||
chunks []*Chunk
|
chunks []*Chunk
|
||||||
count int
|
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
trans ItemBuilder
|
trans ItemBuilder
|
||||||
}
|
}
|
||||||
@@ -21,15 +22,13 @@ type ChunkList struct {
|
|||||||
func NewChunkList(trans ItemBuilder) *ChunkList {
|
func NewChunkList(trans ItemBuilder) *ChunkList {
|
||||||
return &ChunkList{
|
return &ChunkList{
|
||||||
chunks: []*Chunk{},
|
chunks: []*Chunk{},
|
||||||
count: 0,
|
|
||||||
mutex: sync.Mutex{},
|
mutex: sync.Mutex{},
|
||||||
trans: trans}
|
trans: trans}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Chunk) push(trans ItemBuilder, data []byte, index int) bool {
|
func (c *Chunk) push(trans ItemBuilder, data []byte) bool {
|
||||||
item := trans(data, index)
|
if trans(&c.items[c.count], data) {
|
||||||
if item != nil {
|
c.count++
|
||||||
*c = append(*c, item)
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -37,7 +36,7 @@ func (c *Chunk) push(trans ItemBuilder, data []byte, index int) bool {
|
|||||||
|
|
||||||
// IsFull returns true if the Chunk is full
|
// IsFull returns true if the Chunk is full
|
||||||
func (c *Chunk) IsFull() bool {
|
func (c *Chunk) IsFull() bool {
|
||||||
return len(*c) == chunkSize
|
return c.count == chunkSize
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cl *ChunkList) lastChunk() *Chunk {
|
func (cl *ChunkList) lastChunk() *Chunk {
|
||||||
@@ -49,45 +48,35 @@ func CountItems(cs []*Chunk) int {
|
|||||||
if len(cs) == 0 {
|
if len(cs) == 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
return chunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))
|
return chunkSize*(len(cs)-1) + cs[len(cs)-1].count
|
||||||
}
|
}
|
||||||
|
|
||||||
// Push adds the item to the list
|
// Push adds the item to the list
|
||||||
func (cl *ChunkList) Push(data []byte) bool {
|
func (cl *ChunkList) Push(data []byte) bool {
|
||||||
cl.mutex.Lock()
|
cl.mutex.Lock()
|
||||||
defer cl.mutex.Unlock()
|
|
||||||
|
|
||||||
if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {
|
if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {
|
||||||
newChunk := Chunk(make([]*Item, 0, chunkSize))
|
cl.chunks = append(cl.chunks, &Chunk{})
|
||||||
cl.chunks = append(cl.chunks, &newChunk)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if cl.lastChunk().push(cl.trans, data, cl.count) {
|
ret := cl.lastChunk().push(cl.trans, data)
|
||||||
cl.count++
|
cl.mutex.Unlock()
|
||||||
return true
|
return ret
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot returns immutable snapshot of the ChunkList
|
// Snapshot returns immutable snapshot of the ChunkList
|
||||||
func (cl *ChunkList) Snapshot() ([]*Chunk, int) {
|
func (cl *ChunkList) Snapshot() ([]*Chunk, int) {
|
||||||
cl.mutex.Lock()
|
cl.mutex.Lock()
|
||||||
defer cl.mutex.Unlock()
|
|
||||||
|
|
||||||
ret := make([]*Chunk, len(cl.chunks))
|
ret := make([]*Chunk, len(cl.chunks))
|
||||||
copy(ret, cl.chunks)
|
copy(ret, cl.chunks)
|
||||||
|
|
||||||
// Duplicate the last chunk
|
// Duplicate the last chunk
|
||||||
if cnt := len(ret); cnt > 0 {
|
if cnt := len(ret); cnt > 0 {
|
||||||
ret[cnt-1] = ret[cnt-1].dupe()
|
newChunk := *ret[cnt-1]
|
||||||
|
ret[cnt-1] = &newChunk
|
||||||
}
|
}
|
||||||
return ret, cl.count
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Chunk) dupe() *Chunk {
|
cl.mutex.Unlock()
|
||||||
newChunk := make(Chunk, len(*c))
|
return ret, CountItems(ret)
|
||||||
for idx, ptr := range *c {
|
|
||||||
newChunk[idx] = ptr
|
|
||||||
}
|
|
||||||
return &newChunk
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,9 @@ func TestChunkList(t *testing.T) {
|
|||||||
// FIXME global
|
// FIXME global
|
||||||
sortCriteria = []criterion{byScore, byLength}
|
sortCriteria = []criterion{byScore, byLength}
|
||||||
|
|
||||||
cl := NewChunkList(func(s []byte, i int) *Item {
|
cl := NewChunkList(func(item *Item, s []byte) bool {
|
||||||
return &Item{text: util.ToChars(s), index: int32(i * 2)}
|
item.text = util.ToChars(s)
|
||||||
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
// Snapshot
|
// Snapshot
|
||||||
@@ -38,11 +39,11 @@ func TestChunkList(t *testing.T) {
|
|||||||
|
|
||||||
// Check the content of the ChunkList
|
// Check the content of the ChunkList
|
||||||
chunk1 := snapshot[0]
|
chunk1 := snapshot[0]
|
||||||
if len(*chunk1) != 2 {
|
if chunk1.count != 2 {
|
||||||
t.Error("Snapshot should contain only two items")
|
t.Error("Snapshot should contain only two items")
|
||||||
}
|
}
|
||||||
if (*chunk1)[0].text.ToString() != "hello" || (*chunk1)[0].index != 0 ||
|
if chunk1.items[0].text.ToString() != "hello" ||
|
||||||
(*chunk1)[1].text.ToString() != "world" || (*chunk1)[1].index != 2 {
|
chunk1.items[1].text.ToString() != "world" {
|
||||||
t.Error("Invalid data")
|
t.Error("Invalid data")
|
||||||
}
|
}
|
||||||
if chunk1.IsFull() {
|
if chunk1.IsFull() {
|
||||||
@@ -65,14 +66,14 @@ func TestChunkList(t *testing.T) {
|
|||||||
!snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {
|
!snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {
|
||||||
t.Error("Expected two full chunks and one more chunk")
|
t.Error("Expected two full chunks and one more chunk")
|
||||||
}
|
}
|
||||||
if len(*snapshot[2]) != 2 {
|
if snapshot[2].count != 2 {
|
||||||
t.Error("Unexpected number of items")
|
t.Error("Unexpected number of items")
|
||||||
}
|
}
|
||||||
|
|
||||||
cl.Push([]byte("hello"))
|
cl.Push([]byte("hello"))
|
||||||
cl.Push([]byte("world"))
|
cl.Push([]byte("world"))
|
||||||
|
|
||||||
lastChunkCount := len(*snapshot[len(snapshot)-1])
|
lastChunkCount := snapshot[len(snapshot)-1].count
|
||||||
if lastChunkCount != 2 {
|
if lastChunkCount != 2 {
|
||||||
t.Error("Unexpected number of items:", lastChunkCount)
|
t.Error("Unexpected number of items:", lastChunkCount)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
@@ -8,20 +9,22 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
// Current version
|
// Current version
|
||||||
version = "0.16.4"
|
version = "0.17.0"
|
||||||
|
|
||||||
// Core
|
// Core
|
||||||
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
coordinatorDelayMax time.Duration = 100 * time.Millisecond
|
||||||
coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
coordinatorDelayStep time.Duration = 10 * time.Millisecond
|
||||||
|
|
||||||
// Reader
|
// Reader
|
||||||
readerBufferSize = 64 * 1024
|
readerBufferSize = 64 * 1024
|
||||||
|
readerPollIntervalMin = 10 * time.Millisecond
|
||||||
|
readerPollIntervalStep = 5 * time.Millisecond
|
||||||
|
readerPollIntervalMax = 50 * time.Millisecond
|
||||||
|
|
||||||
// Terminal
|
// Terminal
|
||||||
initialDelay = 20 * time.Millisecond
|
initialDelay = 20 * time.Millisecond
|
||||||
initialDelayTac = 100 * time.Millisecond
|
initialDelayTac = 100 * time.Millisecond
|
||||||
spinnerDuration = 200 * time.Millisecond
|
spinnerDuration = 200 * time.Millisecond
|
||||||
maxPatternLength = 100
|
|
||||||
|
|
||||||
// Matcher
|
// Matcher
|
||||||
numPartitionsMultiplier = 8
|
numPartitionsMultiplier = 8
|
||||||
@@ -48,6 +51,18 @@ const (
|
|||||||
defaultJumpLabels string = "asdfghjklqwertyuiopzxcvbnm1234567890ASDFGHJKLQWERTYUIOPZXCVBNM`~;:,<.>/?'\"!@#$%^&*()[{]}-_=+"
|
defaultJumpLabels string = "asdfghjklqwertyuiopzxcvbnm1234567890ASDFGHJKLQWERTYUIOPZXCVBNM`~;:,<.>/?'\"!@#$%^&*()[{]}-_=+"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var defaultCommand string
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if !util.IsWindows() {
|
||||||
|
defaultCommand = `command find -L . -mindepth 1 \( -path '*/\.*' -o -fstype 'sysfs' -o -fstype 'devfs' -o -fstype 'devtmpfs' -o -fstype 'proc' \) -prune -o -type f -print -o -type l -print 2> /dev/null | cut -b3-`
|
||||||
|
} else if os.Getenv("TERM") == "cygwin" {
|
||||||
|
defaultCommand = `sh -c "command find -L . -mindepth 1 -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | cut -b3-"`
|
||||||
|
} else {
|
||||||
|
defaultCommand = `dir /s/b`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// fzf events
|
// fzf events
|
||||||
const (
|
const (
|
||||||
EvtReadNew util.EventType = iota
|
EvtReadNew util.EventType = iota
|
||||||
@@ -56,7 +71,7 @@ const (
|
|||||||
EvtSearchProgress
|
EvtSearchProgress
|
||||||
EvtSearchFin
|
EvtSearchFin
|
||||||
EvtHeader
|
EvtHeader
|
||||||
EvtClose
|
EvtReady
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
// +build !windows
|
|
||||||
|
|
||||||
package fzf
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Reader
|
|
||||||
defaultCommand = `find -L . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
|
|
||||||
)
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
// +build windows
|
|
||||||
|
|
||||||
package fzf
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Reader
|
|
||||||
defaultCommand = `dir /s/b`
|
|
||||||
)
|
|
||||||
80
src/core.go
80
src/core.go
@@ -43,12 +43,16 @@ Matcher -> EvtHeader -> Terminal (update header)
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Run starts fzf
|
// Run starts fzf
|
||||||
func Run(opts *Options) {
|
func Run(opts *Options, revision string) {
|
||||||
sort := opts.Sort > 0
|
sort := opts.Sort > 0
|
||||||
sortCriteria = opts.Criteria
|
sortCriteria = opts.Criteria
|
||||||
|
|
||||||
if opts.Version {
|
if opts.Version {
|
||||||
fmt.Println(version)
|
if len(revision) > 0 {
|
||||||
|
fmt.Printf("%s (%s)\n", version, revision)
|
||||||
|
} else {
|
||||||
|
fmt.Println(version)
|
||||||
|
}
|
||||||
os.Exit(exitOk)
|
os.Exit(exitOk)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,74 +63,64 @@ func Run(opts *Options) {
|
|||||||
ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {
|
ansiProcessor := func(data []byte) (util.Chars, *[]ansiOffset) {
|
||||||
return util.ToChars(data), nil
|
return util.ToChars(data), nil
|
||||||
}
|
}
|
||||||
ansiProcessorRunes := func(data []rune) (util.Chars, *[]ansiOffset) {
|
|
||||||
return util.RunesToChars(data), nil
|
|
||||||
}
|
|
||||||
if opts.Ansi {
|
if opts.Ansi {
|
||||||
if opts.Theme != nil {
|
if opts.Theme != nil {
|
||||||
var state *ansiState
|
var state *ansiState
|
||||||
ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
|
ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
|
||||||
trimmed, offsets, newState := extractColor(string(data), state, nil)
|
trimmed, offsets, newState := extractColor(string(data), state, nil)
|
||||||
state = newState
|
state = newState
|
||||||
return util.RunesToChars([]rune(trimmed)), offsets
|
return util.ToChars([]byte(trimmed)), offsets
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// When color is disabled but ansi option is given,
|
// When color is disabled but ansi option is given,
|
||||||
// we simply strip out ANSI codes from the input
|
// we simply strip out ANSI codes from the input
|
||||||
ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
|
ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {
|
||||||
trimmed, _, _ := extractColor(string(data), nil, nil)
|
trimmed, _, _ := extractColor(string(data), nil, nil)
|
||||||
return util.RunesToChars([]rune(trimmed)), nil
|
return util.ToChars([]byte(trimmed)), nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ansiProcessorRunes = func(data []rune) (util.Chars, *[]ansiOffset) {
|
|
||||||
return ansiProcessor([]byte(string(data)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chunk list
|
// Chunk list
|
||||||
var chunkList *ChunkList
|
var chunkList *ChunkList
|
||||||
|
var itemIndex int32
|
||||||
header := make([]string, 0, opts.HeaderLines)
|
header := make([]string, 0, opts.HeaderLines)
|
||||||
if len(opts.WithNth) == 0 {
|
if len(opts.WithNth) == 0 {
|
||||||
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
chunkList = NewChunkList(func(item *Item, data []byte) bool {
|
||||||
if len(header) < opts.HeaderLines {
|
if len(header) < opts.HeaderLines {
|
||||||
header = append(header, string(data))
|
header = append(header, string(data))
|
||||||
eventBox.Set(EvtHeader, header)
|
eventBox.Set(EvtHeader, header)
|
||||||
return nil
|
return false
|
||||||
}
|
}
|
||||||
chars, colors := ansiProcessor(data)
|
item.text, item.colors = ansiProcessor(data)
|
||||||
return &Item{
|
item.text.Index = itemIndex
|
||||||
index: int32(index),
|
itemIndex++
|
||||||
text: chars,
|
return true
|
||||||
colors: colors}
|
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
chunkList = NewChunkList(func(data []byte, index int) *Item {
|
chunkList = NewChunkList(func(item *Item, data []byte) bool {
|
||||||
tokens := Tokenize(util.ToChars(data), opts.Delimiter)
|
tokens := Tokenize(string(data), opts.Delimiter)
|
||||||
trans := Transform(tokens, opts.WithNth)
|
trans := Transform(tokens, opts.WithNth)
|
||||||
|
transformed := joinTokens(trans)
|
||||||
if len(header) < opts.HeaderLines {
|
if len(header) < opts.HeaderLines {
|
||||||
header = append(header, string(joinTokens(trans)))
|
header = append(header, transformed)
|
||||||
eventBox.Set(EvtHeader, header)
|
eventBox.Set(EvtHeader, header)
|
||||||
return nil
|
return false
|
||||||
}
|
}
|
||||||
textRunes := joinTokens(trans)
|
item.text, item.colors = ansiProcessor([]byte(transformed))
|
||||||
item := Item{
|
item.text.Index = itemIndex
|
||||||
index: int32(index),
|
item.origText = &data
|
||||||
origText: &data,
|
itemIndex++
|
||||||
colors: nil}
|
return true
|
||||||
|
|
||||||
trimmed, colors := ansiProcessorRunes(textRunes)
|
|
||||||
item.text = trimmed
|
|
||||||
item.colors = colors
|
|
||||||
return &item
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reader
|
// Reader
|
||||||
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync
|
||||||
if !streamingFilter {
|
if !streamingFilter {
|
||||||
reader := Reader{func(data []byte) bool {
|
reader := NewReader(func(data []byte) bool {
|
||||||
return chunkList.Push(data)
|
return chunkList.Push(data)
|
||||||
}, eventBox, opts.ReadZero}
|
}, eventBox, opts.ReadZero)
|
||||||
go reader.ReadSource()
|
go reader.ReadSource()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,17 +153,17 @@ func Run(opts *Options) {
|
|||||||
found := false
|
found := false
|
||||||
if streamingFilter {
|
if streamingFilter {
|
||||||
slab := util.MakeSlab(slab16Size, slab32Size)
|
slab := util.MakeSlab(slab16Size, slab32Size)
|
||||||
reader := Reader{
|
reader := NewReader(
|
||||||
func(runes []byte) bool {
|
func(runes []byte) bool {
|
||||||
item := chunkList.trans(runes, 0)
|
item := Item{}
|
||||||
if item != nil {
|
if chunkList.trans(&item, runes) {
|
||||||
if result, _, _ := pattern.MatchItem(item, false, slab); result != nil {
|
if result, _, _ := pattern.MatchItem(&item, false, slab); result != nil {
|
||||||
opts.Printer(item.text.ToString())
|
opts.Printer(item.text.ToString())
|
||||||
found = true
|
found = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}, eventBox, opts.ReadZero}
|
}, eventBox, opts.ReadZero)
|
||||||
reader.ReadSource()
|
reader.ReadSource()
|
||||||
} else {
|
} else {
|
||||||
eventBox.Unwatch(EvtReadNew)
|
eventBox.Unwatch(EvtReadNew)
|
||||||
@@ -215,14 +209,19 @@ func Run(opts *Options) {
|
|||||||
delay := true
|
delay := true
|
||||||
ticks++
|
ticks++
|
||||||
eventBox.Wait(func(events *util.Events) {
|
eventBox.Wait(func(events *util.Events) {
|
||||||
defer events.Clear()
|
if _, fin := (*events)[EvtReadFin]; fin {
|
||||||
|
delete(*events, EvtReadNew)
|
||||||
|
}
|
||||||
for evt, value := range *events {
|
for evt, value := range *events {
|
||||||
switch evt {
|
switch evt {
|
||||||
|
|
||||||
case EvtReadNew, EvtReadFin:
|
case EvtReadNew, EvtReadFin:
|
||||||
reading = reading && evt == EvtReadNew
|
reading = reading && evt == EvtReadNew
|
||||||
snapshot, count := chunkList.Snapshot()
|
snapshot, count := chunkList.Snapshot()
|
||||||
terminal.UpdateCount(count, !reading)
|
terminal.UpdateCount(count, !reading, value.(bool))
|
||||||
|
if opts.Sync {
|
||||||
|
terminal.UpdateList(PassMerger(&snapshot, opts.Tac))
|
||||||
|
}
|
||||||
matcher.Reset(snapshot, terminal.Input(), false, !reading, sort)
|
matcher.Reset(snapshot, terminal.Input(), false, !reading, sort)
|
||||||
|
|
||||||
case EvtSearchNew:
|
case EvtSearchNew:
|
||||||
@@ -275,6 +274,7 @@ func Run(opts *Options) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
events.Clear()
|
||||||
})
|
})
|
||||||
if delay && reading {
|
if delay && reading {
|
||||||
dur := util.DurWithin(
|
dur := util.DurWithin(
|
||||||
|
|||||||
18
src/deps
18
src/deps
@@ -1,18 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
if [ -z "$GOPATH" ]; then
|
|
||||||
echo '$GOPATH not defined'
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
reset() (
|
|
||||||
cd "$GOPATH/src/$1"
|
|
||||||
export GIT_DIR="$(pwd)/.git"
|
|
||||||
[ "$(git rev-parse HEAD)" = "$2" ] ||
|
|
||||||
(git fetch && git reset --hard "$2")
|
|
||||||
)
|
|
||||||
|
|
||||||
reset github.com/junegunn/go-isatty 66b8e73f3f5cda9f96b69efd03dd3d7fc4a5cdb8
|
|
||||||
reset github.com/junegunn/go-runewidth 14207d285c6c197daabb5c9793d63e7af9ab2d50
|
|
||||||
reset github.com/junegunn/go-shellwords 33bd8f1ebe16d6e5eb688cc885749a63059e9167
|
|
||||||
reset golang.org/x/crypto abc5fa7ad02123a41f02bf1391c9760f7586e608
|
|
||||||
19
src/item.go
19
src/item.go
@@ -4,18 +4,23 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Item represents each input line
|
// Item represents each input line. 56 bytes.
|
||||||
type Item struct {
|
type Item struct {
|
||||||
index int32
|
text util.Chars // 32 = 24 + 1 + 1 + 2 + 4
|
||||||
text util.Chars
|
transformed *[]Token // 8
|
||||||
origText *[]byte
|
origText *[]byte // 8
|
||||||
colors *[]ansiOffset
|
colors *[]ansiOffset // 8
|
||||||
transformed []Token
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Index returns ordinal index of the Item
|
// Index returns ordinal index of the Item
|
||||||
func (item *Item) Index() int32 {
|
func (item *Item) Index() int32 {
|
||||||
return item.index
|
return item.text.Index
|
||||||
|
}
|
||||||
|
|
||||||
|
var minItem = Item{text: util.Chars{Index: -1}}
|
||||||
|
|
||||||
|
func (item *Item) TrimLength() uint16 {
|
||||||
|
return item.text.TrimLength()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Colors returns ansiOffsets of the Item
|
// Colors returns ansiOffsets of the Item
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ func (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {
|
|||||||
|
|
||||||
type partialResult struct {
|
type partialResult struct {
|
||||||
index int
|
index int
|
||||||
matches []*Result
|
matches []Result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
||||||
@@ -162,7 +162,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
go func(idx int, slab *util.Slab, chunks []*Chunk) {
|
go func(idx int, slab *util.Slab, chunks []*Chunk) {
|
||||||
defer func() { waitGroup.Done() }()
|
defer func() { waitGroup.Done() }()
|
||||||
count := 0
|
count := 0
|
||||||
allMatches := make([][]*Result, len(chunks))
|
allMatches := make([][]Result, len(chunks))
|
||||||
for idx, chunk := range chunks {
|
for idx, chunk := range chunks {
|
||||||
matches := request.pattern.Match(chunk, slab)
|
matches := request.pattern.Match(chunk, slab)
|
||||||
allMatches[idx] = matches
|
allMatches[idx] = matches
|
||||||
@@ -172,7 +172,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
}
|
}
|
||||||
countChan <- len(matches)
|
countChan <- len(matches)
|
||||||
}
|
}
|
||||||
sliceMatches := make([]*Result, 0, count)
|
sliceMatches := make([]Result, 0, count)
|
||||||
for _, matches := range allMatches {
|
for _, matches := range allMatches {
|
||||||
sliceMatches = append(sliceMatches, matches...)
|
sliceMatches = append(sliceMatches, matches...)
|
||||||
}
|
}
|
||||||
@@ -212,7 +212,7 @@ func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
partialResults := make([][]*Result, numSlices)
|
partialResults := make([][]Result, numSlices)
|
||||||
for _ = range slices {
|
for _ = range slices {
|
||||||
partialResult := <-resultChan
|
partialResult := <-resultChan
|
||||||
partialResults[partialResult.index] = partialResult.matches
|
partialResults[partialResult.index] = partialResult.matches
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ package fzf
|
|||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
// EmptyMerger is a Merger with no data
|
// EmptyMerger is a Merger with no data
|
||||||
var EmptyMerger = NewMerger(nil, [][]*Result{}, false, false)
|
var EmptyMerger = NewMerger(nil, [][]Result{}, false, false)
|
||||||
|
|
||||||
// Merger holds a set of locally sorted lists of items and provides the view of
|
// Merger holds a set of locally sorted lists of items and provides the view of
|
||||||
// a single, globally-sorted list
|
// a single, globally-sorted list
|
||||||
type Merger struct {
|
type Merger struct {
|
||||||
pattern *Pattern
|
pattern *Pattern
|
||||||
lists [][]*Result
|
lists [][]Result
|
||||||
merged []*Result
|
merged []Result
|
||||||
chunks *[]*Chunk
|
chunks *[]*Chunk
|
||||||
cursors []int
|
cursors []int
|
||||||
sorted bool
|
sorted bool
|
||||||
@@ -29,17 +29,17 @@ func PassMerger(chunks *[]*Chunk, tac bool) *Merger {
|
|||||||
count: 0}
|
count: 0}
|
||||||
|
|
||||||
for _, chunk := range *mg.chunks {
|
for _, chunk := range *mg.chunks {
|
||||||
mg.count += len(*chunk)
|
mg.count += chunk.count
|
||||||
}
|
}
|
||||||
return &mg
|
return &mg
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMerger returns a new Merger
|
// NewMerger returns a new Merger
|
||||||
func NewMerger(pattern *Pattern, lists [][]*Result, sorted bool, tac bool) *Merger {
|
func NewMerger(pattern *Pattern, lists [][]Result, sorted bool, tac bool) *Merger {
|
||||||
mg := Merger{
|
mg := Merger{
|
||||||
pattern: pattern,
|
pattern: pattern,
|
||||||
lists: lists,
|
lists: lists,
|
||||||
merged: []*Result{},
|
merged: []Result{},
|
||||||
chunks: nil,
|
chunks: nil,
|
||||||
cursors: make([]int, len(lists)),
|
cursors: make([]int, len(lists)),
|
||||||
sorted: sorted,
|
sorted: sorted,
|
||||||
@@ -59,13 +59,13 @@ func (mg *Merger) Length() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the pointer to the Result object indexed by the given integer
|
// Get returns the pointer to the Result object indexed by the given integer
|
||||||
func (mg *Merger) Get(idx int) *Result {
|
func (mg *Merger) Get(idx int) Result {
|
||||||
if mg.chunks != nil {
|
if mg.chunks != nil {
|
||||||
if mg.tac {
|
if mg.tac {
|
||||||
idx = mg.count - idx - 1
|
idx = mg.count - idx - 1
|
||||||
}
|
}
|
||||||
chunk := (*mg.chunks)[idx/chunkSize]
|
chunk := (*mg.chunks)[idx/chunkSize]
|
||||||
return &Result{item: (*chunk)[idx%chunkSize]}
|
return Result{item: &chunk.items[idx%chunkSize]}
|
||||||
}
|
}
|
||||||
|
|
||||||
if mg.sorted {
|
if mg.sorted {
|
||||||
@@ -89,7 +89,7 @@ func (mg *Merger) cacheable() bool {
|
|||||||
return mg.count < mergerCacheMax
|
return mg.count < mergerCacheMax
|
||||||
}
|
}
|
||||||
|
|
||||||
func (mg *Merger) mergedGet(idx int) *Result {
|
func (mg *Merger) mergedGet(idx int) Result {
|
||||||
for i := len(mg.merged); i <= idx; i++ {
|
for i := len(mg.merged); i <= idx; i++ {
|
||||||
minRank := minRank()
|
minRank := minRank()
|
||||||
minIdx := -1
|
minIdx := -1
|
||||||
@@ -100,7 +100,7 @@ func (mg *Merger) mergedGet(idx int) *Result {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if cursor >= 0 {
|
if cursor >= 0 {
|
||||||
rank := list[cursor].rank
|
rank := list[cursor]
|
||||||
if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {
|
if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {
|
||||||
minRank = rank
|
minRank = rank
|
||||||
minIdx = listIdx
|
minIdx = listIdx
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ func assert(t *testing.T, cond bool, msg ...string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func randResult() *Result {
|
func randResult() Result {
|
||||||
str := fmt.Sprintf("%d", rand.Uint32())
|
str := fmt.Sprintf("%d", rand.Uint32())
|
||||||
return &Result{
|
chars := util.ToChars([]byte(str))
|
||||||
item: &Item{text: util.RunesToChars([]rune(str))},
|
chars.Index = rand.Int31()
|
||||||
rank: rank{index: rand.Int31()}}
|
return Result{item: &Item{text: chars}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEmptyMerger(t *testing.T) {
|
func TestEmptyMerger(t *testing.T) {
|
||||||
@@ -29,14 +29,14 @@ func TestEmptyMerger(t *testing.T) {
|
|||||||
assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")
|
assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildLists(partiallySorted bool) ([][]*Result, []*Result) {
|
func buildLists(partiallySorted bool) ([][]Result, []Result) {
|
||||||
numLists := 4
|
numLists := 4
|
||||||
lists := make([][]*Result, numLists)
|
lists := make([][]Result, numLists)
|
||||||
cnt := 0
|
cnt := 0
|
||||||
for i := 0; i < numLists; i++ {
|
for i := 0; i < numLists; i++ {
|
||||||
numResults := rand.Int() % 20
|
numResults := rand.Int() % 20
|
||||||
cnt += numResults
|
cnt += numResults
|
||||||
lists[i] = make([]*Result, numResults)
|
lists[i] = make([]Result, numResults)
|
||||||
for j := 0; j < numResults; j++ {
|
for j := 0; j < numResults; j++ {
|
||||||
item := randResult()
|
item := randResult()
|
||||||
lists[i][j] = item
|
lists[i][j] = item
|
||||||
@@ -45,7 +45,7 @@ func buildLists(partiallySorted bool) ([][]*Result, []*Result) {
|
|||||||
sort.Sort(ByRelevance(lists[i]))
|
sort.Sort(ByRelevance(lists[i]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
items := []*Result{}
|
items := []Result{}
|
||||||
for _, list := range lists {
|
for _, list := range lists {
|
||||||
items = append(items, list...)
|
items = append(items, list...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/tui"
|
"github.com/junegunn/fzf/src/tui"
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
|
|
||||||
"github.com/junegunn/go-shellwords"
|
"github.com/mattn/go-shellwords"
|
||||||
)
|
)
|
||||||
|
|
||||||
const usage = `usage: fzf [options]
|
const usage = `usage: fzf [options]
|
||||||
@@ -86,6 +86,7 @@ const usage = `usage: fzf [options]
|
|||||||
--read0 Read input delimited by ASCII NUL characters
|
--read0 Read input delimited by ASCII NUL characters
|
||||||
--print0 Print output delimited by ASCII NUL characters
|
--print0 Print output delimited by ASCII NUL characters
|
||||||
--sync Synchronous search for multi-staged filtering
|
--sync Synchronous search for multi-staged filtering
|
||||||
|
--version Display version information and exit
|
||||||
|
|
||||||
Environment variables
|
Environment variables
|
||||||
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
FZF_DEFAULT_COMMAND Default command to use when input is tty
|
||||||
@@ -186,6 +187,7 @@ type Options struct {
|
|||||||
Margin [4]sizeSpec
|
Margin [4]sizeSpec
|
||||||
Bordered bool
|
Bordered bool
|
||||||
Tabstop int
|
Tabstop int
|
||||||
|
ClearOnExit bool
|
||||||
Version bool
|
Version bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,6 +236,7 @@ func defaultOptions() *Options {
|
|||||||
HeaderLines: 0,
|
HeaderLines: 0,
|
||||||
Margin: defaultMargin(),
|
Margin: defaultMargin(),
|
||||||
Tabstop: 8,
|
Tabstop: 8,
|
||||||
|
ClearOnExit: true,
|
||||||
Version: false}
|
Version: false}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,8 +400,10 @@ func parseKeyChords(str string, message string) map[int]string {
|
|||||||
chord = tui.BSpace
|
chord = tui.BSpace
|
||||||
case "ctrl-space":
|
case "ctrl-space":
|
||||||
chord = tui.CtrlSpace
|
chord = tui.CtrlSpace
|
||||||
|
case "change":
|
||||||
|
chord = tui.Change
|
||||||
case "alt-enter", "alt-return":
|
case "alt-enter", "alt-return":
|
||||||
chord = tui.AltEnter
|
chord = tui.CtrlAltM
|
||||||
case "alt-space":
|
case "alt-space":
|
||||||
chord = tui.AltSpace
|
chord = tui.AltSpace
|
||||||
case "alt-/":
|
case "alt-/":
|
||||||
@@ -434,7 +439,9 @@ func parseKeyChords(str string, message string) map[int]string {
|
|||||||
case "f12":
|
case "f12":
|
||||||
chord = tui.F12
|
chord = tui.F12
|
||||||
default:
|
default:
|
||||||
if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
if len(key) == 10 && strings.HasPrefix(lkey, "ctrl-alt-") && isAlphabet(lkey[9]) {
|
||||||
|
chord = tui.CtrlAltA + int(lkey[9]) - 'a'
|
||||||
|
} else if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {
|
||||||
chord = tui.CtrlA + int(lkey[5]) - 'a'
|
chord = tui.CtrlA + int(lkey[5]) - 'a'
|
||||||
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {
|
||||||
chord = tui.AltA + int(lkey[4]) - 'a'
|
chord = tui.AltA + int(lkey[4]) - 'a'
|
||||||
@@ -709,6 +716,8 @@ func parseKeymap(keymap map[int][]action, str string) {
|
|||||||
appendAction(actDown)
|
appendAction(actDown)
|
||||||
case "up":
|
case "up":
|
||||||
appendAction(actUp)
|
appendAction(actUp)
|
||||||
|
case "top":
|
||||||
|
appendAction(actTop)
|
||||||
case "page-up":
|
case "page-up":
|
||||||
appendAction(actPageUp)
|
appendAction(actPageUp)
|
||||||
case "page-down":
|
case "page-down":
|
||||||
@@ -723,6 +732,8 @@ func parseKeymap(keymap map[int][]action, str string) {
|
|||||||
appendAction(actNextHistory)
|
appendAction(actNextHistory)
|
||||||
case "toggle-preview":
|
case "toggle-preview":
|
||||||
appendAction(actTogglePreview)
|
appendAction(actTogglePreview)
|
||||||
|
case "toggle-preview-wrap":
|
||||||
|
appendAction(actTogglePreviewWrap)
|
||||||
case "toggle-sort":
|
case "toggle-sort":
|
||||||
appendAction(actToggleSort)
|
appendAction(actToggleSort)
|
||||||
case "preview-up":
|
case "preview-up":
|
||||||
@@ -951,7 +962,11 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
case "--algo":
|
case "--algo":
|
||||||
opts.FuzzyAlgo = parseAlgo(nextString(allArgs, &i, "algorithm required (v1|v2)"))
|
opts.FuzzyAlgo = parseAlgo(nextString(allArgs, &i, "algorithm required (v1|v2)"))
|
||||||
case "--expect":
|
case "--expect":
|
||||||
opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")
|
for k, v := range parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required") {
|
||||||
|
opts.Expect[k] = v
|
||||||
|
}
|
||||||
|
case "--no-expect":
|
||||||
|
opts.Expect = make(map[int]string)
|
||||||
case "--tiebreak":
|
case "--tiebreak":
|
||||||
opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))
|
||||||
case "--bind":
|
case "--bind":
|
||||||
@@ -1097,6 +1112,10 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))
|
nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))
|
||||||
case "--tabstop":
|
case "--tabstop":
|
||||||
opts.Tabstop = nextInt(allArgs, &i, "tab stop required")
|
opts.Tabstop = nextInt(allArgs, &i, "tab stop required")
|
||||||
|
case "--clear":
|
||||||
|
opts.ClearOnExit = true
|
||||||
|
case "--no-clear":
|
||||||
|
opts.ClearOnExit = false
|
||||||
case "--version":
|
case "--version":
|
||||||
opts.Version = true
|
opts.Version = true
|
||||||
default:
|
default:
|
||||||
@@ -1123,7 +1142,9 @@ func parseOptions(opts *Options, allArgs []string) {
|
|||||||
} else if match, value := optString(arg, "--toggle-sort="); match {
|
} else if match, value := optString(arg, "--toggle-sort="); match {
|
||||||
parseToggleSort(opts.Keymap, value)
|
parseToggleSort(opts.Keymap, value)
|
||||||
} else if match, value := optString(arg, "--expect="); match {
|
} else if match, value := optString(arg, "--expect="); match {
|
||||||
opts.Expect = parseKeyChords(value, "key names required")
|
for k, v := range parseKeyChords(value, "key names required") {
|
||||||
|
opts.Expect[k] = v
|
||||||
|
}
|
||||||
} else if match, value := optString(arg, "--tiebreak="); match {
|
} else if match, value := optString(arg, "--tiebreak="); match {
|
||||||
opts.Criteria = parseTiebreak(value)
|
opts.Criteria = parseTiebreak(value)
|
||||||
} else if match, value := optString(arg, "--color="); match {
|
} else if match, value := optString(arg, "--color="); match {
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/tui"
|
"github.com/junegunn/fzf/src/tui"
|
||||||
"github.com/junegunn/fzf/src/util"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDelimiterRegex(t *testing.T) {
|
func TestDelimiterRegex(t *testing.T) {
|
||||||
@@ -44,7 +43,7 @@ func TestDelimiterRegex(t *testing.T) {
|
|||||||
|
|
||||||
func TestDelimiterRegexString(t *testing.T) {
|
func TestDelimiterRegexString(t *testing.T) {
|
||||||
delim := delimiterRegexp("*")
|
delim := delimiterRegexp("*")
|
||||||
tokens := Tokenize(util.RunesToChars([]rune("-*--*---**---")), delim)
|
tokens := Tokenize("-*--*---**---", delim)
|
||||||
if delim.regex != nil ||
|
if delim.regex != nil ||
|
||||||
tokens[0].text.ToString() != "-*" ||
|
tokens[0].text.ToString() != "-*" ||
|
||||||
tokens[1].text.ToString() != "--*" ||
|
tokens[1].text.ToString() != "--*" ||
|
||||||
@@ -57,7 +56,7 @@ func TestDelimiterRegexString(t *testing.T) {
|
|||||||
|
|
||||||
func TestDelimiterRegexRegex(t *testing.T) {
|
func TestDelimiterRegexRegex(t *testing.T) {
|
||||||
delim := delimiterRegexp("--\\*")
|
delim := delimiterRegexp("--\\*")
|
||||||
tokens := Tokenize(util.RunesToChars([]rune("-*--*---**---")), delim)
|
tokens := Tokenize("-*--*---**---", delim)
|
||||||
if delim.str != nil ||
|
if delim.str != nil ||
|
||||||
tokens[0].text.ToString() != "-*--*" ||
|
tokens[0].text.ToString() != "-*--*" ||
|
||||||
tokens[1].text.ToString() != "---*" ||
|
tokens[1].text.ToString() != "---*" ||
|
||||||
@@ -125,14 +124,14 @@ func TestIrrelevantNth(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseKeys(t *testing.T) {
|
func TestParseKeys(t *testing.T) {
|
||||||
pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g,ALT-enter,alt-SPACE", "")
|
pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g,ctrl-alt-a,ALT-enter,alt-SPACE", "")
|
||||||
check := func(i int, s string) {
|
check := func(i int, s string) {
|
||||||
if pairs[i] != s {
|
if pairs[i] != s {
|
||||||
t.Errorf("%s != %s", pairs[i], s)
|
t.Errorf("%s != %s", pairs[i], s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(pairs) != 11 {
|
if len(pairs) != 12 {
|
||||||
t.Error(11)
|
t.Error(12)
|
||||||
}
|
}
|
||||||
check(tui.CtrlZ, "ctrl-z")
|
check(tui.CtrlZ, "ctrl-z")
|
||||||
check(tui.AltZ, "alt-z")
|
check(tui.AltZ, "alt-z")
|
||||||
@@ -143,7 +142,8 @@ func TestParseKeys(t *testing.T) {
|
|||||||
check(tui.CtrlA+'g'-'a', "ctrl-G")
|
check(tui.CtrlA+'g'-'a', "ctrl-G")
|
||||||
check(tui.AltZ+'J', "J")
|
check(tui.AltZ+'J', "J")
|
||||||
check(tui.AltZ+'g', "g")
|
check(tui.AltZ+'g', "g")
|
||||||
check(tui.AltEnter, "ALT-enter")
|
check(tui.CtrlAltA, "ctrl-alt-a")
|
||||||
|
check(tui.CtrlAltM, "ALT-enter")
|
||||||
check(tui.AltSpace, "alt-SPACE")
|
check(tui.AltSpace, "alt-SPACE")
|
||||||
|
|
||||||
// Synonyms
|
// Synonyms
|
||||||
@@ -414,3 +414,10 @@ func TestPreviewOpts(t *testing.T) {
|
|||||||
t.Error(opts.Preview)
|
t.Error(opts.Preview)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAdditiveExpect(t *testing.T) {
|
||||||
|
opts := optsFor("--expect=a", "--expect", "b", "--expect=c")
|
||||||
|
if len(opts.Expect) != 3 {
|
||||||
|
t.Error(opts.Expect)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
155
src/pattern.go
155
src/pattern.go
@@ -10,12 +10,12 @@ import (
|
|||||||
|
|
||||||
// fuzzy
|
// fuzzy
|
||||||
// 'exact
|
// 'exact
|
||||||
// ^exact-prefix
|
// ^prefix-exact
|
||||||
// exact-suffix$
|
// suffix-exact$
|
||||||
// !not-fuzzy
|
// !inverse-exact
|
||||||
// !'not-exact
|
// !'inverse-fuzzy
|
||||||
// !^not-exact-prefix
|
// !^inverse-prefix-exact
|
||||||
// !not-exact-suffix$
|
// !inverse-suffix-exact$
|
||||||
|
|
||||||
type termType int
|
type termType int
|
||||||
|
|
||||||
@@ -32,7 +32,6 @@ type term struct {
|
|||||||
inv bool
|
inv bool
|
||||||
text []rune
|
text []rune
|
||||||
caseSensitive bool
|
caseSensitive bool
|
||||||
origText []rune
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type termSet []term
|
type termSet []term
|
||||||
@@ -48,6 +47,7 @@ type Pattern struct {
|
|||||||
text []rune
|
text []rune
|
||||||
termSets []termSet
|
termSets []termSet
|
||||||
cacheable bool
|
cacheable bool
|
||||||
|
cacheKey string
|
||||||
delimiter Delimiter
|
delimiter Delimiter
|
||||||
nth []Range
|
nth []Range
|
||||||
procFun map[termType]algo.Algo
|
procFun map[termType]algo.Algo
|
||||||
@@ -60,7 +60,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
_splitRegex = regexp.MustCompile("\\s+")
|
_splitRegex = regexp.MustCompile(" +")
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
clearChunkCache()
|
clearChunkCache()
|
||||||
}
|
}
|
||||||
@@ -81,7 +81,10 @@ func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case,
|
|||||||
|
|
||||||
var asString string
|
var asString string
|
||||||
if extended {
|
if extended {
|
||||||
asString = strings.Trim(string(runes), " ")
|
asString = strings.TrimLeft(string(runes), " ")
|
||||||
|
for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {
|
||||||
|
asString = asString[:len(asString)-1]
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
asString = string(runes)
|
asString = string(runes)
|
||||||
}
|
}
|
||||||
@@ -101,7 +104,7 @@ func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case,
|
|||||||
for idx, term := range termSet {
|
for idx, term := range termSet {
|
||||||
// If the query contains inverse search terms or OR operators,
|
// If the query contains inverse search terms or OR operators,
|
||||||
// we cannot cache the search scope
|
// we cannot cache the search scope
|
||||||
if !cacheable || idx > 0 || term.inv || !fuzzy && term.typ != termExact {
|
if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {
|
||||||
cacheable = false
|
cacheable = false
|
||||||
break Loop
|
break Loop
|
||||||
}
|
}
|
||||||
@@ -130,6 +133,7 @@ func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case,
|
|||||||
delimiter: delimiter,
|
delimiter: delimiter,
|
||||||
procFun: make(map[termType]algo.Algo)}
|
procFun: make(map[termType]algo.Algo)}
|
||||||
|
|
||||||
|
ptr.cacheKey = ptr.buildCacheKey()
|
||||||
ptr.procFun[termFuzzy] = fuzzyAlgo
|
ptr.procFun[termFuzzy] = fuzzyAlgo
|
||||||
ptr.procFun[termEqual] = algo.EqualMatch
|
ptr.procFun[termEqual] = algo.EqualMatch
|
||||||
ptr.procFun[termExact] = algo.ExactMatchNaive
|
ptr.procFun[termExact] = algo.ExactMatchNaive
|
||||||
@@ -141,27 +145,30 @@ func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {
|
func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {
|
||||||
|
str = strings.Replace(str, "\\ ", "\t", -1)
|
||||||
tokens := _splitRegex.Split(str, -1)
|
tokens := _splitRegex.Split(str, -1)
|
||||||
sets := []termSet{}
|
sets := []termSet{}
|
||||||
set := termSet{}
|
set := termSet{}
|
||||||
switchSet := false
|
switchSet := false
|
||||||
|
afterBar := false
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
typ, inv, text := termFuzzy, false, token
|
typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)
|
||||||
lowerText := strings.ToLower(text)
|
lowerText := strings.ToLower(text)
|
||||||
caseSensitive := caseMode == CaseRespect ||
|
caseSensitive := caseMode == CaseRespect ||
|
||||||
caseMode == CaseSmart && text != lowerText
|
caseMode == CaseSmart && text != lowerText
|
||||||
if !caseSensitive {
|
if !caseSensitive {
|
||||||
text = lowerText
|
text = lowerText
|
||||||
}
|
}
|
||||||
origText := []rune(text)
|
|
||||||
if !fuzzy {
|
if !fuzzy {
|
||||||
typ = termExact
|
typ = termExact
|
||||||
}
|
}
|
||||||
|
|
||||||
if text == "|" {
|
if len(set) > 0 && !afterBar && text == "|" {
|
||||||
switchSet = false
|
switchSet = false
|
||||||
|
afterBar = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
afterBar = false
|
||||||
|
|
||||||
if strings.HasPrefix(text, "!") {
|
if strings.HasPrefix(text, "!") {
|
||||||
inv = true
|
inv = true
|
||||||
@@ -169,6 +176,11 @@ func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet
|
|||||||
text = text[1:]
|
text = text[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if text != "$" && strings.HasSuffix(text, "$") {
|
||||||
|
typ = termSuffix
|
||||||
|
text = text[:len(text)-1]
|
||||||
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(text, "'") {
|
if strings.HasPrefix(text, "'") {
|
||||||
// Flip exactness
|
// Flip exactness
|
||||||
if fuzzy && !inv {
|
if fuzzy && !inv {
|
||||||
@@ -179,16 +191,12 @@ func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet
|
|||||||
text = text[1:]
|
text = text[1:]
|
||||||
}
|
}
|
||||||
} else if strings.HasPrefix(text, "^") {
|
} else if strings.HasPrefix(text, "^") {
|
||||||
if strings.HasSuffix(text, "$") {
|
if typ == termSuffix {
|
||||||
typ = termEqual
|
typ = termEqual
|
||||||
text = text[1 : len(text)-1]
|
|
||||||
} else {
|
} else {
|
||||||
typ = termPrefix
|
typ = termPrefix
|
||||||
text = text[1:]
|
|
||||||
}
|
}
|
||||||
} else if strings.HasSuffix(text, "$") {
|
text = text[1:]
|
||||||
typ = termSuffix
|
|
||||||
text = text[:len(text)-1]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(text) > 0 {
|
if len(text) > 0 {
|
||||||
@@ -204,8 +212,7 @@ func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet
|
|||||||
typ: typ,
|
typ: typ,
|
||||||
inv: inv,
|
inv: inv,
|
||||||
text: textRunes,
|
text: textRunes,
|
||||||
caseSensitive: caseSensitive,
|
caseSensitive: caseSensitive})
|
||||||
origText: origText})
|
|
||||||
switchSet = true
|
switchSet = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,46 +235,36 @@ func (p *Pattern) AsString() string {
|
|||||||
return string(p.text)
|
return string(p.text)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CacheKey is used to build string to be used as the key of result cache
|
func (p *Pattern) buildCacheKey() string {
|
||||||
func (p *Pattern) CacheKey() string {
|
|
||||||
if !p.extended {
|
if !p.extended {
|
||||||
return p.AsString()
|
return p.AsString()
|
||||||
}
|
}
|
||||||
cacheableTerms := []string{}
|
cacheableTerms := []string{}
|
||||||
for _, termSet := range p.termSets {
|
for _, termSet := range p.termSets {
|
||||||
if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {
|
if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {
|
||||||
cacheableTerms = append(cacheableTerms, string(termSet[0].origText))
|
cacheableTerms = append(cacheableTerms, string(termSet[0].text))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return strings.Join(cacheableTerms, " ")
|
return strings.Join(cacheableTerms, "\t")
|
||||||
|
}
|
||||||
|
|
||||||
|
// CacheKey is used to build string to be used as the key of result cache
|
||||||
|
func (p *Pattern) CacheKey() string {
|
||||||
|
return p.cacheKey
|
||||||
}
|
}
|
||||||
|
|
||||||
// Match returns the list of matches Items in the given Chunk
|
// Match returns the list of matches Items in the given Chunk
|
||||||
func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {
|
func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {
|
||||||
// ChunkCache: Exact match
|
// ChunkCache: Exact match
|
||||||
cacheKey := p.CacheKey()
|
cacheKey := p.CacheKey()
|
||||||
if p.cacheable {
|
if p.cacheable {
|
||||||
if cached, found := _cache.Find(chunk, cacheKey); found {
|
if cached := _cache.Lookup(chunk, cacheKey); cached != nil {
|
||||||
return cached
|
return cached
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prefix/suffix cache
|
// Prefix/suffix cache
|
||||||
var space []*Result
|
space := _cache.Search(chunk, cacheKey)
|
||||||
Loop:
|
|
||||||
for idx := 1; idx < len(cacheKey); idx++ {
|
|
||||||
// [---------| ] | [ |---------]
|
|
||||||
// [--------| ] | [ |--------]
|
|
||||||
// [-------| ] | [ |-------]
|
|
||||||
prefix := cacheKey[:len(cacheKey)-idx]
|
|
||||||
suffix := cacheKey[idx:]
|
|
||||||
for _, substr := range [2]*string{&prefix, &suffix} {
|
|
||||||
if cached, found := _cache.Find(chunk, *substr); found {
|
|
||||||
space = cached
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
matches := p.matchChunk(chunk, space, slab)
|
matches := p.matchChunk(chunk, space, slab)
|
||||||
|
|
||||||
@@ -277,19 +274,19 @@ Loop:
|
|||||||
return matches
|
return matches
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {
|
func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {
|
||||||
matches := []*Result{}
|
matches := []Result{}
|
||||||
|
|
||||||
if space == nil {
|
if space == nil {
|
||||||
for _, item := range *chunk {
|
for idx := 0; idx < chunk.count; idx++ {
|
||||||
if match, _, _ := p.MatchItem(item, false, slab); match != nil {
|
if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {
|
||||||
matches = append(matches, match)
|
matches = append(matches, *match)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for _, result := range space {
|
for _, result := range space {
|
||||||
if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {
|
if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {
|
||||||
matches = append(matches, match)
|
matches = append(matches, *match)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -299,32 +296,43 @@ func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*
|
|||||||
// MatchItem returns true if the Item is a match
|
// MatchItem returns true if the Item is a match
|
||||||
func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {
|
func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {
|
||||||
if p.extended {
|
if p.extended {
|
||||||
if offsets, bonus, trimLen, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {
|
if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {
|
||||||
return buildResult(item, offsets, bonus, trimLen), offsets, pos
|
result := buildResult(item, offsets, bonus)
|
||||||
|
return &result, offsets, pos
|
||||||
}
|
}
|
||||||
return nil, nil, nil
|
return nil, nil, nil
|
||||||
}
|
}
|
||||||
offset, bonus, trimLen, pos := p.basicMatch(item, withPos, slab)
|
offset, bonus, pos := p.basicMatch(item, withPos, slab)
|
||||||
if sidx := offset[0]; sidx >= 0 {
|
if sidx := offset[0]; sidx >= 0 {
|
||||||
offsets := []Offset{offset}
|
offsets := []Offset{offset}
|
||||||
return buildResult(item, offsets, bonus, trimLen), offsets, pos
|
result := buildResult(item, offsets, bonus)
|
||||||
|
return &result, offsets, pos
|
||||||
}
|
}
|
||||||
return nil, nil, nil
|
return nil, nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {
|
func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {
|
||||||
input := p.prepareInput(item)
|
var input []Token
|
||||||
|
if len(p.nth) == 0 {
|
||||||
|
input = []Token{Token{text: &item.text, prefixLength: 0}}
|
||||||
|
} else {
|
||||||
|
input = p.transformInput(item)
|
||||||
|
}
|
||||||
if p.fuzzy {
|
if p.fuzzy {
|
||||||
return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
|
return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
|
||||||
}
|
}
|
||||||
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
|
return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, int, *[]int) {
|
func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {
|
||||||
input := p.prepareInput(item)
|
var input []Token
|
||||||
|
if len(p.nth) == 0 {
|
||||||
|
input = []Token{Token{text: &item.text, prefixLength: 0}}
|
||||||
|
} else {
|
||||||
|
input = p.transformInput(item)
|
||||||
|
}
|
||||||
offsets := []Offset{}
|
offsets := []Offset{}
|
||||||
var totalScore int
|
var totalScore int
|
||||||
var totalTrimLen int
|
|
||||||
var allPos *[]int
|
var allPos *[]int
|
||||||
if withPos {
|
if withPos {
|
||||||
allPos = &[]int{}
|
allPos = &[]int{}
|
||||||
@@ -332,16 +340,15 @@ func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Of
|
|||||||
for _, termSet := range p.termSets {
|
for _, termSet := range p.termSets {
|
||||||
var offset Offset
|
var offset Offset
|
||||||
var currentScore int
|
var currentScore int
|
||||||
var trimLen int
|
|
||||||
matched := false
|
matched := false
|
||||||
for _, term := range termSet {
|
for _, term := range termSet {
|
||||||
pfun := p.procFun[term.typ]
|
pfun := p.procFun[term.typ]
|
||||||
off, score, tLen, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)
|
off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)
|
||||||
if sidx := off[0]; sidx >= 0 {
|
if sidx := off[0]; sidx >= 0 {
|
||||||
if term.inv {
|
if term.inv {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
offset, currentScore, trimLen = off, score, tLen
|
offset, currentScore = off, score
|
||||||
matched = true
|
matched = true
|
||||||
if withPos {
|
if withPos {
|
||||||
if pos != nil {
|
if pos != nil {
|
||||||
@@ -354,7 +361,7 @@ func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Of
|
|||||||
}
|
}
|
||||||
break
|
break
|
||||||
} else if term.inv {
|
} else if term.inv {
|
||||||
offset, currentScore, trimLen = Offset{0, 0}, 0, 0
|
offset, currentScore = Offset{0, 0}, 0
|
||||||
matched = true
|
matched = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -362,31 +369,25 @@ func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Of
|
|||||||
if matched {
|
if matched {
|
||||||
offsets = append(offsets, offset)
|
offsets = append(offsets, offset)
|
||||||
totalScore += currentScore
|
totalScore += currentScore
|
||||||
totalTrimLen += trimLen
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return offsets, totalScore, totalTrimLen, allPos
|
return offsets, totalScore, allPos
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) prepareInput(item *Item) []Token {
|
func (p *Pattern) transformInput(item *Item) []Token {
|
||||||
if item.transformed != nil {
|
if item.transformed != nil {
|
||||||
return item.transformed
|
return *item.transformed
|
||||||
}
|
}
|
||||||
|
|
||||||
var ret []Token
|
tokens := Tokenize(item.text.ToString(), p.delimiter)
|
||||||
if len(p.nth) == 0 {
|
ret := Transform(tokens, p.nth)
|
||||||
ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}
|
item.transformed = &ret
|
||||||
} else {
|
|
||||||
tokens := Tokenize(item.text, p.delimiter)
|
|
||||||
ret = Transform(tokens, p.nth)
|
|
||||||
}
|
|
||||||
item.transformed = ret
|
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {
|
func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {
|
||||||
for _, part := range tokens {
|
for _, part := range tokens {
|
||||||
if res, pos := pfun(caseSensitive, normalize, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {
|
if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {
|
||||||
sidx := int32(res.Start) + part.prefixLength
|
sidx := int32(res.Start) + part.prefixLength
|
||||||
eidx := int32(res.End) + part.prefixLength
|
eidx := int32(res.End) + part.prefixLength
|
||||||
if pos != nil {
|
if pos != nil {
|
||||||
@@ -394,8 +395,8 @@ func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, norma
|
|||||||
(*pos)[idx] += int(part.prefixLength)
|
(*pos)[idx] += int(part.prefixLength)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Offset{sidx, eidx}, res.Score, int(part.trimLength), pos
|
return Offset{sidx, eidx}, res.Score, pos
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Offset{-1, -1}, 0, -1, nil
|
return Offset{-1, -1}, 0, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func init() {
|
|||||||
|
|
||||||
func TestParseTermsExtended(t *testing.T) {
|
func TestParseTermsExtended(t *testing.T) {
|
||||||
terms := parseTerms(true, CaseSmart, false,
|
terms := parseTerms(true, CaseSmart, false,
|
||||||
"| aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | | zzz$ | !ZZZ |")
|
"aaa 'bbb ^ccc ddd$ !eee !'fff !^ggg !hhh$ | ^iii$ ^xxx | 'yyy | zzz$ | !ZZZ |")
|
||||||
if len(terms) != 9 ||
|
if len(terms) != 9 ||
|
||||||
terms[0][0].typ != termFuzzy || terms[0][0].inv ||
|
terms[0][0].typ != termFuzzy || terms[0][0].inv ||
|
||||||
terms[1][0].typ != termExact || terms[1][0].inv ||
|
terms[1][0].typ != termExact || terms[1][0].inv ||
|
||||||
@@ -33,19 +33,11 @@ func TestParseTermsExtended(t *testing.T) {
|
|||||||
terms[8][3].typ != termExact || !terms[8][3].inv {
|
terms[8][3].typ != termExact || !terms[8][3].inv {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
for idx, termSet := range terms[:8] {
|
for _, termSet := range terms[:8] {
|
||||||
term := termSet[0]
|
term := termSet[0]
|
||||||
if len(term.text) != 3 {
|
if len(term.text) != 3 {
|
||||||
t.Errorf("%s", term)
|
t.Errorf("%s", term)
|
||||||
}
|
}
|
||||||
if idx > 0 && len(term.origText) != 4+idx/5 {
|
|
||||||
t.Errorf("%s", term)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, term := range terms[8] {
|
|
||||||
if len(term.origText) != 4 {
|
|
||||||
t.Errorf("%s", term)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +58,7 @@ func TestParseTermsExtendedExact(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTermsEmpty(t *testing.T) {
|
func TestParseTermsEmpty(t *testing.T) {
|
||||||
terms := parseTerms(true, CaseSmart, false, "' $ ^ !' !^ !$")
|
terms := parseTerms(true, CaseSmart, false, "' ^ !' !^")
|
||||||
if len(terms) != 0 {
|
if len(terms) != 0 {
|
||||||
t.Errorf("%s", terms)
|
t.Errorf("%s", terms)
|
||||||
}
|
}
|
||||||
@@ -77,8 +69,9 @@ func TestExact(t *testing.T) {
|
|||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true,
|
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true,
|
||||||
[]Range{}, Delimiter{}, []rune("'abc"))
|
[]Range{}, Delimiter{}, []rune("'abc"))
|
||||||
|
chars := util.ToChars([]byte("aabbcc abc"))
|
||||||
res, pos := algo.ExactMatchNaive(
|
res, pos := algo.ExactMatchNaive(
|
||||||
pattern.caseSensitive, pattern.normalize, pattern.forward, util.RunesToChars([]rune("aabbcc abc")), pattern.termSets[0][0].text, true, nil)
|
pattern.caseSensitive, pattern.normalize, pattern.forward, &chars, pattern.termSets[0][0].text, true, nil)
|
||||||
if res.Start != 7 || res.End != 10 {
|
if res.Start != 7 || res.End != 10 {
|
||||||
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||||
}
|
}
|
||||||
@@ -93,8 +86,9 @@ func TestEqual(t *testing.T) {
|
|||||||
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune("^AbC$"))
|
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune("^AbC$"))
|
||||||
|
|
||||||
match := func(str string, sidxExpected int, eidxExpected int) {
|
match := func(str string, sidxExpected int, eidxExpected int) {
|
||||||
|
chars := util.ToChars([]byte(str))
|
||||||
res, pos := algo.EqualMatch(
|
res, pos := algo.EqualMatch(
|
||||||
pattern.caseSensitive, pattern.normalize, pattern.forward, util.RunesToChars([]rune(str)), pattern.termSets[0][0].text, true, nil)
|
pattern.caseSensitive, pattern.normalize, pattern.forward, &chars, pattern.termSets[0][0].text, true, nil)
|
||||||
if res.Start != sidxExpected || res.End != eidxExpected {
|
if res.Start != sidxExpected || res.End != eidxExpected {
|
||||||
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
t.Errorf("%s / %d / %d", pattern.termSets, res.Start, res.End)
|
||||||
}
|
}
|
||||||
@@ -133,30 +127,29 @@ func TestCaseSensitivity(t *testing.T) {
|
|||||||
|
|
||||||
func TestOrigTextAndTransformed(t *testing.T) {
|
func TestOrigTextAndTransformed(t *testing.T) {
|
||||||
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune("jg"))
|
pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune("jg"))
|
||||||
tokens := Tokenize(util.RunesToChars([]rune("junegunn")), Delimiter{})
|
tokens := Tokenize("junegunn", Delimiter{})
|
||||||
trans := Transform(tokens, []Range{Range{1, 1}})
|
trans := Transform(tokens, []Range{Range{1, 1}})
|
||||||
|
|
||||||
origBytes := []byte("junegunn.choi")
|
origBytes := []byte("junegunn.choi")
|
||||||
for _, extended := range []bool{false, true} {
|
for _, extended := range []bool{false, true} {
|
||||||
chunk := Chunk{
|
chunk := Chunk{count: 1}
|
||||||
&Item{
|
chunk.items[0] = Item{
|
||||||
text: util.RunesToChars([]rune("junegunn")),
|
text: util.ToChars([]byte("junegunn")),
|
||||||
origText: &origBytes,
|
origText: &origBytes,
|
||||||
transformed: trans},
|
transformed: &trans}
|
||||||
}
|
|
||||||
pattern.extended = extended
|
pattern.extended = extended
|
||||||
matches := pattern.matchChunk(&chunk, nil, slab) // No cache
|
matches := pattern.matchChunk(&chunk, nil, slab) // No cache
|
||||||
if !(matches[0].item.text.ToString() == "junegunn" &&
|
if !(matches[0].item.text.ToString() == "junegunn" &&
|
||||||
string(*matches[0].item.origText) == "junegunn.choi" &&
|
string(*matches[0].item.origText) == "junegunn.choi" &&
|
||||||
reflect.DeepEqual(matches[0].item.transformed, trans)) {
|
reflect.DeepEqual(*matches[0].item.transformed, trans)) {
|
||||||
t.Error("Invalid match result", matches)
|
t.Error("Invalid match result", matches)
|
||||||
}
|
}
|
||||||
|
|
||||||
match, offsets, pos := pattern.MatchItem(chunk[0], true, slab)
|
match, offsets, pos := pattern.MatchItem(&chunk.items[0], true, slab)
|
||||||
if !(match.item.text.ToString() == "junegunn" &&
|
if !(match.item.text.ToString() == "junegunn" &&
|
||||||
string(*match.item.origText) == "junegunn.choi" &&
|
string(*match.item.origText) == "junegunn.choi" &&
|
||||||
offsets[0][0] == 0 && offsets[0][1] == 5 &&
|
offsets[0][0] == 0 && offsets[0][1] == 5 &&
|
||||||
reflect.DeepEqual(match.item.transformed, trans)) {
|
reflect.DeepEqual(*match.item.transformed, trans)) {
|
||||||
t.Error("Invalid match result", match, offsets, extended)
|
t.Error("Invalid match result", match, offsets, extended)
|
||||||
}
|
}
|
||||||
if !((*pos)[0] == 4 && (*pos)[1] == 0) {
|
if !((*pos)[0] == 4 && (*pos)[1] == 0) {
|
||||||
@@ -167,40 +160,47 @@ func TestOrigTextAndTransformed(t *testing.T) {
|
|||||||
|
|
||||||
func TestCacheKey(t *testing.T) {
|
func TestCacheKey(t *testing.T) {
|
||||||
test := func(extended bool, patStr string, expected string, cacheable bool) {
|
test := func(extended bool, patStr string, expected string, cacheable bool) {
|
||||||
|
clearPatternCache()
|
||||||
pat := BuildPattern(true, algo.FuzzyMatchV2, extended, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune(patStr))
|
pat := BuildPattern(true, algo.FuzzyMatchV2, extended, CaseSmart, false, true, true, []Range{}, Delimiter{}, []rune(patStr))
|
||||||
if pat.CacheKey() != expected {
|
if pat.CacheKey() != expected {
|
||||||
t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())
|
t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())
|
||||||
}
|
}
|
||||||
if pat.cacheable != cacheable {
|
if pat.cacheable != cacheable {
|
||||||
t.Errorf("Expected: %s, actual: %s (%s)", cacheable, pat.cacheable, patStr)
|
t.Errorf("Expected: %t, actual: %t (%s)", cacheable, pat.cacheable, patStr)
|
||||||
}
|
}
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
}
|
}
|
||||||
test(false, "foo !bar", "foo !bar", true)
|
test(false, "foo !bar", "foo !bar", true)
|
||||||
test(false, "foo | bar !baz", "foo | bar !baz", true)
|
test(false, "foo | bar !baz", "foo | bar !baz", true)
|
||||||
test(true, "foo bar baz", "foo bar baz", true)
|
test(true, "foo bar baz", "foo\tbar\tbaz", true)
|
||||||
test(true, "foo !bar", "foo", false)
|
test(true, "foo !bar", "foo", false)
|
||||||
test(true, "foo !bar baz", "foo baz", false)
|
test(true, "foo !bar baz", "foo\tbaz", false)
|
||||||
test(true, "foo | bar baz", "baz", false)
|
test(true, "foo | bar baz", "baz", false)
|
||||||
test(true, "foo | bar | baz", "", false)
|
test(true, "foo | bar | baz", "", false)
|
||||||
test(true, "foo | bar !baz", "", false)
|
test(true, "foo | bar !baz", "", false)
|
||||||
test(true, "| | | foo", "foo", true)
|
test(true, "| | foo", "", false)
|
||||||
|
test(true, "| | | foo", "foo", false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCacheable(t *testing.T) {
|
func TestCacheable(t *testing.T) {
|
||||||
test := func(fuzzy bool, str string, cacheable bool) {
|
test := func(fuzzy bool, str string, expected string, cacheable bool) {
|
||||||
clearPatternCache()
|
clearPatternCache()
|
||||||
pat := BuildPattern(fuzzy, algo.FuzzyMatchV2, true, CaseSmart, true, true, true, []Range{}, Delimiter{}, []rune(str))
|
pat := BuildPattern(fuzzy, algo.FuzzyMatchV2, true, CaseSmart, true, true, true, []Range{}, Delimiter{}, []rune(str))
|
||||||
|
if pat.CacheKey() != expected {
|
||||||
|
t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())
|
||||||
|
}
|
||||||
if cacheable != pat.cacheable {
|
if cacheable != pat.cacheable {
|
||||||
t.Errorf("Invalid Pattern.cacheable for \"%s\": %v (expected: %v)", str, pat.cacheable, cacheable)
|
t.Errorf("Invalid Pattern.cacheable for \"%s\": %v (expected: %v)", str, pat.cacheable, cacheable)
|
||||||
}
|
}
|
||||||
|
clearPatternCache()
|
||||||
}
|
}
|
||||||
test(true, "foo bar", true)
|
test(true, "foo bar", "foo\tbar", true)
|
||||||
test(true, "foo 'bar", true)
|
test(true, "foo 'bar", "foo\tbar", false)
|
||||||
test(true, "foo !bar", false)
|
test(true, "foo !bar", "foo", false)
|
||||||
|
|
||||||
test(false, "foo bar", true)
|
test(false, "foo bar", "foo\tbar", true)
|
||||||
test(false, "foo '", true)
|
test(false, "foo 'bar", "foo", false)
|
||||||
test(false, "foo 'bar", false)
|
test(false, "foo '", "foo", true)
|
||||||
test(false, "foo !bar", false)
|
test(false, "foo 'bar", "foo", false)
|
||||||
|
test(false, "foo !bar", "foo", false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
@@ -13,20 +15,54 @@ type Reader struct {
|
|||||||
pusher func([]byte) bool
|
pusher func([]byte) bool
|
||||||
eventBox *util.EventBox
|
eventBox *util.EventBox
|
||||||
delimNil bool
|
delimNil bool
|
||||||
|
event int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewReader returns new Reader object
|
||||||
|
func NewReader(pusher func([]byte) bool, eventBox *util.EventBox, delimNil bool) *Reader {
|
||||||
|
return &Reader{pusher, eventBox, delimNil, int32(EvtReady)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reader) startEventPoller() {
|
||||||
|
go func() {
|
||||||
|
ptr := &r.event
|
||||||
|
pollInterval := readerPollIntervalMin
|
||||||
|
for {
|
||||||
|
if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {
|
||||||
|
r.eventBox.Set(EvtReadNew, true)
|
||||||
|
pollInterval = readerPollIntervalMin
|
||||||
|
} else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
pollInterval += readerPollIntervalStep
|
||||||
|
if pollInterval > readerPollIntervalMax {
|
||||||
|
pollInterval = readerPollIntervalMax
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time.Sleep(pollInterval)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Reader) fin(success bool) {
|
||||||
|
atomic.StoreInt32(&r.event, int32(EvtReadFin))
|
||||||
|
r.eventBox.Set(EvtReadFin, success)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadSource reads data from the default command or from standard input
|
// ReadSource reads data from the default command or from standard input
|
||||||
func (r *Reader) ReadSource() {
|
func (r *Reader) ReadSource() {
|
||||||
|
r.startEventPoller()
|
||||||
|
var success bool
|
||||||
if util.IsTty() {
|
if util.IsTty() {
|
||||||
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
|
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
|
||||||
if len(cmd) == 0 {
|
if len(cmd) == 0 {
|
||||||
cmd = defaultCommand
|
cmd = defaultCommand
|
||||||
}
|
}
|
||||||
r.readFromCommand(cmd)
|
success = r.readFromCommand(cmd)
|
||||||
} else {
|
} else {
|
||||||
r.readFromStdin()
|
success = r.readFromStdin()
|
||||||
}
|
}
|
||||||
r.eventBox.Set(EvtReadFin, nil)
|
r.fin(success)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) feed(src io.Reader) {
|
func (r *Reader) feed(src io.Reader) {
|
||||||
@@ -40,7 +76,7 @@ func (r *Reader) feed(src io.Reader) {
|
|||||||
// end in delim.
|
// end in delim.
|
||||||
bytea, err := reader.ReadBytes(delim)
|
bytea, err := reader.ReadBytes(delim)
|
||||||
byteaLen := len(bytea)
|
byteaLen := len(bytea)
|
||||||
if len(bytea) > 0 {
|
if byteaLen > 0 {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
// get rid of carriage return if under Windows:
|
// get rid of carriage return if under Windows:
|
||||||
if util.IsWindows() && byteaLen >= 2 && bytea[byteaLen-2] == byte('\r') {
|
if util.IsWindows() && byteaLen >= 2 && bytea[byteaLen-2] == byte('\r') {
|
||||||
@@ -50,7 +86,7 @@ func (r *Reader) feed(src io.Reader) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if r.pusher(bytea) {
|
if r.pusher(bytea) {
|
||||||
r.eventBox.Set(EvtReadNew, nil)
|
atomic.StoreInt32(&r.event, int32(EvtReadNew))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -59,20 +95,21 @@ func (r *Reader) feed(src io.Reader) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) readFromStdin() {
|
func (r *Reader) readFromStdin() bool {
|
||||||
r.feed(os.Stdin)
|
r.feed(os.Stdin)
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) readFromCommand(cmd string) {
|
func (r *Reader) readFromCommand(cmd string) bool {
|
||||||
listCommand := util.ExecCommand(cmd)
|
listCommand := util.ExecCommand(cmd)
|
||||||
out, err := listCommand.StdoutPipe()
|
out, err := listCommand.StdoutPipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
err = listCommand.Start()
|
err = listCommand.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
defer listCommand.Wait()
|
|
||||||
r.feed(out)
|
r.feed(out)
|
||||||
|
return listCommand.Wait() == nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package fzf
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
@@ -11,7 +12,10 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
eb := util.NewEventBox()
|
eb := util.NewEventBox()
|
||||||
reader := Reader{
|
reader := Reader{
|
||||||
pusher: func(s []byte) bool { strs = append(strs, string(s)); return true },
|
pusher: func(s []byte) bool { strs = append(strs, string(s)); return true },
|
||||||
eventBox: eb}
|
eventBox: eb,
|
||||||
|
event: int32(EvtReady)}
|
||||||
|
|
||||||
|
reader.startEventPoller()
|
||||||
|
|
||||||
// Check EventBox
|
// Check EventBox
|
||||||
if eb.Peek(EvtReadNew) {
|
if eb.Peek(EvtReadNew) {
|
||||||
@@ -19,21 +23,16 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Normal command
|
// Normal command
|
||||||
reader.readFromCommand(`echo abc && echo def`)
|
reader.fin(reader.readFromCommand(`echo abc && echo def`))
|
||||||
if len(strs) != 2 || strs[0] != "abc" || strs[1] != "def" {
|
if len(strs) != 2 || strs[0] != "abc" || strs[1] != "def" {
|
||||||
t.Errorf("%s", strs)
|
t.Errorf("%s", strs)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check EventBox again
|
// Check EventBox again
|
||||||
if !eb.Peek(EvtReadNew) {
|
eb.WaitFor(EvtReadFin)
|
||||||
t.Error("EvtReadNew should be set yet")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait should return immediately
|
// Wait should return immediately
|
||||||
eb.Wait(func(events *util.Events) {
|
eb.Wait(func(events *util.Events) {
|
||||||
if _, found := (*events)[EvtReadNew]; !found {
|
|
||||||
t.Errorf("%s", events)
|
|
||||||
}
|
|
||||||
events.Clear()
|
events.Clear()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -42,8 +41,14 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
t.Error("EvtReadNew should not be set yet")
|
t.Error("EvtReadNew should not be set yet")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Make sure that event poller is finished
|
||||||
|
time.Sleep(readerPollIntervalMax)
|
||||||
|
|
||||||
|
// Restart event poller
|
||||||
|
reader.startEventPoller()
|
||||||
|
|
||||||
// Failing command
|
// Failing command
|
||||||
reader.readFromCommand(`no-such-command`)
|
reader.fin(reader.readFromCommand(`no-such-command`))
|
||||||
strs = []string{}
|
strs = []string{}
|
||||||
if len(strs) > 0 {
|
if len(strs) > 0 {
|
||||||
t.Errorf("%s", strs)
|
t.Errorf("%s", strs)
|
||||||
@@ -51,6 +56,9 @@ func TestReadFromCommand(t *testing.T) {
|
|||||||
|
|
||||||
// Check EventBox again
|
// Check EventBox again
|
||||||
if eb.Peek(EvtReadNew) {
|
if eb.Peek(EvtReadNew) {
|
||||||
t.Error("Command failed. EvtReadNew should be set")
|
t.Error("Command failed. EvtReadNew should not be set")
|
||||||
|
}
|
||||||
|
if !eb.Peek(EvtReadFin) {
|
||||||
|
t.Error("EvtReadFin should be set")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,22 +19,17 @@ type colorOffset struct {
|
|||||||
index int32
|
index int32
|
||||||
}
|
}
|
||||||
|
|
||||||
type rank struct {
|
|
||||||
points [4]uint16
|
|
||||||
index int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type Result struct {
|
type Result struct {
|
||||||
item *Item
|
item *Item
|
||||||
rank rank
|
points [4]uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildResult(item *Item, offsets []Offset, score int, trimLen int) *Result {
|
func buildResult(item *Item, offsets []Offset, score int) Result {
|
||||||
if len(offsets) > 1 {
|
if len(offsets) > 1 {
|
||||||
sort.Sort(ByOrder(offsets))
|
sort.Sort(ByOrder(offsets))
|
||||||
}
|
}
|
||||||
|
|
||||||
result := Result{item: item, rank: rank{index: item.index}}
|
result := Result{item: item}
|
||||||
numChars := item.text.Length()
|
numChars := item.text.Length()
|
||||||
minBegin := math.MaxUint16
|
minBegin := math.MaxUint16
|
||||||
minEnd := math.MaxUint16
|
minEnd := math.MaxUint16
|
||||||
@@ -57,8 +52,7 @@ func buildResult(item *Item, offsets []Offset, score int, trimLen int) *Result {
|
|||||||
// Higher is better
|
// Higher is better
|
||||||
val = math.MaxUint16 - util.AsUint16(score)
|
val = math.MaxUint16 - util.AsUint16(score)
|
||||||
case byLength:
|
case byLength:
|
||||||
// If offsets is empty, trimLen will be 0, but we don't care
|
val = item.TrimLength()
|
||||||
val = util.AsUint16(trimLen)
|
|
||||||
case byBegin, byEnd:
|
case byBegin, byEnd:
|
||||||
if validOffsetFound {
|
if validOffsetFound {
|
||||||
whitePrefixLen := 0
|
whitePrefixLen := 0
|
||||||
@@ -72,14 +66,14 @@ func buildResult(item *Item, offsets []Offset, score int, trimLen int) *Result {
|
|||||||
if criterion == byBegin {
|
if criterion == byBegin {
|
||||||
val = util.AsUint16(minEnd - whitePrefixLen)
|
val = util.AsUint16(minEnd - whitePrefixLen)
|
||||||
} else {
|
} else {
|
||||||
val = util.AsUint16(math.MaxUint16 - math.MaxUint16*(maxEnd-whitePrefixLen)/trimLen)
|
val = util.AsUint16(math.MaxUint16 - math.MaxUint16*(maxEnd-whitePrefixLen)/int(item.TrimLength()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result.rank.points[idx] = val
|
result.points[3-idx] = val
|
||||||
}
|
}
|
||||||
|
|
||||||
return &result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort criteria to use. Never changes once fzf is started.
|
// Sort criteria to use. Never changes once fzf is started.
|
||||||
@@ -87,11 +81,11 @@ var sortCriteria []criterion
|
|||||||
|
|
||||||
// Index returns ordinal index of the Item
|
// Index returns ordinal index of the Item
|
||||||
func (result *Result) Index() int32 {
|
func (result *Result) Index() int32 {
|
||||||
return result.item.index
|
return result.item.Index()
|
||||||
}
|
}
|
||||||
|
|
||||||
func minRank() rank {
|
func minRank() Result {
|
||||||
return rank{index: 0, points: [4]uint16{math.MaxUint16, 0, 0, 0}}
|
return Result{item: &minItem, points: [4]uint16{math.MaxUint16, 0, 0, 0}}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme, color tui.ColorPair, attr tui.Attr, current bool) []colorOffset {
|
func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme, color tui.ColorPair, attr tui.Attr, current bool) []colorOffset {
|
||||||
@@ -202,7 +196,7 @@ func (a ByOrder) Less(i, j int) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ByRelevance is for sorting Items
|
// ByRelevance is for sorting Items
|
||||||
type ByRelevance []*Result
|
type ByRelevance []Result
|
||||||
|
|
||||||
func (a ByRelevance) Len() int {
|
func (a ByRelevance) Len() int {
|
||||||
return len(a)
|
return len(a)
|
||||||
@@ -213,11 +207,11 @@ func (a ByRelevance) Swap(i, j int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a ByRelevance) Less(i, j int) bool {
|
func (a ByRelevance) Less(i, j int) bool {
|
||||||
return compareRanks((*a[i]).rank, (*a[j]).rank, false)
|
return compareRanks(a[i], a[j], false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ByRelevanceTac is for sorting Items
|
// ByRelevanceTac is for sorting Items
|
||||||
type ByRelevanceTac []*Result
|
type ByRelevanceTac []Result
|
||||||
|
|
||||||
func (a ByRelevanceTac) Len() int {
|
func (a ByRelevanceTac) Len() int {
|
||||||
return len(a)
|
return len(a)
|
||||||
@@ -228,18 +222,5 @@ func (a ByRelevanceTac) Swap(i, j int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a ByRelevanceTac) Less(i, j int) bool {
|
func (a ByRelevanceTac) Less(i, j int) bool {
|
||||||
return compareRanks((*a[i]).rank, (*a[j]).rank, true)
|
return compareRanks(a[i], a[j], true)
|
||||||
}
|
|
||||||
|
|
||||||
func compareRanks(irank rank, jrank rank, tac bool) bool {
|
|
||||||
for idx := 0; idx < 4; idx++ {
|
|
||||||
left := irank.points[idx]
|
|
||||||
right := jrank.points[idx]
|
|
||||||
if left < right {
|
|
||||||
return true
|
|
||||||
} else if left > right {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (irank.index <= jrank.index) != tac
|
|
||||||
}
|
}
|
||||||
|
|||||||
16
src/result_others.go
Normal file
16
src/result_others.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// +build !386,!amd64
|
||||||
|
|
||||||
|
package fzf
|
||||||
|
|
||||||
|
func compareRanks(irank Result, jrank Result, tac bool) bool {
|
||||||
|
for idx := 3; idx >= 0; idx-- {
|
||||||
|
left := irank.points[idx]
|
||||||
|
right := jrank.points[idx]
|
||||||
|
if left < right {
|
||||||
|
return true
|
||||||
|
} else if left > right {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (irank.item.Index() <= jrank.item.Index()) != tac
|
||||||
|
}
|
||||||
@@ -11,6 +11,11 @@ import (
|
|||||||
"github.com/junegunn/fzf/src/util"
|
"github.com/junegunn/fzf/src/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func withIndex(i *Item, index int) *Item {
|
||||||
|
(*i).text.Index = int32(index)
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
func TestOffsetSort(t *testing.T) {
|
func TestOffsetSort(t *testing.T) {
|
||||||
offsets := []Offset{
|
offsets := []Offset{
|
||||||
Offset{3, 5}, Offset{2, 7},
|
Offset{3, 5}, Offset{2, 7},
|
||||||
@@ -26,10 +31,10 @@ func TestOffsetSort(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRankComparison(t *testing.T) {
|
func TestRankComparison(t *testing.T) {
|
||||||
rank := func(vals ...uint16) rank {
|
rank := func(vals ...uint16) Result {
|
||||||
return rank{
|
return Result{
|
||||||
points: [4]uint16{vals[0], vals[1], vals[2], vals[3]},
|
points: [4]uint16{vals[0], vals[1], vals[2], vals[3]},
|
||||||
index: int32(vals[4])}
|
item: &Item{text: util.Chars{Index: int32(vals[4])}}}
|
||||||
}
|
}
|
||||||
if compareRanks(rank(3, 0, 0, 0, 5), rank(2, 0, 0, 0, 7), false) ||
|
if compareRanks(rank(3, 0, 0, 0, 5), rank(2, 0, 0, 0, 7), false) ||
|
||||||
!compareRanks(rank(3, 0, 0, 0, 5), rank(3, 0, 0, 0, 6), false) ||
|
!compareRanks(rank(3, 0, 0, 0, 5), rank(3, 0, 0, 0, 6), false) ||
|
||||||
@@ -52,36 +57,41 @@ func TestResultRank(t *testing.T) {
|
|||||||
sortCriteria = []criterion{byScore, byLength}
|
sortCriteria = []criterion{byScore, byLength}
|
||||||
|
|
||||||
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}
|
||||||
item1 := buildResult(&Item{text: util.RunesToChars(strs[0]), index: 1}, []Offset{}, 2, 3)
|
item1 := buildResult(
|
||||||
if item1.rank.points[0] != math.MaxUint16-2 || // Bonus
|
withIndex(&Item{text: util.RunesToChars(strs[0])}, 1), []Offset{}, 2)
|
||||||
item1.rank.points[1] != 3 || // Length
|
if item1.points[3] != math.MaxUint16-2 || // Bonus
|
||||||
item1.rank.points[2] != 0 || // Unused
|
item1.points[2] != 3 || // Length
|
||||||
item1.rank.points[3] != 0 || // Unused
|
item1.points[1] != 0 || // Unused
|
||||||
item1.item.index != 1 {
|
item1.points[0] != 0 || // Unused
|
||||||
t.Error(item1.rank)
|
item1.item.Index() != 1 {
|
||||||
|
t.Error(item1)
|
||||||
}
|
}
|
||||||
// Only differ in index
|
// Only differ in index
|
||||||
item2 := buildResult(&Item{text: util.RunesToChars(strs[0])}, []Offset{}, 2, 3)
|
item2 := buildResult(&Item{text: util.RunesToChars(strs[0])}, []Offset{}, 2)
|
||||||
|
|
||||||
items := []*Result{item1, item2}
|
items := []Result{item1, item2}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
if items[0] != item2 || items[1] != item1 {
|
if items[0] != item2 || items[1] != item1 {
|
||||||
t.Error(items)
|
t.Error(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
items = []*Result{item2, item1, item1, item2}
|
items = []Result{item2, item1, item1, item2}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
if items[0] != item2 || items[1] != item2 ||
|
if items[0] != item2 || items[1] != item2 ||
|
||||||
items[2] != item1 || items[3] != item1 {
|
items[2] != item1 || items[3] != item1 {
|
||||||
t.Error(items, item1, item1.item.index, item2, item2.item.index)
|
t.Error(items, item1, item1.item.Index(), item2, item2.item.Index())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort by relevance
|
// Sort by relevance
|
||||||
item3 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 3, 0)
|
item3 := buildResult(
|
||||||
item4 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 4, 0)
|
withIndex(&Item{}, 2), []Offset{Offset{1, 3}, Offset{5, 7}}, 3)
|
||||||
item5 := buildResult(&Item{index: 2}, []Offset{Offset{1, 3}, Offset{5, 7}}, 5, 0)
|
item4 := buildResult(
|
||||||
item6 := buildResult(&Item{index: 2}, []Offset{Offset{1, 2}, Offset{6, 7}}, 6, 0)
|
withIndex(&Item{}, 2), []Offset{Offset{1, 2}, Offset{6, 7}}, 4)
|
||||||
items = []*Result{item1, item2, item3, item4, item5, item6}
|
item5 := buildResult(
|
||||||
|
withIndex(&Item{}, 2), []Offset{Offset{1, 3}, Offset{5, 7}}, 5)
|
||||||
|
item6 := buildResult(
|
||||||
|
withIndex(&Item{}, 2), []Offset{Offset{1, 2}, Offset{6, 7}}, 6)
|
||||||
|
items = []Result{item1, item2, item3, item4, item5, item6}
|
||||||
sort.Sort(ByRelevance(items))
|
sort.Sort(ByRelevance(items))
|
||||||
if !(items[0] == item6 && items[1] == item5 &&
|
if !(items[0] == item6 && items[1] == item5 &&
|
||||||
items[2] == item4 && items[3] == item3 &&
|
items[2] == item4 && items[3] == item3 &&
|
||||||
|
|||||||
16
src/result_x86.go
Normal file
16
src/result_x86.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// +build 386 amd64
|
||||||
|
|
||||||
|
package fzf
|
||||||
|
|
||||||
|
import "unsafe"
|
||||||
|
|
||||||
|
func compareRanks(irank Result, jrank Result, tac bool) bool {
|
||||||
|
left := *(*uint64)(unsafe.Pointer(&irank.points[0]))
|
||||||
|
right := *(*uint64)(unsafe.Pointer(&jrank.points[0]))
|
||||||
|
if left < right {
|
||||||
|
return true
|
||||||
|
} else if left > right {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return (irank.item.Index() <= jrank.item.Index()) != tac
|
||||||
|
}
|
||||||
268
src/terminal.go
268
src/terminal.go
@@ -46,6 +46,7 @@ type itemLine struct {
|
|||||||
current bool
|
current bool
|
||||||
selected bool
|
selected bool
|
||||||
label string
|
label string
|
||||||
|
queryLen int
|
||||||
width int
|
width int
|
||||||
result Result
|
result Result
|
||||||
}
|
}
|
||||||
@@ -57,7 +58,9 @@ type Terminal struct {
|
|||||||
initDelay time.Duration
|
initDelay time.Duration
|
||||||
inlineInfo bool
|
inlineInfo bool
|
||||||
prompt string
|
prompt string
|
||||||
|
promptLen int
|
||||||
reverse bool
|
reverse bool
|
||||||
|
fullscreen bool
|
||||||
hscroll bool
|
hscroll bool
|
||||||
hscrollOff int
|
hscrollOff int
|
||||||
wordRubout string
|
wordRubout string
|
||||||
@@ -84,6 +87,7 @@ type Terminal struct {
|
|||||||
margin [4]sizeSpec
|
margin [4]sizeSpec
|
||||||
strong tui.Attr
|
strong tui.Attr
|
||||||
bordered bool
|
bordered bool
|
||||||
|
cleanExit bool
|
||||||
border tui.Window
|
border tui.Window
|
||||||
window tui.Window
|
window tui.Window
|
||||||
pborder tui.Window
|
pborder tui.Window
|
||||||
@@ -91,11 +95,13 @@ type Terminal struct {
|
|||||||
count int
|
count int
|
||||||
progress int
|
progress int
|
||||||
reading bool
|
reading bool
|
||||||
|
success bool
|
||||||
jumping jumpMode
|
jumping jumpMode
|
||||||
jumpLabels string
|
jumpLabels string
|
||||||
printer func(string)
|
printer func(string)
|
||||||
merger *Merger
|
merger *Merger
|
||||||
selected map[int32]selectedItem
|
selected map[int32]selectedItem
|
||||||
|
version int64
|
||||||
reqBox *util.EventBox
|
reqBox *util.EventBox
|
||||||
preview previewOpts
|
preview previewOpts
|
||||||
previewer previewer
|
previewer previewer
|
||||||
@@ -131,7 +137,6 @@ func (a byTimeOrder) Less(i, j int) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var _spinner = []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}
|
var _spinner = []string{`-`, `\`, `|`, `/`, `-`, `\`, `|`, `/`}
|
||||||
var _tabStop int
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
reqPrompt util.EventType = iota
|
reqPrompt util.EventType = iota
|
||||||
@@ -140,6 +145,7 @@ const (
|
|||||||
reqList
|
reqList
|
||||||
reqJump
|
reqJump
|
||||||
reqRefresh
|
reqRefresh
|
||||||
|
reqReinit
|
||||||
reqRedraw
|
reqRedraw
|
||||||
reqClose
|
reqClose
|
||||||
reqPrintQuery
|
reqPrintQuery
|
||||||
@@ -199,6 +205,7 @@ const (
|
|||||||
actPrintQuery
|
actPrintQuery
|
||||||
actToggleSort
|
actToggleSort
|
||||||
actTogglePreview
|
actTogglePreview
|
||||||
|
actTogglePreviewWrap
|
||||||
actPreviewUp
|
actPreviewUp
|
||||||
actPreviewDown
|
actPreviewDown
|
||||||
actPreviewPageUp
|
actPreviewPageUp
|
||||||
@@ -208,6 +215,8 @@ const (
|
|||||||
actExecute
|
actExecute
|
||||||
actExecuteSilent
|
actExecuteSilent
|
||||||
actExecuteMulti // Deprecated
|
actExecuteMulti // Deprecated
|
||||||
|
actSigStop
|
||||||
|
actTop
|
||||||
)
|
)
|
||||||
|
|
||||||
func toActions(types ...actionType) []action {
|
func toActions(types ...actionType) []action {
|
||||||
@@ -244,6 +253,9 @@ func defaultKeymap() map[int][]action {
|
|||||||
keymap[tui.CtrlU] = toActions(actUnixLineDiscard)
|
keymap[tui.CtrlU] = toActions(actUnixLineDiscard)
|
||||||
keymap[tui.CtrlW] = toActions(actUnixWordRubout)
|
keymap[tui.CtrlW] = toActions(actUnixWordRubout)
|
||||||
keymap[tui.CtrlY] = toActions(actYank)
|
keymap[tui.CtrlY] = toActions(actYank)
|
||||||
|
if !util.IsWindows() {
|
||||||
|
keymap[tui.CtrlZ] = toActions(actSigStop)
|
||||||
|
}
|
||||||
|
|
||||||
keymap[tui.AltB] = toActions(actBackwardWord)
|
keymap[tui.AltB] = toActions(actBackwardWord)
|
||||||
keymap[tui.SLeft] = toActions(actBackwardWord)
|
keymap[tui.SLeft] = toActions(actBackwardWord)
|
||||||
@@ -269,9 +281,13 @@ func defaultKeymap() map[int][]action {
|
|||||||
return keymap
|
return keymap
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func trimQuery(query string) []rune {
|
||||||
|
return []rune(strings.Replace(query, "\t", " ", -1))
|
||||||
|
}
|
||||||
|
|
||||||
// NewTerminal returns new Terminal object
|
// NewTerminal returns new Terminal object
|
||||||
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
||||||
input := []rune(opts.Query)
|
input := trimQuery(opts.Query)
|
||||||
var header []string
|
var header []string
|
||||||
if opts.Reverse {
|
if opts.Reverse {
|
||||||
header = opts.Header
|
header = opts.Header
|
||||||
@@ -293,7 +309,15 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
strongAttr = tui.AttrRegular
|
strongAttr = tui.AttrRegular
|
||||||
}
|
}
|
||||||
var renderer tui.Renderer
|
var renderer tui.Renderer
|
||||||
if opts.Height.size > 0 {
|
fullscreen := opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100
|
||||||
|
if fullscreen {
|
||||||
|
if tui.HasFullscreenRenderer() {
|
||||||
|
renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse)
|
||||||
|
} else {
|
||||||
|
renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit,
|
||||||
|
true, func(h int) int { return h })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
maxHeightFunc := func(termHeight int) int {
|
maxHeightFunc := func(termHeight int) int {
|
||||||
var maxHeight int
|
var maxHeight int
|
||||||
if opts.Height.percent {
|
if opts.Height.percent {
|
||||||
@@ -314,12 +338,7 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
}
|
}
|
||||||
return util.Min(termHeight, util.Max(maxHeight, effectiveMinHeight))
|
return util.Min(termHeight, util.Max(maxHeight, effectiveMinHeight))
|
||||||
}
|
}
|
||||||
renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, maxHeightFunc)
|
renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc)
|
||||||
} else if tui.HasFullscreenRenderer() {
|
|
||||||
renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse)
|
|
||||||
} else {
|
|
||||||
renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop,
|
|
||||||
func(h int) int { return h })
|
|
||||||
}
|
}
|
||||||
wordRubout := "[^[:alnum:]][[:alnum:]]"
|
wordRubout := "[^[:alnum:]][[:alnum:]]"
|
||||||
wordNext := "[[:alnum:]][^[:alnum:]]|(.$)"
|
wordNext := "[[:alnum:]][^[:alnum:]]|(.$)"
|
||||||
@@ -328,11 +347,11 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
wordRubout = fmt.Sprintf("%s[^%s]", sep, sep)
|
wordRubout = fmt.Sprintf("%s[^%s]", sep, sep)
|
||||||
wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep)
|
wordNext = fmt.Sprintf("[^%s]%s|(.$)", sep, sep)
|
||||||
}
|
}
|
||||||
return &Terminal{
|
t := Terminal{
|
||||||
initDelay: delay,
|
initDelay: delay,
|
||||||
inlineInfo: opts.InlineInfo,
|
inlineInfo: opts.InlineInfo,
|
||||||
prompt: opts.Prompt,
|
|
||||||
reverse: opts.Reverse,
|
reverse: opts.Reverse,
|
||||||
|
fullscreen: fullscreen,
|
||||||
hscroll: opts.Hscroll,
|
hscroll: opts.Hscroll,
|
||||||
hscrollOff: opts.HscrollOff,
|
hscrollOff: opts.HscrollOff,
|
||||||
wordRubout: wordRubout,
|
wordRubout: wordRubout,
|
||||||
@@ -353,6 +372,7 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
history: opts.History,
|
history: opts.History,
|
||||||
margin: opts.Margin,
|
margin: opts.Margin,
|
||||||
bordered: opts.Bordered,
|
bordered: opts.Bordered,
|
||||||
|
cleanExit: opts.ClearOnExit,
|
||||||
strong: strongAttr,
|
strong: strongAttr,
|
||||||
cycle: opts.Cycle,
|
cycle: opts.Cycle,
|
||||||
header: header,
|
header: header,
|
||||||
@@ -360,6 +380,7 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
ansi: opts.Ansi,
|
ansi: opts.Ansi,
|
||||||
tabstop: opts.Tabstop,
|
tabstop: opts.Tabstop,
|
||||||
reading: true,
|
reading: true,
|
||||||
|
success: true,
|
||||||
jumping: jumpDisabled,
|
jumping: jumpDisabled,
|
||||||
jumpLabels: opts.JumpLabels,
|
jumpLabels: opts.JumpLabels,
|
||||||
printer: opts.Printer,
|
printer: opts.Printer,
|
||||||
@@ -377,6 +398,8 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
|
|||||||
startChan: make(chan bool, 1),
|
startChan: make(chan bool, 1),
|
||||||
tui: renderer,
|
tui: renderer,
|
||||||
initFunc: func() { renderer.Init() }}
|
initFunc: func() { renderer.Init() }}
|
||||||
|
t.prompt, t.promptLen = t.processTabs([]rune(opts.Prompt), 0)
|
||||||
|
return &t
|
||||||
}
|
}
|
||||||
|
|
||||||
// Input returns current query string
|
// Input returns current query string
|
||||||
@@ -387,10 +410,11 @@ func (t *Terminal) Input() []rune {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateCount updates the count information
|
// UpdateCount updates the count information
|
||||||
func (t *Terminal) UpdateCount(cnt int, final bool) {
|
func (t *Terminal) UpdateCount(cnt int, final bool, success bool) {
|
||||||
t.mutex.Lock()
|
t.mutex.Lock()
|
||||||
t.count = cnt
|
t.count = cnt
|
||||||
t.reading = !final
|
t.reading = !final
|
||||||
|
t.success = success
|
||||||
t.mutex.Unlock()
|
t.mutex.Unlock()
|
||||||
t.reqBox.Set(reqInfo, nil)
|
t.reqBox.Set(reqInfo, nil)
|
||||||
if final {
|
if final {
|
||||||
@@ -568,6 +592,7 @@ func (t *Terminal) resizeWindows() {
|
|||||||
pwidth += 1
|
pwidth += 1
|
||||||
}
|
}
|
||||||
t.pwindow = t.tui.NewWindow(y+1, x+2, pwidth, h-2, tui.BorderNone)
|
t.pwindow = t.tui.NewWindow(y+1, x+2, pwidth, h-2, tui.BorderNone)
|
||||||
|
os.Setenv("FZF_PREVIEW_HEIGHT", strconv.Itoa(h-2))
|
||||||
}
|
}
|
||||||
switch t.preview.position {
|
switch t.preview.position {
|
||||||
case posUp:
|
case posUp:
|
||||||
@@ -598,11 +623,12 @@ func (t *Terminal) resizeWindows() {
|
|||||||
width,
|
width,
|
||||||
height, tui.BorderNone)
|
height, tui.BorderNone)
|
||||||
}
|
}
|
||||||
if !t.tui.IsOptimized() && t.theme != nil && t.theme.HasBg() {
|
if !t.tui.IsOptimized() {
|
||||||
for i := 0; i < t.window.Height(); i++ {
|
for i := 0; i < t.window.Height(); i++ {
|
||||||
t.window.MoveAndClear(i, 0)
|
t.window.MoveAndClear(i, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
t.truncateQuery()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) move(y int, x int, clear bool) {
|
func (t *Terminal) move(y int, x int, clear bool) {
|
||||||
@@ -618,7 +644,7 @@ func (t *Terminal) move(y int, x int, clear bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) placeCursor() {
|
func (t *Terminal) placeCursor() {
|
||||||
t.move(0, t.displayWidth([]rune(t.prompt))+t.displayWidth(t.input[:t.cx]), false)
|
t.move(0, t.promptLen+t.displayWidth(t.input[:t.cx]), false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printPrompt() {
|
func (t *Terminal) printPrompt() {
|
||||||
@@ -628,13 +654,19 @@ func (t *Terminal) printPrompt() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printInfo() {
|
func (t *Terminal) printInfo() {
|
||||||
|
pos := 0
|
||||||
if t.inlineInfo {
|
if t.inlineInfo {
|
||||||
t.move(0, t.displayWidth([]rune(t.prompt))+t.displayWidth(t.input)+1, true)
|
pos = t.promptLen + t.displayWidth(t.input) + 1
|
||||||
|
if pos+len(" < ") > t.window.Width() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.move(0, pos, true)
|
||||||
if t.reading {
|
if t.reading {
|
||||||
t.window.CPrint(tui.ColSpinner, t.strong, " < ")
|
t.window.CPrint(tui.ColSpinner, t.strong, " < ")
|
||||||
} else {
|
} else {
|
||||||
t.window.CPrint(tui.ColPrompt, t.strong, " < ")
|
t.window.CPrint(tui.ColPrompt, t.strong, " < ")
|
||||||
}
|
}
|
||||||
|
pos += len(" < ")
|
||||||
} else {
|
} else {
|
||||||
t.move(1, 0, true)
|
t.move(1, 0, true)
|
||||||
if t.reading {
|
if t.reading {
|
||||||
@@ -643,14 +675,15 @@ func (t *Terminal) printInfo() {
|
|||||||
t.window.CPrint(tui.ColSpinner, t.strong, _spinner[idx])
|
t.window.CPrint(tui.ColSpinner, t.strong, _spinner[idx])
|
||||||
}
|
}
|
||||||
t.move(1, 2, false)
|
t.move(1, 2, false)
|
||||||
|
pos = 2
|
||||||
}
|
}
|
||||||
|
|
||||||
output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)
|
output := fmt.Sprintf("%d/%d", t.merger.Length(), t.count)
|
||||||
if t.toggleSort {
|
if t.toggleSort {
|
||||||
if t.sort {
|
if t.sort {
|
||||||
output += "/S"
|
output += " +S"
|
||||||
} else {
|
} else {
|
||||||
output += " "
|
output += " -S"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if t.multi && len(t.selected) > 0 {
|
if t.multi && len(t.selected) > 0 {
|
||||||
@@ -659,7 +692,12 @@ func (t *Terminal) printInfo() {
|
|||||||
if t.progress > 0 && t.progress < 100 {
|
if t.progress > 0 && t.progress < 100 {
|
||||||
output += fmt.Sprintf(" (%d%%)", t.progress)
|
output += fmt.Sprintf(" (%d%%)", t.progress)
|
||||||
}
|
}
|
||||||
t.window.CPrint(tui.ColInfo, 0, output)
|
if !t.success && t.count == 0 {
|
||||||
|
output += " [ERROR]"
|
||||||
|
}
|
||||||
|
if pos+len(output) <= t.window.Width() {
|
||||||
|
t.window.CPrint(tui.ColInfo, 0, output)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printHeader() {
|
func (t *Terminal) printHeader() {
|
||||||
@@ -679,11 +717,11 @@ func (t *Terminal) printHeader() {
|
|||||||
trimmed, colors, newState := extractColor(lineStr, state, nil)
|
trimmed, colors, newState := extractColor(lineStr, state, nil)
|
||||||
state = newState
|
state = newState
|
||||||
item := &Item{
|
item := &Item{
|
||||||
text: util.RunesToChars([]rune(trimmed)),
|
text: util.ToChars([]byte(trimmed)),
|
||||||
colors: colors}
|
colors: colors}
|
||||||
|
|
||||||
t.move(line, 2, true)
|
t.move(line, 2, true)
|
||||||
t.printHighlighted(&Result{item: item},
|
t.printHighlighted(Result{item: item},
|
||||||
tui.AttrRegular, tui.ColHeader, tui.ColDefault, false, false)
|
tui.AttrRegular, tui.ColHeader, tui.ColDefault, false, false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -711,7 +749,7 @@ func (t *Terminal) printList() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printItem(result *Result, line int, i int, current bool) {
|
func (t *Terminal) printItem(result Result, line int, i int, current bool) {
|
||||||
item := result.item
|
item := result.item
|
||||||
_, selected := t.selected[item.Index()]
|
_, selected := t.selected[item.Index()]
|
||||||
label := " "
|
label := " "
|
||||||
@@ -726,11 +764,13 @@ func (t *Terminal) printItem(result *Result, line int, i int, current bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Avoid unnecessary redraw
|
// Avoid unnecessary redraw
|
||||||
newLine := itemLine{current: current, selected: selected, label: label, result: *result, width: 0}
|
newLine := itemLine{current: current, selected: selected, label: label,
|
||||||
|
result: result, queryLen: len(t.input), width: 0}
|
||||||
prevLine := t.prevLines[i]
|
prevLine := t.prevLines[i]
|
||||||
if prevLine.current == newLine.current &&
|
if prevLine.current == newLine.current &&
|
||||||
prevLine.selected == newLine.selected &&
|
prevLine.selected == newLine.selected &&
|
||||||
prevLine.label == newLine.label &&
|
prevLine.label == newLine.label &&
|
||||||
|
prevLine.queryLen == newLine.queryLen &&
|
||||||
prevLine.result == newLine.result {
|
prevLine.result == newLine.result {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -807,7 +847,7 @@ func (t *Terminal) overflow(runes []rune, max int) bool {
|
|||||||
return t.displayWidthWithLimit(runes, 0, max) > max
|
return t.displayWidthWithLimit(runes, 0, max) > max
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) printHighlighted(result *Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {
|
func (t *Terminal) printHighlighted(result Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {
|
||||||
item := result.item
|
item := result.item
|
||||||
|
|
||||||
// Overflow
|
// Overflow
|
||||||
@@ -927,6 +967,8 @@ func (t *Terminal) printPreview() {
|
|||||||
}
|
}
|
||||||
reader := bufio.NewReader(strings.NewReader(t.previewer.text))
|
reader := bufio.NewReader(strings.NewReader(t.previewer.text))
|
||||||
lineNo := -t.previewer.offset
|
lineNo := -t.previewer.offset
|
||||||
|
height := t.pwindow.Height()
|
||||||
|
var ansi *ansiState
|
||||||
for {
|
for {
|
||||||
line, err := reader.ReadString('\n')
|
line, err := reader.ReadString('\n')
|
||||||
eof := err == io.EOF
|
eof := err == io.EOF
|
||||||
@@ -934,17 +976,18 @@ func (t *Terminal) printPreview() {
|
|||||||
line = line[:len(line)-1]
|
line = line[:len(line)-1]
|
||||||
}
|
}
|
||||||
lineNo++
|
lineNo++
|
||||||
if lineNo > t.pwindow.Height() {
|
if lineNo > height ||
|
||||||
|
t.pwindow.Y() == height-1 && t.pwindow.X() > 0 {
|
||||||
break
|
break
|
||||||
} else if lineNo > 0 {
|
} else if lineNo > 0 {
|
||||||
var fillRet tui.FillReturn
|
var fillRet tui.FillReturn
|
||||||
extractColor(line, nil, func(str string, ansi *ansiState) bool {
|
_, _, ansi = extractColor(line, ansi, func(str string, ansi *ansiState) bool {
|
||||||
trimmed := []rune(str)
|
trimmed := []rune(str)
|
||||||
if !t.preview.wrap {
|
if !t.preview.wrap {
|
||||||
trimmed, _ = t.trimRight(trimmed, maxWidth-t.pwindow.X())
|
trimmed, _ = t.trimRight(trimmed, maxWidth-t.pwindow.X())
|
||||||
}
|
}
|
||||||
str, _ = t.processTabs(trimmed, 0)
|
str, _ = t.processTabs(trimmed, 0)
|
||||||
if ansi != nil && ansi.colored() {
|
if t.theme != nil && ansi != nil && ansi.colored() {
|
||||||
fillRet = t.pwindow.CFill(ansi.fg, ansi.bg, ansi.attr, str)
|
fillRet = t.pwindow.CFill(ansi.fg, ansi.bg, ansi.attr, str)
|
||||||
} else {
|
} else {
|
||||||
fillRet = t.pwindow.Fill(str)
|
fillRet = t.pwindow.Fill(str)
|
||||||
@@ -964,7 +1007,7 @@ func (t *Terminal) printPreview() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.pwindow.FinishFill()
|
t.pwindow.FinishFill()
|
||||||
if t.previewer.lines > t.pwindow.Height() {
|
if t.previewer.lines > height {
|
||||||
offset := fmt.Sprintf("%d/%d", t.previewer.offset+1, t.previewer.lines)
|
offset := fmt.Sprintf("%d/%d", t.previewer.offset+1, t.previewer.lines)
|
||||||
pos := t.pwindow.Width() - len(offset)
|
pos := t.pwindow.Width() - len(offset)
|
||||||
if t.tui.DoesAutoWrap() {
|
if t.tui.DoesAutoWrap() {
|
||||||
@@ -1135,8 +1178,7 @@ func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, fo
|
|||||||
}
|
}
|
||||||
|
|
||||||
for idx, item := range items {
|
for idx, item := range items {
|
||||||
chars := util.RunesToChars([]rune(item.AsString(stripAnsi)))
|
tokens := Tokenize(item.AsString(stripAnsi), delimiter)
|
||||||
tokens := Tokenize(chars, delimiter)
|
|
||||||
trans := Transform(tokens, ranges)
|
trans := Transform(tokens, ranges)
|
||||||
str := string(joinTokens(trans))
|
str := string(joinTokens(trans))
|
||||||
if delimiter.str != nil {
|
if delimiter.str != nil {
|
||||||
@@ -1154,6 +1196,12 @@ func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, fo
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) redraw() {
|
||||||
|
t.tui.Clear()
|
||||||
|
t.tui.Refresh()
|
||||||
|
t.printAll()
|
||||||
|
}
|
||||||
|
|
||||||
func (t *Terminal) executeCommand(template string, forcePlus bool, background bool) {
|
func (t *Terminal) executeCommand(template string, forcePlus bool, background bool) {
|
||||||
valid, list := t.buildPlusList(template, forcePlus)
|
valid, list := t.buildPlusList(template, forcePlus)
|
||||||
if !valid {
|
if !valid {
|
||||||
@@ -1165,12 +1213,10 @@ func (t *Terminal) executeCommand(template string, forcePlus bool, background bo
|
|||||||
cmd.Stdin = os.Stdin
|
cmd.Stdin = os.Stdin
|
||||||
cmd.Stdout = os.Stdout
|
cmd.Stdout = os.Stdout
|
||||||
cmd.Stderr = os.Stderr
|
cmd.Stderr = os.Stderr
|
||||||
t.tui.Pause()
|
t.tui.Pause(true)
|
||||||
cmd.Run()
|
cmd.Run()
|
||||||
if t.tui.Resume() {
|
t.tui.Resume(true)
|
||||||
t.tui.Clear()
|
t.redraw()
|
||||||
t.printAll()
|
|
||||||
}
|
|
||||||
t.refresh()
|
t.refresh()
|
||||||
} else {
|
} else {
|
||||||
cmd.Run()
|
cmd.Run()
|
||||||
@@ -1210,6 +1256,30 @@ func (t *Terminal) buildPlusList(template string, forcePlus bool) (bool, []*Item
|
|||||||
return true, sels
|
return true, sels
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) truncateQuery() {
|
||||||
|
maxPatternLength := util.Max(1, t.window.Width()-t.promptLen-1)
|
||||||
|
t.input, _ = t.trimRight(t.input, maxPatternLength)
|
||||||
|
t.cx = util.Constrain(t.cx, 0, len(t.input))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) selectItem(item *Item) {
|
||||||
|
t.selected[item.Index()] = selectedItem{time.Now(), item}
|
||||||
|
t.version++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) deselectItem(item *Item) {
|
||||||
|
delete(t.selected, item.Index())
|
||||||
|
t.version++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Terminal) toggleItem(item *Item) {
|
||||||
|
if _, found := t.selected[item.Index()]; !found {
|
||||||
|
t.selectItem(item)
|
||||||
|
} else {
|
||||||
|
t.deselectItem(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Loop is called to start Terminal I/O
|
// Loop is called to start Terminal I/O
|
||||||
func (t *Terminal) Loop() {
|
func (t *Terminal) Loop() {
|
||||||
// prof := profile.Start(profile.ProfilePath("/tmp/"))
|
// prof := profile.Start(profile.ProfilePath("/tmp/"))
|
||||||
@@ -1222,6 +1292,15 @@ func (t *Terminal) Loop() {
|
|||||||
t.reqBox.Set(reqQuit, nil)
|
t.reqBox.Set(reqQuit, nil)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
contChan := make(chan os.Signal, 1)
|
||||||
|
notifyOnCont(contChan)
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
<-contChan
|
||||||
|
t.reqBox.Set(reqReinit, nil)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
resizeChan := make(chan os.Signal, 1)
|
resizeChan := make(chan os.Signal, 1)
|
||||||
notifyOnResize(resizeChan) // Non-portable
|
notifyOnResize(resizeChan) // Non-portable
|
||||||
go func() {
|
go func() {
|
||||||
@@ -1288,7 +1367,12 @@ func (t *Terminal) Loop() {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
exit := func(code int) {
|
exit := func(getCode func() int) {
|
||||||
|
if !t.cleanExit && t.fullscreen && t.inlineInfo {
|
||||||
|
t.placeCursor()
|
||||||
|
}
|
||||||
|
t.tui.Close()
|
||||||
|
code := getCode()
|
||||||
if code <= exitNoMatch && t.history != nil {
|
if code <= exitNoMatch && t.history != nil {
|
||||||
t.history.append(string(t.input))
|
t.history.append(string(t.input))
|
||||||
}
|
}
|
||||||
@@ -1298,6 +1382,7 @@ func (t *Terminal) Loop() {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
var focused *Item
|
var focused *Item
|
||||||
|
var version int64
|
||||||
for {
|
for {
|
||||||
t.reqBox.Wait(func(events *util.Events) {
|
t.reqBox.Wait(func(events *util.Events) {
|
||||||
defer events.Clear()
|
defer events.Clear()
|
||||||
@@ -1314,7 +1399,8 @@ func (t *Terminal) Loop() {
|
|||||||
case reqList:
|
case reqList:
|
||||||
t.printList()
|
t.printList()
|
||||||
currentFocus := t.currentItem()
|
currentFocus := t.currentItem()
|
||||||
if currentFocus != focused {
|
if currentFocus != focused || version != t.version {
|
||||||
|
version = t.version
|
||||||
focused = currentFocus
|
focused = currentFocus
|
||||||
if t.isPreviewEnabled() {
|
if t.isPreviewEnabled() {
|
||||||
_, list := t.buildPlusList(t.preview.command, false)
|
_, list := t.buildPlusList(t.preview.command, false)
|
||||||
@@ -1330,16 +1416,18 @@ func (t *Terminal) Loop() {
|
|||||||
t.printHeader()
|
t.printHeader()
|
||||||
case reqRefresh:
|
case reqRefresh:
|
||||||
t.suppress = false
|
t.suppress = false
|
||||||
|
case reqReinit:
|
||||||
|
t.tui.Resume(t.fullscreen)
|
||||||
|
t.redraw()
|
||||||
case reqRedraw:
|
case reqRedraw:
|
||||||
t.tui.Clear()
|
t.redraw()
|
||||||
t.tui.Refresh()
|
|
||||||
t.printAll()
|
|
||||||
case reqClose:
|
case reqClose:
|
||||||
t.tui.Close()
|
exit(func() int {
|
||||||
if t.output() {
|
if t.output() {
|
||||||
exit(exitOk)
|
return exitOk
|
||||||
}
|
}
|
||||||
exit(exitNoMatch)
|
return exitNoMatch
|
||||||
|
})
|
||||||
case reqPreviewDisplay:
|
case reqPreviewDisplay:
|
||||||
t.previewer.text = value.(string)
|
t.previewer.text = value.(string)
|
||||||
t.previewer.lines = strings.Count(t.previewer.text, "\n")
|
t.previewer.lines = strings.Count(t.previewer.text, "\n")
|
||||||
@@ -1348,12 +1436,12 @@ func (t *Terminal) Loop() {
|
|||||||
case reqPreviewRefresh:
|
case reqPreviewRefresh:
|
||||||
t.printPreview()
|
t.printPreview()
|
||||||
case reqPrintQuery:
|
case reqPrintQuery:
|
||||||
t.tui.Close()
|
exit(func() int {
|
||||||
t.printer(string(t.input))
|
t.printer(string(t.input))
|
||||||
exit(exitOk)
|
return exitOk
|
||||||
|
})
|
||||||
case reqQuit:
|
case reqQuit:
|
||||||
t.tui.Close()
|
exit(func() int { return exitInterrupt })
|
||||||
exit(exitInterrupt)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.placeCursor()
|
t.placeCursor()
|
||||||
@@ -1378,22 +1466,9 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
selectItem := func(item *Item) bool {
|
|
||||||
if _, found := t.selected[item.Index()]; !found {
|
|
||||||
t.selected[item.Index()] = selectedItem{time.Now(), item}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
toggleY := func(y int) {
|
|
||||||
item := t.merger.Get(y).item
|
|
||||||
if !selectItem(item) {
|
|
||||||
delete(t.selected, item.Index())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
toggle := func() {
|
toggle := func() {
|
||||||
if t.cy < t.merger.Length() {
|
if t.cy < t.merger.Length() {
|
||||||
toggleY(t.cy)
|
t.toggleItem(t.merger.Get(t.cy).item)
|
||||||
req(reqInfo)
|
req(reqInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1443,6 +1518,11 @@ func (t *Terminal) Loop() {
|
|||||||
}
|
}
|
||||||
req(reqList, reqInfo, reqHeader)
|
req(reqList, reqInfo, reqHeader)
|
||||||
}
|
}
|
||||||
|
case actTogglePreviewWrap:
|
||||||
|
if t.hasPreviewWindow() {
|
||||||
|
t.preview.wrap = !t.preview.wrap
|
||||||
|
req(reqPreviewRefresh)
|
||||||
|
}
|
||||||
case actToggleSort:
|
case actToggleSort:
|
||||||
t.sort = !t.sort
|
t.sort = !t.sort
|
||||||
t.eventBox.Set(EvtSearchNew, t.sort)
|
t.eventBox.Set(EvtSearchNew, t.sort)
|
||||||
@@ -1502,17 +1582,14 @@ func (t *Terminal) Loop() {
|
|||||||
case actSelectAll:
|
case actSelectAll:
|
||||||
if t.multi {
|
if t.multi {
|
||||||
for i := 0; i < t.merger.Length(); i++ {
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
item := t.merger.Get(i).item
|
t.selectItem(t.merger.Get(i).item)
|
||||||
selectItem(item)
|
|
||||||
}
|
}
|
||||||
req(reqList, reqInfo)
|
req(reqList, reqInfo)
|
||||||
}
|
}
|
||||||
case actDeselectAll:
|
case actDeselectAll:
|
||||||
if t.multi {
|
if t.multi {
|
||||||
for i := 0; i < t.merger.Length(); i++ {
|
t.selected = make(map[int32]selectedItem)
|
||||||
item := t.merger.Get(i)
|
t.version++
|
||||||
delete(t.selected, item.Index())
|
|
||||||
}
|
|
||||||
req(reqList, reqInfo)
|
req(reqList, reqInfo)
|
||||||
}
|
}
|
||||||
case actToggle:
|
case actToggle:
|
||||||
@@ -1523,7 +1600,7 @@ func (t *Terminal) Loop() {
|
|||||||
case actToggleAll:
|
case actToggleAll:
|
||||||
if t.multi {
|
if t.multi {
|
||||||
for i := 0; i < t.merger.Length(); i++ {
|
for i := 0; i < t.merger.Length(); i++ {
|
||||||
toggleY(i)
|
t.toggleItem(t.merger.Get(i).item)
|
||||||
}
|
}
|
||||||
req(reqList, reqInfo)
|
req(reqList, reqInfo)
|
||||||
}
|
}
|
||||||
@@ -1540,25 +1617,28 @@ func (t *Terminal) Loop() {
|
|||||||
case actToggleDown:
|
case actToggleDown:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
t.vmove(-1)
|
t.vmove(-1, true)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
case actToggleUp:
|
case actToggleUp:
|
||||||
if t.multi && t.merger.Length() > 0 {
|
if t.multi && t.merger.Length() > 0 {
|
||||||
toggle()
|
toggle()
|
||||||
t.vmove(1)
|
t.vmove(1, true)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
}
|
}
|
||||||
case actDown:
|
case actDown:
|
||||||
t.vmove(-1)
|
t.vmove(-1, true)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actUp:
|
case actUp:
|
||||||
t.vmove(1)
|
t.vmove(1, true)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actAccept:
|
case actAccept:
|
||||||
req(reqClose)
|
req(reqClose)
|
||||||
case actClearScreen:
|
case actClearScreen:
|
||||||
req(reqRedraw)
|
req(reqRedraw)
|
||||||
|
case actTop:
|
||||||
|
t.vset(0)
|
||||||
|
req(reqList)
|
||||||
case actUnixLineDiscard:
|
case actUnixLineDiscard:
|
||||||
if t.cx > 0 {
|
if t.cx > 0 {
|
||||||
t.yanked = copySlice(t.input[:t.cx])
|
t.yanked = copySlice(t.input[:t.cx])
|
||||||
@@ -1578,16 +1658,16 @@ func (t *Terminal) Loop() {
|
|||||||
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
t.input = append(append(t.input[:t.cx], t.yanked...), suffix...)
|
||||||
t.cx += len(t.yanked)
|
t.cx += len(t.yanked)
|
||||||
case actPageUp:
|
case actPageUp:
|
||||||
t.vmove(t.maxItems() - 1)
|
t.vmove(t.maxItems()-1, false)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actPageDown:
|
case actPageDown:
|
||||||
t.vmove(-(t.maxItems() - 1))
|
t.vmove(-(t.maxItems() - 1), false)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actHalfPageUp:
|
case actHalfPageUp:
|
||||||
t.vmove(t.maxItems() / 2)
|
t.vmove(t.maxItems()/2, false)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actHalfPageDown:
|
case actHalfPageDown:
|
||||||
t.vmove(-(t.maxItems() / 2))
|
t.vmove(-(t.maxItems() / 2), false)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
case actJump:
|
case actJump:
|
||||||
t.jumping = jumpEnabled
|
t.jumping = jumpEnabled
|
||||||
@@ -1618,15 +1698,24 @@ func (t *Terminal) Loop() {
|
|||||||
case actPreviousHistory:
|
case actPreviousHistory:
|
||||||
if t.history != nil {
|
if t.history != nil {
|
||||||
t.history.override(string(t.input))
|
t.history.override(string(t.input))
|
||||||
t.input = []rune(t.history.previous())
|
t.input = trimQuery(t.history.previous())
|
||||||
t.cx = len(t.input)
|
t.cx = len(t.input)
|
||||||
}
|
}
|
||||||
case actNextHistory:
|
case actNextHistory:
|
||||||
if t.history != nil {
|
if t.history != nil {
|
||||||
t.history.override(string(t.input))
|
t.history.override(string(t.input))
|
||||||
t.input = []rune(t.history.next())
|
t.input = trimQuery(t.history.next())
|
||||||
t.cx = len(t.input)
|
t.cx = len(t.input)
|
||||||
}
|
}
|
||||||
|
case actSigStop:
|
||||||
|
p, err := os.FindProcess(os.Getpid())
|
||||||
|
if err == nil {
|
||||||
|
t.tui.Clear()
|
||||||
|
t.tui.Pause(t.fullscreen)
|
||||||
|
notifyStop(p)
|
||||||
|
t.mutex.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
case actMouse:
|
case actMouse:
|
||||||
me := event.MouseEvent
|
me := event.MouseEvent
|
||||||
mx, my := me.X, me.Y
|
mx, my := me.X, me.Y
|
||||||
@@ -1636,7 +1725,7 @@ func (t *Terminal) Loop() {
|
|||||||
if t.multi && me.Mod {
|
if t.multi && me.Mod {
|
||||||
toggle()
|
toggle()
|
||||||
}
|
}
|
||||||
t.vmove(me.S)
|
t.vmove(me.S, true)
|
||||||
req(reqList)
|
req(reqList)
|
||||||
} else if t.hasPreviewWindow() && t.pwindow.Enclose(my, mx) {
|
} else if t.hasPreviewWindow() && t.pwindow.Enclose(my, mx) {
|
||||||
scrollPreview(-me.S)
|
scrollPreview(-me.S)
|
||||||
@@ -1644,7 +1733,7 @@ func (t *Terminal) Loop() {
|
|||||||
} else if t.window.Enclose(my, mx) {
|
} else if t.window.Enclose(my, mx) {
|
||||||
mx -= t.window.Left()
|
mx -= t.window.Left()
|
||||||
my -= t.window.Top()
|
my -= t.window.Top()
|
||||||
mx = util.Constrain(mx-t.displayWidth([]rune(t.prompt)), 0, len(t.input))
|
mx = util.Constrain(mx-t.promptLen, 0, len(t.input))
|
||||||
if !t.reverse {
|
if !t.reverse {
|
||||||
my = t.window.Height() - my - 1
|
my = t.window.Height() - my - 1
|
||||||
}
|
}
|
||||||
@@ -1688,12 +1777,13 @@ func (t *Terminal) Loop() {
|
|||||||
if !doActions(actions, mapkey) {
|
if !doActions(actions, mapkey) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Truncate the query if it's too long
|
t.truncateQuery()
|
||||||
if len(t.input) > maxPatternLength {
|
|
||||||
t.input = t.input[:maxPatternLength]
|
|
||||||
t.cx = util.Constrain(t.cx, 0, maxPatternLength)
|
|
||||||
}
|
|
||||||
changed = string(previousInput) != string(t.input)
|
changed = string(previousInput) != string(t.input)
|
||||||
|
if onChanges, prs := t.keymap[tui.Change]; changed && prs {
|
||||||
|
if !doActions(onChanges, tui.Change) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
if mapkey == tui.Rune {
|
if mapkey == tui.Rune {
|
||||||
if idx := strings.IndexRune(t.jumpLabels, event.Char); idx >= 0 && idx < t.maxItems() && idx < t.merger.Length() {
|
if idx := strings.IndexRune(t.jumpLabels, event.Char); idx >= 0 && idx < t.maxItems() && idx < t.merger.Length() {
|
||||||
@@ -1732,12 +1822,12 @@ func (t *Terminal) constrain() {
|
|||||||
t.offset = util.Max(0, t.offset)
|
t.offset = util.Max(0, t.offset)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Terminal) vmove(o int) {
|
func (t *Terminal) vmove(o int, allowCycle bool) {
|
||||||
if t.reverse {
|
if t.reverse {
|
||||||
o *= -1
|
o *= -1
|
||||||
}
|
}
|
||||||
dest := t.cy + o
|
dest := t.cy + o
|
||||||
if t.cycle {
|
if t.cycle && allowCycle {
|
||||||
max := t.merger.Length() - 1
|
max := t.merger.Length() - 1
|
||||||
if dest > max {
|
if dest > max {
|
||||||
if t.cy == max {
|
if t.cy == max {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
func newItem(str string) *Item {
|
func newItem(str string) *Item {
|
||||||
bytes := []byte(str)
|
bytes := []byte(str)
|
||||||
trimmed, _, _ := extractColor(str, nil, nil)
|
trimmed, _, _ := extractColor(str, nil, nil)
|
||||||
return &Item{origText: &bytes, text: util.RunesToChars([]rune(trimmed))}
|
return &Item{origText: &bytes, text: util.ToChars([]byte(trimmed))}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReplacePlaceholder(t *testing.T) {
|
func TestReplacePlaceholder(t *testing.T) {
|
||||||
|
|||||||
@@ -11,3 +11,11 @@ import (
|
|||||||
func notifyOnResize(resizeChan chan<- os.Signal) {
|
func notifyOnResize(resizeChan chan<- os.Signal) {
|
||||||
signal.Notify(resizeChan, syscall.SIGWINCH)
|
signal.Notify(resizeChan, syscall.SIGWINCH)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func notifyStop(p *os.Process) {
|
||||||
|
p.Signal(syscall.SIGSTOP)
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyOnCont(resizeChan chan<- os.Signal) {
|
||||||
|
signal.Notify(resizeChan, syscall.SIGCONT)
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,3 +9,11 @@ import (
|
|||||||
func notifyOnResize(resizeChan chan<- os.Signal) {
|
func notifyOnResize(resizeChan chan<- os.Signal) {
|
||||||
// TODO
|
// TODO
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func notifyStop(p *os.Process) {
|
||||||
|
// NOOP
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyOnCont(resizeChan chan<- os.Signal) {
|
||||||
|
// NOOP
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package fzf
|
package fzf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -20,7 +21,6 @@ type Range struct {
|
|||||||
type Token struct {
|
type Token struct {
|
||||||
text *util.Chars
|
text *util.Chars
|
||||||
prefixLength int32
|
prefixLength int32
|
||||||
trimLength int32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delimiter for tokenizing the input
|
// Delimiter for tokenizing the input
|
||||||
@@ -75,14 +75,14 @@ func ParseRange(str *string) (Range, bool) {
|
|||||||
return newRange(n, n), true
|
return newRange(n, n), true
|
||||||
}
|
}
|
||||||
|
|
||||||
func withPrefixLengths(tokens []util.Chars, begin int) []Token {
|
func withPrefixLengths(tokens []string, begin int) []Token {
|
||||||
ret := make([]Token, len(tokens))
|
ret := make([]Token, len(tokens))
|
||||||
|
|
||||||
prefixLength := begin
|
prefixLength := begin
|
||||||
for idx, token := range tokens {
|
for idx := range tokens {
|
||||||
// NOTE: &tokens[idx] instead of &tokens
|
chars := util.ToChars([]byte(tokens[idx]))
|
||||||
ret[idx] = Token{&tokens[idx], int32(prefixLength), int32(token.TrimLength())}
|
ret[idx] = Token{&chars, int32(prefixLength)}
|
||||||
prefixLength += token.Length()
|
prefixLength += chars.Length()
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
@@ -93,16 +93,15 @@ const (
|
|||||||
awkWhite
|
awkWhite
|
||||||
)
|
)
|
||||||
|
|
||||||
func awkTokenizer(input util.Chars) ([]util.Chars, int) {
|
func awkTokenizer(input string) ([]string, int) {
|
||||||
// 9, 32
|
// 9, 32
|
||||||
ret := []util.Chars{}
|
ret := []string{}
|
||||||
prefixLength := 0
|
prefixLength := 0
|
||||||
state := awkNil
|
state := awkNil
|
||||||
numChars := input.Length()
|
|
||||||
begin := 0
|
begin := 0
|
||||||
end := 0
|
end := 0
|
||||||
for idx := 0; idx < numChars; idx++ {
|
for idx := 0; idx < len(input); idx++ {
|
||||||
r := input.Get(idx)
|
r := input[idx]
|
||||||
white := r == 9 || r == 32
|
white := r == 9 || r == 32
|
||||||
switch state {
|
switch state {
|
||||||
case awkNil:
|
case awkNil:
|
||||||
@@ -120,19 +119,19 @@ func awkTokenizer(input util.Chars) ([]util.Chars, int) {
|
|||||||
if white {
|
if white {
|
||||||
end = idx + 1
|
end = idx + 1
|
||||||
} else {
|
} else {
|
||||||
ret = append(ret, input.Slice(begin, end))
|
ret = append(ret, input[begin:end])
|
||||||
state, begin, end = awkBlack, idx, idx+1
|
state, begin, end = awkBlack, idx, idx+1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if begin < end {
|
if begin < end {
|
||||||
ret = append(ret, input.Slice(begin, end))
|
ret = append(ret, input[begin:end])
|
||||||
}
|
}
|
||||||
return ret, prefixLength
|
return ret, prefixLength
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tokenize tokenizes the given string with the delimiter
|
// Tokenize tokenizes the given string with the delimiter
|
||||||
func Tokenize(text util.Chars, delimiter Delimiter) []Token {
|
func Tokenize(text string, delimiter Delimiter) []Token {
|
||||||
if delimiter.str == nil && delimiter.regex == nil {
|
if delimiter.str == nil && delimiter.regex == nil {
|
||||||
// AWK-style (\S+\s*)
|
// AWK-style (\S+\s*)
|
||||||
tokens, prefixLength := awkTokenizer(text)
|
tokens, prefixLength := awkTokenizer(text)
|
||||||
@@ -140,36 +139,31 @@ func Tokenize(text util.Chars, delimiter Delimiter) []Token {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if delimiter.str != nil {
|
if delimiter.str != nil {
|
||||||
return withPrefixLengths(text.Split(*delimiter.str), 0)
|
return withPrefixLengths(strings.SplitAfter(text, *delimiter.str), 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME performance
|
// FIXME performance
|
||||||
var tokens []string
|
var tokens []string
|
||||||
if delimiter.regex != nil {
|
if delimiter.regex != nil {
|
||||||
str := text.ToString()
|
for len(text) > 0 {
|
||||||
for len(str) > 0 {
|
loc := delimiter.regex.FindStringIndex(text)
|
||||||
loc := delimiter.regex.FindStringIndex(str)
|
if len(loc) < 2 {
|
||||||
if loc == nil {
|
loc = []int{0, len(text)}
|
||||||
loc = []int{0, len(str)}
|
|
||||||
}
|
}
|
||||||
last := util.Max(loc[1], 1)
|
last := util.Max(loc[1], 1)
|
||||||
tokens = append(tokens, str[:last])
|
tokens = append(tokens, text[:last])
|
||||||
str = str[last:]
|
text = text[last:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
asRunes := make([]util.Chars, len(tokens))
|
return withPrefixLengths(tokens, 0)
|
||||||
for i, token := range tokens {
|
|
||||||
asRunes[i] = util.RunesToChars([]rune(token))
|
|
||||||
}
|
|
||||||
return withPrefixLengths(asRunes, 0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinTokens(tokens []Token) []rune {
|
func joinTokens(tokens []Token) string {
|
||||||
ret := []rune{}
|
var output bytes.Buffer
|
||||||
for _, token := range tokens {
|
for _, token := range tokens {
|
||||||
ret = append(ret, token.text.ToRunes()...)
|
output.WriteString(token.text.ToString())
|
||||||
}
|
}
|
||||||
return ret
|
return output.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Transform is used to transform the input when --with-nth option is given
|
// Transform is used to transform the input when --with-nth option is given
|
||||||
@@ -182,7 +176,7 @@ func Transform(tokens []Token, withNth []Range) []Token {
|
|||||||
if r.begin == r.end {
|
if r.begin == r.end {
|
||||||
idx := r.begin
|
idx := r.begin
|
||||||
if idx == rangeEllipsis {
|
if idx == rangeEllipsis {
|
||||||
chars := util.RunesToChars(joinTokens(tokens))
|
chars := util.ToChars([]byte(joinTokens(tokens)))
|
||||||
parts = append(parts, &chars)
|
parts = append(parts, &chars)
|
||||||
} else {
|
} else {
|
||||||
if idx < 0 {
|
if idx < 0 {
|
||||||
@@ -225,15 +219,15 @@ func Transform(tokens []Token, withNth []Range) []Token {
|
|||||||
var merged util.Chars
|
var merged util.Chars
|
||||||
switch len(parts) {
|
switch len(parts) {
|
||||||
case 0:
|
case 0:
|
||||||
merged = util.RunesToChars([]rune{})
|
merged = util.ToChars([]byte{})
|
||||||
case 1:
|
case 1:
|
||||||
merged = *parts[0]
|
merged = *parts[0]
|
||||||
default:
|
default:
|
||||||
runes := []rune{}
|
var output bytes.Buffer
|
||||||
for _, part := range parts {
|
for _, part := range parts {
|
||||||
runes = append(runes, part.ToRunes()...)
|
output.WriteString(part.ToString())
|
||||||
}
|
}
|
||||||
merged = util.RunesToChars(runes)
|
merged = util.ToChars([]byte(output.String()))
|
||||||
}
|
}
|
||||||
|
|
||||||
var prefixLength int32
|
var prefixLength int32
|
||||||
@@ -242,7 +236,7 @@ func Transform(tokens []Token, withNth []Range) []Token {
|
|||||||
} else {
|
} else {
|
||||||
prefixLength = 0
|
prefixLength = 0
|
||||||
}
|
}
|
||||||
transTokens[idx] = Token{&merged, prefixLength, int32(merged.TrimLength())}
|
transTokens[idx] = Token{&merged, prefixLength}
|
||||||
}
|
}
|
||||||
return transTokens
|
return transTokens
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package fzf
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/junegunn/fzf/src/util"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestParseRange(t *testing.T) {
|
func TestParseRange(t *testing.T) {
|
||||||
@@ -47,23 +45,23 @@ func TestParseRange(t *testing.T) {
|
|||||||
func TestTokenize(t *testing.T) {
|
func TestTokenize(t *testing.T) {
|
||||||
// AWK-style
|
// AWK-style
|
||||||
input := " abc: def: ghi "
|
input := " abc: def: ghi "
|
||||||
tokens := Tokenize(util.RunesToChars([]rune(input)), Delimiter{})
|
tokens := Tokenize(input, Delimiter{})
|
||||||
if tokens[0].text.ToString() != "abc: " || tokens[0].prefixLength != 2 || tokens[0].trimLength != 4 {
|
if tokens[0].text.ToString() != "abc: " || tokens[0].prefixLength != 2 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With delimiter
|
// With delimiter
|
||||||
tokens = Tokenize(util.RunesToChars([]rune(input)), delimiterRegexp(":"))
|
tokens = Tokenize(input, delimiterRegexp(":"))
|
||||||
if tokens[0].text.ToString() != " abc:" || tokens[0].prefixLength != 0 || tokens[0].trimLength != 4 {
|
if tokens[0].text.ToString() != " abc:" || tokens[0].prefixLength != 0 {
|
||||||
t.Errorf("%s", tokens)
|
t.Error(tokens[0].text.ToString(), tokens[0].prefixLength)
|
||||||
}
|
}
|
||||||
|
|
||||||
// With delimiter regex
|
// With delimiter regex
|
||||||
tokens = Tokenize(util.RunesToChars([]rune(input)), delimiterRegexp("\\s+"))
|
tokens = Tokenize(input, delimiterRegexp("\\s+"))
|
||||||
if tokens[0].text.ToString() != " " || tokens[0].prefixLength != 0 || tokens[0].trimLength != 0 ||
|
if tokens[0].text.ToString() != " " || tokens[0].prefixLength != 0 ||
|
||||||
tokens[1].text.ToString() != "abc: " || tokens[1].prefixLength != 2 || tokens[1].trimLength != 4 ||
|
tokens[1].text.ToString() != "abc: " || tokens[1].prefixLength != 2 ||
|
||||||
tokens[2].text.ToString() != "def: " || tokens[2].prefixLength != 8 || tokens[2].trimLength != 4 ||
|
tokens[2].text.ToString() != "def: " || tokens[2].prefixLength != 8 ||
|
||||||
tokens[3].text.ToString() != "ghi " || tokens[3].prefixLength != 14 || tokens[3].trimLength != 3 {
|
tokens[3].text.ToString() != "ghi " || tokens[3].prefixLength != 14 {
|
||||||
t.Errorf("%s", tokens)
|
t.Errorf("%s", tokens)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,7 +69,7 @@ func TestTokenize(t *testing.T) {
|
|||||||
func TestTransform(t *testing.T) {
|
func TestTransform(t *testing.T) {
|
||||||
input := " abc: def: ghi: jkl"
|
input := " abc: def: ghi: jkl"
|
||||||
{
|
{
|
||||||
tokens := Tokenize(util.RunesToChars([]rune(input)), Delimiter{})
|
tokens := Tokenize(input, Delimiter{})
|
||||||
{
|
{
|
||||||
ranges := splitNth("1,2,3")
|
ranges := splitNth("1,2,3")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
@@ -93,7 +91,7 @@ func TestTransform(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
tokens := Tokenize(util.RunesToChars([]rune(input)), delimiterRegexp(":"))
|
tokens := Tokenize(input, delimiterRegexp(":"))
|
||||||
{
|
{
|
||||||
ranges := splitNth("1..2,3,2..,1")
|
ranges := splitNth("1..2,3,2..,1")
|
||||||
tx := Transform(tokens, ranges)
|
tx := Transform(tokens, ranges)
|
||||||
|
|||||||
@@ -25,13 +25,13 @@ const (
|
|||||||
Reverse = Attr(1 << 6)
|
Reverse = Attr(1 << 6)
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Init() {}
|
func (r *FullscreenRenderer) Init() {}
|
||||||
func (r *FullscreenRenderer) Pause() {}
|
func (r *FullscreenRenderer) Pause(bool) {}
|
||||||
func (r *FullscreenRenderer) Clear() {}
|
func (r *FullscreenRenderer) Resume(bool) {}
|
||||||
func (r *FullscreenRenderer) Refresh() {}
|
func (r *FullscreenRenderer) Clear() {}
|
||||||
func (r *FullscreenRenderer) Close() {}
|
func (r *FullscreenRenderer) Refresh() {}
|
||||||
|
func (r *FullscreenRenderer) Close() {}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Resume() bool { return false }
|
|
||||||
func (r *FullscreenRenderer) DoesAutoWrap() bool { return false }
|
func (r *FullscreenRenderer) DoesAutoWrap() bool { return false }
|
||||||
func (r *FullscreenRenderer) IsOptimized() bool { return false }
|
func (r *FullscreenRenderer) IsOptimized() bool { return false }
|
||||||
func (r *FullscreenRenderer) GetChar() Event { return Event{} }
|
func (r *FullscreenRenderer) GetChar() Event { return Event{} }
|
||||||
|
|||||||
137
src/tui/light.go
137
src/tui/light.go
@@ -32,7 +32,8 @@ var offsetRegexp *regexp.Regexp = regexp.MustCompile("\x1b\\[([0-9]+);([0-9]+)R"
|
|||||||
func openTtyIn() *os.File {
|
func openTtyIn() *os.File {
|
||||||
in, err := os.OpenFile(consoleDevice, syscall.O_RDONLY, 0)
|
in, err := os.OpenFile(consoleDevice, syscall.O_RDONLY, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("Failed to open " + consoleDevice)
|
fmt.Fprintln(os.Stderr, "Failed to open "+consoleDevice)
|
||||||
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
return in
|
return in
|
||||||
}
|
}
|
||||||
@@ -74,6 +75,7 @@ type LightRenderer struct {
|
|||||||
theme *ColorTheme
|
theme *ColorTheme
|
||||||
mouse bool
|
mouse bool
|
||||||
forceBlack bool
|
forceBlack bool
|
||||||
|
clearOnExit bool
|
||||||
prevDownTime time.Time
|
prevDownTime time.Time
|
||||||
clickY []int
|
clickY []int
|
||||||
ttyin *os.File
|
ttyin *os.File
|
||||||
@@ -106,15 +108,16 @@ type LightWindow struct {
|
|||||||
bg Color
|
bg Color
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLightRenderer(theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, maxHeightFunc func(int) int) Renderer {
|
func NewLightRenderer(theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) Renderer {
|
||||||
r := LightRenderer{
|
r := LightRenderer{
|
||||||
theme: theme,
|
theme: theme,
|
||||||
forceBlack: forceBlack,
|
forceBlack: forceBlack,
|
||||||
mouse: mouse,
|
mouse: mouse,
|
||||||
|
clearOnExit: clearOnExit,
|
||||||
ttyin: openTtyIn(),
|
ttyin: openTtyIn(),
|
||||||
yoffset: 0,
|
yoffset: 0,
|
||||||
tabstop: tabstop,
|
tabstop: tabstop,
|
||||||
fullscreen: false,
|
fullscreen: fullscreen,
|
||||||
upOneLine: false,
|
upOneLine: false,
|
||||||
maxHeightFunc: maxHeightFunc}
|
maxHeightFunc: maxHeightFunc}
|
||||||
return &r
|
return &r
|
||||||
@@ -174,20 +177,24 @@ func (r *LightRenderer) Init() {
|
|||||||
}
|
}
|
||||||
r.origState = origState
|
r.origState = origState
|
||||||
terminal.MakeRaw(fd)
|
terminal.MakeRaw(fd)
|
||||||
terminalHeight, capHeight := r.updateTerminalSize()
|
r.updateTerminalSize()
|
||||||
if capHeight == terminalHeight {
|
|
||||||
r.fullscreen = true
|
|
||||||
r.height = terminalHeight
|
|
||||||
}
|
|
||||||
initTheme(r.theme, r.defaultTheme(), r.forceBlack)
|
initTheme(r.theme, r.defaultTheme(), r.forceBlack)
|
||||||
|
|
||||||
if r.fullscreen {
|
if r.fullscreen {
|
||||||
r.smcup()
|
r.smcup()
|
||||||
} else {
|
} else {
|
||||||
r.csi("J")
|
// We assume that --no-clear is used for repetitive relaunching of fzf.
|
||||||
|
// So we do not clear the lower bottom of the screen.
|
||||||
|
if r.clearOnExit {
|
||||||
|
r.csi("J")
|
||||||
|
}
|
||||||
y, x := r.findOffset()
|
y, x := r.findOffset()
|
||||||
r.mouse = r.mouse && y >= 0
|
r.mouse = r.mouse && y >= 0
|
||||||
if x > 0 {
|
// When --no-clear is used for repetitive relaunching, there is a small
|
||||||
|
// time frame between fzf processes where the user keystrokes are not
|
||||||
|
// captured by either of fzf process which can cause x offset to be
|
||||||
|
// increased and we're left with unwanted extra new line.
|
||||||
|
if x > 0 && r.clearOnExit {
|
||||||
r.upOneLine = true
|
r.upOneLine = true
|
||||||
r.makeSpace()
|
r.makeSpace()
|
||||||
}
|
}
|
||||||
@@ -202,7 +209,9 @@ func (r *LightRenderer) Init() {
|
|||||||
r.csi(fmt.Sprintf("%dA", r.MaxY()-1))
|
r.csi(fmt.Sprintf("%dA", r.MaxY()-1))
|
||||||
r.csi("G")
|
r.csi("G")
|
||||||
r.csi("K")
|
r.csi("K")
|
||||||
// r.csi("s")
|
if !r.clearOnExit && !r.fullscreen {
|
||||||
|
r.csi("s")
|
||||||
|
}
|
||||||
if !r.fullscreen && r.mouse {
|
if !r.fullscreen && r.mouse {
|
||||||
r.yoffset, _ = r.findOffset()
|
r.yoffset, _ = r.findOffset()
|
||||||
}
|
}
|
||||||
@@ -240,26 +249,22 @@ func getEnv(name string, defaultValue int) int {
|
|||||||
return atoi(env, defaultValue)
|
return atoi(env, defaultValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) updateTerminalSize() (int, int) {
|
func (r *LightRenderer) updateTerminalSize() {
|
||||||
width, height, err := terminal.GetSize(r.fd())
|
width, height, err := terminal.GetSize(r.fd())
|
||||||
if err == nil {
|
if err == nil {
|
||||||
r.width = width
|
r.width = width
|
||||||
if r.fullscreen {
|
r.height = r.maxHeightFunc(height)
|
||||||
r.height = height
|
|
||||||
} else {
|
|
||||||
r.height = r.maxHeightFunc(height)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
r.width = getEnv("COLUMNS", defaultWidth)
|
r.width = getEnv("COLUMNS", defaultWidth)
|
||||||
r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))
|
r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight))
|
||||||
}
|
}
|
||||||
return height, r.height
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) getch(nonblock bool) (int, bool) {
|
func (r *LightRenderer) getch(nonblock bool) (int, bool) {
|
||||||
b := make([]byte, 1)
|
b := make([]byte, 1)
|
||||||
|
fd := r.fd()
|
||||||
util.SetNonblock(r.ttyin, nonblock)
|
util.SetNonblock(r.ttyin, nonblock)
|
||||||
_, err := r.ttyin.Read(b)
|
_, err := util.Read(fd, b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, false
|
return 0, false
|
||||||
}
|
}
|
||||||
@@ -351,9 +356,10 @@ func (r *LightRenderer) escSequence(sz *int) Event {
|
|||||||
return Event{ESC, 0, nil}
|
return Event{ESC, 0, nil}
|
||||||
}
|
}
|
||||||
*sz = 2
|
*sz = 2
|
||||||
|
if r.buffer[1] >= 1 && r.buffer[1] <= 'z'-'a'+1 {
|
||||||
|
return Event{int(CtrlAltA + r.buffer[1] - 1), 0, nil}
|
||||||
|
}
|
||||||
switch r.buffer[1] {
|
switch r.buffer[1] {
|
||||||
case 13:
|
|
||||||
return Event{AltEnter, 0, nil}
|
|
||||||
case 32:
|
case 32:
|
||||||
return Event{AltSpace, 0, nil}
|
return Event{AltSpace, 0, nil}
|
||||||
case 47:
|
case 47:
|
||||||
@@ -416,10 +422,12 @@ func (r *LightRenderer) escSequence(sz *int) Event {
|
|||||||
return Event{F12, 0, nil}
|
return Event{F12, 0, nil}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Bracketed paste mode \e[200~ / \e[201
|
// Bracketed paste mode: \e[200~ ... \e[201~
|
||||||
if r.buffer[3] == 48 && (r.buffer[4] == 48 || r.buffer[4] == 49) && r.buffer[5] == 126 {
|
if r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' {
|
||||||
*sz = 6
|
// Immediately discard the sequence from the buffer and reread input
|
||||||
return Event{Invalid, 0, nil}
|
r.buffer = r.buffer[6:]
|
||||||
|
*sz = 0
|
||||||
|
return r.GetChar()
|
||||||
}
|
}
|
||||||
return Event{Invalid, 0, nil} // INS
|
return Event{Invalid, 0, nil} // INS
|
||||||
case 51:
|
case 51:
|
||||||
@@ -528,30 +536,41 @@ func (r *LightRenderer) rmcup() {
|
|||||||
r.csi("?1049l")
|
r.csi("?1049l")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) Pause() {
|
func (r *LightRenderer) Pause(clear bool) {
|
||||||
terminal.Restore(r.fd(), r.origState)
|
terminal.Restore(r.fd(), r.origState)
|
||||||
if r.fullscreen {
|
if clear {
|
||||||
r.rmcup()
|
if r.fullscreen {
|
||||||
} else {
|
r.rmcup()
|
||||||
r.smcup()
|
} else {
|
||||||
r.csi("H")
|
r.smcup()
|
||||||
|
r.csi("H")
|
||||||
|
}
|
||||||
|
r.flush()
|
||||||
}
|
}
|
||||||
r.flush()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) Resume() bool {
|
func (r *LightRenderer) Resume(clear bool) {
|
||||||
terminal.MakeRaw(r.fd())
|
terminal.MakeRaw(r.fd())
|
||||||
if r.fullscreen {
|
if clear {
|
||||||
r.smcup()
|
if r.fullscreen {
|
||||||
} else {
|
r.smcup()
|
||||||
r.rmcup()
|
} else {
|
||||||
|
r.rmcup()
|
||||||
|
}
|
||||||
|
r.flush()
|
||||||
|
} else if !r.fullscreen && r.mouse {
|
||||||
|
// NOTE: Resume(false) is only called on SIGCONT after SIGSTOP.
|
||||||
|
// And It's highly likely that the offset we obtained at the beginning will
|
||||||
|
// no longer be correct, so we simply disable mouse input.
|
||||||
|
r.csi("?1000l")
|
||||||
|
r.mouse = false
|
||||||
}
|
}
|
||||||
r.flush()
|
|
||||||
// Should redraw
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) Clear() {
|
func (r *LightRenderer) Clear() {
|
||||||
|
if r.fullscreen {
|
||||||
|
r.csi("H")
|
||||||
|
}
|
||||||
// r.csi("u")
|
// r.csi("u")
|
||||||
r.origin()
|
r.origin()
|
||||||
r.csi("J")
|
r.csi("J")
|
||||||
@@ -568,14 +587,18 @@ func (r *LightRenderer) Refresh() {
|
|||||||
|
|
||||||
func (r *LightRenderer) Close() {
|
func (r *LightRenderer) Close() {
|
||||||
// r.csi("u")
|
// r.csi("u")
|
||||||
if r.fullscreen {
|
if r.clearOnExit {
|
||||||
r.rmcup()
|
if r.fullscreen {
|
||||||
} else {
|
r.rmcup()
|
||||||
r.origin()
|
} else {
|
||||||
if r.upOneLine {
|
r.origin()
|
||||||
r.csi("A")
|
if r.upOneLine {
|
||||||
|
r.csi("A")
|
||||||
|
}
|
||||||
|
r.csi("J")
|
||||||
}
|
}
|
||||||
r.csi("J")
|
} else if !r.fullscreen {
|
||||||
|
r.csi("u")
|
||||||
}
|
}
|
||||||
if r.mouse {
|
if r.mouse {
|
||||||
r.csi("?1000l")
|
r.csi("?1000l")
|
||||||
@@ -593,7 +616,7 @@ func (r *LightRenderer) MaxY() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) DoesAutoWrap() bool {
|
func (r *LightRenderer) DoesAutoWrap() bool {
|
||||||
return true
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *LightRenderer) IsOptimized() bool {
|
func (r *LightRenderer) IsOptimized() bool {
|
||||||
@@ -685,6 +708,10 @@ func (w *LightWindow) X() int {
|
|||||||
return w.posx
|
return w.posx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *LightWindow) Y() int {
|
||||||
|
return w.posy
|
||||||
|
}
|
||||||
|
|
||||||
func (w *LightWindow) Enclose(y int, x int) bool {
|
func (w *LightWindow) Enclose(y int, x int) bool {
|
||||||
return x >= w.left && x < (w.left+w.width) &&
|
return x >= w.left && x < (w.left+w.width) &&
|
||||||
y >= w.top && y < (w.top+w.height)
|
y >= w.top && y < (w.top+w.height)
|
||||||
@@ -819,17 +846,20 @@ func (w *LightWindow) fill(str string, onMove func()) FillReturn {
|
|||||||
for j, wl := range lines {
|
for j, wl := range lines {
|
||||||
if w.posx >= w.Width()-1 && wl.displayWidth == 0 {
|
if w.posx >= w.Width()-1 && wl.displayWidth == 0 {
|
||||||
if w.posy < w.height-1 {
|
if w.posy < w.height-1 {
|
||||||
w.MoveAndClear(w.posy+1, 0)
|
w.Move(w.posy+1, 0)
|
||||||
}
|
}
|
||||||
return FillNextLine
|
return FillNextLine
|
||||||
}
|
}
|
||||||
w.stderrInternal(wl.text, false)
|
w.stderrInternal(wl.text, false)
|
||||||
w.posx += wl.displayWidth
|
w.posx += wl.displayWidth
|
||||||
|
|
||||||
|
// Wrap line
|
||||||
if j < len(lines)-1 || i < len(allLines)-1 {
|
if j < len(lines)-1 || i < len(allLines)-1 {
|
||||||
if w.posy+1 >= w.height {
|
if w.posy+1 >= w.height {
|
||||||
return FillSuspend
|
return FillSuspend
|
||||||
}
|
}
|
||||||
w.MoveAndClear(w.posy+1, 0)
|
w.MoveAndClear(w.posy, w.posx)
|
||||||
|
w.Move(w.posy+1, 0)
|
||||||
onMove()
|
onMove()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -844,24 +874,25 @@ func (w *LightWindow) setBg() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (w *LightWindow) Fill(text string) FillReturn {
|
func (w *LightWindow) Fill(text string) FillReturn {
|
||||||
w.MoveAndClear(w.posy, w.posx)
|
w.Move(w.posy, w.posx)
|
||||||
w.setBg()
|
w.setBg()
|
||||||
return w.fill(text, w.setBg)
|
return w.fill(text, w.setBg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *LightWindow) CFill(fg Color, bg Color, attr Attr, text string) FillReturn {
|
func (w *LightWindow) CFill(fg Color, bg Color, attr Attr, text string) FillReturn {
|
||||||
w.MoveAndClear(w.posy, w.posx)
|
w.Move(w.posy, w.posx)
|
||||||
if bg == colDefault {
|
if bg == colDefault {
|
||||||
bg = w.bg
|
bg = w.bg
|
||||||
}
|
}
|
||||||
if w.csiColor(fg, bg, attr) {
|
if w.csiColor(fg, bg, attr) {
|
||||||
return w.fill(text, func() { w.csiColor(fg, bg, attr) })
|
|
||||||
defer w.csi("m")
|
defer w.csi("m")
|
||||||
|
return w.fill(text, func() { w.csiColor(fg, bg, attr) })
|
||||||
}
|
}
|
||||||
return w.fill(text, w.setBg)
|
return w.fill(text, w.setBg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *LightWindow) FinishFill() {
|
func (w *LightWindow) FinishFill() {
|
||||||
|
w.MoveAndClear(w.posy, w.posx)
|
||||||
for y := w.posy + 1; y < w.height; y++ {
|
for y := w.posy + 1; y < w.height; y++ {
|
||||||
w.MoveAndClear(y, 0)
|
w.MoveAndClear(y, 0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -176,12 +176,11 @@ func initPairs(theme *ColorTheme) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Pause() {
|
func (r *FullscreenRenderer) Pause(bool) {
|
||||||
C.endwin()
|
C.endwin()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Resume() bool {
|
func (r *FullscreenRenderer) Resume(bool) {
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Close() {
|
func (r *FullscreenRenderer) Close() {
|
||||||
@@ -353,7 +352,7 @@ func escSequence() Event {
|
|||||||
case C.ERR:
|
case C.ERR:
|
||||||
return Event{ESC, 0, nil}
|
return Event{ESC, 0, nil}
|
||||||
case CtrlM:
|
case CtrlM:
|
||||||
return Event{AltEnter, 0, nil}
|
return Event{CtrlAltM, 0, nil}
|
||||||
case '/':
|
case '/':
|
||||||
return Event{AltSlash, 0, nil}
|
return Event{AltSlash, 0, nil}
|
||||||
case ' ':
|
case ' ':
|
||||||
|
|||||||
@@ -3,16 +3,16 @@
|
|||||||
package tui
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
// https://github.com/gdamore/tcell/pull/135
|
"github.com/gdamore/tcell"
|
||||||
"github.com/junegunn/tcell"
|
"github.com/gdamore/tcell/encoding"
|
||||||
"github.com/junegunn/tcell/encoding"
|
|
||||||
|
|
||||||
"github.com/junegunn/go-runewidth"
|
"github.com/mattn/go-runewidth"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HasFullscreenRenderer() bool {
|
func HasFullscreenRenderer() bool {
|
||||||
@@ -141,6 +141,9 @@ func (r *FullscreenRenderer) initScreen() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Init() {
|
func (r *FullscreenRenderer) Init() {
|
||||||
|
if os.Getenv("TERM") == "cygwin" {
|
||||||
|
os.Setenv("TERM", "")
|
||||||
|
}
|
||||||
encoding.Register()
|
encoding.Register()
|
||||||
|
|
||||||
r.initScreen()
|
r.initScreen()
|
||||||
@@ -161,6 +164,10 @@ func (w *TcellWindow) X() int {
|
|||||||
return w.lastX
|
return w.lastX
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (w *TcellWindow) Y() int {
|
||||||
|
return w.lastY
|
||||||
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) DoesAutoWrap() bool {
|
func (r *FullscreenRenderer) DoesAutoWrap() bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -221,61 +228,68 @@ func (r *FullscreenRenderer) GetChar() Event {
|
|||||||
// process keyboard:
|
// process keyboard:
|
||||||
case *tcell.EventKey:
|
case *tcell.EventKey:
|
||||||
alt := (ev.Modifiers() & tcell.ModAlt) > 0
|
alt := (ev.Modifiers() & tcell.ModAlt) > 0
|
||||||
|
keyfn := func(r rune) int {
|
||||||
|
if alt {
|
||||||
|
return CtrlAltA - 'a' + int(r)
|
||||||
|
}
|
||||||
|
return CtrlA - 'a' + int(r)
|
||||||
|
}
|
||||||
switch ev.Key() {
|
switch ev.Key() {
|
||||||
case tcell.KeyCtrlA:
|
case tcell.KeyCtrlA:
|
||||||
return Event{CtrlA, 0, nil}
|
return Event{keyfn('a'), 0, nil}
|
||||||
case tcell.KeyCtrlB:
|
case tcell.KeyCtrlB:
|
||||||
return Event{CtrlB, 0, nil}
|
return Event{keyfn('b'), 0, nil}
|
||||||
case tcell.KeyCtrlC:
|
case tcell.KeyCtrlC:
|
||||||
return Event{CtrlC, 0, nil}
|
return Event{keyfn('c'), 0, nil}
|
||||||
case tcell.KeyCtrlD:
|
case tcell.KeyCtrlD:
|
||||||
return Event{CtrlD, 0, nil}
|
return Event{keyfn('d'), 0, nil}
|
||||||
case tcell.KeyCtrlE:
|
case tcell.KeyCtrlE:
|
||||||
return Event{CtrlE, 0, nil}
|
return Event{keyfn('e'), 0, nil}
|
||||||
case tcell.KeyCtrlF:
|
case tcell.KeyCtrlF:
|
||||||
return Event{CtrlF, 0, nil}
|
return Event{keyfn('f'), 0, nil}
|
||||||
case tcell.KeyCtrlG:
|
case tcell.KeyCtrlG:
|
||||||
return Event{CtrlG, 0, nil}
|
return Event{keyfn('g'), 0, nil}
|
||||||
|
case tcell.KeyCtrlH:
|
||||||
|
return Event{keyfn('h'), 0, nil}
|
||||||
|
case tcell.KeyCtrlI:
|
||||||
|
return Event{keyfn('i'), 0, nil}
|
||||||
case tcell.KeyCtrlJ:
|
case tcell.KeyCtrlJ:
|
||||||
return Event{CtrlJ, 0, nil}
|
return Event{keyfn('j'), 0, nil}
|
||||||
case tcell.KeyCtrlK:
|
case tcell.KeyCtrlK:
|
||||||
return Event{CtrlK, 0, nil}
|
return Event{keyfn('k'), 0, nil}
|
||||||
case tcell.KeyCtrlL:
|
case tcell.KeyCtrlL:
|
||||||
return Event{CtrlL, 0, nil}
|
return Event{keyfn('l'), 0, nil}
|
||||||
case tcell.KeyCtrlM:
|
case tcell.KeyCtrlM:
|
||||||
if alt {
|
return Event{keyfn('m'), 0, nil}
|
||||||
return Event{AltEnter, 0, nil}
|
|
||||||
}
|
|
||||||
return Event{CtrlM, 0, nil}
|
|
||||||
case tcell.KeyCtrlN:
|
case tcell.KeyCtrlN:
|
||||||
return Event{CtrlN, 0, nil}
|
return Event{keyfn('n'), 0, nil}
|
||||||
case tcell.KeyCtrlO:
|
case tcell.KeyCtrlO:
|
||||||
return Event{CtrlO, 0, nil}
|
return Event{keyfn('o'), 0, nil}
|
||||||
case tcell.KeyCtrlP:
|
case tcell.KeyCtrlP:
|
||||||
return Event{CtrlP, 0, nil}
|
return Event{keyfn('p'), 0, nil}
|
||||||
case tcell.KeyCtrlQ:
|
case tcell.KeyCtrlQ:
|
||||||
return Event{CtrlQ, 0, nil}
|
return Event{keyfn('q'), 0, nil}
|
||||||
case tcell.KeyCtrlR:
|
case tcell.KeyCtrlR:
|
||||||
return Event{CtrlR, 0, nil}
|
return Event{keyfn('r'), 0, nil}
|
||||||
case tcell.KeyCtrlS:
|
case tcell.KeyCtrlS:
|
||||||
return Event{CtrlS, 0, nil}
|
return Event{keyfn('s'), 0, nil}
|
||||||
case tcell.KeyCtrlT:
|
case tcell.KeyCtrlT:
|
||||||
return Event{CtrlT, 0, nil}
|
return Event{keyfn('t'), 0, nil}
|
||||||
case tcell.KeyCtrlU:
|
case tcell.KeyCtrlU:
|
||||||
return Event{CtrlU, 0, nil}
|
return Event{keyfn('u'), 0, nil}
|
||||||
case tcell.KeyCtrlV:
|
case tcell.KeyCtrlV:
|
||||||
return Event{CtrlV, 0, nil}
|
return Event{keyfn('v'), 0, nil}
|
||||||
case tcell.KeyCtrlW:
|
case tcell.KeyCtrlW:
|
||||||
return Event{CtrlW, 0, nil}
|
return Event{keyfn('w'), 0, nil}
|
||||||
case tcell.KeyCtrlX:
|
case tcell.KeyCtrlX:
|
||||||
return Event{CtrlX, 0, nil}
|
return Event{keyfn('x'), 0, nil}
|
||||||
case tcell.KeyCtrlY:
|
case tcell.KeyCtrlY:
|
||||||
return Event{CtrlY, 0, nil}
|
return Event{keyfn('y'), 0, nil}
|
||||||
case tcell.KeyCtrlZ:
|
case tcell.KeyCtrlZ:
|
||||||
return Event{CtrlZ, 0, nil}
|
return Event{keyfn('z'), 0, nil}
|
||||||
case tcell.KeyCtrlSpace:
|
case tcell.KeyCtrlSpace:
|
||||||
return Event{CtrlSpace, 0, nil}
|
return Event{CtrlSpace, 0, nil}
|
||||||
case tcell.KeyBackspace, tcell.KeyBackspace2:
|
case tcell.KeyBackspace2:
|
||||||
if alt {
|
if alt {
|
||||||
return Event{AltBS, 0, nil}
|
return Event{AltBS, 0, nil}
|
||||||
}
|
}
|
||||||
@@ -301,8 +315,6 @@ func (r *FullscreenRenderer) GetChar() Event {
|
|||||||
case tcell.KeyPgDn:
|
case tcell.KeyPgDn:
|
||||||
return Event{PgDn, 0, nil}
|
return Event{PgDn, 0, nil}
|
||||||
|
|
||||||
case tcell.KeyTab:
|
|
||||||
return Event{Tab, 0, nil}
|
|
||||||
case tcell.KeyBacktab:
|
case tcell.KeyBacktab:
|
||||||
return Event{BTab, 0, nil}
|
return Event{BTab, 0, nil}
|
||||||
|
|
||||||
@@ -359,13 +371,12 @@ func (r *FullscreenRenderer) GetChar() Event {
|
|||||||
return Event{Invalid, 0, nil}
|
return Event{Invalid, 0, nil}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Pause() {
|
func (r *FullscreenRenderer) Pause(bool) {
|
||||||
_screen.Fini()
|
_screen.Fini()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Resume() bool {
|
func (r *FullscreenRenderer) Resume(bool) {
|
||||||
r.initScreen()
|
r.initScreen()
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *FullscreenRenderer) Close() {
|
func (r *FullscreenRenderer) Close() {
|
||||||
|
|||||||
@@ -75,7 +75,8 @@ const (
|
|||||||
F11
|
F11
|
||||||
F12
|
F12
|
||||||
|
|
||||||
AltEnter
|
Change
|
||||||
|
|
||||||
AltSpace
|
AltSpace
|
||||||
AltSlash
|
AltSlash
|
||||||
AltBS
|
AltBS
|
||||||
@@ -90,7 +91,9 @@ const ( // Reset iota
|
|||||||
AltD
|
AltD
|
||||||
AltE
|
AltE
|
||||||
AltF
|
AltF
|
||||||
AltZ = AltA + 'z' - 'a'
|
AltZ = AltA + 'z' - 'a'
|
||||||
|
CtrlAltA = AltZ + 1
|
||||||
|
CtrlAltM = CtrlAltA + 'm' - 'a'
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -205,8 +208,8 @@ const (
|
|||||||
|
|
||||||
type Renderer interface {
|
type Renderer interface {
|
||||||
Init()
|
Init()
|
||||||
Pause()
|
Pause(clear bool)
|
||||||
Resume() bool
|
Resume(clear bool)
|
||||||
Clear()
|
Clear()
|
||||||
RefreshWindows(windows []Window)
|
RefreshWindows(windows []Window)
|
||||||
Refresh()
|
Refresh()
|
||||||
@@ -233,6 +236,7 @@ type Window interface {
|
|||||||
Close()
|
Close()
|
||||||
|
|
||||||
X() int
|
X() int
|
||||||
|
Y() int
|
||||||
Enclose(y int, x int) bool
|
Enclose(y int, x int) bool
|
||||||
|
|
||||||
Move(y int, x int)
|
Move(y int, x int)
|
||||||
|
|||||||
@@ -3,63 +3,103 @@ package util
|
|||||||
import (
|
import (
|
||||||
"unicode"
|
"unicode"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
overflow64 uint64 = 0x8080808080808080
|
||||||
|
overflow32 uint32 = 0x80808080
|
||||||
)
|
)
|
||||||
|
|
||||||
type Chars struct {
|
type Chars struct {
|
||||||
runes []rune
|
slice []byte // or []rune
|
||||||
bytes []byte
|
inBytes bool
|
||||||
|
trimLengthKnown bool
|
||||||
|
trimLength uint16
|
||||||
|
|
||||||
|
// XXX Piggybacking item index here is a horrible idea. But I'm trying to
|
||||||
|
// minimize the memory footprint by not wasting padded spaces.
|
||||||
|
Index int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAscii(bytes []byte) (bool, int) {
|
||||||
|
i := 0
|
||||||
|
for ; i <= len(bytes)-8; i += 8 {
|
||||||
|
if (overflow64 & *(*uint64)(unsafe.Pointer(&bytes[i]))) > 0 {
|
||||||
|
return false, i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ; i <= len(bytes)-4; i += 4 {
|
||||||
|
if (overflow32 & *(*uint32)(unsafe.Pointer(&bytes[i]))) > 0 {
|
||||||
|
return false, i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ; i < len(bytes); i++ {
|
||||||
|
if bytes[i] >= utf8.RuneSelf {
|
||||||
|
return false, i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// ToChars converts byte array into rune array
|
// ToChars converts byte array into rune array
|
||||||
func ToChars(bytea []byte) Chars {
|
func ToChars(bytes []byte) Chars {
|
||||||
var runes []rune
|
inBytes, bytesUntil := checkAscii(bytes)
|
||||||
ascii := true
|
if inBytes {
|
||||||
numBytes := len(bytea)
|
return Chars{slice: bytes, inBytes: inBytes}
|
||||||
for i := 0; i < numBytes; {
|
|
||||||
if bytea[i] < utf8.RuneSelf {
|
|
||||||
if !ascii {
|
|
||||||
runes = append(runes, rune(bytea[i]))
|
|
||||||
}
|
|
||||||
i++
|
|
||||||
} else {
|
|
||||||
if ascii {
|
|
||||||
ascii = false
|
|
||||||
runes = make([]rune, i, numBytes)
|
|
||||||
for j := 0; j < i; j++ {
|
|
||||||
runes[j] = rune(bytea[j])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
r, sz := utf8.DecodeRune(bytea[i:])
|
|
||||||
i += sz
|
|
||||||
runes = append(runes, r)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if ascii {
|
|
||||||
return Chars{bytes: bytea}
|
runes := make([]rune, bytesUntil, len(bytes))
|
||||||
|
for i := 0; i < bytesUntil; i++ {
|
||||||
|
runes[i] = rune(bytes[i])
|
||||||
}
|
}
|
||||||
return Chars{runes: runes}
|
for i := bytesUntil; i < len(bytes); {
|
||||||
|
r, sz := utf8.DecodeRune(bytes[i:])
|
||||||
|
i += sz
|
||||||
|
runes = append(runes, r)
|
||||||
|
}
|
||||||
|
return RunesToChars(runes)
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunesToChars(runes []rune) Chars {
|
func RunesToChars(runes []rune) Chars {
|
||||||
return Chars{runes: runes}
|
return Chars{slice: *(*[]byte)(unsafe.Pointer(&runes)), inBytes: false}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (chars *Chars) IsBytes() bool {
|
||||||
|
return chars.inBytes
|
||||||
|
}
|
||||||
|
|
||||||
|
func (chars *Chars) Bytes() []byte {
|
||||||
|
return chars.slice
|
||||||
|
}
|
||||||
|
|
||||||
|
func (chars *Chars) optionalRunes() []rune {
|
||||||
|
if chars.inBytes {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return *(*[]rune)(unsafe.Pointer(&chars.slice))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) Get(i int) rune {
|
func (chars *Chars) Get(i int) rune {
|
||||||
if chars.runes != nil {
|
if runes := chars.optionalRunes(); runes != nil {
|
||||||
return chars.runes[i]
|
return runes[i]
|
||||||
}
|
}
|
||||||
return rune(chars.bytes[i])
|
return rune(chars.slice[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) Length() int {
|
func (chars *Chars) Length() int {
|
||||||
if chars.runes != nil {
|
if runes := chars.optionalRunes(); runes != nil {
|
||||||
return len(chars.runes)
|
return len(runes)
|
||||||
}
|
}
|
||||||
return len(chars.bytes)
|
return len(chars.slice)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrimLength returns the length after trimming leading and trailing whitespaces
|
// TrimLength returns the length after trimming leading and trailing whitespaces
|
||||||
func (chars *Chars) TrimLength() int {
|
func (chars *Chars) TrimLength() uint16 {
|
||||||
|
if chars.trimLengthKnown {
|
||||||
|
return chars.trimLength
|
||||||
|
}
|
||||||
|
chars.trimLengthKnown = true
|
||||||
var i int
|
var i int
|
||||||
len := chars.Length()
|
len := chars.Length()
|
||||||
for i = len - 1; i >= 0; i-- {
|
for i = len - 1; i >= 0; i-- {
|
||||||
@@ -80,7 +120,8 @@ func (chars *Chars) TrimLength() int {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return i - j + 1
|
chars.trimLength = AsUint16(i - j + 1)
|
||||||
|
return chars.trimLength
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) TrailingWhitespaces() int {
|
func (chars *Chars) TrailingWhitespaces() int {
|
||||||
@@ -96,62 +137,31 @@ func (chars *Chars) TrailingWhitespaces() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) ToString() string {
|
func (chars *Chars) ToString() string {
|
||||||
if chars.runes != nil {
|
if runes := chars.optionalRunes(); runes != nil {
|
||||||
return string(chars.runes)
|
return string(runes)
|
||||||
}
|
}
|
||||||
return string(chars.bytes)
|
return string(chars.slice)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) ToRunes() []rune {
|
func (chars *Chars) ToRunes() []rune {
|
||||||
if chars.runes != nil {
|
if runes := chars.optionalRunes(); runes != nil {
|
||||||
return chars.runes
|
return runes
|
||||||
}
|
}
|
||||||
runes := make([]rune, len(chars.bytes))
|
bytes := chars.slice
|
||||||
for idx, b := range chars.bytes {
|
runes := make([]rune, len(bytes))
|
||||||
|
for idx, b := range bytes {
|
||||||
runes[idx] = rune(b)
|
runes[idx] = rune(b)
|
||||||
}
|
}
|
||||||
return runes
|
return runes
|
||||||
}
|
}
|
||||||
|
|
||||||
func (chars *Chars) Slice(b int, e int) Chars {
|
func (chars *Chars) CopyRunes(dest []rune) {
|
||||||
if chars.runes != nil {
|
if runes := chars.optionalRunes(); runes != nil {
|
||||||
return Chars{runes: chars.runes[b:e]}
|
copy(dest, runes)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return Chars{bytes: chars.bytes[b:e]}
|
for idx, b := range chars.slice[:len(dest)] {
|
||||||
}
|
dest[idx] = rune(b)
|
||||||
|
}
|
||||||
func (chars *Chars) Split(delimiter string) []Chars {
|
return
|
||||||
delim := []rune(delimiter)
|
|
||||||
numChars := chars.Length()
|
|
||||||
numDelim := len(delim)
|
|
||||||
begin := 0
|
|
||||||
ret := make([]Chars, 0, 1)
|
|
||||||
|
|
||||||
for index := 0; index < numChars; {
|
|
||||||
if index+numDelim <= numChars {
|
|
||||||
match := true
|
|
||||||
for off, d := range delim {
|
|
||||||
if chars.Get(index+off) != d {
|
|
||||||
match = false
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Found the delimiter
|
|
||||||
if match {
|
|
||||||
incr := Max(numDelim, 1)
|
|
||||||
ret = append(ret, chars.Slice(begin, index+incr))
|
|
||||||
index += incr
|
|
||||||
begin = index
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Impossible to find the delimiter in the remaining substring
|
|
||||||
break
|
|
||||||
}
|
|
||||||
index++
|
|
||||||
}
|
|
||||||
if begin < numChars || len(ret) == 0 {
|
|
||||||
ret = append(ret, chars.Slice(begin, numChars))
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,27 +2,16 @@ package util
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func TestToCharsNil(t *testing.T) {
|
|
||||||
bs := Chars{bytes: []byte{}}
|
|
||||||
if bs.bytes == nil || bs.runes != nil {
|
|
||||||
t.Error()
|
|
||||||
}
|
|
||||||
rs := RunesToChars([]rune{})
|
|
||||||
if rs.bytes != nil || rs.runes == nil {
|
|
||||||
t.Error()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestToCharsAscii(t *testing.T) {
|
func TestToCharsAscii(t *testing.T) {
|
||||||
chars := ToChars([]byte("foobar"))
|
chars := ToChars([]byte("foobar"))
|
||||||
if chars.ToString() != "foobar" || chars.runes != nil {
|
if !chars.inBytes || chars.ToString() != "foobar" || !chars.inBytes {
|
||||||
t.Error()
|
t.Error()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCharsLength(t *testing.T) {
|
func TestCharsLength(t *testing.T) {
|
||||||
chars := ToChars([]byte("\tabc한글 "))
|
chars := ToChars([]byte("\tabc한글 "))
|
||||||
if chars.Length() != 8 || chars.TrimLength() != 5 {
|
if chars.inBytes || chars.Length() != 8 || chars.TrimLength() != 5 {
|
||||||
t.Error()
|
t.Error()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,7 +25,7 @@ func TestCharsToString(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestTrimLength(t *testing.T) {
|
func TestTrimLength(t *testing.T) {
|
||||||
check := func(str string, exp int) {
|
check := func(str string, exp uint16) {
|
||||||
chars := ToChars([]byte(str))
|
chars := ToChars([]byte(str))
|
||||||
trimmed := chars.TrimLength()
|
trimmed := chars.TrimLength()
|
||||||
if trimmed != exp {
|
if trimmed != exp {
|
||||||
@@ -55,28 +44,3 @@ func TestTrimLength(t *testing.T) {
|
|||||||
check(" h o ", 5)
|
check(" h o ", 5)
|
||||||
check(" ", 0)
|
check(" ", 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSplit(t *testing.T) {
|
|
||||||
check := func(str string, delim string, tokens ...string) {
|
|
||||||
input := ToChars([]byte(str))
|
|
||||||
result := input.Split(delim)
|
|
||||||
if len(result) != len(tokens) {
|
|
||||||
t.Errorf("Invalid Split result for '%s': %d tokens found (expected %d): %s",
|
|
||||||
str, len(result), len(tokens), result)
|
|
||||||
}
|
|
||||||
for idx, token := range tokens {
|
|
||||||
if result[idx].ToString() != token {
|
|
||||||
t.Errorf("Invalid Split result for '%s': %s (expected %s)",
|
|
||||||
str, result[idx].ToString(), token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
check("abc:def::", ":", "abc:", "def:", ":")
|
|
||||||
check("abc:def::", "-", "abc:def::")
|
|
||||||
check("abc", "", "a", "b", "c")
|
|
||||||
check("abc", "a", "a", "bc")
|
|
||||||
check("abc", "ab", "ab", "c")
|
|
||||||
check("abc", "abc", "abc")
|
|
||||||
check("abc", "abcd", "abc")
|
|
||||||
check("", "abcd", "")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -26,23 +26,23 @@ func NewEventBox() *EventBox {
|
|||||||
// Wait blocks the goroutine until signaled
|
// Wait blocks the goroutine until signaled
|
||||||
func (b *EventBox) Wait(callback func(*Events)) {
|
func (b *EventBox) Wait(callback func(*Events)) {
|
||||||
b.cond.L.Lock()
|
b.cond.L.Lock()
|
||||||
defer b.cond.L.Unlock()
|
|
||||||
|
|
||||||
if len(b.events) == 0 {
|
if len(b.events) == 0 {
|
||||||
b.cond.Wait()
|
b.cond.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
callback(&b.events)
|
callback(&b.events)
|
||||||
|
b.cond.L.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set turns on the event type on the box
|
// Set turns on the event type on the box
|
||||||
func (b *EventBox) Set(event EventType, value interface{}) {
|
func (b *EventBox) Set(event EventType, value interface{}) {
|
||||||
b.cond.L.Lock()
|
b.cond.L.Lock()
|
||||||
defer b.cond.L.Unlock()
|
|
||||||
b.events[event] = value
|
b.events[event] = value
|
||||||
if _, found := b.ignore[event]; !found {
|
if _, found := b.ignore[event]; !found {
|
||||||
b.cond.Broadcast()
|
b.cond.Broadcast()
|
||||||
}
|
}
|
||||||
|
b.cond.L.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear clears the events
|
// Clear clears the events
|
||||||
@@ -56,27 +56,27 @@ func (events *Events) Clear() {
|
|||||||
// Peek peeks at the event box if the given event is set
|
// Peek peeks at the event box if the given event is set
|
||||||
func (b *EventBox) Peek(event EventType) bool {
|
func (b *EventBox) Peek(event EventType) bool {
|
||||||
b.cond.L.Lock()
|
b.cond.L.Lock()
|
||||||
defer b.cond.L.Unlock()
|
|
||||||
_, ok := b.events[event]
|
_, ok := b.events[event]
|
||||||
|
b.cond.L.Unlock()
|
||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// Watch deletes the events from the ignore list
|
// Watch deletes the events from the ignore list
|
||||||
func (b *EventBox) Watch(events ...EventType) {
|
func (b *EventBox) Watch(events ...EventType) {
|
||||||
b.cond.L.Lock()
|
b.cond.L.Lock()
|
||||||
defer b.cond.L.Unlock()
|
|
||||||
for _, event := range events {
|
for _, event := range events {
|
||||||
delete(b.ignore, event)
|
delete(b.ignore, event)
|
||||||
}
|
}
|
||||||
|
b.cond.L.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwatch adds the events to the ignore list
|
// Unwatch adds the events to the ignore list
|
||||||
func (b *EventBox) Unwatch(events ...EventType) {
|
func (b *EventBox) Unwatch(events ...EventType) {
|
||||||
b.cond.L.Lock()
|
b.cond.L.Lock()
|
||||||
defer b.cond.L.Unlock()
|
|
||||||
for _, event := range events {
|
for _, event := range events {
|
||||||
b.ignore[event] = true
|
b.ignore[event] = true
|
||||||
}
|
}
|
||||||
|
b.cond.L.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// WaitFor blocks the execution until the event is received
|
// WaitFor blocks the execution until the event is received
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/junegunn/go-isatty"
|
"github.com/mattn/go-isatty"
|
||||||
"github.com/junegunn/go-runewidth"
|
"github.com/mattn/go-runewidth"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _runeWidths = make(map[rune]int)
|
var _runeWidths = make(map[rune]int)
|
||||||
|
|||||||
@@ -26,3 +26,8 @@ func IsWindows() bool {
|
|||||||
func SetNonblock(file *os.File, nonblock bool) {
|
func SetNonblock(file *os.File, nonblock bool) {
|
||||||
syscall.SetNonblock(int(file.Fd()), nonblock)
|
syscall.SetNonblock(int(file.Fd()), nonblock)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read executes syscall.Read on file descriptor
|
||||||
|
func Read(fd int, b []byte) (int, error) {
|
||||||
|
return syscall.Read(int(fd), b)
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,20 +7,16 @@ import (
|
|||||||
"os/exec"
|
"os/exec"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/junegunn/go-shellwords"
|
"github.com/mattn/go-shellwords"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ExecCommand executes the given command with $SHELL
|
// ExecCommand executes the given command with $SHELL
|
||||||
func ExecCommand(command string) *exec.Cmd {
|
func ExecCommand(command string) *exec.Cmd {
|
||||||
shell := os.Getenv("SHELL")
|
|
||||||
if len(shell) == 0 {
|
|
||||||
shell = "cmd"
|
|
||||||
}
|
|
||||||
args, _ := shellwords.Parse(command)
|
args, _ := shellwords.Parse(command)
|
||||||
allArgs := make([]string, len(args)+1)
|
allArgs := make([]string, len(args)+1)
|
||||||
allArgs[0] = "/c"
|
allArgs[0] = "/c"
|
||||||
copy(allArgs[1:], args)
|
copy(allArgs[1:], args)
|
||||||
return exec.Command(shell, allArgs...)
|
return exec.Command("cmd", allArgs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsWindows returns true on Windows
|
// IsWindows returns true on Windows
|
||||||
@@ -32,3 +28,8 @@ func IsWindows() bool {
|
|||||||
func SetNonblock(file *os.File, nonblock bool) {
|
func SetNonblock(file *os.File, nonblock bool) {
|
||||||
syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)
|
syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read executes syscall.Read on file descriptor
|
||||||
|
func Read(fd int, b []byte) (int, error) {
|
||||||
|
return syscall.Read(syscall.Handle(fd), b)
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ Execute (Setup):
|
|||||||
|
|
||||||
Execute (fzf#run with dir option):
|
Execute (fzf#run with dir option):
|
||||||
let cwd = getcwd()
|
let cwd = getcwd()
|
||||||
let result = fzf#run({ 'options': '--filter=vdr', 'dir': g:dir })
|
let result = fzf#run({ 'source': 'git ls-files', 'options': '--filter=vdr', 'dir': g:dir })
|
||||||
AssertEqual ['fzf.vader'], result
|
AssertEqual ['fzf.vader'], result
|
||||||
AssertEqual getcwd(), cwd
|
AssertEqual getcwd(), cwd
|
||||||
|
|
||||||
let result = sort(fzf#run({ 'options': '--filter e', 'dir': g:dir }))
|
let result = sort(fzf#run({ 'source': 'git ls-files', 'options': '--filter e', 'dir': g:dir }))
|
||||||
AssertEqual ['fzf.vader', 'test_go.rb'], result
|
AssertEqual ['fzf.vader', 'test_go.rb'], result
|
||||||
AssertEqual getcwd(), cwd
|
AssertEqual getcwd(), cwd
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ Execute (fzf#run with Funcref command):
|
|||||||
function! g:FzfTest(e)
|
function! g:FzfTest(e)
|
||||||
call add(g:ret, a:e)
|
call add(g:ret, a:e)
|
||||||
endfunction
|
endfunction
|
||||||
let result = sort(fzf#run({ 'sink': function('g:FzfTest'), 'options': '--filter e', 'dir': g:dir }))
|
let result = sort(fzf#run({ 'source': 'git ls-files', 'sink': function('g:FzfTest'), 'options': '--filter e', 'dir': g:dir }))
|
||||||
AssertEqual ['fzf.vader', 'test_go.rb'], result
|
AssertEqual ['fzf.vader', 'test_go.rb'], result
|
||||||
AssertEqual ['fzf.vader', 'test_go.rb'], sort(g:ret)
|
AssertEqual ['fzf.vader', 'test_go.rb'], sort(g:ret)
|
||||||
|
|
||||||
@@ -140,13 +140,33 @@ Execute (fzf#wrap):
|
|||||||
let g:fzf_history_dir = '/tmp'
|
let g:fzf_history_dir = '/tmp'
|
||||||
let opts = fzf#wrap('foobar', {'options': '--color light'})
|
let opts = fzf#wrap('foobar', {'options': '--color light'})
|
||||||
Log opts
|
Log opts
|
||||||
Assert opts.options =~ '--history /tmp/foobar'
|
Assert opts.options =~ "--history '/tmp/foobar'"
|
||||||
Assert opts.options =~ '--color light'
|
Assert opts.options =~ '--color light'
|
||||||
|
|
||||||
let g:fzf_colors = { 'fg': ['fg', 'Error'] }
|
let g:fzf_colors = { 'fg': ['fg', 'Error'] }
|
||||||
let opts = fzf#wrap({})
|
let opts = fzf#wrap({})
|
||||||
Assert opts.options =~ '^--color=fg:'
|
Assert opts.options =~ '^--color=fg:'
|
||||||
|
|
||||||
|
Execute (fzf#shellescape with sh):
|
||||||
|
AssertEqual '''''', fzf#shellescape('', 'sh')
|
||||||
|
AssertEqual '''\''', fzf#shellescape('\', 'sh')
|
||||||
|
AssertEqual '''""''', fzf#shellescape('""', 'sh')
|
||||||
|
AssertEqual '''foobar>''', fzf#shellescape('foobar>', 'sh')
|
||||||
|
AssertEqual '''\\\"\\\''', fzf#shellescape('\\\"\\\', 'sh')
|
||||||
|
AssertEqual '''echo ''\''''a''\'''' && echo ''\''''b''\''''''', fzf#shellescape('echo ''a'' && echo ''b''', 'sh')
|
||||||
|
|
||||||
|
Execute (fzf#shellescape with cmd.exe):
|
||||||
|
AssertEqual '^"^"', fzf#shellescape('', 'cmd.exe')
|
||||||
|
AssertEqual '^"\\^"', fzf#shellescape('\', 'cmd.exe')
|
||||||
|
AssertEqual '^"\^"\^"^"', fzf#shellescape('""', 'cmd.exe')
|
||||||
|
AssertEqual '^"foobar^>^"', fzf#shellescape('foobar>', 'cmd.exe')
|
||||||
|
AssertEqual '^"\\\\\\\^"\\\\\\^"', fzf#shellescape('\\\"\\\', 'cmd.exe')
|
||||||
|
AssertEqual '^"echo ''a'' ^&^& echo ''b''^"', fzf#shellescape('echo ''a'' && echo ''b''', 'cmd.exe')
|
||||||
|
|
||||||
|
AssertEqual '^"C:\Program Files ^(x86^)\\^"', fzf#shellescape('C:\Program Files (x86)\', 'cmd.exe')
|
||||||
|
AssertEqual '^"C:/Program Files ^(x86^)/^"', fzf#shellescape('C:/Program Files (x86)/', 'cmd.exe')
|
||||||
|
AssertEqual '^"%%USERPROFILE%%^"', fzf#shellescape('%USERPROFILE%', 'cmd.exe')
|
||||||
|
|
||||||
Execute (Cleanup):
|
Execute (Cleanup):
|
||||||
unlet g:dir
|
unlet g:dir
|
||||||
Restore
|
Restore
|
||||||
|
|||||||
630
test/test_go.rb
630
test/test_go.rb
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user