DEFAULT_HEADER = '' module-attribute

Default header

DEFAULT_LAYOUT = 'default' module-attribute

Default layout

DEFAULT_MATCHER = 'extended' module-attribute

Default matcher

DEFAULT_POINTER = '>' module-attribute

Default pointer

DEFAULT_PROMPT = '> ' module-attribute

Default input prompt

Finder

Bases: ActionsHandler

Source code in pzp/finder.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
class Finder(ActionsHandler):
    def __init__(
        self,
        candidates: Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]],
        fullscreen: bool = True,
        height: Optional[int] = None,
        format_fn: Callable[[Any], str] = lambda x: str(x),
        layout: Union[Type[Layout], str] = DEFAULT_LAYOUT,
        info_style: Union[InfoStyle, str] = InfoStyle.DEFAULT,
        pointer_str: str = DEFAULT_POINTER,
        prompt_str: str = DEFAULT_PROMPT,
        header_str: str = DEFAULT_HEADER,
        keys_binding: Optional[KeysBinding] = None,
        matcher: Union[Matcher, Type[Matcher], str] = DEFAULT_MATCHER,
        lazy: bool = False,
        output_stream: TextIO = sys.stderr,
        auto_refresh: Optional[int] = None,
    ):
        """
        Initializate Finder object

        Args:
            candidates: Candidates
            fullscreen: Full screen mode
            height: Finder window height
            format_fn: Items format function
            layout: Finder layout
            info_style: Determines the display style of finder info
            pointer_str: Pointer to the current line
            prompt_str: Input prompt
            header_str: Header
            keys_binding: Custom keys binding
            matcher: Matcher
            lazy: Lazy mode, starts the finder only if the candidates are more than one
            output_stream: Output stream
            auto_refresh: Auto refresh period (in seconds)
        """
        super().__init__(keys_binding=keys_binding)
        self.config = Config(
            fullscreen,
            height,
            format_fn,
            info_style,
            pointer_str,
            prompt_str,
            header_str,
            lazy,
            output_stream,
            auto_refresh,
        )
        self.candidates = Candidates(candidates=candidates, format_fn=format_fn, matcher=matcher)
        self.layout: Layout = get_layout(layout=layout, config=self.config, candidates=self.candidates)

    def setup(self, input: Optional[str] = None, selected: Optional[int] = None) -> None:
        """
        Setup Finder execution

        Args:
            input: Initial search string
            selected: Initial selected line number
        """
        self.line_editor = LineEditor(line=input or "", keys_handler=self.keys_handler)
        # Load the candidate list
        self.refresh_candidates()
        # Filter the items, calculate the screen offset
        self.apply_filter()
        if selected is not None:
            self.selected = selected
        # If lazy mode is enabled, starts the finder only if the candidates are more than one
        if self.config.lazy and self.candidates.matching_candidates_len <= 1:
            raise AcceptAction(action="lazy-accept", ch=None, selected_item=self.prepare_result(), line=self.line_editor.line)
        # Calculate the required height and setup the screen
        self.layout.screen_setup(self.line_editor, self.selected)

    def show(self, input: Optional[str] = None, selected: Optional[int] = None) -> Any:
        """
        Open pzp and return the selected element

        Args:
            input: Initial search string
            selected: Initial selected line number

        Raises:
            AcceptAction: Raises when the user presses a key that is mapped to the "accept" action.
            AbortAction: Raises when the user presses a key that is mapped to the "abort" action.
            CustomAction: Raises when the user presses a key that is mapped to the "custom" action.
        """
        try:
            self.setup(input=input, selected=selected)
            while True:
                self.process_key()
                self.apply_filter()
                self.update_screen()
        finally:
            self.layout.cleanup()

    def refresh_candidates(self) -> None:
        "Load/reload the candidate list"
        self.candidates.refresh_candidates()
        self.selected = 0

    def process_key(self, ch: Optional[str] = None) -> None:
        "Process the pressed key"
        key_event = self.keys_handler.get_key_event(ch, timeout=self.config.auto_refresh)
        try:
            self.line_editor.process_key_event(key_event)
        except MissingHander:
            try:
                self.process_key_event(key_event)
            except MissingHander:
                raise CustomAction(
                    action=key_event.action,  # type: ignore
                    ch=key_event.ch,
                    selected_item=self.prepare_result(),
                    line=self.line_editor.line,
                )

    def apply_filter(self) -> None:
        "Filter the items"
        if self.config.auto_refresh:
            self.candidates.refresh_candidates()
        self.candidates.apply_filter(pattern=str(self.line_editor))
        self.selected = max(min(self.selected, self.candidates.matching_candidates_len - 1), 0)

    def update_screen(self) -> None:
        "Update the screen - erase the old items, print the filtered items and the prompt"
        self.layout.update_screen(selected=self.selected)

    def prepare_result(self) -> Any:
        "Output the selected item, if any"
        try:
            return self.candidates.matching_candidates[self.selected]
        except IndexError:
            return None

    @Action("accept", keys=["enter"])
    def accept(self, key_event: KeyEvent) -> None:
        "Confirm"
        raise AcceptAction(action="accept", ch=key_event.ch, selected_item=self.prepare_result(), line=self.line_editor.line)

    @Action("abort", keys=["ctrl-c", "ctrl-g", "ctrl-q", "esc"])
    def abort(self, key_event: KeyEvent) -> None:
        "Cancel"
        raise AbortAction(action="abort", ch=key_event.ch, line=self.line_editor.line)

    @Action("down", keys=["ctrl-j", "ctrl-n", "down"])
    def down(self) -> None:
        "Move one line down"
        self.selected = self.layout.move_selection(self.selected, lines=-1)

    @Action("up", keys=["ctrl-k", "ctrl-p", "up"])
    def up(self) -> None:
        "Move one line up"
        self.selected = self.layout.move_selection(self.selected, lines=+1)

    @Action("page-down", keys=["page-down", "pgdn"])
    def page_down(self) -> None:
        "Move one page down"
        self.selected = self.layout.move_selection(self.selected, pages=-1)

    @Action("page-up", keys=["page-up", "pgup"])
    def page_up(self) -> None:
        "Move one page up"
        self.selected = self.layout.move_selection(self.selected, pages=+1)

    @Action("ignore", keys=["null", "insert"])
    def ignore(self) -> None:
        "Do nothing"
        pass

