peco

package module
v0.2.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2014 License: MIT Imports: 20 Imported by: 3

README

peco

Simplistic interactive filtering tool

Description

peco (pronounced peh-koh) is based on a python tool, percol. percol was darn useful, but I wanted a tool that was a single binary, and forget about python. peco is written in Go, and therefore you can just grab the binary releases and drop it in your $PATH.

peco can be a great tool to filter stuff like logs, process stats, find files, because unlike grep, you can type as you think and look through the current results.

For basic usage, continue down below. For more cool elaborate usage samples, please see the wiki, and if you have any other tricks you want to share, please add to it!

Demo

Demos speak more than a thousand words! Here's me looking for a process on my mac. As you can see, you can page through your results, and you can keep changing the query:

optimized

Here's me trying to figure out which file to open:

optimized

When you combine tools like zsh, peco, and ghq, you can make managing/moving around your huge dev area a piece of cake! (this example doesn't use zsh functions so you can see what I'm doing)

optimized

Features

Search results are filtered as you type. This is great to drill down to the line you are looking for

Multiple terms turn the query into an "AND" query:

optimized

When you find that line that you want, press enter, and the resulting line is printed to stdout, which allows you to pipe it to other tools

Select Multiple Lines

You can select multiple lines!

optimized

Select Range Of Lines

Not only can you select multiple lines one by one, you can select a range of lines (Note: The ToggleRangeMode action is not enabled by default. You need to put a custom key binding in your config file)

optimized

Select Matchers

Different types of matchers are available. Default is case-insensitive matcher, so lines with any case will match. You can toggle between IgnoreCase, CaseSensitive, SmartCase and RegExp matchers.

The SmartCase matcher uses case-insensitive matching when the all of the queries iare lower case, and case-sensitive matching otherwise.

The RegExp matcher allows you to use any valid regular expression to match lines

optimized

Selectable Layout

As of v0.2.5, if you would rather not move your eyes off of the bottom of the screen, you can change the screen layout by either proviging the --layout=bottom-up command line option, or set the Layout variable in your configuration file

optmized

Works on Windows!

I have been told that peco even works on windows :) Look ma! I'm not lying!

optimized

Installation

Just want the binary?

Go to the releases page, find the version you want, and download the zip file. Unpack the zip file, and put the binary to somewhere you want (on UNIX-y systems, /usr/local/bin or the like). Make sure it has execution bits turned on. Yes, it is a single binary! You can put it anywhere you want :)

THIS IS THE RECOMMENDED WAY (except for OS X homebrew users)

Mac OS X / Homebrew

If you're on OS X and want to use homebrew, use my custom tap:

brew tap peco/peco
brew install peco

optimized

Windows (Chocolatey NuGet Users)

There's a third-party peco package available for Chocolatey NuGet.

C:\> choco install peco
go get

If you want to go the Go way (install in GOPATH/bin) and just want the command:

go get github.com/peco/peco/cmd/peco

Command Line Options

-h, --help

Display a help message

--version

Display the version of peco

--query

Specifies the default query to be used upon startup. This is useful for scripts and functions where you can figure out before hand what the most likely query string is.

--rcfile

Pass peco a configuration file, which currently must be a JSON file. If unspecified it will try a series of files by default. See Configuration File for the actual locationes searched.

-b, --buffer-size

Limits the buffer size to num. This is an important feature when you are using peco against a possibbly infinite stream, as it limits the number of lines that peco holds at any given time, preventing it from exhausting all the memory. By default the buffer size is unlimited.

--null

WARNING: EXPERIMENTAL. This feature will probably stay, but the option name may change in the future.

Changes how peco interprets incoming data. When this flag is set, you may insert NUL ('\0') characters in your input. Anything before the NUL character is treated as the string to be displaed by peco and is used for matching against user query. Anything after the NUL character is used as the "result": i.e., when peco is about to exit, it displays this string instead of the original string displayed.

Here's a simple example of how to use this feature

--no-ignore-case

This option has been DEPRECATED. Use --initial-matcher instead.

By default peco starts in case insensitive mode. When this option is specified, peco will start in case sensitive mode. This can be toggled while peco is still in session.

--initial-index

Specifies the initial line position upon start up. E.g. If you want to start out with the second line selected, set it to "1" (because the index is 0 based)

--initial-matcher IgnoreCase|CaseSensitive|SmartCase|Regexp

Specifies the initial matcher to use upon start up. You should specify the name of the macher like IgnoreCase, CaseSensitive, SmartCase and Regexp. Default is IgnoreCase.

--prompt

Specifies the query line's prompt string. When specified, takes precedence over the configuration file's Prompt section. The default value is QUERY>

--layout top-down|bottom-up

Specifies the display layout. Default is top-down, where query prompt is at the top, followed by the list, then the system status message line. bottom-up changes this to the list first (displayed in reverse order), the query prompt, and then the system status message line.

For percol users, --layout=bottom-up is almost equivalent of --prompt-bottom --result-bottom-up.

Configuration File

peco by default consults a few locations for the config files.

  1. Location specified in --rcfile. If this doesn't exist, peco complains and exits
  2. $XDG_CONFIG_HOME/config.json
  3. $HOME/.config/peco/config.json
  4. for each directories listed in $XDG_CONFIG_DIRS, $DIR/peco/config.json
  5. If all else fails, $HOME/.peco/config.json

Below are configuration sections that you may specify in your config file:

Keymaps

Example:

