m/fzf
1
0
mirror of https://github.com/junegunn/fzf.git synced 2025-11-15 14:53:47 -05:00

Compare commits

...

7 Commits

Author SHA1 Message Date
Junegunn Choi
3222d62ddf 0.15.4 2016-10-04 02:17:36 +09:00
Junegunn Choi
aeb957a285 Use exact match by default for inverse search term
This is a breaking change, but I believe it makes much more sense. It is
almost impossible to predict which entries will be filtered out due to
a fuzzy inverse term. You can still perform inverse-fuzzy-match by
prepending `!'` to the term.

| Token    | Match type                 | Description                       |
| -------- | -------------------------- | --------------------------------- |
| `sbtrkt` | fuzzy-match                | Items that match `sbtrkt`         |
| `^music` | prefix-exact-match         | Items that start with `music`     |
| `.mp3$`  | suffix-exact-match         | Items that end with `.mp3`        |
| `'wild`  | exact-match (quoted)       | Items that include `wild`         |
| `!fire`  | inverse-exact-match        | Items that do not include `fire`  |
| `!.mp3$` | inverse-suffix-exact-match | Items that do not end with `.mp3` |
2016-10-04 02:09:03 +09:00
Junegunn Choi
154cf22ffa Display scroll indicator in preview window 2016-10-04 01:40:45 +09:00
Junegunn Choi
51f532697e Adjust maximum scroll offset
It was possible that a few lines at the bottom may not be visible if
there are lines above that span multiple lines.
2016-10-04 01:39:48 +09:00
Junegunn Choi
01b88539ba [vim] Apply --multi and --prompt to :FZF command 2016-10-04 00:30:04 +09:00
Junegunn Choi
3066b206af Support field index expressions in preview and execute action
Also close #679. The placeholder for the current query is {q}.
2016-10-03 14:33:28 +09:00
Junegunn Choi
04492bab10 Use unicode.IsSpace to cover more whitespace characters 2016-09-29 22:40:22 +09:00
13 changed files with 224 additions and 59 deletions

View File

@@ -1,6 +1,19 @@
CHANGELOG CHANGELOG
========= =========
0.15.4
------
- Added support for range expression in preview and execute action
- e.g. `ls -l | fzf --preview="echo user={3} when={-4..-2}; cat {-1}" --header-lines=1`
- `{q}` will be replaced to the single-quoted string of the current query
- Fixed to properly handle unicode whitespace characters
- Display scroll indicator in preview window
- Inverse search term will use exact matcher by default
- This is a breaking change, but I believe it makes much more sense. It is
almost impossible to predict which entries will be filtered out due to
a fuzzy inverse term. You can still perform inverse-fuzzy-match by
prepending `!'` to the term.
0.15.3 0.15.3
------ ------
- Added support for more ANSI attributes: dim, underline, blink, and reverse - Added support for more ANSI attributes: dim, underline, blink, and reverse

View File