__init__(candidates, fullscreen=True, height=None, format_fn=lambda x: str(x), layout=DEFAULT_LAYOUT, info_style=InfoStyle.DEFAULT, pointer_str=DEFAULT_POINTER, prompt_str=DEFAULT_PROMPT, header_str=DEFAULT_HEADER, keys_binding=None, matcher=DEFAULT_MATCHER, lazy=False, output_stream=sys.stderr, auto_refresh=None)

Initializate Finder object

Parameters:
  • candidates (Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]]) –

    Candidates

  • fullscreen (bool, default: True ) –

    Full screen mode

  • height (Optional[int], default: None ) –

    Finder window height

  • format_fn (Callable[[Any], str], default: lambda x: str(x) ) –

    Items format function

  • layout (Union[Type[Layout], str], default: DEFAULT_LAYOUT ) –

    Finder layout

  • info_style (Union[InfoStyle, str], default: DEFAULT ) –

    Determines the display style of finder info

  • pointer_str (str, default: DEFAULT_POINTER ) –

    Pointer to the current line

  • prompt_str (str, default: DEFAULT_PROMPT ) –

    Input prompt

  • header_str (str, default: DEFAULT_HEADER ) –

    Header

  • keys_binding (Optional[KeysBinding], default: None ) –

    Custom keys binding

  • matcher (Union[Matcher, Type[Matcher], str], default: DEFAULT_MATCHER ) –

    Matcher

  • lazy (bool, default: False ) –

    Lazy mode, starts the finder only if the candidates are more than one

  • output_stream (TextIO, default: stderr ) –

    Output stream

  • auto_refresh (Optional[int], default: None ) –

    Auto refresh period (in seconds)