{
    "Keymap": {
        "M-v": "peco.ScrollPageUp",
        "C-v": "peco.ScrollPageDown",
        "C-x,C-c": "peco.Cancel"
    }
}
Key sequences

As of v0.2.0, you can use a list of keys (separated by comma) to register an action that is associated with a key sequence (instead of a single key). Please note that if there is a conflict in the key map, the longest sequence always wins. So In the above example, if you add another sequence, say, C-x,C-c,C-c, then the above peco.Cancel will never be invoked.

Combined actions

As of v0.2.1, you can create custom combined actions. For example, if you find yourself repeatedly needing to select 4 lines out of the list, you may want to define your own action like this:

{
    "Action": {
        "foo.SelectFour": [
            "peco.ToggleRangeMode",
            "peco.SelectDown",
            "peco.SelectDown",
            "peco.SelectDown",
            "peco.ToggleRangeMode"
        ]
    },
    "Keymap": {
        "M-f": "foo.SelectFour"
    }
}

This creates a new combined action foo.SelectFour (the format of the name is totally arbitrary, I just like to put namespaces), and assigns that action to M-f. When it's fired, it toggles the range selection mode and highlights 4 lines, and then goes back to waiting for your input.

As a similar example, a common idiom in emacs is that C-c C-c means "take the contents of this buffer and accept it", whatever that means. This adds exactly that keybinding:

{
    "Action": {
        "selectAllAndFinish": [
            "peco.SelectAll",
            "peco.Finish"
        ]
    },
    "Keymap": {
        "C-c,C-c": "selectAllAndFinish"
    }
}
Available keys

Since v0.1.8, in addition to values below, you may put a M- prefix on any key item to use Alt/Option key as a mask.

Name Notes
C-a ... C-z Control + whatever character
C-1 ... C-8 Control + 1..8
C-[
C-]
C-~
C-_
C-\\ Note that you need to escape the backslash
C-/
Esc
Tab
Insert
Delete
Home
End
Pgup
Pgdn
ArrowUp
ArrowDown
ArrowLeft
ArrowRight
Key workarounds

Some keys just... don't map correctly / too easily for various reasons. Here, we'll list possible workarounds for key sequences that are often asked for:

