Skip to content

Commit 343fcad

Browse files
committed
Updated change log and docs.
1 parent f2bce71 commit 343fcad

File tree

8 files changed

+61
-48
lines changed

8 files changed

+61
-48
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,17 @@ shell, and the option for a persistent bottom bar that can display realtime stat
2727
`cmd2.Cmd.async_alert`
2828
- Removed `cmd2.Cmd.async_refresh_prompt` and `cmd2.Cmd.need_prompt_refresh` as they are no
2929
longer needed
30+
- `completer` functions must now return a `cmd2.Completions` object instead of `list[str]`.
31+
- `choices_provider` functions must now return a `cmd2.Choices` object instead of `list[str]`.
32+
- An argparse argument's `descriptive_headers` field is now called `table_header`.
33+
- `CompletionItem.descriptive_data` is now called `CompletionItem.table_row`.
34+
- `Cmd.default_sort_key` moved to `utils.DEFAULT_STR_SORT_KEY`.
35+
- Moved completion state data, which previously resided in `Cmd`, into other classes.
36+
1. `Cmd.matches_sorted` -> `Completions.is_sorted` and `Choices.is_sorted`
37+
1. `Cmd.completion_hint` -> `Completions.completion_hint`
38+
1. `Cmd.formatted_completions` -> `Completions.completion_table`
39+
1. `Cmd.matches_delimited` -> `Completions.is_delimited`
40+
1. `Cmd.allow_appended_space/allow_closing_quote` -> `Completions.allow_finalization`
3041
- Enhancements
3142
- New `cmd2.Cmd` parameters
3243
- **auto_suggest**: (boolean) if `True`, provide fish shell style auto-suggestions. These

docs/features/builtin_commands.md

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -77,19 +77,19 @@ application:
7777

7878
```text
7979
(Cmd) set
80-
Name Value Description
81-
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
82-
allow_style Terminal Allow ANSI text style sequences in output (valid values: Always, Never, Terminal)
83-
always_show_hint False Display tab completion hint even when completion suggestions print
84-
debug False Show full traceback on exception
85-
echo False Echo command issued into output
86-
editor vim Program used by 'edit'
87-
feedback_to_output False Include nonessentials in '|' and '>' results
88-
foreground_color cyan Foreground color to use with echo command
89-
max_completion_items 50 Maximum number of CompletionItems to display during tab completion
90-
quiet False Don't print nonessential feedback
91-
scripts_add_to_history True Scripts and pyscripts add commands to history
92-
timing False Report execution times
80+
Name Value Description
81+
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
82+
allow_style Terminal Allow ANSI text style sequences in output (valid values: Always, Never, Terminal)
83+
always_show_hint False Display completion hint even when completion suggestions print
84+
debug False Show full traceback on exception
85+
echo False Echo command issued into output
86+
editor vim Program used by 'edit'
87+
feedback_to_output False Include nonessentials in '|' and '>' results
88+
max_column_completion_results 7 Maximum number of completion results to display in a single column
89+
max_completion_table_items 50 Maximum number of completion results allowed for a completion table to appear
90+
quiet False Don't print nonessential feedback
91+
scripts_add_to_history True Scripts and pyscripts add commands to history
92+
timing False Report execution times
9393
```
9494

9595
Any of these user-settable parameters can be set while running your app with the `set` command like

docs/features/initialization.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ Here are instance attributes of `cmd2.Cmd` which developers might wish to overri
3131
- **debug**: if `True`, show full stack trace on error (Default: `False`)
3232
- **default_category**: if any command has been categorized, then all other commands that haven't been categorized will display under this section in the help output.
3333
- **default_error**: the error that prints when a non-existent command is run
34-
- **default_sort_key**: the default key for sorting string results. Its default value performs a case-insensitive alphabetical sort.
3534
- **default_to_shell**: if `True`, attempt to run unrecognized commands as shell commands (Default: `False`)
3635
- **disabled_commands**: commands that have been disabled from use. This is to support commands that are only available during specific states of the application. This dictionary's keys are the command names and its values are DisabledCommand objects.
3736
- **doc_header**: Set the header used for the help function's listing of documented functions
@@ -45,7 +44,7 @@ Here are instance attributes of `cmd2.Cmd` which developers might wish to overri
4544
- **last_result**: stores results from the last command run to enable usage of results in a Python script or interactive console. Built-in commands don't make use of this. It is purely there for user-defined commands and convenience.
4645
- **macros**: dictionary of macro names and their values
4746
- **max_column_completion_results**: The maximum number of completion results to display in a single column (Default: 7)
48-
- **max_completion_items**: max number of CompletionItems to display during tab completion (Default: 50)
47+
- **max_completion_table_items**: The maximum number of completion results allowed for a completion table to appear (Default: 50)
4948
- **pager**: sets the pager command used by the `Cmd.ppaged()` method for displaying wrapped output using a pager
5049
- **pager_chop**: sets the pager command used by the `Cmd.ppaged()` method for displaying chopped/truncated output using a pager
5150
- **py_bridge_name**: name by which embedded Python environments and scripts refer to the `cmd2` application by in order to call commands (Default: `app`)