Source code in pzp/finder.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    candidates: Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]],
    fullscreen: bool = True,
    height: Optional[int] = None,
    format_fn: Callable[[Any], str] = lambda x: str(x),
    layout: Union[Type[Layout], str] = DEFAULT_LAYOUT,
    info_style: Union[InfoStyle, str] = InfoStyle.DEFAULT,
    pointer_str: str = DEFAULT_POINTER,
    prompt_str: str = DEFAULT_PROMPT,
    header_str: str = DEFAULT_HEADER,
    keys_binding: Optional[KeysBinding] = None,
    matcher: Union[Matcher, Type[Matcher], str] = DEFAULT_MATCHER,
    lazy: bool = False,
    output_stream: TextIO = sys.stderr,
    auto_refresh: Optional[int] = None,
):
    """
    Initializate Finder object

    Args:
        candidates: Candidates
        fullscreen: Full screen mode
        height: Finder window height
        format_fn: Items format function
        layout: Finder layout
        info_style: Determines the display style of finder info
        pointer_str: Pointer to the current line
        prompt_str: Input prompt
        header_str: Header
        keys_binding: Custom keys binding
        matcher: Matcher
        lazy: Lazy mode, starts the finder only if the candidates are more than one
        output_stream: Output stream
        auto_refresh: Auto refresh period (in seconds)
    """
    super().__init__(keys_binding=keys_binding)
    self.config = Config(
        fullscreen,
        height,
        format_fn,
        info_style,
        pointer_str,
        prompt_str,
        header_str,
        lazy,
        output_stream,
        auto_refresh,
    )
    self.candidates = Candidates(candidates=candidates, format_fn=format_fn, matcher=matcher)
    self.layout: Layout = get_layout(layout=layout, config=self.config, candidates=self.candidates)

abort(key_event)

Cancel

Source code in pzp/finder.py
177
178
179
180
@Action("abort", keys=["ctrl-c", "ctrl-g", "ctrl-q", "esc"])
def abort(self, key_event: KeyEvent) -> None:
    "Cancel"
    raise AbortAction(action="abort", ch=key_event.ch, line=self.line_editor.line)

accept(key_event)

Confirm

Source code in pzp/finder.py
172
173
174
175
@Action("accept", keys=["enter"])
def accept(self, key_event: KeyEvent) -> None:
    "Confirm"
    raise AcceptAction(action="accept", ch=key_event.ch, selected_item=self.prepare_result(), line=self.line_editor.line)

apply_filter()

Filter the items

Source code in pzp/finder.py
154
155
156
157
158
159
def apply_filter(self) -> None:
    "Filter the items"
    if self.config.auto_refresh:
        self.candidates.refresh_candidates()
    self.candidates.apply_filter(pattern=str(self.line_editor))
    self.selected = max(min(self.selected, self.candidates.matching_candidates_len - 1), 0)

down()

Move one line down

Source code in pzp/finder.py
182
183
184
185
@Action("down", keys=["ctrl-j", "ctrl-n", "down"])
def down(self) -> None:
    "Move one line down"
    self.selected = self.layout.move_selection(self.selected, lines=-1)

ignore()

Do nothing

Source code in pzp/finder.py
202
203
204
205
@Action("ignore", keys=["null", "insert"])
def ignore(self) -> None:
    "Do nothing"
    pass

page_down()

Move one page down

Source code in pzp/finder.py
192
193
194
195
@Action("page-down", keys=["page-down", "pgdn"])
def page_down(self) -> None:
    "Move one page down"
    self.selected = self.layout.move_selection(self.selected, pages=-1)

page_up()

Move one page up

Source code in pzp/finder.py
197
198
199
200
@Action("page-up", keys=["page-up", "pgup"])
def page_up(self) -> None:
    "Move one page up"
    self.selected = self.layout.move_selection(self.selected, pages=+1)