You want this Use this instead Notes
Shift+Tab M-[,Z Verified on OS X
Available actions
Name Notes
peco.ForwardChar Move caret forward 1 character
peco.BackwardChar Move caret backward 1 character
peco.ForwardWord Move caret forward 1 word
peco.BackwardWord Move caret backward 1 word
peco.BeginningOfLine Move caret to the beginning of line
peco.EndOfLine Move caret to the end of line
peco.EndOfFile Delete one character forward, otherwise exit from peco with failure status
peco.DeleteForwardChar Delete one character forward
peco.DeleteBackwardChar Delete one character backward
peco.DeleteForwardWord Delete one word forward
peco.DeleteBackwardWord Delete one word backward
peco.KillEndOfLine Delete the characters under the cursor until the end of the line
peco.DeleteAll Delete all entered characters
peco.RefreshScreen Redraws the screen. Note that this effectively re-runs your query
peco.SelectPreviousPage (DEPRECATED) Alias to ScrollPageUp
peco.SelectNextPage (DEPRECATED) Alias to ScrollPageDown
peco.ScrollPageDown Moves the selected line cursor for an entire page, downwards
peco.ScrollPageUp Moves the selected line cursor for an entire page, upwards
peco.SelectUp Moves the selected line cursor to one line above
peco.SelectDown Moves the selected line cursor to one line below
peco.SelectPrevious (DEPRECATED) Alias to SelectUp
peco.SelectNext (DEPRECATED) Alias to SelectDown
peco.ToggleSelection Selects the current line, and saves it
peco.ToggleSelectionAndSelectNext Selects the current line, saves it, and proceeds to the next line
peco.ToggleRangeMode Start selecting by range, or append selecting range to selections
peco.CancelRangeMode Finish selecting by range and cancel range selection
peco.RotateMatcher Rotate between matchers (by default, ignore-case/no-ignore-case)
peco.Finish Exits from peco with success status
peco.Cancel Exits from peco with failure status, or cancel select mode
Default Keymap

Note: If in case below keymap seems wrong, check the source code in keymap.go (look for NewKeymap).

Key Action
Esc peco.Cancel
Ctrl-c peco.Cancel
Enter peco.Finish
Ctrl-f peco.ForwardChar
Ctrl-a peco.BeginningOfLine
Ctrl-b peco.BackwardChar
Ctrl-d peco.DeleteForwardChar
Ctrl-e peco.EndOfLine
Ctrl-k peco.KillEndOfLine
Ctrl-l peco.RefreshScreen
Ctrl-n peco.SelectDown
Ctrl-p peco.SelectUp
Ctrl-u peco.KillBeginOfLine
Ctrl-r peco.RotateMatcher
Ctrl-w peco/DeleteBackwardWord
Ctrl-space peco.ToggleSelectionAndSelectNext
ArrorUp peco.SelectPrevious
ArrowDown peco.SelectNext
ArrowLeft peco.SelectPreviousPage
ArrowRight peco.SelectNextPage
Backspace peco.DeleteBackwardChar

Styles

For now, styles of following 5 items can be customized in config.json.

{
    "Style": {
        "Basic": ["on_default", "default"],
        "SavedSelection": ["bold", "on_yellow", "white"],
        "Selected": ["underline", "on_cyan", "black"],
        "Query": ["yellow", "bold"],
        "Matched": ["red", "on_blue"]
    }
}
  • Basic for not selected lines
  • SavedSelection for lines of saved selection
  • Selected for a currently selecting line
  • Query for a query line
  • Matched for a query matched word
Foreground Colors
  • "black" for termbox.ColorBlack
  • "red" for termbox.ColorRed
  • "green" for termbox.ColorGreen
  • "yellow" for termbox.ColorYellow
  • "blue" for termbox.ColorBlue
  • "magenta" for termbox.ColorMagenta
  • "cyan" for termbox.ColorCyan
  • "white" for termbox.ColorWhite
Background Colors
  • "on_black" for termbox.ColorBlack
  • "on_red" for termbox.ColorRed
  • "on_green" for termbox.ColorGreen
  • "on_yellow" for termbox.ColorYellow
  • "on_blue" for termbox.ColorBlue
  • "on_magenta" for termbox.ColorMagenta
  • "on_cyan" for termbox.ColorCyan
  • "on_white" for termbox.ColorWhite
Attributes
  • "bold" for fg: termbox.AttrBold
  • "underline" for fg: termbox.AttrUnderline
  • "reverse" for fg: termbox.AttrReverse
  • "on_bold" for bg: termbox.AttrBold (this attribute actually makes the background blink on some platforms/environments, e.g. linux console, xterm...)

CustomMatcher

This is an experimental feature. Please note that some details of this specificaiton may change

By default peco comes with IgnoreCase, CaseSensitive, SmartCase and Regexp matchers, but since v0.1.3, it is possible to create your own custom matcher.

The matcher will be executed via Command.Run() as an external process, and it will be passed the query values in the command line, and the original unaltered buffer is passed via os.Stdin. Your matcher must perform the matching, and print out to os.Stdout matched lines. Note that currently there is no way to specify where in the line the match occurred. Note that the matcher does not need to be a go program. It can be a perl/ruby/python/bash script, or anything else that is executable.

Once you have a matcher, you must specify how the matcher is spawned:

{
    "CustomMatcher": {
        "MyMatcher": [ "/path/to/my-matcher", "$QUERY" ]
    }
}

Elements in the CustomMatcher section are string keys to array of program arguments. The special token $QUERY will be replaced with the unaltered query as the user typed in (i.e. multiple-word queries will be passed as a single string). You may pass in any other arguments in this array.

You may specify as many matchers as you like.

Examples

Prompt

You can change the query line's prompt, which is QUERY> by default.

{
    "Prompt": "[peco]"
}

InitialMatcher

Specifies the matcher name to start peco with. You should specify the name of the matcher, such as IgnoreCase, CaseSensitive, SmartCase and Regexp

Note: Matcher key has been deprecated in favor of InitialMatcher. Matcher will be unavailable in peco 0.3.0

Layout

See --layout.

Hacking

First, fork this repo, and get your clone locally.

  1. Make sure you have go 1.x, with GOPATH appropriately set
  2. Run go get github.com/jessevdk/go-flags
  3. Run go get github.com/mattn/go-runewidth
  4. Run go get github.com/nsf/termbox-go

Then from the root of this repository run:

go build cmd/peco/peco.go

This will create a peco binary in the local directory.

TODO

Test it. In doing so, we may change the repo structure

Implement all(?) of the original percol options

AUTHORS

  • Daisuke Maki (lestrrat)
  • mattn
  • syohex

CONTRIBUTORS

  • HIROSE Masaaki
  • Joel Segerlind
  • Lukas Lueg
  • Mitsuoka Mimura
  • Ryota Arai
  • Shinya Ohyanagi
  • Takashi Kokubun
  • Yuya Takeyama
  • cho45
  • cubicdaiya
  • kei_q
  • negipo
  • sona_tar
  • sugyan
  • swdyh
  • MURAOKA Taro (kaoriya/koron), for aho-corasick search
  • taichi, for the gif working on Windows
  • uobikiemukot
  • Samuel Lemaitre
  • Yousuke Ushiki
  • Linda_pp

Notes

Obviously, kudos to the original percol: https://github.com/mooz/percol Much code stolen from https://github.com/mattn/gof

Documentation

Index

Constants

View Source
const (
	// LayoutTypeTopDown is the default. All the items read from top to bottom
	LayoutTypeTopDown = "top-down"
	// LayoutTypeBottomUp changes the layout to read from bottom to up
	LayoutTypeBottomUp = "bottom-up"
)
View Source
const (
	IgnoreCaseMatch    = "IgnoreCase"
	CaseSensitiveMatch = "CaseSensitive"
	SmartCaseMatch     = "SmartCase"
	RegexpMatch        = "Regexp"
)

These are used as keys in the config file

Variables

This section is empty.

Functions

func IsTty

func IsTty(fd uintptr) bool

IsTty checks if the given fd is a tty

func IsValidLayoutType added in v0.2.5

func IsValidLayoutType(v LayoutType) bool

IsValidLayoutType checks if a string is a supported layout type

func IsValidVerticalAnchor added in v0.2.6

func IsValidVerticalAnchor(anchor VerticalAnchor) bool

IsValidVerticalAnchor checks if the specified anchor is supported

func LocateRcfile added in v0.1.3

func LocateRcfile() (string, error)

LocateRcfile attempts to find the config file in various locations

func TtyReady

func TtyReady() error

TtyReady checks if the tty is ready to go

func TtyTerm

func TtyTerm()

TtyTerm restores any state, if necessary

Types

type Action added in v0.2.0

type Action interface {
	Register(string, ...termbox.Key)
	RegisterKeySequence(keyseq.KeyList)
	Execute(*Input, termbox.Event)
}

Action describes an action that can be executed upon receiving user input. It's an interface so you can create any kind of Action you need, but most everything is implemented in terms of ActionFunc, which is callback based Action

type ActionFunc added in v0.2.0

type ActionFunc func(*Input, termbox.Event)

ActionFunc is a type of Action that is basically just a callback.

func (ActionFunc) Execute added in v0.2.0

func (a ActionFunc) Execute(i *Input, e termbox.Event)

Execute fulfills the Action interface for AfterFunc

func (ActionFunc) Register added in v0.2.0

func (a ActionFunc) Register(name string, defaultKeys ...termbox.Key)

Register fulfills the Actin interface for AfterFunc. Registers `a` into the global action registry by the name `name`, and maps to default keys via `defaultKeys`

func (ActionFunc) RegisterKeySequence added in v0.2.0

func (a ActionFunc) RegisterKeySequence(k keyseq.KeyList)

RegisterKeySequence satisfies the Action interface for AfterFun. Registers the action to be mapped against a key sequence

type AnchorSettings added in v0.2.5

type AnchorSettings struct {
	// contains filtered or unexported fields
}

AnchorSettings groups items that are required to control where an anchored item is actually placed

func NewAnchorSettings added in v0.2.6

func NewAnchorSettings(anchor VerticalAnchor, offset int) *AnchorSettings

NewAnchorSettings creates a new AnchorSetting struct. Panics if an unknown VerticalAnchor is sent

func (AnchorSettings) AnchorPosition added in v0.2.5

func (as AnchorSettings) AnchorPosition() int

AnchorPosition returns the starting y-offset, based on the anchor type and offset

type BasicLayout added in v0.2.5

type BasicLayout struct {
	*Ctx
	*StatusBar
	// contains filtered or unexported fields
}

BasicLayout is... the basic layout :) At this point this is the only struct for layouts, which means that while the position of components may be configurable, the actual types of components that are used are set and static