@@ -113,16 +113,16 @@ vim $(fzf)
Unless otherwise specified, fzf starts in "extended-search mode" where you can Unless otherwise specified, fzf starts in "extended-search mode" where you can
type in multiple search terms delimited by spaces. e.g. `^music .mp3$ sbtrkt type in multiple search terms delimited by spaces. e.g. `^music .mp3$ sbtrkt
!rmx` !fire`
| Token | Match type | Description | | Token | Match type | Description |
| -------- | -------------------- | -------------------------------- | | -------- | -------------------------- | --------------------------------- |
| `sbtrkt` | fuzzy-match | Items that match `sbtrkt` | | `sbtrkt` | fuzzy-match | Items that match `sbtrkt` |
| `^music` | prefix-exact-match | Items that start with `music` | | `^music` | prefix-exact-match | Items that start with `music` |
| `.mp3$` | suffix-exact-match | Items that end with `.mp3` | | `.mp3$` | suffix-exact-match | Items that end with `.mp3` |
| `'wild` | exact-match (quoted) | Items that include `wild` | | `'wild` | exact-match (quoted) | Items that include `wild` |
| `!rmx` | inverse-fuzzy-match | Items that do not match `rmx` | | `!fire` | inverse-exact-match | Items that do not include `fire` |
| `!'fire` | inverse-exact-match | Items that do not include `fire` | | `!.mp3$` | inverse-suffix-exact-match | Items that do not end with `.mp3` |
If you don't prefer fuzzy matching and do not wish to "quote" every word, If you don't prefer fuzzy matching and do not wish to "quote" every word,
start fzf with `-e` or `--exact` option. Note that when `--exact` is set, start fzf with `-e` or `--exact` option. Note that when `--exact` is set,
@@ -305,7 +305,7 @@ If you have set up fzf for Vim, `:FZF` command will be added.
:FZF ~ :FZF ~
" With options " With options
:FZF --no-sort -m /tmp :FZF --no-sort --reverse --inline-info /tmp
" Bang version starts in fullscreen instead of using tmux pane or Neovim split " Bang version starts in fullscreen instead of using tmux pane or Neovim split
:FZF! :FZF!

View File

@@ -2,8 +2,8 @@
set -u set -u
[[ "$@" =~ --pre ]] && version=0.15.3 pre=1 || [[ "$@" =~ --pre ]] && version=0.15.4 pre=1 ||
version=0.15.3 pre=0 version=0.15.4 pre=0
auto_completion= auto_completion=
key_bindings= key_bindings=

View File

@@ -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 "Sep 2016" "fzf 0.15.3" "fzf-tmux - open fzf in tmux split pane" .TH fzf-tmux 1 "Oct 2016" "fzf 0.15.4" "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

View File