prepare_result()

Output the selected item, if any

Source code in pzp/finder.py
165
166
167
168
169
170
def prepare_result(self) -> Any:
    "Output the selected item, if any"
    try:
        return self.candidates.matching_candidates[self.selected]
    except IndexError:
        return None

process_key(ch=None)

Process the pressed key

Source code in pzp/finder.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def process_key(self, ch: Optional[str] = None) -> None:
    "Process the pressed key"
    key_event = self.keys_handler.get_key_event(ch, timeout=self.config.auto_refresh)
    try:
        self.line_editor.process_key_event(key_event)
    except MissingHander:
        try:
            self.process_key_event(key_event)
        except MissingHander:
            raise CustomAction(
                action=key_event.action,  # type: ignore
                ch=key_event.ch,
                selected_item=self.prepare_result(),
                line=self.line_editor.line,
            )

refresh_candidates()

Load/reload the candidate list

Source code in pzp/finder.py
133
134
135
136
def refresh_candidates(self) -> None:
    "Load/reload the candidate list"
    self.candidates.refresh_candidates()
    self.selected = 0

setup(input=None, selected=None)

Setup Finder execution

Parameters:
  • input (Optional[str], default: None ) –

    Initial search string

  • selected (Optional[int], default: None ) –

    Initial selected line number

Source code in pzp/finder.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def setup(self, input: Optional[str] = None, selected: Optional[int] = None) -> None:
    """
    Setup Finder execution

    Args:
        input: Initial search string
        selected: Initial selected line number
    """
    self.line_editor = LineEditor(line=input or "", keys_handler=self.keys_handler)
    # Load the candidate list
    self.refresh_candidates()
    # Filter the items, calculate the screen offset
    self.apply_filter()
    if selected is not None:
        self.selected = selected
    # If lazy mode is enabled, starts the finder only if the candidates are more than one
    if self.config.lazy and self.candidates.matching_candidates_len <= 1:
        raise AcceptAction(action="lazy-accept", ch=None, selected_item=self.prepare_result(), line=self.line_editor.line)
    # Calculate the required height and setup the screen
    self.layout.screen_setup(self.line_editor, self.selected)

show(input=None, selected=None)

Open pzp and return the selected element

Parameters:
  • input (Optional[str], default: None ) –

    Initial search string

  • selected (Optional[int], default: None ) –

    Initial selected line number

Raises:
  • AcceptAction

    Raises when the user presses a key that is mapped to the "accept" action.

  • AbortAction

    Raises when the user presses a key that is mapped to the "abort" action.

  • CustomAction

    Raises when the user presses a key that is mapped to the "custom" action.

Source code in pzp/finder.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def show(self, input: Optional[str] = None, selected: Optional[int] = None) -> Any:
    """
    Open pzp and return the selected element

    Args:
        input: Initial search string
        selected: Initial selected line number

    Raises:
        AcceptAction: Raises when the user presses a key that is mapped to the "accept" action.
        AbortAction: Raises when the user presses a key that is mapped to the "abort" action.
        CustomAction: Raises when the user presses a key that is mapped to the "custom" action.
    """
    try:
        self.setup(input=input, selected=selected)
        while True:
            self.process_key()
            self.apply_filter()
            self.update_screen()
    finally:
        self.layout.cleanup()

up()

Move one line up

Source code in pzp/finder.py
187
188
189
190
@Action("up", keys=["ctrl-k", "ctrl-p", "up"])
def up(self) -> None:
    "Move one line up"
    self.selected = self.layout.move_selection(self.selected, lines=+1)

update_screen()

Update the screen - erase the old items, print the filtered items and the prompt

Source code in pzp/finder.py
161
162
163
def update_screen(self) -> None:
    "Update the screen - erase the old items, print the filtered items and the prompt"
    self.layout.update_screen(selected=self.selected)