func NewBottomUpLayout added in v0.2.5

func NewBottomUpLayout(ctx *Ctx) *BasicLayout

NewBottomUpLayout creates a new Layout in bottom-up format

func NewDefaultLayout added in v0.2.5

func NewDefaultLayout(ctx *Ctx) *BasicLayout

NewDefaultLayout creates a new Layout in the default format (top-down)

func (*BasicLayout) CalculatePage added in v0.2.5

func (l *BasicLayout) CalculatePage(targets []Match, perPage int) error

CalculatePage calculates which page we're displaying

func (*BasicLayout) DrawPrompt added in v0.2.9

func (l *BasicLayout) DrawPrompt()

func (*BasicLayout) DrawScreen added in v0.2.5

func (l *BasicLayout) DrawScreen(targets []Match)

DrawScreen draws the entire screen

func (*BasicLayout) MovePage added in v0.2.5

func (l *BasicLayout) MovePage(p PagingRequest)

MovePage moves the cursor

type BufferReader added in v0.1.12

type BufferReader struct {
	*Ctx
	// contains filtered or unexported fields
}

BufferReader reads lines from the input, either Stdin or a file. If the incoming data is endless, it keeps reading and adding to the search buffer, as long as it can.

If you would like to limit the number of lines to keep in the buffer, you should set --buffer-size to a number > 0

func (*BufferReader) InputReadyCh added in v0.2.0

func (b *BufferReader) InputReadyCh() <-chan struct{}

InputReadyCh returns a channel which, when the input starts coming in, sends a struct{}{}

func (*BufferReader) Loop added in v0.1.12

func (b *BufferReader) Loop()

Loop keeps reading from the input

type CaretPosition added in v0.2.6

type CaretPosition int

func (CaretPosition) CaretPos added in v0.2.6

func (p CaretPosition) CaretPos() CaretPosition

func (CaretPosition) Int added in v0.2.6

func (p CaretPosition) Int() int

func (*CaretPosition) MoveCaretPos added in v0.2.6

func (p *CaretPosition) MoveCaretPos(offset int)

func (*CaretPosition) SetCaretPos added in v0.2.6

func (p *CaretPosition) SetCaretPos(where int)

type CaseSensitiveMatcher added in v0.1.1

type CaseSensitiveMatcher struct {
	*RegexpMatcher
}

CaseSensitiveMatcher extends the RegxpMatcher, but always turns off the ignore-case flag in the regexp

func NewCaseSensitiveMatcher added in v0.1.2

func NewCaseSensitiveMatcher(enableSep bool) *CaseSensitiveMatcher

NewCaseSensitiveMatcher creates a new CaseSensitiveMatcher

func (*CaseSensitiveMatcher) String added in v0.1.1

func (m *CaseSensitiveMatcher) String() string

type Config

type Config struct {
	Action map[string][]string `json:"Action"`
	// Keymap used to be directly responsible for dispatching
	// events against user input, but since then this has changed
	// into something that just records the user's config input
	Keymap         map[string]string `json:"Keymap"`
	Matcher        string            `json:"Matcher"`        // Deprecated.
	InitialMatcher string            `json:"InitialMatcher"` // Use this instead of Matcher
	Style          *StyleSet         `json:"Style"`
	Prompt         string            `json:"Prompt"`
	Layout         string            `json:"Layout"`
	CustomMatcher  map[string][]string
}

Config holds all the data that can be configured in the external configuran file

func NewConfig

func NewConfig() *Config

NewConfig creates a new Config

