Add --preview and --preview-window
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Close #587
authored by Junegunn Choi · committed by Junegunn Choi · parent b8737b7 · Browse files · 4 files·+467 added−122 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+467 added−122 removed
- tests:+22 added−0 removed
- other:+445 added−122 removed
Provenance
- Commit
2bbc120- Tree
804bc07- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
b8737b7
4 files changed+467 added−122 removed
modified:src/curses/curses.go+83 added-17 removed
111 unmodified lines112 ColInfo113 ColCursor114 ColSelected115 ColHeader116- ColUser116+ ColBorder117+ ColUser // Should be the last entry118 )119 120 const (121 doubleClickDuration = 500 * time.Millisecond14 unmodified lines136 Info int16137 Cursor int16138 Selected int16139 Header int16140+ Border int16141 }142 143 type Event struct {144 Type int26 unmodified lines171 BG int172 DarkBG int173 )174 175+type Window struct {176+ win *C.WINDOW177+ Top int178+ Left int179+ Width int180+ Height int181+}182+183+func NewWindow(top int, left int, width int, height int, border bool) *Window {184+ win := C.newwin(C.int(height), C.int(width), C.int(top), C.int(left))185+ if border {186+ attr := _color(ColBorder, false)187+ C.wattron(win, attr)188+ C.box(win, 0, 0)189+ C.wattroff(win, attr)190+ }191+ return &Window{192+ win: win,193+ Top: top,194+ Left: left,195+ Width: width,196+ Height: height,197+ }198+}199+200 func EmptyTheme() *ColorTheme {201 return &ColorTheme{202 UseDefault: true,203 Fg: colUndefined,6 unmodified lines210 Spinner: colUndefined,211 Info: colUndefined,212 Cursor: colUndefined,213 Selected: colUndefined,187- Header: colUndefined}214+ Header: colUndefined,215+ Border: colUndefined}216 }217 218 func init() {219 _prevDownTime = time.Unix(0, 0)11 unmodified lines231 Spinner: C.COLOR_GREEN,232 Info: C.COLOR_WHITE,233 Cursor: C.COLOR_RED,234 Selected: C.COLOR_MAGENTA,207- Header: C.COLOR_CYAN}235+ Header: C.COLOR_CYAN,236+ Border: C.COLOR_BLACK}237 Dark256 = &ColorTheme{238 UseDefault: true,239 Fg: 15,240 Bg: 0,5 unmodified lines246 Spinner: 148,247 Info: 144,248 Cursor: 161,249 Selected: 168,221- Header: 109}250+ Header: 109,251+ Border: 59}252 Light256 = &ColorTheme{253 UseDefault: true,254 Fg: 15,255 Bg: 0,5 unmodified lines261 Spinner: 65,262 Info: 101,263 Cursor: 161,264 Selected: 168,235- Header: 31}265+ Header: 31,266+ Border: 145}267 }268 269 func attrColored(pair int, bold bool) C.int {270 var attr C.int119 unmodified lines390 C.init_pair(ColInfo, override(baseTheme.Info, theme.Info), bg)391 C.init_pair(ColCursor, override(baseTheme.Cursor, theme.Cursor), darkBG)392 C.init_pair(ColSelected, override(baseTheme.Selected, theme.Selected), darkBG)393 C.init_pair(ColHeader, override(baseTheme.Header, theme.Header), bg)394+ C.init_pair(ColBorder, override(baseTheme.Border, theme.Border), bg)395 }396 397 func Close() {398 C.endwin()47 unmodified lines446 case 96, 100, 104, 112, // scroll-up / shift / cmd / ctrl447 97, 101, 105, 113: // scroll-down / shift / cmd / ctrl448 mod := _buf[3] >= 100449 s := 1 - int(_buf[3]%2)*2450+ x := int(_buf[4] - 33)451+ y := int(_buf[5] - 33)418- return Event{Mouse, 0, &MouseEvent{0, 0, s, false, false, mod}}452+ return Event{Mouse, 0, &MouseEvent{y, x, s, false, false, mod}}453 }454 return Event{Invalid, 0, nil}455 }456 164 unmodified lines621 sz = rsz622 return Event{Rune, r, nil}623 }624 591-func Move(y int, x int) {592- C.move(C.int(y), C.int(x))625+func (w *Window) Close() {626+ C.delwin(w.win)627 }628 595-func MoveAndClear(y int, x int) {596- Move(y, x)597- C.clrtoeol()629+func (w *Window) Enclose(y int, x int) bool {630+ return bool(C.wenclose(w.win, C.int(y), C.int(x)))631 }632 633+func (w *Window) Move(y int, x int) {634+ C.wmove(w.win, C.int(y), C.int(x))635+}636+637+func (w *Window) MoveAndClear(y int, x int) {638+ w.Move(y, x)639+ C.wclrtoeol(w.win)640+}641+600-func Print(text string) {601- C.addstr(C.CString(strings.Map(func(r rune) rune {642+func (w *Window) Print(text string) {643+ C.waddstr(w.win, C.CString(strings.Map(func(r rune) rune {644 if r < 32 {645 return -1646 }647 return r648 }, text)))649 }650 609-func CPrint(pair int, bold bool, text string) {651+func (w *Window) CPrint(pair int, bold bool, text string) {652 attr := _color(pair, bold)611- C.attron(attr)612- Print(text)613- C.attroff(attr)653+ C.wattron(w.win, attr)654+ w.Print(text)655+ C.wattroff(w.win, attr)656 }657 658 func Clear() {659 C.clear()6 unmodified lines666 func Refresh() {667 C.refresh()668 }669 670+func (w *Window) Erase() {671+ C.werase(w.win)672+}673+674+func (w *Window) Fill(str string) bool {675+ return C.waddstr(w.win, C.CString(str)) == C.OK676+}677+678+func (w *Window) CFill(str string, fg int, bg int, bold bool) bool {679+ attr := _color(PairFor(fg, bg), bold)680+ C.wattron(w.win, attr)681+ ret := w.Fill(str)682+ C.wattroff(w.win, attr)683+ return ret684+}685+686+func (w *Window) Refresh() {687+ C.wnoutrefresh(w.win)688+}689+690+func DoUpdate() {691+ C.doupdate()692+}693+694 func PairFor(fg int, bg int) int {695 key := (fg << 8) + bg696 if found, prs := _colorMap[key]; prs {697 return found7 unmodified linesmodified:src/options.go+134 added-38 removed
1 package fzf2 3 import (4+ "fmt"5 "os"6 "regexp"7 "strconv"8 "strings"14 unmodified lines23 +i Case-sensitive match24 -n, --nth=N[,..] Comma-separated list of field index expressions25 for limiting search scope. Each can be a non-zero26 integer or a range expression ([BEGIN]..[END]).26- --with-nth=N[,..] Transform item using index expressions within finder27- -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)27+ --with-nth=N[,..] Transform the presentation of each line using28+ field index expressions29+ -d, --delimiter=STR Field delimiter regex (default: AWK-style)30 +s, --no-sort Do not sort the result31 --tac Reverse the order of the input32 --tiebreak=CRI[,..] Comma-separated list of sort criteria to apply31- when the scores are tied;32- [length|begin|end|index] (default: length)33+ when the scores are tied [length|begin|end|index]34+ (default: length)35 36 Interface37 -m, --multi Enable multi-select with tab/shift-tab36- --ansi Enable processing of ANSI color codes38 --no-mouse Disable mouse38- --color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors39- --black Use black background40- --reverse Reverse orientation41- --margin=MARGIN Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)42- --tabstop=SPACES Number of spaces for a tab character (default: 8)39+ --bind=KEYBINDS Custom key bindings. Refer to the man page.40 --cycle Enable cyclic scroll41 --no-hscroll Disable horizontal scroll42 --hscroll-off=COL Number of screen columns to keep to the right of the43 highlighted substring (default: 10)47- --inline-info Display finder info inline with the query44 --jump-labels=CHARS Label characters for jump and jump-accept45+46+ Layout47+ --reverse Reverse orientation48+ --margin=MARGIN Screen margin (TRBL / TB,RL / T,RL,B / T,R,B,L)49+ --inline-info Display finder info inline with the query50 --prompt=STR Input prompt (default: '> ')50- --bind=KEYBINDS Custom key bindings. Refer to the man page.51- --history=FILE History file52- --history-size=N Maximum number of history entries (default: 1000)51 --header=STR String to print as header52 --header-lines=N The first N lines of the input are treated as header53 54+ Display55+ --ansi Enable processing of ANSI color codes56+ --tabstop=SPACES Number of spaces for a tab character (default: 8)57+ --color=COLSPEC Base scheme (dark|light|16|bw) and/or custom colors58+59+ History60+ --history=FILE History file61+ --history-size=N Maximum number of history entries (default: 1000)62+63+ Preview64+ --preview=COMMAND Command to preview highlighted line ({})65+ --preview-window=OPT Preview window layout (default: right:50%)66+ [up|down|left|right][:SIZE[%]][:hidden]67+68 Scripting69 -q, --query=STR Start the finder with the given query70 -1, --select-1 Automatically select the only match71 -0, --exit-0 Exit immediately when there's no match27 unmodified lines99 byBegin100 byEnd101 )102 91-func defaultMargin() [4]string {92- return [4]string{"0", "0", "0", "0"}103+type sizeSpec struct {104+ size float64105+ percent bool106 }107 108+func defaultMargin() [4]sizeSpec {109+ return [4]sizeSpec{}110+}111+112+type windowPosition int113+114+const (115+ posUp windowPosition = iota116+ posDown117+ posLeft118+ posRight119+)120+121+type previewOpts struct {122+ command string123+ position windowPosition124+ size sizeSpec125+ hidden bool126+}127+128 // Options stores the values of command-line options129 type Options struct {130 Fuzzy bool131 Extended bool23 unmodified lines155 ToggleSort bool156 Expect map[int]string157 Keymap map[int]actionType158 Execmap map[int]string159+ Preview previewOpts160 PrintQuery bool161 ReadZero bool162 Sync bool163 History *History164 Header []string165 HeaderLines int132- Margin [4]string166+ Margin [4]sizeSpec167 Tabstop int168 Version bool169 }170 27 unmodified lines198 ToggleSort: false,199 Expect: make(map[int]string),200 Keymap: make(map[int]actionType),201 Execmap: make(map[int]string),202+ Preview: previewOpts{"", posRight, sizeSpec{50, true}, false},203 PrintQuery: false,204 ReadZero: false,205 Sync: false,206 History: nil,285 unmodified lines492 case "hl":493 theme.Match = ansi494 case "hl+":495 theme.CurrentMatch = ansi496+ case "border":497+ theme.Border = ansi498 case "prompt":499 theme.Prompt = ansi500 case "spinner":501 theme.Spinner = ansi138 unmodified lines640 case "previous-history":641 keymap[key] = actPreviousHistory642 case "next-history":643 keymap[key] = actNextHistory644+ case "toggle-preview":645+ keymap[key] = actTogglePreview646 case "toggle-sort":647 keymap[key] = actToggleSort648 default:649 if isExecuteAction(actLower) {47 unmodified lines697 func strLines(str string) []string {698 return strings.Split(strings.TrimSuffix(str, "\n"), "\n")699 }700 662-func parseMargin(margin string) [4]string {663- margins := strings.Split(margin, ",")664- checked := func(str string) string {665- if strings.HasSuffix(str, "%") {666- val := atof(str[:len(str)-1])667- if val < 0 {668- errorExit("margin must be non-negative")669- }670- if val > 100 {671- errorExit("margin too large")672- }673- } else {674- val := atoi(str)675- if val < 0 {676- errorExit("margin must be non-negative")677- }701+func parseSize(str string, maxPercent float64, label string) sizeSpec {702+ var val float64703+ percent := strings.HasSuffix(str, "%")704+ if percent {705+ val = atof(str[:len(str)-1])706+ if val < 0 {707+ errorExit(label + " must be non-negative")708 }679- return str709+ if val > maxPercent {710+ errorExit(fmt.Sprintf("%s too large (max: %d%%)", label, int(maxPercent)))711+ }712+ } else {713+ if strings.Contains(str, ".") {714+ errorExit(label + " (without %) must be a non-negative integer")715+ }716+717+ val = float64(atoi(str))718+ if val < 0 {719+ errorExit(label + " must be non-negative")720+ }721 }722+ return sizeSpec{val, percent}723+}724+725+func parsePreviewWindow(opts *previewOpts, input string) {726+ layout := input727+ if strings.HasSuffix(layout, ":hidden") {728+ opts.hidden = true729+ layout = strings.TrimSuffix(layout, ":hidden")730+ }731+732+ tokens := strings.Split(layout, ":")733+ if len(tokens) == 0 || len(tokens) > 2 {734+ errorExit("invalid window layout: " + input)735+ }736+737+ if len(tokens) > 1 {738+ opts.size = parseSize(tokens[1], 99, "window size")739+ } else {740+ opts.size = sizeSpec{50, true}741+ }742+ if !opts.size.percent && opts.size.size > 0 {743+ // Adjust size for border744+ opts.size.size += 2745+ }746+747+ switch tokens[0] {748+ case "up":749+ opts.position = posUp750+ case "down":751+ opts.position = posDown752+ case "left":753+ opts.position = posLeft754+ case "right":755+ opts.position = posRight756+ default:757+ errorExit("invalid window position: " + input)758+ }759+}760+761+func parseMargin(margin string) [4]sizeSpec {762+ margins := strings.Split(margin, ",")763+ checked := func(str string) sizeSpec {764+ return parseSize(str, 49, "margin")765+ }766 switch len(margins) {767 case 1:768 m := checked(margins[0])684- return [4]string{m, m, m, m}769+ return [4]sizeSpec{m, m, m, m}770 case 2:771 tb := checked(margins[0])772 rl := checked(margins[1])688- return [4]string{tb, rl, tb, rl}773+ return [4]sizeSpec{tb, rl, tb, rl}774 case 3:775 t := checked(margins[0])776 rl := checked(margins[1])777 b := checked(margins[2])693- return [4]string{t, rl, b, rl}778+ return [4]sizeSpec{t, rl, b, rl}779 case 4:695- return [4]string{780+ return [4]sizeSpec{781 checked(margins[0]), checked(margins[1]),782 checked(margins[2]), checked(margins[3])}783 default:784 errorExit("invalid margin: " + margin)157 unmodified lines942 opts.Header = strLines(nextString(allArgs, &i, "header string required"))943 case "--header-lines":944 opts.HeaderLines = atoi(945 nextString(allArgs, &i, "number of header lines required"))946+ case "--preview":947+ opts.Preview.command = nextString(allArgs, &i, "preview command required")948+ case "--no-preview":949+ opts.Preview.command = ""950+ case "--preview-window":951+ parsePreviewWindow(&opts.Preview,952+ nextString(allArgs, &i, "preview window layout required: [up|down|left|right][:SIZE[%]]"))953 case "--no-margin":954 opts.Margin = defaultMargin()955 case "--margin":956 opts.Margin = parseMargin(34 unmodified lines991 } else if match, value := optString(arg, "--header="); match {992 opts.Header = strLines(value)993 } else if match, value := optString(arg, "--header-lines="); match {994 opts.HeaderLines = atoi(value)995+ } else if match, value := optString(arg, "--preview="); match {996+ opts.Preview.command = value997+ } else if match, value := optString(arg, "--preview-window="); match {998+ parsePreviewWindow(&opts.Preview, value)999 } else if match, value := optString(arg, "--margin="); match {1000 opts.Margin = parseMargin(value)1001 } else if match, value := optString(arg, "--tabstop="); match {1002 opts.Tabstop = atoi(value)84 unmodified linesmodified:src/terminal.go+228 added-67 removed
5 unmodified lines6 "os"7 "os/signal"8 "regexp"9 "sort"10- "strconv"10 "strings"11 "sync"12 "syscall"13 "time"37 unmodified lines51 cycle bool52 header []string53 header0 []string54 ansi bool56- margin [4]string57- marginInt [4]int55+ margin [4]sizeSpec56+ window *C.Window57+ bwindow *C.Window58+ pwindow *C.Window59 count int60 progress int61 reading bool62 jumping jumpMode63 jumpLabels string64 merger *Merger65 selected map[int32]selectedItem66 reqBox *util.EventBox67+ preview previewOpts68+ previewing bool69+ previewTxt string70+ previewBox *util.EventBox71 eventBox *util.EventBox72 mutex sync.Mutex73 initFunc func()74 suppress bool32 unmodified lines107 reqRefresh108 reqRedraw109 reqClose110 reqPrintQuery111+ reqPreviewEnqueue112+ reqPreviewDisplay113 reqQuit114 )115 116 type actionType int37 unmodified lines154 actJump155 actJumpAccept156 actPrintQuery157 actToggleSort158+ actTogglePreview159 actPreviousHistory160 actNextHistory161 actExecute162 actExecuteMulti64 unmodified lines227 delay = initialDelayTac228 } else {229 delay = initialDelay230 }231+ var previewBox *util.EventBox232+ if len(opts.Preview.command) > 0 {233+ previewBox = util.NewEventBox()234+ }235 return &Terminal{236 initDelay: delay,237 inlineInfo: opts.InlineInfo,238 prompt: opts.Prompt,14 unmodified lines253 pressed: "",254 printQuery: opts.PrintQuery,255 history: opts.History,256 margin: opts.Margin,245- marginInt: [4]int{0, 0, 0, 0},257 cycle: opts.Cycle,258 header: header,259 header0: header,260 ansi: opts.Ansi,2 unmodified lines263 jumpLabels: opts.JumpLabels,264 merger: EmptyMerger,265 selected: make(map[int32]selectedItem),266 reqBox: util.NewEventBox(),267+ preview: opts.Preview,268+ previewing: previewBox != nil && !opts.Preview.hidden,269+ previewTxt: "",270+ previewBox: previewBox,271 eventBox: eventBox,272 mutex: sync.Mutex{},273 suppress: true,274 startChan: make(chan bool, 1),71 unmodified lines346 found := len(t.selected) > 0347 if !found {348 cnt := t.merger.Length()349 if cnt > 0 && cnt > t.cy {335- fmt.Println(t.merger.Get(t.cy).AsString(t.ansi))350+ fmt.Println(t.current())351 found = true352 }353 } else {354 for _, sel := range t.sortSelected() {31 unmodified lines386 }387 return l388 }389 390+const (375-const minWidth = 16376-const minHeight = 4391+ minWidth = 16392+ minHeight = 4393+)394 378-func (t *Terminal) calculateMargins() {395+func calculateSize(base int, size sizeSpec, margin int, minSize int) int {396+ max := base - margin397+ if size.percent {398+ return util.Constrain(int(float64(base)*0.01*size.size), minSize, max)399+ }400+ return util.Constrain(int(size.size), minSize, max)401+}402+403+func (t *Terminal) resizeWindows() {404 screenWidth := C.MaxX()405 screenHeight := C.MaxY()381- for idx, str := range t.margin {382- if str == "0" {383- t.marginInt[idx] = 0384- } else if strings.HasSuffix(str, "%") {385- num, _ := strconv.ParseFloat(str[:len(str)-1], 64)386- var val float64406+ marginInt := [4]int{}407+ for idx, sizeSpec := range t.margin {408+ if sizeSpec.percent {409+ var max float64410 if idx%2 == 0 {388- val = float64(screenHeight)411+ max = float64(screenHeight)412 } else {390- val = float64(screenWidth)413+ max = float64(screenWidth)414 }392- t.marginInt[idx] = int(val * num * 0.01)415+ marginInt[idx] = int(max * sizeSpec.size * 0.01)416 } else {394- num, _ := strconv.Atoi(str)395- t.marginInt[idx] = num417+ marginInt[idx] = int(sizeSpec.size)418 }419 }420 adjust := func(idx1 int, idx2 int, max int, min int) {421 if max >= min {400- margin := t.marginInt[idx1] + t.marginInt[idx2]422+ margin := marginInt[idx1] + marginInt[idx2]423 if max-margin < min {424 desired := max - min403- t.marginInt[idx1] = desired * t.marginInt[idx1] / margin404- t.marginInt[idx2] = desired * t.marginInt[idx2] / margin425+ marginInt[idx1] = desired * marginInt[idx1] / margin426+ marginInt[idx2] = desired * marginInt[idx2] / margin427 }428 }429 }430+ minAreaWidth := minWidth431+ minAreaHeight := minHeight432+ if t.isPreviewEnabled() {433+ switch t.preview.position {434+ case posUp, posDown:435+ minAreaHeight *= 2436+ case posLeft, posRight:437+ minAreaWidth *= 2438+ }439+ }408- adjust(1, 3, screenWidth, minWidth)409- adjust(0, 2, screenHeight, minHeight)440+ adjust(1, 3, screenWidth, minAreaWidth)441+ adjust(0, 2, screenHeight, minAreaHeight)442+ if t.window != nil {443+ t.window.Close()444+ }445+ if t.bwindow != nil {446+ t.bwindow.Close()447+ t.pwindow.Close()448+ }449+450+ width := screenWidth - marginInt[1] - marginInt[3]451+ height := screenHeight - marginInt[0] - marginInt[2]452+ if t.isPreviewEnabled() {453+ createPreviewWindow := func(y int, x int, w int, h int) {454+ t.bwindow = C.NewWindow(y, x, w, h, true)455+ t.pwindow = C.NewWindow(y+1, x+2, w-4, h-2, false)456+ }457+ switch t.preview.position {458+ case posUp:459+ pheight := calculateSize(height, t.preview.size, minHeight, 3)460+ t.window = C.NewWindow(461+ marginInt[0]+pheight, marginInt[3], width, height-pheight, false)462+ createPreviewWindow(marginInt[0], marginInt[3], width, pheight)463+ case posDown:464+ pheight := calculateSize(height, t.preview.size, minHeight, 3)465+ t.window = C.NewWindow(466+ marginInt[0], marginInt[3], width, height-pheight, false)467+ createPreviewWindow(marginInt[0]+height-pheight, marginInt[3], width, pheight)468+ case posLeft:469+ pwidth := calculateSize(width, t.preview.size, minWidth, 5)470+ t.window = C.NewWindow(471+ marginInt[0], marginInt[3]+pwidth, width-pwidth, height, false)472+ createPreviewWindow(marginInt[0], marginInt[3], pwidth, height)473+ case posRight:474+ pwidth := calculateSize(width, t.preview.size, minWidth, 5)475+ t.window = C.NewWindow(476+ marginInt[0], marginInt[3], width-pwidth, height, false)477+ createPreviewWindow(marginInt[0], marginInt[3]+width-pwidth, pwidth, height)478+ }479+ } else {480+ t.window = C.NewWindow(481+ marginInt[0],482+ marginInt[3],483+ width,484+ height, false)485+ }486 }487 488 func (t *Terminal) move(y int, x int, clear bool) {413- x += t.marginInt[3]414- maxy := C.MaxY()489 if !t.reverse {416- y = maxy - y - 1 - t.marginInt[2]417- } else {418- y += t.marginInt[0]490+ y = t.window.Height - y - 1491 }492 493 if clear {422- C.MoveAndClear(y, x)494+ t.window.MoveAndClear(y, x)495 } else {424- C.Move(y, x)496+ t.window.Move(y, x)497 }498 }499 500 func (t *Terminal) placeCursor() {1 unmodified line502 }503 504 func (t *Terminal) printPrompt() {505 t.move(0, 0, true)434- C.CPrint(C.ColPrompt, true, t.prompt)435- C.CPrint(C.ColNormal, true, string(t.input))506+ t.window.CPrint(C.ColPrompt, true, t.prompt)507+ t.window.CPrint(C.ColNormal, true, string(t.input))508 }509 510 func (t *Terminal) printInfo() {511 if t.inlineInfo {512 t.move(0, displayWidth([]rune(t.prompt))+displayWidth(t.input)+1, true)513 if t.reading {442- C.CPrint(C.ColSpinner, true, " < ")514+ t.window.CPrint(C.ColSpinner, true, " < ")515 } else {444- C.CPrint(C.ColPrompt, true, " < ")516+ t.window.CPrint(C.ColPrompt, true, " < ")517 }518 } else {519 t.move(1, 0, true)520 if t.reading {521 duration := int64(spinnerDuration)522 idx := (time.Now().UnixNano() % (duration * int64(len(_spinner)))) / duration451- C.CPrint(C.ColSpinner, true, _spinner[idx])523+ t.window.CPrint(C.ColSpinner, true, _spinner[idx])524 }525 t.move(1, 2, false)526 }527 10 unmodified lines538 }539 if t.progress > 0 && t.progress < 100 {540 output += fmt.Sprintf(" (%d%%)", t.progress)541 }470- C.CPrint(C.ColInfo, false, output)542+ t.window.CPrint(C.ColInfo, false, output)543 }544 473-func (t *Terminal) maxHeight() int {474- return C.MaxY() - t.marginInt[0] - t.marginInt[2]475-}476-545 func (t *Terminal) printHeader() {546 if len(t.header) == 0 {547 return548 }481- max := t.maxHeight()549+ max := t.window.Height550 var state *ansiState551 for idx, lineStr := range t.header {552 line := idx + 2553 if t.inlineInfo {42 unmodified lines596 }597 } else if current {598 label = ">"599 }532- C.CPrint(C.ColCursor, true, label)600+ t.window.CPrint(C.ColCursor, true, label)601 if current {602 if selected {535- C.CPrint(C.ColSelected, true, ">")603+ t.window.CPrint(C.ColSelected, true, ">")604 } else {537- C.CPrint(C.ColCurrent, true, " ")605+ t.window.CPrint(C.ColCurrent, true, " ")606 }607 t.printHighlighted(item, true, C.ColCurrent, C.ColCurrentMatch, true)608 } else {609 if selected {542- C.CPrint(C.ColSelected, true, ">")610+ t.window.CPrint(C.ColSelected, true, ">")611 } else {544- C.Print(" ")612+ t.window.Print(" ")613 }614 t.printHighlighted(item, false, 0, C.ColMatch, false)615 }616 }43 unmodified lines660 // Overflow661 text := make([]rune, len(item.text))662 copy(text, item.text)663 offsets := item.colorOffsets(col2, bold, current)596- maxWidth := C.MaxX() - 3 - t.marginInt[1] - t.marginInt[3]664+ maxWidth := t.window.Width - 3665 maxe = util.Constrain(maxe+util.Min(maxWidth/2-2, t.hscrollOff), 0, len(text))666 fullWidth := displayWidth(text)667 if fullWidth > maxWidth {668 if t.hscroll {41 unmodified lines710 b := util.Constrain32(offset.offset[0], index, maxOffset)711 e := util.Constrain32(offset.offset[1], index, maxOffset)712 713 substr, prefixWidth = processTabs(text[index:b], prefixWidth)646- C.CPrint(col1, bold, substr)714+ t.window.CPrint(col1, bold, substr)715 716 if b < e {717 substr, prefixWidth = processTabs(text[b:e], prefixWidth)650- C.CPrint(offset.color, offset.bold, substr)718+ t.window.CPrint(offset.color, offset.bold, substr)719 }720 721 index = e722 if index >= maxOffset {1 unmodified line724 }725 }726 if index < maxOffset {727 substr, _ = processTabs(text[index:], prefixWidth)660- C.CPrint(col1, bold, substr)728+ t.window.CPrint(col1, bold, substr)729 }730 }731 732+func (t *Terminal) printPreview() {733+ trimmed, ansiOffsets, _ := extractColor(t.previewTxt, nil)734+ var index int32735+ t.pwindow.Erase()736+ for _, o := range ansiOffsets {737+ b := o.offset[0]738+ e := o.offset[1]739+ if b > index {740+ if !t.pwindow.Fill(trimmed[index:b]) {741+ return742+ }743+ }744+ if !t.pwindow.CFill(trimmed[b:e], o.color.fg, o.color.bg, o.color.bold) {745+ return746+ }747+ index = e748+ }749+ if int(index) < len(trimmed) {750+ t.pwindow.Fill(trimmed[index:])751+ }752+}753+754 func processTabs(runes []rune, prefixWidth int) (string, int) {755 var strbuf bytes.Buffer756 l := prefixWidth757 for _, r := range runes {8 unmodified lines766 return strbuf.String(), l767 }768 769 func (t *Terminal) printAll() {680- t.calculateMargins()770+ t.resizeWindows()771 t.printList()772 t.printPrompt()773 t.printInfo()774 t.printHeader()775+ if t.isPreviewEnabled() {776+ t.printPreview()777+ }778 }779 780 func (t *Terminal) refresh() {781 if !t.suppress {782+ if t.isPreviewEnabled() {783+ t.bwindow.Refresh()784+ t.pwindow.Refresh()785+ }689- C.Refresh()786+ t.window.Refresh()787+ C.DoUpdate()788 }789 }790 791 func (t *Terminal) delChar() bool {51 unmodified lines843 func quoteEntry(entry string) string {844 return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'"845 }846 749-func executeCommand(template string, replacement string) {847+func (t *Terminal) executeCommand(template string, replacement string) {848 command := strings.Replace(template, "{}", replacement, -1)849 cmd := util.ExecCommand(command)850 cmd.Stdin = os.Stdin851 cmd.Stdout = os.Stdout852 cmd.Stderr = os.Stderr853 C.Endwin()854 cmd.Run()757- C.Refresh()855+ t.refresh()856 }857 858+func (t *Terminal) hasPreviewWindow() bool {859+ return t.previewBox != nil860+}861+862+func (t *Terminal) isPreviewEnabled() bool {863+ return t.previewBox != nil && t.previewing864+}865+866+func (t *Terminal) current() string {867+ return t.merger.Get(t.cy).AsString(t.ansi)868+}869+870 // Loop is called to start Terminal I/O871 func (t *Terminal) Loop() {872 <-t.startChan873 { // Late initialization14 unmodified lines888 }()889 890 t.mutex.Lock()891 t.initFunc()782- t.calculateMargins()892+ t.resizeWindows()893 t.printPrompt()894 t.placeCursor()785- C.Refresh()895+ t.refresh()896 t.printInfo()897 t.printHeader()898 t.mutex.Unlock()899 go func() {16 unmodified lines916 }917 }()918 }919 920+ if t.hasPreviewWindow() {921+ go func() {922+ for {923+ focused := ""924+ t.previewBox.Wait(func(events *util.Events) {925+ for req, value := range *events {926+ switch req {927+ case reqPreviewEnqueue:928+ focused = value.(string)929+ }930+ }931+ events.Clear()932+ })933+ if len(focused) > 0 {934+ command := strings.Replace(t.preview.command, "{}", quoteEntry(focused), -1)935+ cmd := util.ExecCommand(command)936+ out, _ := cmd.CombinedOutput()937+ t.reqBox.Set(reqPreviewDisplay, string(out))938+ }939+ }940+ }()941+ }942+943 exit := func(code int) {944 if code <= exitNoMatch && t.history != nil {945 t.history.append(string(t.input))946 }947 os.Exit(code)948 }949 950 go func() {951+ focused := ""952 for {953 t.reqBox.Wait(func(events *util.Events) {954 defer events.Clear()955 t.mutex.Lock()822- for req := range *events {956+ for req, value := range *events {957 switch req {958 case reqPrompt:959 t.printPrompt()960 if t.inlineInfo {2 unmodified lines963 case reqInfo:964 t.printInfo()965 case reqList:966 t.printList()967+ cnt := t.merger.Length()968+ if cnt > 0 && cnt > t.cy {969+ currentFocus := t.current()970+ if currentFocus != focused {971+ focused = currentFocus972+ if t.isPreviewEnabled() {973+ t.previewBox.Set(reqPreviewEnqueue, focused)974+ }975+ }976+ } else {977+ if focused != "" && t.isPreviewEnabled() {978+ t.pwindow.Erase()979+ }980+ focused = ""981+ }982 case reqJump:983 if t.merger.Length() == 0 {984 t.jumping = jumpDisabled985 }12 unmodified lines998 if t.output() {999 exit(exitOk)1000 }1001 exit(exitNoMatch)1002+ case reqPreviewDisplay:1003+ t.previewTxt = value.(string)1004+ t.printPreview()1005 case reqPrintQuery:1006 C.Close()1007 fmt.Println(string(t.input))1008 exit(exitOk)57 unmodified lines1066 case actIgnore:1067 case actExecute:1068 if t.cy >= 0 && t.cy < t.merger.Length() {1069 item := t.merger.Get(t.cy)918- executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))1070+ t.executeCommand(t.execmap[mapkey], quoteEntry(item.AsString(t.ansi)))1071 }1072 case actExecuteMulti:1073 if len(t.selected) > 0 {1074 sels := make([]string, len(t.selected))1075 for i, sel := range t.sortSelected() {1076 sels[i] = quoteEntry(*sel.text)1077 }926- executeCommand(t.execmap[mapkey], strings.Join(sels, " "))1078+ t.executeCommand(t.execmap[mapkey], strings.Join(sels, " "))1079 } else {1080 return doAction(actExecute, mapkey)1081 }1082 case actInvalid:1083 t.mutex.Unlock()1084 return false1085+ case actTogglePreview:1086+ if t.hasPreviewWindow() {1087+ t.previewing = !t.previewing1088+ t.resizeWindows()1089+ cnt := t.merger.Length()1090+ if t.previewing && cnt > 0 && cnt > t.cy {1091+ t.previewBox.Set(reqPreviewEnqueue, t.current())1092+ }1093+ req(reqList, reqInfo)1094+ }1095 case actToggleSort:1096 t.sort = !t.sort1097 t.eventBox.Set(EvtSearchNew, t.sort)1098 t.mutex.Unlock()159 unmodified lines1258 me := event.MouseEvent1259 mx, my := me.X, me.Y1260 if me.S != 0 {1261 // Scroll1100- if t.merger.Length() > 0 {1262+ if t.window.Enclose(my, mx) && t.merger.Length() > 0 {1263 if t.multi && me.Mod {1264 toggle()1265 }1266 t.vmove(me.S)1267 req(reqList)1268 }1107- } else if mx >= t.marginInt[3] && mx < C.MaxX()-t.marginInt[1] &&1108- my >= t.marginInt[0] && my < C.MaxY()-t.marginInt[2] {1109- mx -= t.marginInt[3]1110- my -= t.marginInt[0]1269+ } else if t.window.Enclose(my, mx) {1270+ mx -= t.window.Left1271+ my -= t.window.Top1272 mx = util.Constrain(mx-displayWidth([]rune(t.prompt)), 0, len(t.input))1273 if !t.reverse {1113- my = t.maxHeight() - my - 11274+ my = t.window.Height - my - 11275 }1276 min := 2 + len(t.header)1277 if t.inlineInfo {1278 min--98 unmodified lines1377 return t.cy == o1378 }1379 1380 func (t *Terminal) maxItems() int {1220- max := t.maxHeight() - 2 - len(t.header)1381+ max := t.window.Height - 2 - len(t.header)1382 if t.inlineInfo {1383 max++1384 }1385 return util.Max(max, 0)1 unmodified linemodified:test/test_go.rb+22 added
1226 unmodified lines1227 tmux.send_keys '3'1228 assert_equal '3', readonce.chomp1229 end1230 1231+ def test_preview1232+ tmux.send_keys %[seq 1000 | #{FZF} --preview 'echo {{}-{}}' --bind ?:toggle-preview], :Enter1233+ tmux.until { |lines| lines[1].include?(' {1-1}') }1234+ tmux.send_keys '555'1235+ tmux.until { |lines| lines[1].include?(' {555-555}') }1236+ tmux.send_keys '?'1237+ tmux.until { |lines| !lines[1].include?(' {555-555}') }1238+ tmux.send_keys '?'1239+ tmux.until { |lines| lines[1].include?(' {555-555}') }1240+ end1241+1242+ def test_preview_hidden1243+ tmux.send_keys %[seq 1000 | #{FZF} --preview 'echo {{}-{}}' --preview-window down:1:hidden --bind ?:toggle-preview], :Enter1244+ tmux.until { |lines| lines[-1] == '>' }1245+ tmux.send_keys '?'1246+ tmux.until { |lines| lines[-2].include?(' {1-1}') }1247+ tmux.send_keys '555'1248+ tmux.until { |lines| lines[-2].include?(' {555-555}') }1249+ tmux.send_keys '?'1250+ tmux.until { |lines| lines[-1] == '> 555' }1251+ end1252+1253 private1254 def writelines path, lines1255 File.unlink path while File.exists? path1256 File.open(path, 'w') { |f| f << lines.join($/) + $/ }335 unmodified lines