__version__ = '0.0.22' module-attribute

PZP Version

CustomAction

Bases: GenericAction

The CustomAction exception is raised when the user presses a key that is mapped to the "custom" action.

Parameters:

Name Type Description Default
action str

action

required
selected_item Any

selected item, if any

None
ch Optional[str]

pressed key

required
line Optional[str]

user input

None

Attributes:

Name Type Description
action

action

selected_item

selected item, if any

ch

pressed key

line

user input

Source code in pzp/exceptions.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class CustomAction(GenericAction):
    """
    The CustomAction exception is raised when the user presses a key
    that is mapped to the "custom" action.

    Args:
        action: action
        selected_item: selected item, if any
        ch: pressed key
        line: user input

    Attributes:
        action: action
        selected_item: selected item, if any
        ch: pressed key
        line: user input
    """

    def __init__(self, action: str, ch: Optional[str], selected_item: Any = None, line: Optional[str] = None):
        super().__init__(action, ch, selected_item, line)

Finder

Bases: ActionsHandler

Source code in pzp/finder.py
 36
 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
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,
    ):
        """
        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
        """
        super().__init__(keys_binding=keys_binding)
        self.config = Config(fullscreen, height, format_fn, info_style, pointer_str, prompt_str, header_str, lazy, output_stream)
        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) -> None:
        """
        Setup Finder execution

        Args:
            input: initial search string
        """
        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 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)

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

        Args:
            input: initial search string

        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)
            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: int = 0

    def process_key(self, ch: Optional[str] = None) -> None:
        "Process the pressed key"
        key_event = self.keys_handler.get_key_event(ch)
        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, ch=key_event.ch, selected_item=self.prepare_result(), line=self.line_editor.line)  # type: ignore

    def apply_filter(self) -> None:
        "Filter the items"
        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)

Initializate Finder object

Parameters:

Name Type Description Default
candidates Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]]

Candidates

required
fullscreen bool

Full screen mode

True
height Optional[int]

Finder window height

None
format_fn Callable[[Any], str]

Items format function

lambda x: str(x)
layout Union[Type[Layout], str]

Finder layout

DEFAULT_LAYOUT
info_style Union[InfoStyle, str]

Determines the display style of finder info

InfoStyle.DEFAULT
pointer_str str

Pointer to the current line

DEFAULT_POINTER
prompt_str str

Input prompt

DEFAULT_PROMPT
header_str str

Header

DEFAULT_HEADER
keys_binding Optional[KeysBinding]

Custom keys binding

None
matcher Union[Matcher, Type[Matcher], str]

Matcher

DEFAULT_MATCHER
lazy bool

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

False
output_stream TextIO

Output stream

sys.stderr
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
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,
):
    """
    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
    """
    super().__init__(keys_binding=keys_binding)
    self.config = Config(fullscreen, height, format_fn, info_style, pointer_str, prompt_str, header_str, lazy, output_stream)
    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
152
153
154
155
@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
147
148
149
150
@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
131
132
133
134
def apply_filter(self) -> None:
    "Filter the items"
    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
157
158
159
160
@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
177
178
179
180
@Action("ignore", keys=["null", "insert"])
def ignore(self) -> None:
    "Do nothing"
    pass

page_down()

Move one page down

Source code in pzp/finder.py
167
168
169
170
@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
172
173
174
175
@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
140
141
142
143
144
145
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
120
121
122
123
124
125
126
127
128
129
def process_key(self, ch: Optional[str] = None) -> None:
    "Process the pressed key"
    key_event = self.keys_handler.get_key_event(ch)
    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, ch=key_event.ch, selected_item=self.prepare_result(), line=self.line_editor.line)  # type: ignore

refresh_candidates()

Load/reload the candidate list

Source code in pzp/finder.py
115
116
117
118
def refresh_candidates(self) -> None:
    "Load/reload the candidate list"
    self.candidates.refresh_candidates()
    self.selected: int = 0

setup(input=None)

Setup Finder execution

Parameters:

Name Type Description Default
input Optional[str]

initial search string

None
Source code in pzp/finder.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def setup(self, input: Optional[str] = None) -> None:
    """
    Setup Finder execution

    Args:
        input: initial search string
    """
    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 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)