func (*Config) ReadFilename

func (c *Config) ReadFilename(filename string) error

ReadFilename reads the config from the given file, and does the appropriate processing, if any

type Ctx

type Ctx struct {
	*Hub
	CaretPosition
	FilterQuery

	Matchers []Matcher
	// contains filtered or unexported fields
}

Ctx contains all the important data. while you can easily access data in this struct from anwyehre, only do so via channels

func NewCtx

func NewCtx(o CtxOptions) *Ctx

func (*Ctx) AddMatcher added in v0.1.2

func (c *Ctx) AddMatcher(m Matcher) error

func (*Ctx) AddWaitGroup

func (c *Ctx) AddWaitGroup(v int)

func (*Ctx) Buffer

func (c *Ctx) Buffer() []Match

func (*Ctx) DrawMatches

func (c *Ctx) DrawMatches(m []Match)

func (*Ctx) DrawPrompt added in v0.2.9

func (c *Ctx) DrawPrompt()

func (*Ctx) ExecQuery

func (c *Ctx) ExecQuery() bool

func (Ctx) ExitStatus

func (c Ctx) ExitStatus() int

ExitStatus() returns the exit status that we think should be used

func (*Ctx) ExitWith added in v0.1.11

func (c *Ctx) ExitWith(i int)

func (*Ctx) IsBufferOverflowing added in v0.2.0

func (c *Ctx) IsBufferOverflowing() bool

func (*Ctx) IsRangeMode added in v0.2.0

func (c *Ctx) IsRangeMode() bool

func (*Ctx) LoadCustomMatcher added in v0.1.3

func (c *Ctx) LoadCustomMatcher() error

func (*Ctx) Matcher added in v0.1.1

func (c *Ctx) Matcher() Matcher

func (*Ctx) NewBufferReader added in v0.1.12

func (c *Ctx) NewBufferReader(r io.ReadCloser) *BufferReader

func (*Ctx) NewFilter

func (c *Ctx) NewFilter() *Filter

func (*Ctx) NewInput

func (c *Ctx) NewInput() *Input

func (*Ctx) NewSignalHandler added in v0.2.0

func (c *Ctx) NewSignalHandler() *signalHandler

func (*Ctx) NewView

func (c *Ctx) NewView() *View

func (*Ctx) ReadConfig

func (c *Ctx) ReadConfig(file string) error

func (*Ctx) Refresh

func (c *Ctx) Refresh()

func (*Ctx) ReleaseWaitGroup

func (c *Ctx) ReleaseWaitGroup()

func (*Ctx) Result

func (c *Ctx) Result() []Match

func (*Ctx) RotateMatcher added in v0.2.6

func (c *Ctx) RotateMatcher()

RotateMatcher rotates the matchers

func (*Ctx) SelectedRange added in v0.2.0

func (c *Ctx) SelectedRange() Selection

func (*Ctx) SetCurrentMatcher added in v0.1.2

func (c *Ctx) SetCurrentMatcher(n string) bool

func (*Ctx) SetPrompt added in v0.2.0

func (c *Ctx) SetPrompt(p string)

func (*Ctx) SetQuery

func (c *Ctx) SetQuery(q []rune)

func (*Ctx) WaitDone

func (c *Ctx) WaitDone()

type CtxOptions added in v0.2.0

type CtxOptions interface {
	// EnableNullSep should return if the null separator is
	// enabled (--null)
	EnableNullSep() bool

	// BufferSize should return the buffer size. By default (i.e.
	// when it returns 0), the buffer size is unlimited.
	// (--buffer-size)
	BufferSize() int

	// InitialIndex is the line number to put the cursor on
	// when peco starts
	InitialIndex() int

	// LayoutType returns the name of the layout to use
	LayoutType() string
}

CtxOptions is the interface that defines that options can be passed in from the command line

type CustomMatcher added in v0.1.3

type CustomMatcher struct {
	// contains filtered or unexported fields
}

CustomMatcher spawns a new process to filter the buffer in peco, and uses the output in its Stdout to figure out what to display

func NewCustomMatcher added in v0.1.3

func NewCustomMatcher(enableSep bool, name string, args []string) *CustomMatcher

NewCustomMatcher creates a new CustomMatcher

func (*CustomMatcher) Match added in v0.1.3

func (m *CustomMatcher) Match(quit chan struct{}, q string, buffer []Match) []Match

Match matches `q` aginst `buffer`

func (*CustomMatcher) String added in v0.1.3

func (m *CustomMatcher) String() string

func (*CustomMatcher) Verify added in v0.1.11

func (m *CustomMatcher) Verify() error

Verify checks to see that the executable given to CustomMatcher is actual found and is executable via exec.LookPath

type DidMatch added in v0.1.3

type DidMatch struct {
	// contains filtered or unexported fields
}

DidMatch contains the actual match, and the indices to the matches in the line

func NewDidMatch added in v0.1.5

func NewDidMatch(v string, enableSep bool, m [][]int) *DidMatch

NewDidMatch creates a new DidMatch struct

func (DidMatch) Buffer added in v0.2.1

func (m DidMatch) Buffer() string

func (DidMatch) Indices added in v0.1.3

func (d DidMatch) Indices() [][]int

Indices returns the indices in the buffer that matched

func (DidMatch) Line added in v0.1.3

func (m DidMatch) Line() string

func (DidMatch) Output added in v0.2.1

func (m DidMatch) Output() string

type Filter

type Filter struct {
	*Ctx
	// contains filtered or unexported fields
}

