Debian Codegraph @

docs/source/text_editor.rst

raw
1 ===========
2 Text Editor
3 ===========
4 Some CLI programs require users to edit more complex fields in a text editor.
5 For example, ``git`` may open a text editor for the user when rebasing or editing a commit message.
6 While not directly related to CLI command parsing, Cyclopts provides :func:`cyclopts.edit` to satisfy this common need.
7
8 Here is an example application that mimics ``git commit`` functionality.
9
10 .. code-block:: python
11
12 # git.py
13 import cyclopts
14 from textwrap import dedent
15 import sys
16
17 app = cyclopts.App(name="git")
18
19 @app.command
20 def commit():
21 try:
22 response = cyclopts.edit( # blocks until text editor is closed.
23 dedent( # removes the leading 4-tab indentation.
24 """\
25
26
27 # Please enter the commit message for your changes.Lines starting
28 # with '#' will be ignored, and an empty message aborts the commit.
29 """
30 )
31 )
32 except (cyclopts.EditorDidNotSaveError, cyclopts.EditorDidNotChangeError):
33 print("Aborting commit due to empty commit message.")
34 sys.exit(1)
35 filtered = "\n".join(x for x in response.split("\n") if not x.startswith("#"))
36 filtered = filtered.strip() # remove leading/trailing whitespace.
37 print(f"Your commit message: {filtered}")
38
39 if __name__ == "__main__":
40 app()
41
42 Running ``python git.py commit`` will bring up a text editor with the pre-defined text, and then return the contents of the file. For more interactive CLI prompting, we recommend using the questionary_ package. See :func:`.edit` API page for more advanced usage.
43
44 .. _questionary: https://github.com/tmbo/questionary