show(input=None)

Open pzp and return the selected element

Parameters:

Name Type Description Default
input Optional[str]

initial search string

None

Raises:

Type Description
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
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def show(self, input: Optional[str] = None) -> Any:
    """
    Open pzp and return the selected element

    Args:
        input: initial search string

    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)
        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
162
163
164
165
@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
136
137
138
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)

GenericAction

Bases: PZPException

Generic Action Event

Parameters:

Name Type Description Default
action str

action

required
ch Optional[str]

pressed key

required
selected_item Any

selected item, if any

None
line Optional[str]

user input

None

Attributes:

Name Type Description
action

action

ch

pressed key

selected_item

selected item, if any

line

user input

Source code in pzp/exceptions.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class GenericAction(PZPException):
    """
    Generic Action Event

    Args:
        action: action
        ch: pressed key
        selected_item: selected item, if any
        line: user input

    Attributes:
        action: action
        ch: pressed key
        selected_item: selected item, if any
        line: user input
    """

    def __init__(self, action: str, ch: Optional[str], selected_item: Any = None, line: Optional[str] = None):
        super().__init__(action)
        self.action = action
        self.ch = ch
        self.selected_item = selected_item
        self.line = line

pzp(candidates, height=None, fullscreen=True, 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, handle_actions={AcceptAction, AbortAction}, input=None)

Open pzp and return the selected element

If the Lazy mode is enabled, starts the finder only if the candidates are more than one. If there is only one match returns the only match, if there is no match returns None.

Examples:

>>> pzp(candidates=list(Path('.').iterdir()))
PosixPath('README.md')

Parameters:

Name Type Description Default
candidates Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]]

Candidates

required
fullscreen bool

Full screen mode

True
height Optional[int]

Finder window height

None
format_fn Callable[[Any], str]

Items format function

lambda x: str(x)
layout Union[Type[Layout], str]

Finder layout

DEFAULT_LAYOUT
info_style InfoStyle

Determines the display style of finder info

InfoStyle.DEFAULT
pointer_str str

Pointer to the current line

DEFAULT_POINTER
prompt_str str

Input prompt

DEFAULT_PROMPT
header_str str

Header

DEFAULT_HEADER
keys_binding Optional[KeysBinding]

Custom keys binding

None
matcher Union[Matcher, Type[Matcher], str]

Matcher

DEFAULT_MATCHER
lazy bool

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

False
handle_actions Set[Type[GenericAction]]

Actions to be handled

{AcceptAction, AbortAction}

Returns:

Name Type Description
item Any

the selected item

Source code in pzp/__init__.py
30
31
32
33
34
35
36
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
def pzp(
    candidates: Union[Callable[[], Sequence[Any]], Iterator[Any], Sequence[Any]],
    height: Optional[int] = None,
    fullscreen: bool = True,
    format_fn: Callable[[Any], str] = lambda x: str(x),
    layout: Union[Type[Layout], str] = DEFAULT_LAYOUT,
    info_style: InfoStyle = 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,
    handle_actions: Set[Type[GenericAction]] = {AcceptAction, AbortAction},
    input: Optional[str] = None,
) -> Any:
    """
    Open pzp and return the selected element

    If the Lazy mode is enabled, starts the finder only if the candidates are more than one.
    If there is only one match returns the only match, if there is no match returns None.

    Examples:
        >>> pzp(candidates=list(Path('.').iterdir()))
        PosixPath('README.md')

    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
        handle_actions: Actions to be handled

    Returns:
        item: the selected item
    """
    finder = Finder(
        candidates=candidates,
        fullscreen=fullscreen,
        height=height,
        format_fn=format_fn,
        layout=layout,
        info_style=info_style,
        pointer_str=pointer_str,
        prompt_str=prompt_str,
        header_str=header_str,
        keys_binding=keys_binding,
        matcher=matcher,
        lazy=lazy,
    )
    try:
        finder.show(input=input)
    except GenericAction as ex:
        if type(ex) in (handle_actions or set()):
            return ex.selected_item if isinstance(ex, AcceptAction) else None
        else:
            raise