Filter is responsible for the actual "grep" part of peco

func (*Filter) Loop

func (f *Filter) Loop()

Loop keeps watching for incoming queries, and upon receiving a query, spawns a goroutine to do the heavy work. It also checks for previously running queries, so we can avoid running many goroutines doing the grep at the same time

func (*Filter) Work added in v0.1.3

func (f *Filter) Work(cancel chan struct{}, q HubReq)

Work is the actual work horse that that does the matching in a goroutine of its own. It wraps Matcher.Match().

type FilterQuery added in v0.2.6

type FilterQuery []rune

func (*FilterQuery) AppendQuery added in v0.2.6

func (q *FilterQuery) AppendQuery(r rune)

func (*FilterQuery) InsertQueryAt added in v0.2.6

func (q *FilterQuery) InsertQueryAt(ch rune, where int)

func (FilterQuery) Query added in v0.2.6

func (q FilterQuery) Query() FilterQuery

func (FilterQuery) QueryLen added in v0.2.6

func (q FilterQuery) QueryLen() int

func (FilterQuery) QueryString added in v0.2.9

func (q FilterQuery) QueryString() string

type Hub added in v0.2.1

type Hub struct {
	// contains filtered or unexported fields
}

Hub acts as the messaging hub between components -- that is, it controls how the communication that goes through channels are handled.

func NewHub added in v0.2.1

func NewHub() *Hub

NewHub creates a new Hub struct

func (*Hub) Batch added in v0.2.1

func (h *Hub) Batch(f func())

Batch allows you to synchronously send messages during the scope of f() being executed.

func (*Hub) DrawCh added in v0.2.1

func (h *Hub) DrawCh() chan HubReq

DrawCh returns the channel to redraw the terminal display

func (*Hub) LoopCh added in v0.2.1

func (h *Hub) LoopCh() chan struct{}

LoopCh returns the channel to control the main execution loop. Nothing should ever be sent through this channel. The only way the channel communicates anything to its receivers is when it is closed -- which is when peco is done.

func (*Hub) PagingCh added in v0.2.1

func (h *Hub) PagingCh() chan HubReq

PagingCh returns the channel to page through the results

func (*Hub) QueryCh added in v0.2.1

func (h *Hub) QueryCh() chan HubReq

QueryCh returns the underlying channel for queries

func (*Hub) SendDraw added in v0.2.1

func (h *Hub) SendDraw(matches []Match)

SendDraw sends a request to redraw the terminal display

func (*Hub) SendDrawPrompt added in v0.2.9

func (h *Hub) SendDrawPrompt()

SendDrawPrompt sends a request to redraw the prompt only

func (*Hub) SendPaging added in v0.2.1

func (h *Hub) SendPaging(x PagingRequest)

SendPaging sends a request to move the cursor around

func (*Hub) SendQuery added in v0.2.1

func (h *Hub) SendQuery(q string)

SendQuery sends the query string to be processed by the Filter

func (*Hub) SendStatusMsg added in v0.2.1

func (h *Hub) SendStatusMsg(q string)

SendStatusMsg sends a string to be displayed in the status message

func (*Hub) SendStatusMsgAndClear added in v0.2.10

func (h *Hub) SendStatusMsgAndClear(q string, clearDelay time.Duration)

func (*Hub) StatusMsgCh added in v0.2.1

func (h *Hub) StatusMsgCh() chan HubReq

StatusMsgCh returns the channel to update the status message

func (*Hub) Stop added in v0.2.1

func (h *Hub) Stop()

Stop closes the LoopCh so that peco shutsdown

type HubReq added in v0.2.1

type HubReq struct {
	// contains filtered or unexported fields
}

HubReq is a wrapper around the actual requst value that needs to be passed. It contains an optional channel field which can be filled to force synchronous communication between the sender and receiver

func (HubReq) DataInterface added in v0.2.1

func (hr HubReq) DataInterface() interface{}

DataInterface returns the underlying data as interface{}

func (HubReq) DataString added in v0.2.1

func (hr HubReq) DataString() string

DataString returns the underlying data as a string. Panics if type conversion fails.

func (HubReq) Done added in v0.2.1

func (hr HubReq) Done()

Done marks the request as done. If Hub is operating in asynchronous mode (default), it's a no op. Otherwise it sends a message back the reply channel to finish up the synchronous communication

type IgnoreCaseMatcher added in v0.1.1

type IgnoreCaseMatcher struct {
	*RegexpMatcher
}

IgnoreCaseMatcher extends the RegexpMatcher, and always turns ON the ignore-case flag in the regexp

func NewIgnoreCaseMatcher added in v0.1.2

func NewIgnoreCaseMatcher(enableSep bool) *IgnoreCaseMatcher

NewIgnoreCaseMatcher creates a new IgnoreCaseMatcher

func (*IgnoreCaseMatcher) String added in v0.1.1

func (m *IgnoreCaseMatcher) String() string

type Input

type Input struct {
	*Ctx
	// contains filtered or unexported fields
}

Input handles input events from termbox.

func (*Input) Loop

func (i *Input) Loop()

Loop watches for incoming events from termbox, and pass them to the appropriate handler when something arrives.

type Keymap

type Keymap struct {
	Config map[string]string
	Action map[string][]string // custom actions
	Keyseq *keyseq.Keyseq
}

Keymap holds all the key sequence to action map

func NewKeymap

func NewKeymap(config map[string]string, actions map[string][]string) Keymap

NewKeymap creates a new Keymap struct

