Compare commits

..

2 Commits

Author SHA1 Message Date
Junegunn Choi
e8a39eeb0f Ignore invalid byte sequence in UTF-8 2024-07-29 20:24:35 +09:00
Junegunn Choi
c790ab2024 [bash] CTRL-R: Show timestamp and syntax highlighted command 2024-07-29 20:24:35 +09:00
40 changed files with 229 additions and 594 deletions

View File

@@ -36,7 +36,7 @@ jobs:
run: sudo apt-get install --yes zsh fish tmux
- name: Install Ruby gems
run: sudo gem install --no-document minitest:5.25.1 rubocop:1.65.0 rubocop-minitest:0.35.1 rubocop-performance:1.21.1
run: sudo gem install --no-document minitest:5.17.0 rubocop:1.43.0 rubocop-minitest:0.25.1 rubocop-performance:1.15.2
- name: Rubocop
run: rubocop --require rubocop-minitest --require rubocop-performance

View File

@@ -7,4 +7,4 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: crate-ci/typos@v1.26.0
- uses: crate-ci/typos@v1.23.1

View File

@@ -6,7 +6,7 @@ Lint/ShadowingOuterLocalVariable:
Enabled: false
Style/MethodCallWithArgsParentheses:
Enabled: true
AllowedMethods:
IgnoredMethods:
- assert
- exit
- paste
@@ -15,7 +15,7 @@ Style/MethodCallWithArgsParentheses:
- refute
- require
- send_keys
AllowedPatterns:
IgnoredPatterns:
- ^assert_
- ^refute_
Style/NumericPredicate:

View File

@@ -1,69 +1,9 @@
CHANGELOG
=========
0.56.0
------
- Added `--gap[=N]` option to display empty lines between items.
- This can be useful to visually separate adjacent multi-line items.
```sh
# All bash functions, highlighted
declare -f | perl -0777 -pe 's/^}\n/}\0/gm' |
bat --plain --language bash --color always |
fzf --read0 --ansi --reverse --multi --highlight-line --gap
```
- Or just to make the list easier to read. For single-line items, you probably want to set `--color gutter:-1` as well to hide the gutter.
```sh
fzf --info inline-right --gap --color gutter:-1
```
- Added `noinfo` option to `--preview-window` to hide the scroll indicator in the preview window
- Bug fixes
- Thanks to @LangLangBart, @akinomyoga, and @charlievieth for fixing the bugs
0.55.0
------
_Release highlights: https://junegunn.github.io/fzf/releases/0.55.0/_
- Added `exact-boundary-match` type to the search syntax. When a search term is single-quoted, fzf will search for the exact occurrences of the string with both ends at word boundaries.
```sh
fzf --query "'here'" << EOF
come here
not there
EOF
```
- [bash] Fuzzy path completion is enabled for all commands
- 1. If the default completion is not already set
- 2. And if the current bash supports `complete -D` option
- However, fuzzy completion for some commands can be "dynamically" disabled by the dynamic completion loader
- See the comment in `__fzf_default_completion` function for more information
- Comments are now allowed in `$FZF_DEFAULT_OPTS` and `$FZF_DEFAULT_OPTS_FILE`
```sh
export FZF_DEFAULT_OPTS='
# Layout options
--layout=reverse
--info=inline-right # Show info on the right side of the prompt line
# ...
'
```
- Hyperlinks (OSC 8) are now supported in the preview window and in the main window
```sh
printf '<< \e]8;;http://github.com/junegunn/fzf\e\\Link to \e[32mfz\e[0mf\e]8;;\e\\ >>' | fzf --ansi
fzf --preview "printf '<< \e]8;;http://github.com/junegunn/fzf\e\\Link to \e[32mfz\e[0mf\e]8;;\e\\ >>'"
```
- The default `--ellipsis` is now `··` instead of `..`.
- [vim] A spec can have `exit` callback that is called with the exit status of fzf
- This can be used to clean up temporary resources or restore the original state when fzf is closed without a selection
- Fixed `--tmux bottom` when the status line is not at the bottom
- Fixed extra scroll offset in multi-line mode (`--read0` or `--wrap`)
- Added fallback `ps` command for `kill` completion on Cygwin
0.54.3
------
- Fixed incompatibility of adaptive height specification and 'start:reload'
```sh
# A regression in 0.54.0 would cause this to fail
fzf --height '~100%' --bind 'start:reload:seq 10'
```
- Fixed incompatibility of adaptive height and 'start:reload'
- Environment variables are now available to `$FZF_DEFAULT_COMMAND`
```sh
FZF_DEFAULT_COMMAND='echo $FZF_QUERY' fzf --query foo

View File

@@ -77,6 +77,7 @@ endif
all: target/$(BINARY)
test: $(SOURCES)
[ -z "$$(gofmt -s -d src)" ] || (gofmt -s -d src; exit 1)
SHELL=/bin/sh GOOS= $(GO) test -v -tags "$(TAGS)" \
github.com/junegunn/fzf/src \
github.com/junegunn/fzf/src/algo \
@@ -86,10 +87,6 @@ test: $(SOURCES)
bench:
cd src && SHELL=/bin/sh GOOS= $(GO) test -v -tags "$(TAGS)" -run=Bench -bench=. -benchmem
lint: $(SOURCES) test/test_go.rb
[ -z "$$(gofmt -s -d src)" ] || (gofmt -s -d src; exit 1)
rubocop --require rubocop-minitest --require rubocop-performance
install: bin/fzf
generate:
@@ -187,4 +184,4 @@ update:
$(GO) get -u
$(GO) mod tidy
.PHONY: all generate build release test bench lint install clean docker docker-test update
.PHONY: all generate build release test bench install clean docker docker-test update

View File

@@ -289,9 +289,8 @@ The following table summarizes the available options.
| `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 | Function to be called with each selected item |
| `sink` | funcref | Reference to function to process each selected item |
| `sinklist` (or `sink*`) | funcref | Similar to `sink`, but takes the list of output lines at once |
| `exit` | funcref | Function to be called with the exit status of fzf (e.g. 0, 1, 2, 130) |
| `options` | string/list | Options to fzf |
| `dir` | string | Working directory |
| `up`/`down`/`left`/`right` | number/string | (Layout) Window position and size (e.g. `20`, `50%`) |

File diff suppressed because one or more lines are too long

View File