examples/argparse_completion.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from rich.text import Text
1010

1111
from cmd2 import (
12+
Choices,
1213
Cmd,
1314
Cmd2ArgumentParser,
1415
Cmd2Style,
@@ -27,23 +28,23 @@ def __init__(self) -> None:
2728
super().__init__(include_ipy=True)
2829
self.sport_item_strs = ['Bat', 'Basket', 'Basketball', 'Football', 'Space Ball']
2930

30-
def choices_provider(self) -> list[str]:
31+
def choices_provider(self) -> Choices:
3132
"""A choices provider is useful when the choice list is based on instance data of your application."""
32-
return self.sport_item_strs
33+
return Choices.from_values(self.sport_item_strs)
3334

34-
def choices_completion_error(self) -> list[str]:
35+
def choices_completion_error(self) -> Choices:
3536
"""CompletionErrors can be raised if an error occurs while tab completing.
3637
3738
Example use cases
3839
- Reading a database to retrieve a tab completion data set failed
3940
- A previous command line argument that determines the data set being completed is invalid
4041
"""
4142
if self.debug:
42-
return self.sport_item_strs
43+
return Choices.from_values(self.sport_item_strs)
4344
raise CompletionError("debug must be true")
4445

45-
def choices_completion_item(self) -> list[CompletionItem]:
46-
"""Return CompletionItem instead of strings. These give more context to what's being tab completed."""
46+
def choices_completion_tables(self) -> Choices:
47+
"""Return CompletionItems with completion tables. These give more context to what's being tab completed."""
4748
fancy_item = Text.assemble(
4849
"These things can\ncontain newlines and\n",
4950
Text("styled text!!", style=Style(color=Color.BRIGHT_YELLOW, underline=True)),
@@ -58,16 +59,18 @@ def choices_completion_item(self) -> list[CompletionItem]:
5859
table_item.add_row("Yes, it's true.", "CompletionItems can")
5960
table_item.add_row("even display description", "data in tables!")
6061

61-
items = {
62+
item_dict = {
6263
1: "My item",
6364
2: "Another item",
6465
3: "Yet another item",
6566
4: fancy_item,
6667
5: table_item,
6768
}
68-
return [CompletionItem(item_id, [description]) for item_id, description in items.items()]
6969

70-
def choices_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> list[str]:
70+
completion_items = [CompletionItem(item_id, table_row=[description]) for item_id, description in item_dict.items()]
71+
return Choices(items=completion_items)
72+
73+
def choices_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> Choices:
7174
"""If a choices or completer function/method takes a value called arg_tokens, then it will be
7275
passed a dictionary that maps the command line tokens up through the one being completed
7376
to their argparse argument name. All values of the arg_tokens dictionary are lists, even if
@@ -79,7 +82,7 @@ def choices_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> list[str]:
7982
values.append('is {}'.format(arg_tokens['choices_provider'][0]))
8083
else:
8184
values.append('not supplied')
82-
return values
85+
return Choices.from_values(values)
8386

8487
# Parser for example command
8588
example_parser = Cmd2ArgumentParser(
@@ -105,10 +108,10 @@ def choices_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> list[str]:
105108
help="raise a CompletionError while tab completing if debug is False",
106109
)
107110

108-
# Demonstrate returning CompletionItems instead of strings
111+
# Demonstrate use of completion table
109112
example_parser.add_argument(
110-
'--completion_item',
111-
choices_provider=choices_completion_item,
113+
'--completion_table',
114+
choices_provider=choices_completion_tables,
112115
metavar="ITEM_ID",
113116
table_header=["Description"],
114117
help="demonstrate use of CompletionItems",

examples/basic_completion.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import functools
1515

1616
import cmd2
17+
from cmd2 import Completions
1718

1819
# List of strings used with completion functions
1920
food_item_strs = ['Pizza', 'Ham', 'Ham Sandwich', 'Potato']
@@ -41,7 +42,7 @@ def do_flag_based(self, statement: cmd2.Statement) -> None:
4142
"""
4243
self.poutput(f"Args: {statement.args}")
4344

44-
def complete_flag_based(self, text, line, begidx, endidx) -> list[str]:
45+
def complete_flag_based(self, text, line, begidx, endidx) -> Completions:
4546
"""Completion function for do_flag_based."""
4647
flag_dict = {
4748
# Tab complete food items after -f and --food flags in command line
@@ -61,7 +62,7 @@ def do_index_based(self, statement: cmd2.Statement) -> None:
6162
"""Tab completes first 3 arguments using index_based_complete."""
6263
self.poutput(f"Args: {statement.args}")
6364

64-
def complete_index_based(self, text, line, begidx, endidx) -> list[str]:
65+
def complete_index_based(self, text, line, begidx, endidx) -> Completions:
6566
"""Completion function for do_index_based."""
6667
index_dict = {
6768
1: food_item_strs, # Tab complete food items at index 1 in command line
@@ -82,7 +83,7 @@ def do_raise_error(self, statement: cmd2.Statement) -> None:
8283
"""Demonstrates effect of raising CompletionError."""
8384
self.poutput(f"Args: {statement.args}")
8485

85-
def complete_raise_error(self, _text, _line, _begidx, _endidx) -> list[str]:
86+
def complete_raise_error(self, _text, _line, _begidx, _endidx) -> Completions:
8687
"""CompletionErrors can be raised if an error occurs while tab completing.
8788
8889
Example use cases

examples/transcripts/exampleSession.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ debug: False
88
echo: False
99
editor: /.*?/
1010
feedback_to_output: False
11-
max_completion_items: 50
11+
max_completion_table_items: 50
1212
maxrepeats: 3
1313
quiet: False
1414
timing: False

examples/transcripts/transcript_regex.txt

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,18 @@
22
# Anything between two forward slashes, /, is interpreted as a regular expression (regex).
33
# The regex for editor will match whatever program you use.
44
# regexes on prompts just make the trailing space obvious
5-
(Cmd) set
6-
7-
Name Value Description
8-
───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
9-
allow_style Terminal Allow ANSI text style sequences in output (valid values: Always, Never, Terminal)
10-
always_show_hint False Display tab completion hint even when completion suggestions print
11-
debug False Show full traceback on exception
12-
echo False Echo command issued into output
13-
editor /.*?/ Program used by 'edit'
14-
feedback_to_output False Include nonessentials in '|' and '>' results
15-
max_completion_items 50 Maximum number of CompletionItems to display during tab completion
16-
maxrepeats 3 max repetitions for speak command
17-
quiet False Don't print nonessential feedback
18-
scripts_add_to_history True Scripts and pyscripts add commands to history
19-
timing False Report execution times
5+
(Cmd) set
206

7+
Name Value Description
8+
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
9+
allow_style Terminal Allow ANSI text style sequences in output (valid values: Always, Never, Terminal)
10+
always_show_hint False Display completion hint even when completion suggestions print
11+
debug True Show full traceback on exception
12+
echo False Echo command issued into output
13+
editor vim Program used by 'edit'
14+
feedback_to_output False Include nonessentials in '|' and '>' results
15+
max_column_completion_results 7 Maximum number of completion results to display in a single column
16+
max_completion_table_items 50 Maximum number of completion results allowed for a completion table to appear
17+
quiet False Don't print nonessential feedback
18+
scripts_add_to_history True Scripts and pyscripts add commands to history
19+
timing False Report execution times

tests/test_completion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def test_complete_macro(base_app, request) -> None:
288288
assert completions.to_strings() == Completions.from_values(expected).to_strings()
289289

290290

291-
def test_default_sort_key(cmd2_app) -> None:
291+
def test_default_str_sort_key(cmd2_app) -> None:
292292
text = ''
293293
line = f'test_sort_key {text}'
294294
endidx = len(line)

0 commit comments

Comments
 (0)