func (Keymap) ApplyKeybinding added in v0.2.0

func (km Keymap) ApplyKeybinding()

ApplyKeybinding applies all of the custom key bindings on top of the default key bindings

func (Keymap) Handler

func (km Keymap) Handler(ev termbox.Event) Action

Handler returns the appropriate action for the given termbox event

type Layout added in v0.2.5

type Layout interface {
	PrintStatus(string, time.Duration)
	DrawPrompt()
	DrawScreen([]Match)
	MovePage(PagingRequest)
}

Layout represents the component that controls where elements are placed on screen

type LayoutType added in v0.2.5

type LayoutType string

LayoutType describes the types of layout that peco can take

type ListArea added in v0.2.5

type ListArea struct {
	*Ctx
	*AnchorSettings
	// contains filtered or unexported fields
}

ListArea represents the area where the actual line buffer is displayed in the screen

func NewListArea added in v0.2.5

func NewListArea(ctx *Ctx, anchor VerticalAnchor, anchorOffset int, sortTopDown bool) *ListArea

NewListArea creates a new ListArea struct

func (*ListArea) Draw added in v0.2.5

func (l *ListArea) Draw(targets []Match, perPage int)

Draw displays the ListArea on the screen

type Match

type Match interface {
	Buffer() string // Raw buffer, may contain null
	Line() string   // Line to be displayed
	Output() string // Output string to be displayed after peco is done
	Indices() [][]int
}

Match defines the interface for matches. Note that to make drawing easier, we have a DidMatch and NoMatch types instead of using []Match and []string.

type Matcher added in v0.1.1

type Matcher interface {
	// Match takes in three parameters.
	//
	// The first chan is the channel where cancel requests are sent.
	// If you receive a request here, you should stop running your query.
	//
	// The second is the query. Do what you want with it
	//
	// The third is the buffer in which to match the query against.
	Match(chan struct{}, string, []Match) []Match
	String() string

	// This is fugly. We just added a method only for CustomMatcner.
	// Must think about this again
	Verify() error
}

Matcher interface defines the API for things that want to match against the buffer

type NoMatch added in v0.1.3

type NoMatch struct {
	// contains filtered or unexported fields
}

NoMatch is actually an alias to a regular string. It implements the Match interface, but just returns the underlying string with no matches

func NewNoMatch added in v0.1.5

func NewNoMatch(v string, enableSep bool) *NoMatch

NewNoMatch creates a NoMatch struct

func (NoMatch) Buffer added in v0.2.1

func (m NoMatch) Buffer() string

func (NoMatch) Indices added in v0.1.3

func (m NoMatch) Indices() [][]int

Indices always returns nil

func (NoMatch) Line added in v0.1.3

func (m NoMatch) Line() string

func (NoMatch) Output added in v0.2.1

func (m NoMatch) Output() string

type PageInfo added in v0.2.1

type PageInfo struct {
	// contains filtered or unexported fields
}

type PagingRequest

type PagingRequest int

PagingRequest can be sent to move the selection cursor

const (
	// ToLineAbove moves the selection to the line above
	ToLineAbove PagingRequest = iota
	// ToScrollPageDown moves the selection to the next page
	ToScrollPageDown
	// ToLineBelow moves the selection to the line below
	ToLineBelow
	// ToScrollPageUp moves the selection to the previous page
	ToScrollPageUp
)

type RegexpMatcher added in v0.1.2

type RegexpMatcher struct {
	// contains filtered or unexported fields
}

RegexpMatcher is the most basic matcher

func NewRegexpMatcher added in v0.1.2

func NewRegexpMatcher(enableSep bool) *RegexpMatcher

NewRegexpMatcher creates a new RegexpMatcher

func (*RegexpMatcher) Match added in v0.1.2

func (m *RegexpMatcher) Match(quit chan struct{}, q string, buffer []Match) []Match

Match does the heavy lifting, and matches `q` against `buffer`. While it is doing the match, it also listens for messages via `quit`. If anything is received via `quit`, the match is halted.

func (*RegexpMatcher) MatchAllRegexps added in v0.1.2

func (m *RegexpMatcher) MatchAllRegexps(regexps []*regexp.Regexp, line string) [][]int

MatchAllRegexps matches all the regexps in `regexps` against line

func (*RegexpMatcher) String added in v0.1.2

func (m *RegexpMatcher) String() string

func (*RegexpMatcher) Verify added in v0.1.11

func (m *RegexpMatcher) Verify() error

Verify always returns nil

type Screen added in v0.2.6

type Screen interface {
	Clear(termbox.Attribute, termbox.Attribute) error
	Flush() error
	PollEvent() chan termbox.Event
	SetCell(int, int, rune, termbox.Attribute, termbox.Attribute)
	Size() (int, int)
}

Screen hides termbox from tne consuming code so that it can be swapped out for testing

type Selection added in v0.1.3

type Selection []int

Selection stores the line numbers that were selected by the user. The contents of the Selection is always sorted from smallest to largest line number

func (*Selection) Add added in v0.1.3

func (s *Selection) Add(v int)

Add adds a new line number to the selection. If the line already exists in the selection, it is silently ignored

func (*Selection) Clear added in v0.1.3

func (s *Selection) Clear()

Clear empties the selection

func (Selection) Has added in v0.1.3

func (s Selection) Has(v int) bool

Has returns true if line `v` is in the selection

func (Selection) Len added in v0.1.3

func (s Selection) Len() int

Len returns the number of elements in the selection. Satisfies sort.Interface