@@ -19,9 +19,6 @@ term=""
[[ -n "$LINES" ]] && lines=$LINES || lines=$(tput lines) || lines=$(tmux display-message -p "#{pane_height}")
[[ -n "$COLUMNS" ]] && columns=$COLUMNS || columns=$(tput cols) || columns=$(tmux display-message -p "#{pane_width}")
tmux_version=$(tmux -V | sed 's/[^0-9.]//g')
tmux_32=$(awk '{print ($1 >= 3.2)}' <<< "$tmux_version" 2> /dev/null || bc -l <<< "$tmux_version >= 3.2")
help() {
>&2 echo 'usage: fzf-tmux [LAYOUT OPTIONS] [--] [FZF OPTIONS]
@@ -97,18 +94,10 @@ while [[ $# -gt 0 ]]; do
opt="$opt ${arg:0:2}$size"
elif [[ "$size" =~ %$ ]]; then
size=${size:0:((${#size}-1))}
if [[ $tmux_32 = 1 ]]; then
if [[ -n "$swap" ]]; then
opt="$opt -l $(( 100 - size ))%"
else
opt="$opt -l $size%"
fi
if [[ -n "$swap" ]]; then
opt="$opt -l $(( 100 - size ))%"
else
if [[ -n "$swap" ]]; then
opt="$opt -p $(( 100 - size ))"
else
opt="$opt -p $size"
fi
opt="$opt -l $size%"
fi
else
if [[ -n "$swap" ]]; then
@@ -198,11 +187,12 @@ trap 'cleanup' EXIT
envs="export TERM=$TERM "
if [[ "$opt" =~ "-E" ]]; then
if [[ $tmux_version = 3.2 ]]; then
FZF_DEFAULT_OPTS="--margin 0,1 $FZF_DEFAULT_OPTS"
elif [[ $tmux_32 = 1 ]]; then
tmux_version=$(tmux -V | sed 's/[^0-9.]//g')
if [[ $(awk '{print ($1 > 3.2)}' <<< "$tmux_version" 2> /dev/null || bc -l <<< "$tmux_version > 3.2") = 1 ]]; then
FZF_DEFAULT_OPTS="--border $FZF_DEFAULT_OPTS"
opt="-B $opt"
elif [[ $tmux_version = 3.2 ]]; then
FZF_DEFAULT_OPTS="--margin 0,1 $FZF_DEFAULT_OPTS"
else
echo "fzf-tmux: tmux 3.2 or above is required for popup mode" >&2
exit 2

View File

@@ -306,9 +306,8 @@ The following table summarizes the available options.
`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 | Function to be called with each selected item
`sink` | funcref | Reference to function to process each selected item
`sinklist` (or `sink*` ) | funcref | Similar to `sink` , but takes the list of output lines at once
`exit` | funcref | Function to be called with the exit status of fzf (e.g. 0, 1, 2, 130)
`options` | string/list | Options to fzf
`dir` | string | Working directory
`up` / `down` / `left` / `right` | number/string | (Layout) Window position and size (e.g. `20` , `50%` )

8
go.mod
View File

@@ -1,13 +1,13 @@
module github.com/junegunn/fzf
require (
github.com/charlievieth/fastwalk v1.0.9
github.com/charlievieth/fastwalk v1.0.8
github.com/gdamore/tcell/v2 v2.7.4
github.com/junegunn/go-shellwords v0.0.0-20240813092932-a62c48c52e97
github.com/mattn/go-isatty v0.0.20
github.com/mattn/go-shellwords v1.0.12
github.com/rivo/uniseg v0.4.7
golang.org/x/sys v0.26.0
golang.org/x/term v0.25.0
golang.org/x/sys v0.22.0
golang.org/x/term v0.22.0
)
require (

16
go.sum
View File

@@ -1,17 +1,17 @@
github.com/charlievieth/fastwalk v1.0.9 h1:Odb92AfoReO3oFBfDGT5J+nwgzQPF/gWAw6E6/lkor0=
github.com/charlievieth/fastwalk v1.0.9/go.mod h1:yGy1zbxog41ZVMcKA/i8ojXLFsuayX5VvwhQVoj9PBI=
github.com/charlievieth/fastwalk v1.0.8 h1:uaoH6cAKSk73aK7aKXqs0+bL+J3Txzd3NGH8tRXgHko=
github.com/charlievieth/fastwalk v1.0.8/go.mod h1:yGy1zbxog41ZVMcKA/i8ojXLFsuayX5VvwhQVoj9PBI=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell/v2 v2.7.4 h1:sg6/UnTM9jGpZU+oFYAsDahfchWAFW8Xx2yFinNSAYU=
github.com/gdamore/tcell/v2 v2.7.4/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
github.com/junegunn/go-shellwords v0.0.0-20240813092932-a62c48c52e97 h1:rqzLixVo1c/GQW6px9j1xQmlvQIn+lf/V6M1UQ7IFzw=
github.com/junegunn/go-shellwords v0.0.0-20240813092932-a62c48c52e97/go.mod h1:6EILKtGpo5t+KLb85LNZLAF6P9LKp78hJI80PXMcn3c=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk=
github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
@@ -36,14 +36,14 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk=
golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=

View File

@@ -2,7 +2,7 @@
set -u
version=0.56.0
version=0.54.2
auto_completion=
key_bindings=
update_config=2

View File

@@ -1,4 +1,4 @@
$version="0.56.0"
$version="0.54.2"
$fzf_base=Split-Path -Parent $MyInvocation.MyCommand.Definition

View File

@@ -11,7 +11,7 @@ import (
"github.com/junegunn/fzf/src/protector"
)
var version = "0.56"
var version = "0.54"
var revision = "devel"
//go:embed shell/key-bindings.bash

View File

@@ -21,13 +21,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
..
.TH fzf\-tmux 1 "Oct 2024" "fzf 0.56.0" "fzf\-tmux - open fzf in tmux split pane"
.TH fzf\-tmux 1 "Jul 2024" "fzf 0.54.2" "fzf\-tmux - open fzf in tmux split pane"
.SH NAME
fzf\-tmux - open fzf in tmux split pane
.SH SYNOPSIS
.B fzf\-tmux [\fILAYOUT OPTIONS\fR] [\-\-] [\fIFZF OPTIONS\fR]
.B fzf\-tmux [LAYOUT OPTIONS] [\-\-] [FZF OPTIONS]
.SH DESCRIPTION
fzf\-tmux is a wrapper script for fzf that opens fzf in a tmux split pane or in

View File

@@ -21,13 +21,13 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
..
.TH fzf 1 "Oct 2024" "fzf 0.56.0" "fzf - a command-line fuzzy finder"
.TH fzf 1 "Jul 2024" "fzf 0.54.2" "fzf - a command-line fuzzy finder"
.SH NAME
fzf - a command-line fuzzy finder
.SH SYNOPSIS
fzf [\fIoptions\fR]
fzf [options]
.SH DESCRIPTION
fzf is an interactive filter program for any kind of list.
@@ -208,9 +208,6 @@ Indicator for wrapped lines. The default is '↳ ' or '> ' depending on
.B "\-\-no\-multi\-line"
Disable multi-line display of items when using \fB\-\-read0\fR
.TP
.BI "\-\-gap" "[=N]"
Render empty lines between each item
.TP
.B "\-\-keep\-right"
Keep the right end of the line visible when it's too long. Effective only when
the query string is empty.
@@ -529,7 +526,7 @@ lines that follow.
Print header before the prompt line
.TP
.BI "\-\-ellipsis=" "STR"
Ellipsis to show when line is truncated (default: '··')
Ellipsis to show when line is truncated (default: '..')
.SS Display
.TP
.B "\-\-ansi"
@@ -759,7 +756,7 @@ default value 0 (or \fBcenter\fR) will put the label at the center of the
border line.
.TP
.BI "\-\-preview\-window=" "[POSITION][,SIZE[%]][,border\-BORDER_OPT][,[no]wrap][,[no]follow][,[no]cycle][,[no]info][,[no]hidden][,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES][,default][,<SIZE_THRESHOLD(ALTERNATIVE_LAYOUT)]"
.BI "\-\-preview\-window=" "[POSITION][,SIZE[%]][,border\-BORDER_OPT][,[no]wrap][,[no]follow][,[no]cycle][,[no]hidden][,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES][,default][,<SIZE_THRESHOLD(ALTERNATIVE_LAYOUT)]"
.RS
.B POSITION: (default: right)
@@ -793,9 +790,6 @@ e.g.
* Cyclic scrolling is enabled with \fBcycle\fR flag.
* To hide the scroll offset information on the top right corner, specify
\fBnoinfo\fR.
* To change the style of the border of the preview window, specify one of
the options for \fB\-\-border\fR with \fBborder\-\fR prefix.
e.g. \fBborder\-rounded\fR (border with rounded edges, default),
@@ -1152,22 +1146,6 @@ A term can be prefixed by \fB^\fR, or suffixed by \fB$\fR to become an
anchored-match term. Then fzf will search for the lines that start with or end
with the given string. An anchored-match term is also an exact-match term.
.SS Exact\-boundary\-match (quoted both ends)
A single-quoted term is interpreted as an "exact\-boundary\-match". fzf will
search for the exact occurrences of the string with both ends at the word
boundaries. Unlike in regular expressions, this also sees an underscore as
a word boundary. But the words around underscores are ranked lower and appear
later in the result than the other words around the other types of word
boundaries.
1. xxx foo xxx (highest score)
.br
2. xxx foo_xxx
.br
3. xxx_foo xxx
.br
4. xxx_foo_xxx (lowest score)
.SS Negation
If a term is prefixed by \fB!\fR, fzf will exclude the lines that satisfy the
term from the result. In this case, fzf performs exact match by default.

View File

@@ -198,7 +198,6 @@ function! s:compare_binary_versions(a, b)
return s:compare_versions(s:get_version(a:a), s:get_version(a:b))
endfunction
let s:min_version = '0.53.0'
let s:checked = {}
function! fzf#exec(...)
if !exists('s:exec')
@@ -226,11 +225,7 @@ function! fzf#exec(...)
let s:exec = binaries[-1]
endif
let min_version = s:min_version
if a:0 && s:compare_versions(a:1, min_version) > 0
let min_version = a:1
endif
if !has_key(s:checked, min_version)
if a:0 && !has_key(s:checked, a:1)
let fzf_version = s:get_version(s:exec)
if empty(fzf_version)
let message = printf('Failed to run "%s --version"', s:exec)
@@ -238,17 +233,17 @@ function! fzf#exec(...)
throw message
end
if s:compare_versions(fzf_version, min_version) >= 0
let s:checked[min_version] = 1
if s:compare_versions(fzf_version, a:1) >= 0
let s:checked[a:1] = 1
return s:exec
elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', min_version, fzf_version)) =~? '^y'
elseif a:0 < 2 && input(printf('You need fzf %s or above. Found: %s. Download binary? (y/n) ', a:1, fzf_version)) =~? '^y'
let s:versions = {}
unlet s:exec
redraw
call fzf#install()
return fzf#exec(min_version, 1)
return fzf#exec(a:1, 1)
else
throw printf('You need to upgrade fzf (required: %s or above)', min_version)
throw printf('You need to upgrade fzf (required: %s or above)', a:1)
endif
endif
@@ -670,17 +665,21 @@ else
let s:launcher = function('s:xterm_launcher')
endif
function! s:exit_handler(dict, code, command, ...)
if has_key(a:dict, 'exit')
call a:dict.exit(a:code)
endif
if a:code == 2
function! s:exit_handler(code, command, ...)
if a:code == 130
return 0
elseif has('nvim') && a:code == 129
" When deleting the terminal buffer while fzf is still running,
" Nvim sends SIGHUP.
return 0
elseif a:code > 1
call s:error('Error running ' . a:command)
if !empty(a:000)
sleep
endif
return 0
endif
return a:code
return 1
endfunction
function! s:execute(dict, command, use_height, temps) abort
@@ -732,7 +731,7 @@ function! s:execute(dict, command, use_height, temps) abort
let exit_status = v:shell_error
redraw!
let lines = s:collect(a:temps)
return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []
return s:exit_handler(exit_status, command) ? lines : []
endfunction
function! s:execute_tmux(dict, command, temps) abort
@@ -747,7 +746,7 @@ function! s:execute_tmux(dict, command, temps) abort
let exit_status = v:shell_error
redraw!
let lines = s:collect(a:temps)
return s:exit_handler(a:dict, exit_status, command) < 2 ? lines : []
return s:exit_handler(exit_status, command) ? lines : []
endfunction
function! s:calc_size(max, val, dict)
@@ -913,7 +912,7 @@ function! s:execute_term(dict, command, temps) abort
endif
let lines = s:collect(self.temps)
if s:exit_handler(self.dict, a:code, self.command, 1) >= 2
if !s:exit_handler(a:code, self.command, 1)
return
endif

View File

@@ -264,7 +264,6 @@ _fzf_handle_dynamic_completion() {
# _completion_loader may not have updated completion for the command
if [[ "$(complete -p "$orig_cmd" 2> /dev/null)" != "$orig_complete" ]]; then
__fzf_orig_completion < <(complete -p "$orig_cmd" 2> /dev/null)
__fzf_orig_completion_get_orig_func "$cmd" || ret=1
# Update orig_complete by _fzf_orig_completion entry
[[ $orig_complete =~ ' -F '(_fzf_[^ ]+)' ' ]] &&
@@ -290,7 +289,7 @@ __fzf_generic_path_completion() {
fi
COMPREPLY=()
trigger=${FZF_COMPLETION_TRIGGER-'**'}
[[ $COMP_CWORD -ge 0 ]] && cur="${COMP_WORDS[COMP_CWORD]}"
cur="${COMP_WORDS[COMP_CWORD]}"
if [[ "$cur" == *"$trigger" ]] && [[ $cur != *'$('* ]] && [[ $cur != *':='* ]] && [[ $cur != *'`'* ]]; then
base=${cur:0:${#cur}-${#trigger}}
eval "base=$base" 2> /dev/null || return
@@ -377,7 +376,7 @@ _fzf_complete() {
selected=$(
FZF_DEFAULT_OPTS=$(__fzf_defaults "--reverse" "${FZF_COMPLETION_OPTS-} $str_arg") \
FZF_DEFAULT_OPTS_FILE='' \
__fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | eval "$post" | command tr '\n' ' ')
__fzf_comprun "${rest[0]}" "${args[@]}" -q "$cur" | $post | command tr '\n' ' ')
selected=${selected% } # Strip trailing space not to repeat "-o nospace"
if [[ -n "$selected" ]]; then
COMPREPLY=("$selected")
@@ -411,8 +410,7 @@ _fzf_complete_kill() {
_fzf_proc_completion() {
_fzf_complete -m --header-lines=1 --no-preview --wrap -- "$@" < <(
command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||
command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox
command ps --everyone --full --windows # For cygwin
command ps -eo user,pid,ppid,time,args # For BusyBox
)
}
@@ -482,36 +480,10 @@ complete -o default -F _fzf_opts_completion fzf
# fzf-tmux specific options (like `-w WIDTH`) are left as a future patch.
complete -o default -F _fzf_opts_completion fzf-tmux
# Default path completion
__fzf_default_completion() {
__fzf_generic_path_completion _fzf_compgen_path "-m" "" "$@"
# Dynamic completion loader has updated the completion for the command
if [[ $? -eq 124 ]]; then
# We trigger _fzf_setup_completion so that fuzzy completion for the command
# still works. However, loader can update the completion for multiple
# commands at once, and fuzzy completion will no longer work for those
# other commands. e.g. pytest -> py.test, pytest-2, pytest-3, etc
_fzf_setup_completion path "$1"
return 124
fi
}
# Set fuzzy path completion as the default completion for all commands.
# We can't set up default completion,
# 1. if it's already set up by another script
# 2. or if the current version of bash doesn't support -D option
complete | command grep -q __fzf_default_completion ||
complete | command grep -- '-D$' | command grep -qv _comp_complete_load ||
complete -D -F __fzf_default_completion -o default -o bashdefault 2> /dev/null
d_cmds="${FZF_COMPLETION_DIR_COMMANDS-cd pushd rmdir}"
# NOTE: $FZF_COMPLETION_PATH_COMMANDS and $FZF_COMPLETION_VAR_COMMANDS are
# undocumented and subject to change in the future.
#
# NOTE: Although we have default completion, we still need to set up completion
# for each command in case they already have completion set up by another script.
a_cmds="${FZF_COMPLETION_PATH_COMMANDS-"
awk bat cat code diff diff3
emacs emacsclient ex file ftp g++ gcc gvim head hg hx java

View File

@@ -300,8 +300,7 @@ _fzf_complete_unalias() {
_fzf_complete_kill() {
_fzf_complete -m --header-lines=1 --no-preview --wrap -- "$@" < <(
command ps -eo user,pid,ppid,start,time,command 2> /dev/null ||
command ps -eo user,pid,ppid,time,args 2> /dev/null || # For BusyBox
command ps --everyone --full --windows # For cygwin
command ps -eo user,pid,ppid,time,args # For BusyBox
)
}

View File

@@ -54,7 +54,45 @@ __fzf_cd__() {
) && printf 'builtin cd -- %q' "$(builtin unset CDPATH && builtin cd -- "$dir" && builtin pwd)"
}
if command -v perl > /dev/null; then
if command -v ruby > /dev/null; then
__fzf_history__() {
local n output
builtin history -w /tmp/fzf-bash-history
output=$(
ruby -e '
fmt = begin
require "rouge"
formatter = Rouge::Formatters::Terminal256.new(Rouge::Themes::Monokai.new)
lexer = Rouge::Lexers::Shell.new
lambda { |c| formatter.format(lexer.lex(c)) }
rescue LoadError
lambda { |c| c }
end
h = {}
i = 0
File.read("/tmp/fzf-bash-history").encode!("UTF-8", "UTF-8", :invalid => :replace).scan(/^#([0-9]+)$\n(.*?)\n(?=^#[0-9]+$|\z)/m) do |t, c|
next if c.empty?
h.delete(c)
h[c] = [i += 1, t]
end
h.to_a.reverse.each do |c, it|
i, t = it
print "\x1b[33m#{i}\t\x1b[32m#{Time.at(t.to_i).strftime(%[%F %T])}\x1b[m "
print fmt[c.gsub("\n", "\n\t")]
print "\0"
end
' | FZF_DEFAULT_OPTS=$(__fzf_defaults "" "-n1,4.. --ansi --scheme=history --bind=ctrl-r:toggle-sort --wrap-sign '"$'\t'"↳ ' --highlight-line ${FZF_CTRL_R_OPTS-} +m --read0") \
FZF_DEFAULT_OPTS_FILE='' $(__fzfcmd) --query "$READLINE_LINE" --bind 'enter:become:echo {4..}'
) || return
READLINE_LINE=$(command perl -pe 's/^\d*\t//' <<< "$output")
if [[ -z "$READLINE_POINT" ]]; then
echo "$READLINE_LINE"
else
READLINE_POINT=0x7fffffff
fi
}
elif command -v perl > /dev/null; then
__fzf_history__() {
local output script
script='BEGIN { getc; $/ = "\n\t"; $HISTCOUNT = $ENV{last_hist} + 1 } s/^[ *]//; s/\n/\n\t/gm; print $HISTCOUNT - $. . "\t$_" if !$seen{$_}++'

View File

@@ -798,14 +798,6 @@ func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text *util.C
// The solution is much cheaper since there is only one possible alignment of
// the pattern.
func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
return exactMatchNaive(caseSensitive, normalize, forward, false, text, pattern, withPos, slab)
}
func ExactMatchBoundary(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
return exactMatchNaive(caseSensitive, normalize, forward, true, text, pattern, withPos, slab)
}
func exactMatchNaive(caseSensitive bool, normalize bool, forward bool, boundaryCheck bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {
if len(pattern) == 0 {
return Result{0, 0, 0}, nil
}
@@ -840,22 +832,10 @@ func exactMatchNaive(caseSensitive bool, normalize bool, forward bool, boundaryC
}
pidx_ := indexAt(pidx, lenPattern, forward)
pchar := pattern[pidx_]
ok := pchar == char
if ok {
if pchar == char {
if pidx_ == 0 {
bonus = bonusAt(text, index_)
}
if boundaryCheck {
ok = bonus >= bonusBoundary
if ok && pidx_ == 0 {
ok = index_ == 0 || charClassOf(text.Get(index_-1)) <= charDelimiter
}
if ok && pidx_ == len(pattern)-1 {
ok = index_ == lenRunes-1 || charClassOf(text.Get(index_+1)) <= charDelimiter
}
}
}
if ok {
pidx++
if pidx == lenPattern {
if bonus > bestBonus {
@@ -881,23 +861,7 @@ func exactMatchNaive(caseSensitive bool, normalize bool, forward bool, boundaryC
sidx = lenRunes - (bestPos + 1)
eidx = lenRunes - (bestPos - lenPattern + 1)
}
var score int
if boundaryCheck {
// Underscore boundaries should be ranked lower than the other types of boundaries
score = int(bonus)
deduct := int(bonus-bonusBoundary) + 1
if sidx > 0 && text.Get(sidx-1) == '_' {
score -= deduct + 1
deduct = 1
}
if eidx < lenRunes && text.Get(eidx) == '_' {
score -= deduct
}
// Add base score so that this can compete with other match types e.g. 'foo' | bar
score += scoreMatch*lenPattern + int(bonusBoundaryWhite)*(lenPattern+1)
} else {
score, _ = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false)
}
score, _ := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false)
return Result{sidx, eidx, score}, nil
}
return Result{-1, -1, 0}, nil

View File

@@ -1,7 +1,6 @@
package fzf
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
@@ -14,28 +13,22 @@ type ansiOffset struct {
color ansiState
}
type url struct {
uri string
params string
}
type ansiState struct {
fg tui.Color
bg tui.Color
attr tui.Attr
lbg tui.Color
url *url
}
func (s *ansiState) colored() bool {
return s.fg != -1 || s.bg != -1 || s.attr > 0 || s.lbg >= 0 || s.url != nil
return s.fg != -1 || s.bg != -1 || s.attr > 0 || s.lbg >= 0
}
func (s *ansiState) equals(t *ansiState) bool {
if t == nil {
return !s.colored()
}
return s.fg == t.fg && s.bg == t.bg && s.attr == t.attr && s.lbg == t.lbg && s.url == t.url
return s.fg == t.fg && s.bg == t.bg && s.attr == t.attr && s.lbg == t.lbg
}
func (s *ansiState) ToString() string {
@@ -67,11 +60,7 @@ func (s *ansiState) ToString() string {
}
ret += toAnsiString(s.fg, 30) + toAnsiString(s.bg, 40)
ret = "\x1b[" + strings.TrimSuffix(ret, ";") + "m"
if s.url != nil {
ret = fmt.Sprintf("\x1b]8;%s;%s\x1b\\%s\x1b]8;;\x1b", s.url.params, s.url.uri, ret)
}
return ret
return "\x1b[" + strings.TrimSuffix(ret, ";") + "m"
}
func toAnsiString(color tui.Color, offset int) string {
@@ -109,19 +98,10 @@ func matchOperatingSystemCommand(s string) int {
if s[i] == '\x07' {
return i + 1
}
// `\x1b]8;PARAMS;URI\x1b\\TITLE\x1b]8;;\x1b`
// ------
if s[i] == '\x1b' && i < len(s)-1 && s[i+1] == '\\' {
return i + 2
}
}
// `\x1b]8;PARAMS;URI\x1b\\TITLE\x1b]8;;\x1b`
// ------------
if i < len(s) && s[:i+1] == "\x1b]8;;\x1b" {
return i + 1
}
return -1
}
@@ -348,21 +328,13 @@ func parseAnsiCode(s string, delimiter byte) (int, byte, string) {
func interpretCode(ansiCode string, prevState *ansiState) ansiState {
var state ansiState
if prevState == nil {
state = ansiState{-1, -1, 0, -1, nil}
state = ansiState{-1, -1, 0, -1}
} else {
state = ansiState{prevState.fg, prevState.bg, prevState.attr, prevState.lbg, prevState.url}
state = ansiState{prevState.fg, prevState.bg, prevState.attr, prevState.lbg}
}
if ansiCode[0] != '\x1b' || ansiCode[1] != '[' || ansiCode[len(ansiCode)-1] != 'm' {
if prevState != nil && strings.HasSuffix(ansiCode, "0K") {
state.lbg = prevState.bg
} else if ansiCode == "\x1b]8;;\x1b\\" { // End of a hyperlink
state.url = nil
} else if strings.HasPrefix(ansiCode, "\x1b]8;") && strings.HasSuffix(ansiCode, "\x1b\\") {
if paramsEnd := strings.IndexRune(ansiCode[4:], ';'); paramsEnd >= 0 {
params := ansiCode[4 : 4+paramsEnd]
uri := ansiCode[5+paramsEnd : len(ansiCode)-2]
state.url = &url{uri: uri, params: params}
}
}
return state
}

View File

@@ -102,7 +102,7 @@ func (m *Matcher) Loop() {
if !cacheCleared {
if count == prevCount {
// Look up mergerCache
if cached, found := m.mergerCache[patternString]; found && cached.final == request.final {
if cached, found := m.mergerCache[patternString]; found {
merger = cached
}
} else {

View File

@@ -12,7 +12,7 @@ import (
"github.com/junegunn/fzf/src/algo"
"github.com/junegunn/fzf/src/tui"
"github.com/junegunn/go-shellwords"
"github.com/mattn/go-shellwords"
"github.com/rivo/uniseg"
)
@@ -56,7 +56,6 @@ Usage: fzf [options]
--wrap Enable line wrap
--wrap-sign=STR Indicator for wrapped lines
--no-multi-line Disable multi-line display of items when using --read0
--gap[=N] Render empty lines between each item
--keep-right Keep the right end of the line visible on overflow
--scroll-off=LINES Number of screen lines to keep above or below when
scrolling to the top or to the bottom (default: 0)
@@ -104,7 +103,7 @@ Usage: fzf [options]
--header=STR String to print as header
--header-lines=N The first N lines of the input are treated as header
--header-first Print header before the prompt line
--ellipsis=STR Ellipsis to show when line is truncated (default: '··')
--ellipsis=STR Ellipsis to show when line is truncated (default: '..')
Display
--ansi Enable processing of ANSI color codes
@@ -121,8 +120,8 @@ Usage: fzf [options]
--preview=COMMAND Command to preview highlighted line ({})
--preview-window=OPT Preview window layout (default: right:50%)
[up|down|left|right][,SIZE[%]]
[,[no]wrap][,[no]cycle][,[no]follow][,[no]info]
[,[no]hidden][,border-BORDER_OPT]
[,[no]wrap][,[no]cycle][,[no]follow][,[no]hidden]
[,border-BORDER_OPT]
[,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES]
[,default][,<SIZE_THRESHOLD(ALTERNATIVE_LAYOUT)]
--preview-label=LABEL
@@ -272,7 +271,6 @@ type previewOpts struct {
wrap bool
cycle bool
follow bool
info bool
border tui.BorderShape
headerLines int
threshold int
@@ -388,7 +386,7 @@ func (a previewOpts) sameLayout(b previewOpts) bool {
}
func (a previewOpts) sameContentLayout(b previewOpts) bool {
return a.wrap == b.wrap && a.headerLines == b.headerLines && a.info == b.info
return a.wrap == b.wrap && a.headerLines == b.headerLines
}
func firstLine(s string) string {
@@ -474,8 +472,7 @@ type Options struct {
Header []string
HeaderLines int
HeaderFirst bool
Gap int
Ellipsis *string
Ellipsis string
Scrollbar *string
Margin [4]sizeSpec
Padding [4]sizeSpec
@@ -511,7 +508,7 @@ func filterNonEmpty(input []string) []string {
}
func defaultPreviewOpts(command string) previewOpts {
return previewOpts{command, posRight, sizeSpec{50, true}, "", false, false, false, false, true, tui.DefaultBorderShape, 0, 0, nil}
return previewOpts{command, posRight, sizeSpec{50, true}, "", false, false, false, false, tui.DefaultBorderShape, 0, 0, nil}
}
func defaultOptions() *Options {
@@ -581,8 +578,7 @@ func defaultOptions() *Options {
Header: make([]string, 0),
HeaderLines: 0,
HeaderFirst: false,
Gap: 0,
Ellipsis: nil,
Ellipsis: "..",
Scrollbar: nil,
Margin: defaultMargin(),
Padding: defaultMargin(),
@@ -1793,10 +1789,6 @@ func parsePreviewWindowImpl(opts *previewOpts, input string) error {
opts.follow = true
case "nofollow":
opts.follow = false
case "info":
opts.info = true
case "noinfo":
opts.info = false
default:
if headerRegex.MatchString(token) {
if opts.headerLines, err = atoi(token[1:]); err != nil {
@@ -2346,19 +2338,10 @@ func parseOptions(index *int, opts *Options, allArgs []string) error {
opts.HeaderFirst = true
case "--no-header-first":
opts.HeaderFirst = false
case "--gap":
if opts.Gap, err = optionalNumeric(allArgs, &i, 1); err != nil {
return err
}
case "--no-gap":
opts.Gap = 0
case "--ellipsis":
str, err := nextString(allArgs, &i, "ellipsis string required")
if err != nil {
if opts.Ellipsis, err = nextString(allArgs, &i, "ellipsis string required"); err != nil {
return err
}
str = firstLine(str)
opts.Ellipsis = &str
case "--preview":
if opts.Preview.command, err = nextString(allArgs, &i, "preview command required"); err != nil {
return err
@@ -2639,13 +2622,8 @@ func parseOptions(index *int, opts *Options, allArgs []string) error {
if opts.HeaderLines, err = atoi(value); err != nil {
return err
}
} else if match, value := optString(arg, "--gap="); match {
if opts.Gap, err = atoi(value); err != nil {
return err
}
} else if match, value := optString(arg, "--ellipsis="); match {
str := firstLine(value)
opts.Ellipsis = &str
opts.Ellipsis = value
} else if match, value := optString(arg, "--preview="); match {
opts.Preview.command = value
} else if match, value := optString(arg, "--preview-window="); match {
@@ -2937,12 +2915,6 @@ func postProcessOptions(opts *Options) error {
return processScheme(opts)
}
func parseShellWords(str string) ([]string, error) {
parser := shellwords.NewParser()
parser.ParseComment = true
return parser.Parse(str)
}
// ParseOptions parses command-line options
func ParseOptions(useDefaults bool, args []string) (*Options, error) {
opts := defaultOptions()
@@ -2956,7 +2928,7 @@ func ParseOptions(useDefaults bool, args []string) (*Options, error) {
return nil, errors.New("$FZF_DEFAULT_OPTS_FILE: " + err.Error())
}
words, parseErr := parseShellWords(string(bytes))
words, parseErr := shellwords.Parse(string(bytes))
if parseErr != nil {
return nil, errors.New(path + ": " + parseErr.Error())
}
@@ -2968,7 +2940,7 @@ func ParseOptions(useDefaults bool, args []string) (*Options, error) {
}
// 2. Options from $FZF_DEFAULT_OPTS string
words, parseErr := parseShellWords(os.Getenv("FZF_DEFAULT_OPTS"))
words, parseErr := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))
if parseErr != nil {
return nil, errors.New("$FZF_DEFAULT_OPTS: " + parseErr.Error())
}

View File

@@ -23,7 +23,6 @@ type termType int
const (
termFuzzy termType = iota
termExact
termExactBoundary
termPrefix
termSuffix
termEqual
@@ -148,7 +147,6 @@ func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy boo
ptr.procFun[termFuzzy] = fuzzyAlgo
ptr.procFun[termEqual] = algo.EqualMatch
ptr.procFun[termExact] = algo.ExactMatchNaive
ptr.procFun[termExactBoundary] = algo.ExactMatchBoundary
ptr.procFun[termPrefix] = algo.PrefixMatch
ptr.procFun[termSuffix] = algo.SuffixMatch
@@ -195,10 +193,7 @@ func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet
text = text[:len(text)-1]
}
if len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {
typ = termExactBoundary
text = text[1 : len(text)-1]
} else if strings.HasPrefix(text, "'") {
if strings.HasPrefix(text, "'") {
// Flip exactness
if fuzzy && !inv {
typ = termExact

View File

@@ -9,7 +9,6 @@ import (
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strings"
"time"
@@ -33,7 +32,7 @@ func fifo(name string) (string, error) {
return output, nil
}
func runProxy(commandPrefix string, cmdBuilder func(temp string, needBash bool) (*exec.Cmd, error), opts *Options, withExports bool) (int, error) {
func runProxy(commandPrefix string, cmdBuilder func(temp string) *exec.Cmd, opts *Options, withExports bool) (int, error) {
output, err := fifo("proxy-output")
if err != nil {
return ExitError, err
@@ -93,28 +92,17 @@ func runProxy(commandPrefix string, cmdBuilder func(temp string, needBash bool)
// To ensure that the options are processed by a POSIX-compliant shell,
// we need to write the command to a temporary file and execute it with sh.
var exports []string
needBash := false
if withExports {
validIdentifier := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
for _, pairStr := range os.Environ() {
exports = os.Environ()
for idx, pairStr := range exports {
pair := strings.SplitN(pairStr, "=", 2)
if validIdentifier.MatchString(pair[0]) {
exports = append(exports, fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1])))
} else if strings.HasPrefix(pair[0], "BASH_FUNC_") && strings.HasSuffix(pair[0], "%%") {
name := pair[0][10 : len(pair[0])-2]
exports = append(exports, name+pair[1])
exports = append(exports, "export -f "+name)
needBash = true
}
exports[idx] = fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1]))
}
}
temp := WriteTemporaryFile(append(exports, command), "\n")
defer os.Remove(temp)
cmd, err := cmdBuilder(temp, needBash)
if err != nil {
return ExitError, err
}
cmd := cmdBuilder(temp)
cmd.Stderr = os.Stderr
intChan := make(chan os.Signal, 1)
defer close(intChan)

View File

@@ -9,10 +9,7 @@ import (
"golang.org/x/sys/unix"
)
func sh(bash bool) (string, error) {
if bash {
return "bash", nil
}
func sh() (string, error) {
return "sh", nil
}

View File

@@ -13,16 +13,12 @@ import (
var shPath atomic.Value
func sh(bash bool) (string, error) {
func sh() (string, error) {
if cached := shPath.Load(); cached != nil {
return cached.(string), nil
}
name := "sh"
if bash {
name = "bash"
}
cmd := exec.Command("cygpath", "-w", "/usr/bin/"+name)
cmd := exec.Command("cygpath", "-w", "/usr/bin/sh")
bytes, err := cmd.Output()
if err != nil {
return "", err
@@ -35,7 +31,7 @@ func sh(bash bool) (string, error) {
func mkfifo(path string, mode uint32) (string, error) {
m := strconv.FormatUint(uint64(mode), 8)
sh, err := sh(false)
sh, err := sh()
if err != nil {
return path, err
}
@@ -47,7 +43,7 @@ func mkfifo(path string, mode uint32) (string, error) {
}
func withOutputPipe(output string, task func(io.ReadCloser)) error {
sh, err := sh(false)
sh, err := sh()
if err != nil {
return err
}
@@ -66,7 +62,7 @@ func withOutputPipe(output string, task func(io.ReadCloser)) error {
}
func withInputPipe(input string, task func(io.WriteCloser)) error {
sh, err := sh(false)
sh, err := sh()
if err != nil {
return err
}

View File

@@ -265,7 +265,7 @@ func (r *Reader) readFiles(root string, opts walkerOpts, ignores []string) bool
isDir := de.IsDir()
if isDir || opts.follow && isSymlinkToDir(path, de) {
base := filepath.Base(path)
if !opts.hidden && base[0] == '.' && base != ".." {
if !opts.hidden && base[0] == '.' {
return filepath.SkipDir
}
for _, ignore := range ignores {

View File

@@ -16,7 +16,6 @@ type colorOffset struct {
offset [2]int32
color tui.ColorPair
match bool
url *url
}
type Result struct {
@@ -178,11 +177,8 @@ func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme,
if curr != 0 && idx > start {
if curr < 0 {
color := colMatch
var url *url
if curr < -1 && theme.Colored {
ansi := itemColors[-curr-2]
url = ansi.color.url
origColor := ansiToColorPair(ansi, colMatch)
origColor := ansiToColorPair(itemColors[-curr-2], colMatch)
// hl or hl+ only sets the foreground color, so colMatch is the
// combination of either [hl and bg] or [hl+ and bg+].
//
@@ -198,14 +194,13 @@ func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme,
}
}
colors = append(colors, colorOffset{
offset: [2]int32{int32(start), int32(idx)}, color: color, match: true, url: url})
offset: [2]int32{int32(start), int32(idx)}, color: color, match: true})
} else {
ansi := itemColors[curr-1]
colors = append(colors, colorOffset{
offset: [2]int32{int32(start), int32(idx)},
color: ansiToColorPair(ansi, colBase),
match: false,
url: ansi.color.url})
match: false})
}
}
}

View File

@@ -124,10 +124,10 @@ func TestColorOffset(t *testing.T) {
item := Result{
item: &Item{
colors: &[]ansiOffset{
{[2]int32{0, 20}, ansiState{1, 5, 0, -1, nil}},
{[2]int32{22, 27}, ansiState{2, 6, tui.Bold, -1, nil}},
{[2]int32{30, 32}, ansiState{3, 7, 0, -1, nil}},
{[2]int32{33, 40}, ansiState{4, 8, tui.Bold, -1, nil}}}}}
{[2]int32{0, 20}, ansiState{1, 5, 0, -1}},
{[2]int32{22, 27}, ansiState{2, 6, tui.Bold, -1}},
{[2]int32{30, 32}, ansiState{3, 7, 0, -1}},
{[2]int32{33, 40}, ansiState{4, 8, tui.Bold, -1}}}}}
colBase := tui.NewColorPair(89, 189, tui.AttrUndefined)
colMatch := tui.NewColorPair(99, 199, tui.AttrUndefined)

View File

@@ -245,7 +245,6 @@ type Terminal struct {
hscroll bool
hscrollOff int
scrollOff int
gap int
wordRubout string
wordNext string
cx int
@@ -383,7 +382,6 @@ const (
reqRedrawPreviewLabel
reqClose
reqPrintQuery
reqPreviewReady
reqPreviewEnqueue
reqPreviewDisplay
reqPreviewRefresh
@@ -826,9 +824,9 @@ func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor
headerVisible: true,
headerFirst: opts.HeaderFirst,
headerLines: opts.HeaderLines,
gap: opts.Gap,
header: []string{},
header0: opts.Header,
ellipsis: opts.Ellipsis,
ansi: opts.Ansi,
tabstop: opts.Tabstop,
hasStartActions: false,
@@ -856,6 +854,7 @@ func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor
mutex: sync.Mutex{},
uiMutex: sync.Mutex{},
suppress: true,
sigstop: false,
slab: util.MakeSlab(slab16Size, slab32Size),
theme: opts.Theme,
startChan: make(chan fitpad, 1),
@@ -884,15 +883,6 @@ func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor
}
t.separator, t.separatorLen = t.ansiLabelPrinter(bar, &tui.ColSeparator, true)
}
if opts.Ellipsis != nil {
t.ellipsis = *opts.Ellipsis
} else if t.unicode {
t.ellipsis = "··"
} else {
t.ellipsis = ".."
}
if t.unicode {
t.wrapSign = "↳ "
t.borderWidth = uniseg.StringWidth("│")
@@ -1077,7 +1067,7 @@ func (t *Terminal) parsePrompt(prompt string) (func(), int) {
// // unless the part has a non-default ANSI state
loc := whiteSuffix.FindStringIndex(trimmed)
if loc != nil {
blankState := ansiOffset{[2]int32{int32(loc[0]), int32(loc[1])}, ansiState{-1, -1, tui.AttrClear, -1, nil}}
blankState := ansiOffset{[2]int32{int32(loc[0]), int32(loc[1])}, ansiState{-1, -1, tui.AttrClear, -1}}
if item.colors != nil {
lastColor := (*item.colors)[len(*item.colors)-1]
if lastColor.offset[1] < int32(loc[1]) {
@@ -1138,23 +1128,15 @@ func (t *Terminal) wrapCols() int {
return util.Max(t.window.Width()-(t.pointerLen+t.markerLen+1), 1)
}
// Number of lines the item takes including the gap
func (t *Terminal) numItemLines(item *Item, atMost int) (int, bool) {
var numLines int
if !t.wrap && !t.multiLine {
numLines = 1 + t.gap
return numLines, numLines > atMost
return 1, false
}
var overflow bool
if !t.wrap && t.multiLine {
numLines, overflow = item.text.NumLines(atMost)
} else {
var lines [][]rune
lines, overflow = item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop)
numLines = len(lines)
return item.text.NumLines(atMost)
}
numLines += t.gap
return numLines, overflow || numLines > atMost
lines, overflow := item.text.Lines(t.multiLine, atMost, t.wrapCols(), t.wrapSignWidth, t.tabstop)
return len(lines), overflow
}
func (t *Terminal) itemLines(item *Item, atMost int) ([][]rune, bool) {
@@ -2060,21 +2042,6 @@ func (t *Terminal) printHeader() {
t.wrap = wrap
}
func (t *Terminal) canSpanMultiLines() bool {
return t.multiLine || t.wrap || t.gap > 0
}
func (t *Terminal) renderEmptyLine(line int, barRange [2]int) {
t.move(line, 0, true)
t.markEmptyLine(line)
// If the screen is not filled with the list in non-multi-line mode,
// scrollbar is not visible at all. But in multi-line mode, we may need
// to redraw the scrollbar character at the end.
if t.canSpanMultiLines() {
t.prevLines[line].hasBar = t.printBar(line, true, barRange)
}
}
func (t *Terminal) printList() {
t.constrain()
barLength, barStart := t.getScrollbar()
@@ -2095,7 +2062,14 @@ func (t *Terminal) printList() {
item := t.merger.Get(itemCount + t.offset)
line = t.printItem(item, line, maxy, itemCount, itemCount == t.cy-t.offset, barRange)
} else if !t.prevLines[line].empty {
t.renderEmptyLine(line, barRange)
t.move(line, 0, true)
t.markEmptyLine(line)
// If the screen is not filled with the list in non-multi-line mode,
// scrollbar is not visible at all. But in multi-line mode, we may need
// to redraw the scrollbar character at the end.
if t.multiLine || t.wrap {
t.prevLines[line].hasBar = t.printBar(line, true, barRange)
}
}
}
}
@@ -2143,6 +2117,9 @@ func (t *Terminal) printItem(result Result, line int, maxLine int, index int, cu
prevLine.queryLen == newLine.queryLen &&
prevLine.result == newLine.result {
t.prevLines[line].hasBar = printBar(line, false)
if !t.multiLine && !t.wrap {
return line
}
return line + numLines - 1
}
@@ -2229,10 +2206,6 @@ func (t *Terminal) printItem(result Result, line int, maxLine int, index int, cu
}
finalLineNum = t.printHighlighted(result, base, match, false, true, line, maxLine, forceRedraw, preTask, postTask)
}
for i := 0; i < t.gap && finalLineNum < maxLine; i++ {
finalLineNum++
t.renderEmptyLine(finalLineNum, barRange)
}
return finalLineNum
}
@@ -2294,7 +2267,7 @@ func (t *Terminal) printHighlighted(result Result, colBase tui.ColorPair, colMat
allOffsets := result.colorOffsets(charOffsets, t.theme, colBase, colMatch, current)
maxLines := 1
if t.canSpanMultiLines() {
if t.multiLine || t.wrap {
maxLines = maxLineNum - lineNum + 1
}
lines, overflow := t.itemLines(item, maxLines)
@@ -2304,7 +2277,7 @@ func (t *Terminal) printHighlighted(result Result, colBase tui.ColorPair, colMat
topCutoff := false
skipLines := 0
wrapped := false
if t.canSpanMultiLines() {
if t.multiLine || t.wrap {
// Cut off the upper lines in the 'default' layout
if t.layout == layoutDefault && !current && maxLines == numItemLines && overflow {
lines, _ = t.itemLines(item, math.MaxInt)
@@ -2486,24 +2459,15 @@ func (t *Terminal) printColoredString(window tui.Window, text []rune, offsets []
var substr string
var prefixWidth int
maxOffset := int32(len(text))
var url *url
for _, offset := range offsets {
b := util.Constrain32(offset.offset[0], index, maxOffset)
e := util.Constrain32(offset.offset[1], index, maxOffset)
if url != nil && offset.url == nil {
url = nil
window.LinkEnd()
}
substr, prefixWidth = t.processTabs(text[index:b], prefixWidth)
window.CPrint(colBase, substr)
if b < e {
substr, prefixWidth = t.processTabs(text[b:e], prefixWidth)
if url == nil && offset.url != nil {
url = offset.url
window.LinkBegin(url.uri, url.params)
}
window.CPrint(offset.color, substr)
}
@@ -2512,9 +2476,6 @@ func (t *Terminal) printColoredString(window tui.Window, text []rune, offsets []
break
}
}
if url != nil {
window.LinkEnd()
}
if index < maxOffset {
substr, _ = t.processTabs(text[index:], prefixWidth)
window.CPrint(colBase, substr)
@@ -2526,7 +2487,7 @@ func (t *Terminal) renderPreviewSpinner() {
spin := t.previewer.spinner
if len(spin) > 0 || t.previewer.scrollable {
maxWidth := t.pwindow.Width()
if !t.previewer.scrollable || !t.previewOpts.info {
if !t.previewer.scrollable {
if maxWidth > 0 {
t.pwindow.Move(0, maxWidth-1)
t.pwindow.CPrint(tui.ColPreviewSpinner, spin)
@@ -2706,30 +2667,17 @@ Loop:
var fillRet tui.FillReturn
prefixWidth := 0
var url *url
_, _, ansi = extractColor(line, ansi, func(str string, ansi *ansiState) bool {
trimmed := []rune(str)
isTrimmed := false
if !t.previewOpts.wrap {
trimmed, isTrimmed = t.trimRight(trimmed, maxWidth-t.pwindow.X())
}
if url == nil && ansi != nil && ansi.url != nil {
url = ansi.url
t.pwindow.LinkBegin(url.uri, url.params)
}
if url != nil && (ansi == nil || ansi.url == nil) {
url = nil
t.pwindow.LinkEnd()
}
if ansi != nil {
lbg = ansi.lbg
} else {
lbg = -1
}
str, width := t.processTabs(trimmed, prefixWidth)
if width > prefixWidth {
prefixWidth = width
if t.theme.Colored && ansi != nil && ansi.colored() {
lbg = ansi.lbg
fillRet = t.pwindow.CFill(ansi.fg, ansi.bg, ansi.attr, str)
} else {
fillRet = t.pwindow.CFill(tui.ColPreview.Fg(), tui.ColPreview.Bg(), tui.AttrRegular, str)
@@ -2738,9 +2686,6 @@ Loop:
return !isTrimmed &&
(fillRet == tui.FillContinue || t.previewOpts.wrap && fillRet == tui.FillNextLine)
})
if url != nil {
t.pwindow.LinkEnd()
}
t.previewer.scrollable = t.previewer.scrollable || t.pwindow.Y() == height-1 && t.pwindow.X() == t.pwindow.Width()
if fillRet == tui.FillNextLine {
continue
@@ -2751,15 +2696,11 @@ Loop:
if unchanged && lineNo == 0 {
break
}
if t.theme.Colored && lbg >= 0 {
fillRet = t.pwindow.CFill(-1, lbg, tui.AttrRegular,
if lbg >= 0 {
t.pwindow.CFill(-1, lbg, tui.AttrRegular,
strings.Repeat(" ", t.pwindow.Width()-t.pwindow.X())+"\n")
} else {
fillRet = t.pwindow.Fill("\n")
}
if fillRet == tui.FillSuspend {
t.previewed.filled = true
break
t.pwindow.Fill("\n")
}
}
lineNo++
@@ -3459,6 +3400,19 @@ func (t *Terminal) Loop() error {
}
}()
contChan := make(chan os.Signal, 1)
notifyOnCont(contChan)
go func() {
for {
select {
case <-ctx.Done():
return
case <-contChan:
t.reqBox.Set(reqReinit, nil)
}
}
}()
if !t.tui.ShouldEmitResizeEvent() {
resizeChan := make(chan os.Signal, 1)
notifyOnResize(resizeChan) // Non-portable
@@ -3515,7 +3469,6 @@ func (t *Terminal) Loop() error {
go func() {
var version int64
stop := false
t.previewBox.WaitFor(reqPreviewReady)
for {
var items []*Item
var commandTemplate string
@@ -3544,9 +3497,6 @@ func (t *Terminal) Loop() error {
if stop {
break
}
if items == nil {
continue
}
version++
// We don't display preview window if no match
if items[0] != nil {
@@ -3788,15 +3738,12 @@ func (t *Terminal) Loop() error {
t.printHeader()
case reqActivate:
t.suppress = false
if t.hasPreviewer() {
t.previewBox.Set(reqPreviewReady, nil)
}
case reqRedrawBorderLabel:
t.printLabel(t.border, t.borderLabel, t.borderLabelOpts, t.borderLabelLen, t.borderShape, true)
case reqRedrawPreviewLabel:
t.printLabel(t.pborder, t.previewLabel, t.previewLabelOpts, t.previewLabelLen, t.previewOpts.border, true)
case reqReinit:
t.tui.Resume(t.fullscreen, true)
t.tui.Resume(t.fullscreen, t.sigstop)
t.fullRedraw()
case reqResize, reqFullRedraw:
if req == reqResize {
@@ -4536,11 +4483,11 @@ func (t *Terminal) Loop() error {
case actSigStop:
p, err := os.FindProcess(os.Getpid())
if err == nil {
t.sigstop = true
t.tui.Clear()
t.tui.Pause(t.fullscreen)
notifyStop(p)
t.mutex.Unlock()
t.reqBox.Set(reqReinit, nil)
return false
}
case actMouse:
@@ -4898,23 +4845,16 @@ func (t *Terminal) constrain() {
for tries := 0; tries < maxLines; tries++ {
numItems := maxLines
// How many items can be fit on screen including the current item?
if t.canSpanMultiLines() && t.merger.Length() > 0 {
if (t.multiLine || t.wrap) && t.merger.Length() > 0 {
numItemsFound := 0
linesSum := 0
add := func(i int) bool {
lines, overflow := t.numItemLines(t.merger.Get(i).item, numItems-linesSum)
lines, _ := t.numItemLines(t.merger.Get(i).item, numItems-linesSum)
linesSum += lines
if linesSum >= numItems {
/*
# Should show all 3 items
printf "file1\0file2\0file3\0" | fzf --height=5 --read0 --bind load:last --reverse
# Should not truncate the last item
printf "file\n1\0file\n2\0file\n3\0" | fzf --height=5 --read0 --bind load:last --reverse
*/
if numItemsFound == 0 || !overflow {
numItemsFound++
if numItemsFound == 0 {
numItemsFound = 1
}
return false
}
@@ -4953,12 +4893,12 @@ func (t *Terminal) constrain() {
for {
prevOffset := newOffset
numItems := t.merger.Length()
itemLines := 1 + t.gap
if t.canSpanMultiLines() && t.cy < numItems {
itemLines := 1
if (t.multiLine || t.wrap) && t.cy < numItems {
itemLines, _ = t.numItemLines(t.merger.Get(t.cy).item, maxLines)
}
linesBefore := t.cy - newOffset
if t.canSpanMultiLines() {
if t.multiLine || t.wrap {
linesBefore = 0
for i := newOffset; i < t.cy && i < numItems; i++ {
lines, _ := t.numItemLines(t.merger.Get(i).item, maxLines-linesBefore-itemLines)

View File

@@ -20,5 +20,9 @@ func notifyStop(p *os.Process) {
if err == nil {
pid = pgid * -1
}
unix.Kill(pid, syscall.SIGTSTP)
unix.Kill(pid, syscall.SIGSTOP)
}
func notifyOnCont(resizeChan chan<- os.Signal) {
signal.Notify(resizeChan, syscall.SIGCONT)
}

View File

@@ -13,3 +13,7 @@ func notifyOnResize(resizeChan chan<- os.Signal) {
func notifyStop(p *os.Process) {
// NOOP
}
func notifyOnCont(resizeChan chan<- os.Signal) {
// NOOP
}

View File

@@ -38,7 +38,7 @@ func runTmux(args []string, opts *Options) (int, error) {
case posUp:
tmuxArgs = append(tmuxArgs, "-xC", "-y0")
case posDown:
tmuxArgs = append(tmuxArgs, "-xC", "-y9999")
tmuxArgs = append(tmuxArgs, "-xC", "-yS")
case posLeft:
tmuxArgs = append(tmuxArgs, "-x0", "-yC")
case posRight:
@@ -49,12 +49,9 @@ func runTmux(args []string, opts *Options) (int, error) {
tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String())
tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String())
return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {
sh, err := sh(needBash)
if err != nil {
return nil, err
}
return runProxy(argStr, func(temp string) *exec.Cmd {
sh, _ := sh()
tmuxArgs = append(tmuxArgs, sh, temp)
return exec.Command("tmux", tmuxArgs...), nil
return exec.Command("tmux", tmuxArgs...)
}, opts, true)
}

View File

@@ -1030,13 +1030,13 @@ func cleanse(str string) string {
func (w *LightWindow) CPrint(pair ColorPair, text string) {
_, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Attr())
w.stderrInternal(cleanse(text), false, code)
w.csi("0m")
w.csi("m")
}
func (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) {
hasColors, code := w.csiColor(fg, bg, attr)
if hasColors {
defer w.csi("0m")
defer w.csi("m")
}
w.stderrInternal(cleanse(text), false, code)
}
@@ -1118,14 +1118,6 @@ func (w *LightWindow) setBg() string {
return "\x1b[m"
}
func (w *LightWindow) LinkBegin(uri string, params string) {
w.renderer.queued.WriteString("\x1b]8;" + params + ";" + uri + "\x1b\\")
}
func (w *LightWindow) LinkEnd() {
w.renderer.queued.WriteString("\x1b]8;;\x1b\\")
}
func (w *LightWindow) Fill(text string) FillReturn {
w.Move(w.posy, w.posx)
code := w.setBg()
@@ -1141,7 +1133,7 @@ func (w *LightWindow) CFill(fg Color, bg Color, attr Attr, text string) FillRetu
bg = w.bg
}
if hasColors, resetCode := w.csiColor(fg, bg, attr); hasColors {
defer w.csi("0m")
defer w.csi("m")
return w.fill(text, resetCode)
}
return w.fill(text, w.setBg())

View File

@@ -4,7 +4,6 @@ package tui
import (
"os"
"regexp"
"time"
"github.com/gdamore/tcell/v2"
@@ -50,8 +49,6 @@ type TcellWindow struct {
lastY int
moveCursor bool
borderStyle BorderStyle
uri *string
params *string
}
func (w *TcellWindow) Top() int {
@@ -604,16 +601,6 @@ func (w *TcellWindow) Print(text string) {
w.printString(text, w.normal)
}
func (w *TcellWindow) withUrl(style tcell.Style) tcell.Style {
if w.uri != nil {
style = style.Url(*w.uri)
if md := regexp.MustCompile(`id=([^:]+)`).FindStringSubmatch(*w.params); len(md) > 1 {
style = style.UrlId(md[1])
}
}
return style
}
func (w *TcellWindow) printString(text string, pair ColorPair) {
lx := 0
a := pair.Attr()
@@ -628,7 +615,6 @@ func (w *TcellWindow) printString(text string, pair ColorPair) {
Blink(a&Attr(tcell.AttrBlink) != 0).
Dim(a&Attr(tcell.AttrDim) != 0)
}
style = w.withUrl(style)
gr := uniseg.NewGraphemes(text)
for gr.Next() {
@@ -679,7 +665,6 @@ func (w *TcellWindow) fillString(text string, pair ColorPair) FillReturn {
Underline(a&Attr(tcell.AttrUnderline) != 0).
StrikeThrough(a&Attr(tcell.AttrStrikeThrough) != 0).
Italic(a&Attr(tcell.AttrItalic) != 0)
style = w.withUrl(style)
gr := uniseg.NewGraphemes(text)
Loop:
@@ -731,16 +716,6 @@ func (w *TcellWindow) Fill(str string) FillReturn {
return w.fillString(str, w.normal)
}
func (w *TcellWindow) LinkBegin(uri string, params string) {
w.uri = &uri
w.params = &params
}
func (w *TcellWindow) LinkEnd() {
w.uri = nil
w.params = nil
}
func (w *TcellWindow) CFill(fg Color, bg Color, a Attr, str string) FillReturn {
if fg == colDefault {
fg = w.normal.Fg()

View File

@@ -564,8 +564,6 @@ type Window interface {
CPrint(color ColorPair, text string)
Fill(text string) FillReturn
CFill(fg Color, bg Color, attr Attr, text string) FillReturn
LinkBegin(uri string, params string)
LinkEnd()
Erase()
EraseMaybe() bool
}

View File

@@ -44,6 +44,11 @@ func needWinpty(opts *Options) bool {
}
func runWinpty(args []string, opts *Options) (int, error) {
sh, err := sh()
if err != nil {
return ExitError, err
}
argStr := escapeSingleQuote(args[0])
for _, arg := range args[1:] {
argStr += " " + escapeSingleQuote(arg)
@@ -51,30 +56,20 @@ func runWinpty(args []string, opts *Options) (int, error) {
argStr += ` --no-winpty`
if isMintty345() {
return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {
sh, err := sh(needBash)
if err != nil {
return nil, err
}
return runProxy(argStr, func(temp string) *exec.Cmd {
cmd := exec.Command(sh, temp)
cmd.Env = append(os.Environ(), "MSYS=enable_pcon")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd, nil
return cmd
}, opts, false)
}
return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {
sh, err := sh(needBash)
if err != nil {
return nil, err
}
return runProxy(argStr, func(temp string) *exec.Cmd {
cmd := exec.Command(sh, "-c", fmt.Sprintf(`winpty < /dev/tty > /dev/tty -- sh %q`, temp))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd, nil
return cmd
}, opts, false)
}

View File

@@ -1443,7 +1443,7 @@ class TestGoFZF < TestBase
[0, 3, 6].each do |off|
tmux.prepare
tmux.send_keys "#{FZF} --hscroll-off=#{off} -q 0 < #{tempname}", :Enter
tmux.until { |lines| assert lines[-3]&.end_with?((0..off).to_a.join + '··') }
tmux.until { |lines| assert lines[-3]&.end_with?((0..off).to_a.join + '..') }
tmux.send_keys '9'
tmux.until { |lines| assert lines[-3]&.end_with?('789') }
tmux.send_keys :Enter
@@ -3366,66 +3366,6 @@ class TestGoFZF < TestBase
tmux.send_keys :Space
tmux.until { |lines| assert_includes lines[-3], 'bar' }
end
def test_boundary_match
# Underscore boundaries should be ranked lower
{
default: [' x '] + %w[/x/ [x] -x- -x_ _x- _x_],
path: ['/x/', ' x '] + %w[[x] -x- -x_ _x- _x_],
history: ['[x]', '-x-', ' x '] + %w[/x/ -x_ _x- _x_]
}.each do |scheme, expected|
result = `printf -- 'xxx\n-xx\nxx-\n_x_\n_x-\n-x_\n[x]\n-x-\n x \n/x/\n' | #{FZF} -f"'x'" --scheme=#{scheme}`.lines(chomp: true)
assert_equal expected, result
end
end
def test_preview_window_noinfo
# │ 1 ││
tmux.send_keys %(#{FZF} --preview 'seq 1000' --preview-window top,noinfo --scrollbar --bind space:change-preview-window:info), :Enter
tmux.until do |lines|
assert lines[1]&.start_with?('│ 1')
assert lines[1]&.end_with?(' ││')
end
tmux.send_keys :Space
tmux.until do |lines|
assert lines[1]&.start_with?('│ 1')
assert lines[1]&.end_with?('1000││')
end
end
def test_gap
tmux.send_keys %(seq 100 | #{FZF} --gap --border --reverse), :Enter
block = <<~BLOCK
>
100/100
> 1
2
3
4
BLOCK
tmux.until { assert_block(block, _1) }
end
def test_gap_2
tmux.send_keys %(seq 100 | #{FZF} --gap=2 --border --reverse), :Enter
block = <<~BLOCK
>
100/100
> 1
2
3
BLOCK
tmux.until { assert_block(block, _1) }
end
end
module TestShell