@@ -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 "Sep 2016" "fzf 0.15.3" "fzf - a command-line fuzzy finder" .TH fzf 1 "Oct 2016" "fzf 0.15.4" "fzf - a command-line fuzzy finder"
.SH NAME .SH NAME
fzf - a command-line fuzzy finder fzf - a command-line fuzzy finder
@@ -232,11 +232,17 @@ automatically truncated when the number of the lines exceeds the value.
.TP .TP
.BI "--preview=" "COMMAND" .BI "--preview=" "COMMAND"
Execute the given command for the current line and display the result on the Execute the given command for the current line and display the result on the
preview window. \fB{}\fR is the placeholder for the quoted string of the preview window. \fB{}\fR in the command is the placeholder that is replaced to
current line. the single-quoted string of the current line. To transform the replacement
string, specify field index expressions between the braces (See \fBFIELD INDEX
EXPRESSION\fR for the details). Also, \fB{q}\fR is replaced to the current
query string.
.RS .RS
e.g. \fBfzf --preview="head -$LINES {}"\fR e.g. \fBfzf --preview="head -$LINES {}"\fR
\fBls -l | fzf --preview="echo user={3} when={-4..-2}; cat {-1}" --header-lines=1\fR
Note that you can escape a placeholder pattern by prepending a backslash.
.RE .RE
.TP .TP
.BI "--preview-window=" "[POSITION][:SIZE[%]][:hidden]" .BI "--preview-window=" "[POSITION][:SIZE[%]][:hidden]"
@@ -358,7 +364,7 @@ with the given string. An anchored-match term is also an exact-match term.
.SS Negation .SS Negation
If a term is prefixed by \fB!\fR, fzf will exclude the lines that satisfy the If a term is prefixed by \fB!\fR, fzf will exclude the lines that satisfy the
term from the result. term from the result. In this case, fzf performs exact match by default.
.SS Exact-match by default .SS Exact-match by default
If you don't prefer fuzzy matching and do not wish to "quote" (prefixing with If you don't prefer fuzzy matching and do not wish to "quote" (prefixing with
@@ -460,9 +466,11 @@ binding \fBenter\fR key to \fBless\fR command like follows.
\fBfzf --bind "enter:execute(less {})"\fR \fBfzf --bind "enter:execute(less {})"\fR
\fB{}\fR is the placeholder for the quoted string of the current line. You can use the same placeholder expressions as in \fB--preview\fR.
If the command contains parentheses, you can use any of the following
alternative notations to avoid parse errors. If the command contains parentheses, fzf may fail to parse the expression. In
that case, you can use any of the following alternative notations to avoid
parse errors.
\fBexecute[...]\fR \fBexecute[...]\fR
\fBexecute~...~\fR \fBexecute~...~\fR
@@ -481,7 +489,7 @@ alternative notations to avoid parse errors.
.RS .RS
This is the special form that frees you from parse errors as it does not expect This is the special form that frees you from parse errors as it does not expect
the closing character. The catch is that it should be the last one in the the closing character. The catch is that it should be the last one in the
comma-separated list. comma-separated list of key-action pairs.
.RE .RE
\fBexecute-multi(...)\fR is an alternative action that executes the command \fBexecute-multi(...)\fR is an alternative action that executes the command

View File

@@ -558,11 +558,15 @@ let s:default_action = {
function! s:cmd(bang, ...) abort function! s:cmd(bang, ...) abort
let args = copy(a:000) let args = copy(a:000)
let opts = {} let opts = { 'options': '--multi ' }
if len(args) && isdirectory(expand(args[-1])) if len(args) && isdirectory(expand(args[-1]))
let opts.dir = substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g') let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '/*$', '/', '')
let opts.options .= ' --prompt '.shellescape(opts.dir)
else
let opts.options .= ' --prompt '.shellescape(pathshorten(getcwd()).'/')
endif endif
call fzf#run(fzf#wrap('FZF', extend({'options': join(args)}, opts), a:bang)) let opts.options .= ' '.join(args)
call fzf#run(fzf#wrap('FZF', opts, a:bang))
endfunction endfunction
command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>) command! -nargs=* -complete=dir -bang FZF call s:cmd(<bang>0, <f-args>)

View File

@@ -8,7 +8,7 @@ import (
const ( const (
// Current version // Current version
version = "0.15.3" version = "0.15.4"
// Core // Core
coordinatorDelayMax time.Duration = 100 * time.Millisecond coordinatorDelayMax time.Duration = 100 * time.Millisecond

View File

@@ -163,12 +163,13 @@ func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {
if strings.HasPrefix(text, "!") { if strings.HasPrefix(text, "!") {
inv = true inv = true
typ = termExact
text = text[1:] text = text[1:]
} }
if strings.HasPrefix(text, "'") { if strings.HasPrefix(text, "'") {
// Flip exactness // Flip exactness
if fuzzy { if fuzzy && !inv {
typ = termExact typ = termExact
text = text[1:] text = text[1:]
} else { } else {

View File

@@ -22,15 +22,15 @@ func TestParseTermsExtended(t *testing.T) {
terms[1][0].typ != termExact || terms[1][0].inv || terms[1][0].typ != termExact || terms[1][0].inv ||
terms[2][0].typ != termPrefix || terms[2][0].inv || terms[2][0].typ != termPrefix || terms[2][0].inv ||
terms[3][0].typ != termSuffix || terms[3][0].inv || terms[3][0].typ != termSuffix || terms[3][0].inv ||
terms[4][0].typ != termFuzzy || !terms[4][0].inv || terms[4][0].typ != termExact || !terms[4][0].inv ||
terms[5][0].typ != termExact || !terms[5][0].inv || terms[5][0].typ != termFuzzy || !terms[5][0].inv ||
terms[6][0].typ != termPrefix || !terms[6][0].inv || terms[6][0].typ != termPrefix || !terms[6][0].inv ||
terms[7][0].typ != termSuffix || !terms[7][0].inv || terms[7][0].typ != termSuffix || !terms[7][0].inv ||
terms[7][1].typ != termEqual || terms[7][1].inv || terms[7][1].typ != termEqual || terms[7][1].inv ||
terms[8][0].typ != termPrefix || terms[8][0].inv || terms[8][0].typ != termPrefix || terms[8][0].inv ||
terms[8][1].typ != termExact || terms[8][1].inv || terms[8][1].typ != termExact || terms[8][1].inv ||
terms[8][2].typ != termSuffix || terms[8][2].inv || terms[8][2].typ != termSuffix || terms[8][2].inv ||
terms[8][3].typ != termFuzzy || !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 idx, termSet := range terms[:8] {

View File

@@ -3,6 +3,7 @@ package fzf
import ( import (
"math" "math"
"sort" "sort"
"unicode"
"github.com/junegunn/fzf/src/curses" "github.com/junegunn/fzf/src/curses"
"github.com/junegunn/fzf/src/util" "github.com/junegunn/fzf/src/util"
@@ -62,7 +63,7 @@ func buildResult(item *Item, offsets []Offset, score int, trimLen int) *Result {
for idx := 0; idx < numChars; idx++ { for idx := 0; idx < numChars; idx++ {
r := item.text.Get(idx) r := item.text.Get(idx)
whitePrefixLen = idx whitePrefixLen = idx
if idx == minBegin || r != ' ' && r != '\t' { if idx == minBegin || !unicode.IsSpace(r) {
break break
} }
} }

View File

@@ -20,6 +20,12 @@ import (
// import "github.com/pkg/profile" // import "github.com/pkg/profile"
var placeholder *regexp.Regexp
func init() {
placeholder = regexp.MustCompile("\\\\?(?:{[0-9,-.]*}|{q})")
}
type jumpMode int type jumpMode int
const ( const (
@@ -51,6 +57,7 @@ type Terminal struct {
multi bool multi bool
sort bool sort bool
toggleSort bool toggleSort bool
delimiter Delimiter
expect map[int]string expect map[int]string
keymap map[int]actionType keymap map[int]actionType
execmap map[int]string execmap map[int]string
@@ -87,16 +94,11 @@ type Terminal struct {
type selectedItem struct { type selectedItem struct {
at time.Time at time.Time
text string item *Item
} }
type byTimeOrder []selectedItem type byTimeOrder []selectedItem
type previewRequest struct {
ok bool
str string
}
func (a byTimeOrder) Len() int { func (a byTimeOrder) Len() int {
return len(a) return len(a)
} }
@@ -267,6 +269,7 @@ func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {
multi: opts.Multi, multi: opts.Multi,
sort: opts.Sort > 0, sort: opts.Sort > 0,
toggleSort: opts.ToggleSort, toggleSort: opts.ToggleSort,
delimiter: opts.Delimiter,
expect: opts.Expect, expect: opts.Expect,
keymap: opts.Keymap, keymap: opts.Keymap,
execmap: opts.Execmap, execmap: opts.Execmap,
@@ -373,7 +376,7 @@ func (t *Terminal) output() bool {
} }
} else { } else {
for _, sel := range t.sortSelected() { for _, sel := range t.sortSelected() {
t.printer(sel.text) t.printer(sel.item.AsString(t.ansi))
} }
} }
return found return found
@@ -819,6 +822,11 @@ func (t *Terminal) printPreview() {
} }
return t.pwindow.Fill(str) return t.pwindow.Fill(str)
}) })
if t.previewer.offset > 0 {
offset := fmt.Sprintf("%d/%d", t.previewer.offset+1, t.previewer.lines)
t.pwindow.Move(0, t.pwindow.Width-len(offset))
t.pwindow.CPrint(C.ColInfo, C.Reverse, offset)
}
} }
func processTabs(runes []rune, prefixWidth int) (string, int) { func processTabs(runes []rune, prefixWidth int) (string, int) {
@@ -912,8 +920,60 @@ func quoteEntry(entry string) string {
return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'" return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'"
} }
func (t *Terminal) executeCommand(template string, replacement string) { func replacePlaceholder(template string, stripAnsi bool, delimiter Delimiter, query string, items []*Item) string {
command := strings.Replace(template, "{}", replacement, -1) return placeholder.ReplaceAllStringFunc(template, func(match string) string {
// Escaped pattern
if match[0] == '\\' {
return match[1:]
}
// Current query
if match == "{q}" {
return quoteEntry(query)
}
replacements := make([]string, len(items))
if match == "{}" {
for idx, item := range items {
replacements[idx] = quoteEntry(item.AsString(stripAnsi))
}
return strings.Join(replacements, " ")
}
tokens := strings.Split(match[1:len(match)-1], ",")
ranges := make([]Range, len(tokens))
for idx, s := range tokens {
r, ok := ParseRange(&s)
if !ok {
// Invalid expression, just return the original string in the template
return match
}
ranges[idx] = r
}
for idx, item := range items {
chars := util.RunesToChars([]rune(item.AsString(stripAnsi)))
tokens := Tokenize(chars, delimiter)
trans := Transform(tokens, ranges)
str := string(joinTokens(trans))
if delimiter.str != nil {
str = strings.TrimSuffix(str, *delimiter.str)
} else if delimiter.regex != nil {
delims := delimiter.regex.FindAllStringIndex(str, -1)
if len(delims) > 0 && delims[len(delims)-1][1] == len(str) {
str = str[:delims[len(delims)-1][0]]
}
}
str = strings.TrimSpace(str)
replacements[idx] = quoteEntry(str)
}
return strings.Join(replacements, " ")
})
}
func (t *Terminal) executeCommand(template string, items []*Item) {
command := replacePlaceholder(template, t.ansi, t.delimiter, string(t.input), items)
cmd := util.ExecCommand(command) cmd := util.ExecCommand(command)
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
@@ -931,8 +991,12 @@ func (t *Terminal) isPreviewEnabled() bool {
return t.previewBox != nil && t.previewer.enabled return t.previewBox != nil && t.previewer.enabled
} }
func (t *Terminal) currentItem() *Item {
return t.merger.Get(t.cy).item
}
func (t *Terminal) current() string { func (t *Terminal) current() string {
return t.merger.Get(t.cy).item.AsString(t.ansi) return t.currentItem().AsString(t.ansi)
} }
// Loop is called to start Terminal I/O // Loop is called to start Terminal I/O
@@ -989,18 +1053,19 @@ func (t *Terminal) Loop() {
if t.hasPreviewWindow() { if t.hasPreviewWindow() {
go func() { go func() {
for { for {
request := previewRequest{false, ""} var request *Item
t.previewBox.Wait(func(events *util.Events) { t.previewBox.Wait(func(events *util.Events) {
for req, value := range *events { for req, value := range *events {
switch req { switch req {
case reqPreviewEnqueue: case reqPreviewEnqueue:
request = value.(previewRequest) request = value.(*Item)
} }
} }
events.Clear() events.Clear()
}) })
if request.ok { if request != nil {
command := strings.Replace(t.preview.command, "{}", quoteEntry(request.str), -1) command := replacePlaceholder(t.preview.command,
t.ansi, t.delimiter, string(t.input), []*Item{request})
cmd := util.ExecCommand(command) cmd := util.ExecCommand(command)
out, _ := cmd.CombinedOutput() out, _ := cmd.CombinedOutput()
t.reqBox.Set(reqPreviewDisplay, string(out)) t.reqBox.Set(reqPreviewDisplay, string(out))
@@ -1020,7 +1085,7 @@ func (t *Terminal) Loop() {
} }
go func() { go func() {
focused := previewRequest{false, ""} var focused *Item
for { for {
t.reqBox.Wait(func(events *util.Events) { t.reqBox.Wait(func(events *util.Events) {
defer events.Clear() defer events.Clear()
@@ -1037,11 +1102,11 @@ func (t *Terminal) Loop() {
case reqList: case reqList:
t.printList() t.printList()
cnt := t.merger.Length() cnt := t.merger.Length()
var currentFocus previewRequest var currentFocus *Item
if cnt > 0 && cnt > t.cy { if cnt > 0 && cnt > t.cy {
currentFocus = previewRequest{true, t.current()} currentFocus = t.currentItem()
} else { } else {
currentFocus = previewRequest{false, ""} currentFocus = nil
} }
if currentFocus != focused { if currentFocus != focused {
focused = currentFocus focused = currentFocus
@@ -1109,7 +1174,7 @@ func (t *Terminal) Loop() {
} }
selectItem := func(item *Item) bool { selectItem := func(item *Item) bool {
if _, found := t.selected[item.Index()]; !found { if _, found := t.selected[item.Index()]; !found {
t.selected[item.Index()] = selectedItem{time.Now(), item.AsString(t.ansi)} t.selected[item.Index()] = selectedItem{time.Now(), item}
return true return true
} }
return false return false
@@ -1128,7 +1193,7 @@ func (t *Terminal) Loop() {
} }
scrollPreview := func(amount int) { scrollPreview := func(amount int) {
t.previewer.offset = util.Constrain( t.previewer.offset = util.Constrain(
t.previewer.offset+amount, 0, t.previewer.lines-t.pwindow.Height) t.previewer.offset+amount, 0, t.previewer.lines-1)
req(reqPreviewRefresh) req(reqPreviewRefresh)
} }
for key, ret := range t.expect { for key, ret := range t.expect {
@@ -1146,16 +1211,15 @@ func (t *Terminal) Loop() {
case actIgnore: case actIgnore:
case actExecute: case actExecute:
if t.cy >= 0 && t.cy < t.merger.Length() { if t.cy >= 0 && t.cy < t.merger.Length() {
item := t.merger.Get(t.cy).item t.executeCommand(t.execmap[mapkey], []*Item{t.currentItem()})
t.executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))
} }
case actExecuteMulti: case actExecuteMulti:
if len(t.selected) > 0 { if len(t.selected) > 0 {
sels := make([]string, len(t.selected)) sels := make([]*Item, len(t.selected))
for i, sel := range t.sortSelected() { for i, sel := range t.sortSelected() {
sels[i] = quoteEntry(sel.text) sels[i] = sel.item
} }
t.executeCommand(t.execmap[mapkey], strings.Join(sels, " ")) t.executeCommand(t.execmap[mapkey], sels)
} else { } else {
return doAction(actExecute, mapkey) return doAction(actExecute, mapkey)
} }
@@ -1168,7 +1232,7 @@ func (t *Terminal) Loop() {
t.resizeWindows() t.resizeWindows()
cnt := t.merger.Length() cnt := t.merger.Length()
if t.previewer.enabled && cnt > 0 && cnt > t.cy { if t.previewer.enabled && cnt > 0 && cnt > t.cy {
t.previewBox.Set(reqPreviewEnqueue, previewRequest{true, t.current()}) t.previewBox.Set(reqPreviewEnqueue, t.currentItem())
} }
req(reqList, reqInfo) req(reqList, reqInfo)
} }

73
src/terminal_test.go Normal file
View File

@@ -0,0 +1,73 @@
package fzf
import (
"regexp"
"testing"
"github.com/junegunn/fzf/src/util"
)
func newItem(str string) *Item {
bytes := []byte(str)
trimmed, _, _ := extractColor(str, nil, nil)
return &Item{origText: &bytes, text: util.RunesToChars([]rune(trimmed))}
}
func TestReplacePlaceholder(t *testing.T) {
items1 := []*Item{newItem(" foo'bar \x1b[31mbaz\x1b[m")}
items2 := []*Item{
newItem("foo'bar \x1b[31mbaz\x1b[m"),
newItem("FOO'BAR \x1b[31mBAZ\x1b[m")}
var result string
check := func(expected string) {
if result != expected {
t.Errorf("expected: %s, actual: %s", expected, result)
}
}
// {}, preserve ansi
result = replacePlaceholder("echo {}", false, Delimiter{}, "query", items1)
check("echo ' foo'\\''bar \x1b[31mbaz\x1b[m'")
// {}, strip ansi
result = replacePlaceholder("echo {}", true, Delimiter{}, "query", items1)
check("echo ' foo'\\''bar baz'")
// {}, with multiple items
result = replacePlaceholder("echo {}", true, Delimiter{}, "query", items2)
check("echo 'foo'\\''bar baz' 'FOO'\\''BAR BAZ'")
// {..}, strip leading whitespaces, preserve ansi
result = replacePlaceholder("echo {..}", false, Delimiter{}, "query", items1)
check("echo 'foo'\\''bar \x1b[31mbaz\x1b[m'")
// {..}, strip leading whitespaces, strip ansi
result = replacePlaceholder("echo {..}", true, Delimiter{}, "query", items1)
check("echo 'foo'\\''bar baz'")
// {q}
result = replacePlaceholder("echo {} {q}", true, Delimiter{}, "query", items1)
check("echo ' foo'\\''bar baz' 'query'")
// {q}, multiple items
result = replacePlaceholder("echo {}{q}{}", true, Delimiter{}, "query 'string'", items2)
check("echo 'foo'\\''bar baz' 'FOO'\\''BAR BAZ''query '\\''string'\\''''foo'\\''bar baz' 'FOO'\\''BAR BAZ'")
result = replacePlaceholder("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, "query", items1)
check("echo 'foo'\\''bar'/'baz'/'bazfoo'\\''bar'/'baz'/'foo'\\''bar'/' foo'\\''bar baz'/'foo'\\''bar baz'/{n.t}/{}/{1}/{q}/''")
result = replacePlaceholder("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, "query", items2)
check("echo 'foo'\\''bar' 'FOO'\\''BAR'/'baz' 'BAZ'/'baz' 'BAZ'/'foo'\\''bar' 'FOO'\\''BAR'/'foo'\\''bar baz' 'FOO'\\''BAR BAZ'/{n.t}/{}/{1}/{q}/'' ''")
// String delimiter
delim := "'"
result = replacePlaceholder("echo {}/{1}/{2}", true, Delimiter{str: &delim}, "query", items1)
check("echo ' foo'\\''bar baz'/'foo'/'bar baz'")
// Regex delimiter
regex := regexp.MustCompile("[oa]+")
// foo'bar baz
result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, "query", items1)
check("echo ' foo'\\''bar baz'/'f'/'r b'/''\\''bar b'")
}

View File

@@ -1,6 +1,7 @@
package util package util
import ( import (
"unicode"
"unicode/utf8" "unicode/utf8"
) )
@@ -63,7 +64,7 @@ func (chars *Chars) TrimLength() int {
len := chars.Length() len := chars.Length()
for i = len - 1; i >= 0; i-- { for i = len - 1; i >= 0; i-- {
char := chars.Get(i) char := chars.Get(i)
if char != ' ' && char != '\t' { if !unicode.IsSpace(char) {
break break
} }
} }
@@ -75,7 +76,7 @@ func (chars *Chars) TrimLength() int {
var j int var j int
for j = 0; j < len; j++ { for j = 0; j < len; j++ {
char := chars.Get(j) char := chars.Get(j)
if char != ' ' && char != '\t' { if !unicode.IsSpace(char) {
break break
} }
} }
@@ -86,7 +87,7 @@ func (chars *Chars) TrailingWhitespaces() int {
whitespaces := 0 whitespaces := 0
for i := chars.Length() - 1; i >= 0; i-- { for i := chars.Length() - 1; i >= 0; i-- {
char := chars.Get(i) char := chars.Get(i)
if char != ' ' && char != '\t' { if !unicode.IsSpace(char) {
break break
} }
whitespaces++ whitespaces++