func (Selection) Less added in v0.1.3

func (s Selection) Less(i, j int) bool

Less returns true if element at index i is less than the element at index j. Satisfies sort.Interface

func (*Selection) Remove added in v0.1.3

func (s *Selection) Remove(v int)

Remove removes the specified line number from the selection

func (Selection) Swap added in v0.1.3

func (s Selection) Swap(i, j int)

Swap swaps the elements in indices i and j. Satisfies sort.Interface

type SmartCaseMatcher added in v0.2.9

type SmartCaseMatcher struct {
	*RegexpMatcher
}

SmartCaseMatcher turns ON the ignore-case flag in the regexp if the query contains a upper-case character

func NewSmartCaseMatcher added in v0.2.9

func NewSmartCaseMatcher(enableSep bool) *SmartCaseMatcher

NewSmartCaseMatcher creates a new SmartCaseMatcher

func (*SmartCaseMatcher) String added in v0.2.9

func (m *SmartCaseMatcher) String() string

type StatusBar added in v0.2.5

type StatusBar struct {
	*Ctx
	*AnchorSettings
	// contains filtered or unexported fields
}

StatusBar draws the status message bar

func NewStatusBar added in v0.2.5

func NewStatusBar(ctx *Ctx, anchor VerticalAnchor, anchorOffset int) *StatusBar

NewStatusBar creates a new StatusBar struct

func (*StatusBar) PrintStatus added in v0.2.5

func (s *StatusBar) PrintStatus(msg string, clearDelay time.Duration)

PrintStatus prints a new status message. This also resets the timer created by ClearStatus()

type StatusMsgRequest added in v0.2.10

type StatusMsgRequest struct {
	// contains filtered or unexported fields
}

StatusMsgRequest specifies the string to be drawn on the status message bar and an optional delay that tells the view to clear that message

type Style added in v0.1.2

type Style struct {
	// contains filtered or unexported fields
}

Style describes termbox styles

func (*Style) UnmarshalJSON added in v0.1.2

func (s *Style) UnmarshalJSON(buf []byte) error

UnmarshalJSON satisfies json.RawMessage.

type StyleSet added in v0.1.2

type StyleSet struct {
	Basic          Style `json:"Basic"`
	SavedSelection Style `json:"SavedSelection"`
	Selected       Style `json:"Selected"`
	Query          Style `json:"Query"`
	Matched        Style `json:"Matched"`
}

StyleSet holds styles for various sections

func NewStyleSet added in v0.1.2

func NewStyleSet() *StyleSet

NewStyleSet creates a new StyleSet struct

func (StyleSet) BasicBG added in v0.2.5

func (s StyleSet) BasicBG() termbox.Attribute

func (StyleSet) BasicFG added in v0.2.5

func (s StyleSet) BasicFG() termbox.Attribute

func (StyleSet) MatchedBG added in v0.2.5

func (s StyleSet) MatchedBG() termbox.Attribute

func (StyleSet) MatchedFG added in v0.2.5

func (s StyleSet) MatchedFG() termbox.Attribute

func (StyleSet) QueryBG added in v0.2.5

func (s StyleSet) QueryBG() termbox.Attribute

func (StyleSet) QueryFG added in v0.2.5

func (s StyleSet) QueryFG() termbox.Attribute

func (StyleSet) SavedSelectionBG added in v0.2.5

func (s StyleSet) SavedSelectionBG() termbox.Attribute

func (StyleSet) SavedSelectionFG added in v0.2.5

func (s StyleSet) SavedSelectionFG() termbox.Attribute

func (StyleSet) SelectedBG added in v0.2.5

func (s StyleSet) SelectedBG() termbox.Attribute

func (StyleSet) SelectedFG added in v0.2.5

func (s StyleSet) SelectedFG() termbox.Attribute

type Termbox added in v0.2.6

type Termbox struct{}

Termbox just hands out the processing to the termbox library

func (Termbox) Clear added in v0.2.6

func (t Termbox) Clear(fg, bg termbox.Attribute) error

func (Termbox) Flush added in v0.2.6

func (t Termbox) Flush() error

func (Termbox) PollEvent added in v0.2.6

func (t Termbox) PollEvent() chan termbox.Event

func (Termbox) SetCell added in v0.2.6

func (t Termbox) SetCell(x, y int, ch rune, fg, bg termbox.Attribute)

func (Termbox) Size added in v0.2.6

func (t Termbox) Size() (int, int)

type UserPrompt added in v0.2.5

type UserPrompt struct {
	*Ctx
	*AnchorSettings
	// contains filtered or unexported fields
}

UserPrompt draws the prompt line

func NewUserPrompt added in v0.2.5

func NewUserPrompt(ctx *Ctx, anchor VerticalAnchor, anchorOffset int) *UserPrompt

NewUserPrompt creates a new UserPrompt struct

func (UserPrompt) Draw added in v0.2.5

func (u UserPrompt) Draw()

Draw draws the query prompt

type VerticalAnchor added in v0.2.5

type VerticalAnchor int

VerticalAnchor describes the direction to which elements in the layout are anchored to

const (
	// AnchorTop anchors elements towards the top of the screen
	AnchorTop VerticalAnchor = iota + 1
	// AnchorBottom anchors elements towards the bottom of the screen
	AnchorBottom
)

type View

type View struct {
	*Ctx
	// contains filtered or unexported fields
}

View handles the drawing/updating the screen

func (*View) Loop

func (v *View) Loop()

Loop receives requests to update the screen

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL