From 3470018d919f6295ada022ce5078e015d6bbd287 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 22 Nov 2019 22:14:54 -0700 Subject: Work on Generating Output docs for #765 --- docs/features/generating_output.rst | 118 +++++++++++++++++++++++++----------- docs/features/startup_commands.rst | 2 +- 2 files changed, 84 insertions(+), 36 deletions(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 2ee820f1..d63acea2 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -1,45 +1,93 @@ Generating Output ================= -how to generate output +A standard ``cmd`` application can produce output by using either of these +methods:: + + print("Greetings, Professor Falken.", file=self.stdout) + self.stdout.write("Shall we play a game?\n") + +While you could send output directly to ``sys.stdout``, ``cmd`` can be +initialized with a ``stdin`` and ``stdout`` variables, which it stores +as ``self.stdin`` and ``self.stdout``. By using these variables every +time you produce output, you can trivially change where all the output +goes by changing how you initialize your class. + +``cmd2`` extends this approach in a number of convenient ways. See +:ref:`features/redirection:Output Redirection And Pipes` for information +on how users can change where the output of a command is sent. In order +for those features to work, the output you generate must be sent to +``self.stdout``. You can use the methods described above, and everything +will work fine. ``cmd2`` also includes a number of convenience methods +which you may use to enhance the output your application produces. + + +TODO: - poutput - perror -- paging +- pwarning +- pexcept +- ppaging + +- column formatting? +- wcswidth? + +- allow_ansi setting +- cmd2.ansi.style() + - exceptions -- color support - -Standard ``cmd`` applications produce their output with -``self.stdout.write('output')`` (or with ``print``, but ``print`` decreases -output flexibility). ``cmd2`` applications can use ``self.poutput('output')``, -``self.pfeedback('message')``, ``self.perror('errmsg')``, and -``self.ppaged('text')`` instead. These methods have these advantages: - -- Handle output redirection to file and/or pipe appropriately -- More concise - - ``.pfeedback()`` destination is controlled by ``quiet`` parameter. -- Option to display long output using a pager via ``ppaged()`` - -.. automethod:: cmd2.cmd2.Cmd.poutput - :noindex: -.. automethod:: cmd2.cmd2.Cmd.perror - :noindex: -.. automethod:: cmd2.cmd2.Cmd.pfeedback - :noindex: -.. automethod:: cmd2.cmd2.Cmd.ppaged - :noindex: - - -Suppressing non-essential output --------------------------------- - -The ``quiet`` setting controls whether ``self.pfeedback()`` actually produces -any output. If ``quiet`` is ``False``, then the output will be produced. If -``quiet`` is ``True``, no output will be produced. - -This makes ``self.pfeedback()`` useful for non-essential output like status -messages. Users can control whether they would like to see these messages by -changing the value of the ``quiet`` setting. + +Ordinary Output +--------------- + + +Error Messages +-------------- + + +Warning Messages +---------------- + + +Feedback +-------- + +You may have the need to display information to the user which is not intended +to be part of the generated output. This could be debugging information or +status information about the progress of long running commands. It's not output, +it's not error messages, it's feedback. If you use the +:ref:`features/settings:Timing` setting, the output of how long it took the +command to run will be output as feedback. ``cmd2`` has a ``self.pfeedback()`` +method to produce this type of output, and several +:ref:`features/settings:Settings` to control how this output is handled. + +If the ``quiet`` setting is ``True``, then calling ``self.pfeedback()`` produces +no output. If ``quiet`` is ``False``, then the ``feedback_to_output`` setting is +consulted to determine which file descriptor the feedback will be sent to. The +default value of ``False`` means all feedback is sent to ``sys.stderr``. If set +to ``True``, then the feedback output will be sent to ``self.stdout`` along with +the rest of the generated output. + + +Exceptions +---------- + + +Paging Output +------------- + + +Centering Text +-------------- + +utils.center_text() + + +Columnar Output +--------------- + +Using wcswidth() and ansi.ansi_safe_wcswidth() Colored Output diff --git a/docs/features/startup_commands.rst b/docs/features/startup_commands.rst index 93984db6..aaaf7722 100644 --- a/docs/features/startup_commands.rst +++ b/docs/features/startup_commands.rst @@ -5,7 +5,7 @@ Startup Commands after your application starts up: 1. Commands at Invocation -1. Startup Script +2. Startup Script Commands run as part of a startup script are always run immediately after the application finishes initializing so they are guaranteed to run before any -- cgit v1.2.1 From 8b2b537b5f61ee29d1952d86615bfa99704379de Mon Sep 17 00:00:00 2001 From: kotfu Date: Sat, 23 Nov 2019 22:54:02 -0700 Subject: Documentation for colored output #765 --- docs/api/ansi.rst | 5 ++ docs/api/index.rst | 1 + docs/features/generating_output.rst | 95 ++++++++++++++++++++----------------- docs/features/settings.rst | 62 ++++++++++++++++-------- 4 files changed, 99 insertions(+), 64 deletions(-) create mode 100644 docs/api/ansi.rst diff --git a/docs/api/ansi.rst b/docs/api/ansi.rst new file mode 100644 index 00000000..e361bd4f --- /dev/null +++ b/docs/api/ansi.rst @@ -0,0 +1,5 @@ +cmd2.ansi +========= + +.. automodule:: cmd2.ansi + :members: diff --git a/docs/api/index.rst b/docs/api/index.rst index 94d0fdd4..f0324eab 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -7,5 +7,6 @@ API Reference cmd decorators exceptions + ansi utility_classes utility_functions diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index d63acea2..16ff044d 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -14,17 +14,17 @@ time you produce output, you can trivially change where all the output goes by changing how you initialize your class. ``cmd2`` extends this approach in a number of convenient ways. See -:ref:`features/redirection:Output Redirection And Pipes` for information -on how users can change where the output of a command is sent. In order -for those features to work, the output you generate must be sent to -``self.stdout``. You can use the methods described above, and everything -will work fine. ``cmd2`` also includes a number of convenience methods -which you may use to enhance the output your application produces. +:ref:`features/redirection:Output Redirection And Pipes` for information on how +users can change where the output of a command is sent. In order for those +features to work, the output you generate must be sent to ``self.stdout``. You +can use the methods described above, and everything will work fine. ``cmd2`` +also adds a number of output related methods to ``Cmd2.Cmd`` which you may use +to enhance the output your application produces. TODO: -- poutput + - perror - pwarning - pexcept @@ -33,14 +33,47 @@ TODO: - column formatting? - wcswidth? -- allow_ansi setting -- cmd2.ansi.style() - - exceptions Ordinary Output --------------- +The ``poutput()`` method is almost like using the Python built-in ``print()`` +function. ``poutput()`` adds two conveniences. + +Since users can pipe output to a shell command, it catches ``BrokenPipeError`` +and outputs the contents of ``self.broken_pipe_warning`` to ``stderr``. +``self.broken_pipe_warning`` defaults to an empty string so this method will +just swallow the exception. If you want to show some error message, put it in +``self.broken_pipe_warning`` when you initialize ``Cmd2.cmd``. + +``poutput()`` also honors the :ref:`features/settings:allow_ansi` setting, +which controls whether ANSI escape sequences that instruct the terminal to +colorize output are stripped from the output. + + +Colored Output +-------------- + +You may want to generate output in different colors, which is typically done by +adding `ANSI escape sequences +`_ which tell the +terminal to change the foreground and background colors. If you want to give +yourself a headache, you can generate these by hand. You could also use another +Python color library like `plumbum.colors +`_, `colored +`_, or `colorama +`_. Colorama is unique because when it's +running on Windows, it wraps ``stdout``, looks for ANSI escape sequences, and +converts them into the appropriate ``win32`` calls to modify the state of the +terminal. + +``cmd2`` imports and uses Colorama and also provides a number of convenience +methods for generating colorized output, measuring the screen width of +colorized output, setting the window title in the terminal, and removing ANSI +escape codes from a string. These functions are all documentated in +:ref:`api/ansi:cmd2.ansi`. + Error Messages -------------- @@ -55,19 +88,19 @@ Feedback You may have the need to display information to the user which is not intended to be part of the generated output. This could be debugging information or -status information about the progress of long running commands. It's not output, -it's not error messages, it's feedback. If you use the +status information about the progress of long running commands. It's not +output, it's not error messages, it's feedback. If you use the :ref:`features/settings:Timing` setting, the output of how long it took the command to run will be output as feedback. ``cmd2`` has a ``self.pfeedback()`` method to produce this type of output, and several :ref:`features/settings:Settings` to control how this output is handled. -If the ``quiet`` setting is ``True``, then calling ``self.pfeedback()`` produces -no output. If ``quiet`` is ``False``, then the ``feedback_to_output`` setting is -consulted to determine which file descriptor the feedback will be sent to. The -default value of ``False`` means all feedback is sent to ``sys.stderr``. If set -to ``True``, then the feedback output will be sent to ``self.stdout`` along with -the rest of the generated output. +If the ``quiet`` setting is ``True``, then calling ``self.pfeedback()`` +produces no output. If ``quiet`` is ``False``, then the ``feedback_to_output`` +setting is consulted to determine which file descriptor the feedback will be +sent to. The default value of ``False`` means all feedback is sent to +``sys.stderr``. If set to ``True``, then the feedback output will be sent to +``self.stdout`` along with the rest of the generated output. Exceptions @@ -90,30 +123,4 @@ Columnar Output Using wcswidth() and ansi.ansi_safe_wcswidth() -Colored Output --------------- - -The output methods in the previous section all honor the ``allow_ansi`` -setting, which has three possible values: - -Never - poutput(), pfeedback(), and ppaged() strip all ANSI escape sequences - which instruct the terminal to colorize output - -Terminal - (the default value) poutput(), pfeedback(), and ppaged() do not strip any - ANSI escape sequences when the output is a terminal, but if the output is a - pipe or a file the escape sequences are stripped. If you want colorized - output you must add ANSI escape sequences using either cmd2's internal ansi - module or another color library such as `plumbum.colors`, `colorama`, or - `colored`. - -Always - poutput(), pfeedback(), and ppaged() never strip ANSI escape sequences, - regardless of the output destination - -Colored and otherwise styled output can be generated using the `ansi.style()` -function: - -.. automethod:: cmd2.ansi.style diff --git a/docs/features/settings.rst b/docs/features/settings.rst index b0575468..25162aed 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -11,6 +11,26 @@ Built In Settings ``cmd2`` has a number of built in settings, which a developer can set a default value, and which users can modify to change the behavior of the application. +A list of all user-settable parameters, with brief comments, is viewable from +within a running application:: + + (Cmd) set --long + allow_ansi: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) + continuation_prompt: > # On 2nd+ line of input + debug: False # Show full error stack on error + echo: False # Echo command issued into output + editor: vim # Program used by ``edit`` + feedback_to_output: False # include nonessentials in `|`, `>` results + locals_in_py: False # Allow access to your application in py via self + max_completion_items: 50 # Maximum number of CompletionItems to display during tab completion + prompt: (Cmd) # The prompt issued to solicit input + quiet: False # Don't print nonessential feedback + timing: False # Report execution times + +Any of these user-settable parameters can be set while running your app with +the ``set`` command like so:: + + (Cmd) set allow_ansi Never Timing ~~~~~~ @@ -38,31 +58,29 @@ the application generates an error. |settable| .. _parameters: -Other user-settable parameters -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A list of all user-settable parameters, with brief -comments, is viewable from within a running application -with:: +allow_ansi +~~~~~~~~~~ - (Cmd) set --long - allow_ansi: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) - continuation_prompt: > # On 2nd+ line of input - debug: False # Show full error stack on error - echo: False # Echo command issued into output - editor: vim # Program used by ``edit`` - feedback_to_output: False # include nonessentials in `|`, `>` results - locals_in_py: False # Allow access to your application in py via self - max_completion_items: 50 # Maximum number of CompletionItems to display during tab completion - prompt: (Cmd) # The prompt issued to solicit input - quiet: False # Don't print nonessential feedback - timing: False # Report execution times +The ``allow_ansi`` setting controls the behavior of ANSI escape sequences +in output generated with any of the following methods: -Any of these user-settable parameters can be set while running your app with -the ``set`` command like so:: +- ``poutput()`` +- ``perror()`` +- ``pwarning()`` +- ``pfeedback()`` +- ``ppaged()`` - set allow_ansi Never +This setting can be one of three values: +- ``Never`` - all ANSI escape sequences which instruct the terminal to colorize + output are stripped from the output. + +- ``Terminal`` - (the default value) pass through ANSI escape sequences when + the output is being sent to the terminal, but if the output is redirected to + a pipe or a file the escape sequences are stripped. + +- ``Always`` - ANSI escape sequences are always passed through, regardless Create New Settings @@ -100,3 +118,7 @@ changes a setting, and will receive both the old value and the new value. now: 13 (Cmd) sunbathe It's 13 C - are you a penguin? + + +Hide Built-in Settings +---------------------- -- cgit v1.2.1 From 7175181a8dfe3d0b5b620a12338912625e1d0045 Mon Sep 17 00:00:00 2001 From: kotfu Date: Sun, 24 Nov 2019 10:31:51 -0700 Subject: Fix minor errors in docstrings --- cmd2/ansi.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cmd2/ansi.py b/cmd2/ansi.py index f1b2def8..32d01399 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -91,6 +91,7 @@ def ansi_safe_wcswidth(text: str) -> int: Wrap wcswidth to make it compatible with strings that contains ANSI escape sequences :param text: the string being measured + :return: the width of the string when printed to the terminal """ # Strip ANSI escape sequences since they cause wcswidth to return -1 return wcswidth(strip_ansi(text)) @@ -114,7 +115,7 @@ def fg_lookup(fg_name: str) -> str: :param fg_name: foreground color name to look up ANSI escape code(s) for :return: ANSI escape code(s) associated with this color - :raises ValueError if the color cannot be found + :raises ValueError: if the color cannot be found """ try: ansi_escape = FG_COLORS[fg_name.lower()] @@ -128,7 +129,7 @@ def bg_lookup(bg_name: str) -> str: :param bg_name: background color name to look up ANSI escape code(s) for :return: ANSI escape code(s) associated with this color - :raises ValueError if the color cannot be found + :raises ValueError: if the color cannot be found """ try: ansi_escape = BG_COLORS[bg_name.lower()] @@ -246,6 +247,6 @@ def set_title_str(title: str) -> str: """Get the required string, including ANSI escape codes, for setting window title for the terminal. :param title: new title for the window - :return string to write to sys.stderr in order to set the window title to the desired test + :return: string to write to sys.stderr in order to set the window title to the desired test """ return colorama.ansi.set_title(title) -- cgit v1.2.1 From 5058d7ad4e6ce308b0e923838f6a0f03aedfe150 Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 27 Nov 2019 09:53:16 -0700 Subject: Remove unused variable --- examples/plumbum_colors.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/plumbum_colors.py b/examples/plumbum_colors.py index a969c4de..b4f0ad1c 100755 --- a/examples/plumbum_colors.py +++ b/examples/plumbum_colors.py @@ -104,7 +104,7 @@ class CmdLineApp(cmd2.Cmd): repetitions = args.repeat or 1 output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline) - for i in range(min(repetitions, self.maxrepeats)): + for _ in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too self.poutput(output_str) -- cgit v1.2.1 From 633074ea4d7acb10e76665dd7c7080b570149e9c Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 27 Nov 2019 10:52:00 -0700 Subject: Fix flake8 error --- cmd2/ansi.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cmd2/ansi.py b/cmd2/ansi.py index 32d01399..db828af4 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -185,8 +185,13 @@ def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, underlin # These can be altered to suit an application's needs and only need to be a # function with the following structure: func(str) -> str style_success = functools.partial(style, fg='green', bold=True) +"""Partial function supplying arguments to style() to generate bold green text""" + style_warning = functools.partial(style, fg='bright_yellow') +"""Partial function supplying arguments to ansi.style() to generate yellow text""" + style_error = functools.partial(style, fg='bright_red') +"""Partial function supplying arguments to ansi.style() to generate bright red text""" def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_offset: int, alert_msg: str) -> str: -- cgit v1.2.1 From 965d46bd60557efca3e75cf46c8aa76194c4039b Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 27 Nov 2019 23:12:04 -0700 Subject: Write details for two sections - titles and headings - referencing methods --- docs/doc_conventions.rst | 119 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 104 insertions(+), 15 deletions(-) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index 39302fc6..226c5edc 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -22,25 +22,60 @@ In addition: Naming Files ------------ -- all lower case file names +All source files in the documentation must: + +- have all lower case file names - if the name has multiple words, separate them with an underscore -- all documentation file names end in '.rst' +- end in '.rst' + + +Titles and Headings +------------------- + +reStructuredText allows flexibility in how headings are defined. You only have +to worry about the heirarchy of headings within a single file. Sphinx magically +handles the intra-file heirarchy on it's own. This magic means that no matter +how you style titles and headings in the various files that comprise the +documentation, Sphinx will render properly structured output. To ensure we have +a similar consistency when viewing the source files, we use the following +conventions for titles and headings: + +1. When creating a heading for a section, do not use the overline and underline +syntax. Use the underline syntax only:: + + Document Title + ============== + +2. The string of adornment characters on the line following the heading should +be the same length as the title. + +3. The title of a document should use the '=' adornment character on the next +line and only one heading of this level should appear in each file. + +4. Sections within a document should have their titles adorned with the '-' +character:: + + Section Title + ------------- +5. Subsections within a section should have their titles adorned with the '~' +character:: -Heirarchy of headings ---------------------- + Subsection Title + ~~~~~~~~~~~~~~~~ -show the heirarchy of sphinx headings we use, and the conventions (underline -only, no overline) +6. Use two blank lines before every title unless it's the first heading in the +file. Use one blank line after every heading. -Use '=', then '-', then '~'. If your document needs more levels than that, -break it into separate documents. +7. If your document needs more than three levels of sections, break it into +separate documents. -You only have to worry about the heirarchy of headings within a single file. -Sphinx handles the intra-file heirarchy magically on it's own. -Use two blank lines before every heading unless it's the first heading in the -file. Use one blank line after every heading +Indenting +--------- + +In reStructuredText all indenting is significant. Use 2 spaces per indenting +level. Code @@ -85,9 +120,6 @@ and See :ref:`custom title` -[TODO what's the right way to link to source code? Can we make it link to the -tag that the documentation is rendered from?] - Autolinking ----------- @@ -96,6 +128,63 @@ Autolinking Referencing cmd2 API documentation ---------------------------------- +[TODO what's the right way to link to source code? Can we make it link to the +tag that the documentation is rendered from?] + +It's easy to reference and create a link to the API documentation for classes, +methods, functions, or attributes. + + +Referencing Methods +~~~~~~~~~~~~~~~~~~~ + +To reference a method, use one of the following approaches: + +1. Reference the full dotted path of the method:: + + The :meth:`cmd2.cmd2.Cmd.poutput` method is similar to the Python built-in + print function. + +Which renders as: The :meth:`cmd2.cmd2.Cmd.poutput` method is similar to the +Python built-in print function. + +2. Reference the full dotted path to the method, but only display the method +name:: + + The :meth:`~cmd2.cmd2.Cmd.poutput` method is similar to the Python built-in print function. + +Which renders as: The :meth:`~cmd2.cmd2.Cmd.poutput` method is similar to the +Python built-in print function. + +3. Reference a portion of the dotted path of the method:: + + The :meth:`.cmd2.Cmd.poutput` method is similar to the Python built-in print + function. + +Which renders as: The :meth:`.cmd2.Cmd.poutput` method is similar to the Python +built-in print function. + +Avoid either of these approaches: + +1. Reference just the class name without enough dotted path:: + + The :meth:`.Cmd.poutput` method is similar to the Python built-in print + function. + +Because ``cmd2.Cmd`` subclasses ``cmd.Cmd`` from the standard library, this +approach does not clarify which class it is referring to. + +2. Reference just a method name:: + + The :meth:`poutput` method is similar to the Python built-in print + function. + +While Sphinx may be smart enough to generate the correct output, the potential +for multiple matching references is high, which causes Sphinx to generate +warnings. The build pipeline that renders the documentation treats warnings as +fatal errors. It's best to just be specific about what you are referencing. + + Info and Warning Callouts ------------------------- -- cgit v1.2.1 From 029afe48b09bf32001d830c880fb32ca9defb8ef Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 16:10:20 -0700 Subject: Show various options for documenting attributes --- cmd2/cmd2.py | 16 +++++++++- docs/api/cmd.rst | 4 +++ docs/features/generating_output.rst | 58 +++++++++++++++++++++++++------------ 3 files changed, 59 insertions(+), 19 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 1eeb4212..9f2dd329 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -292,8 +292,8 @@ class Cmd(cmd.Cmd): # The error that prints when a non-existent command is run self.default_error = "{} is not a recognized command, alias, or macro" + """The error message displayed when a non-existent command is run.""" - # If this string is non-empty, then this warning message will print if a broken pipe error occurs while printing self.broken_pipe_warning = '' # Commands that will run at the beginning of the command loop @@ -416,6 +416,20 @@ class Cmd(cmd.Cmd): self.perror('Invalid value: {} (valid values: {}, {}, {})'.format(new_val, ansi.ANSI_TERMINAL, ansi.ANSI_ALWAYS, ansi.ANSI_NEVER)) + @property + def broken_pipe_warning(self) -> str: + """Message to display if a BrokenPipeError is raised while writing output. + + :meth:`~cmd2.cmd2.Cmd.poutput()` catches BrokenPipeError exceptions and + outputs the contents of `broken_pipe_warning`. The default value is an + empty string meaning the BrokenPipeError is silently swallowed. + """ + return self.broken_pipe_error + + @broken_pipe_warning.setter + def broken_pipe_warning(self, new_val: str) -> None: + self.broken_pipe_error = new_val + def _completion_supported(self) -> bool: """Return whether tab completion is supported""" return self.use_rawinput and self.completekey and rl_type != RlType.NONE diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst index 4f88101e..ebec17c3 100644 --- a/docs/api/cmd.rst +++ b/docs/api/cmd.rst @@ -3,3 +3,7 @@ cmd2.Cmd .. autoclass:: cmd2.cmd2.Cmd :members: + + .. attribute:: default_error + + diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 16ff044d..58e53962 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -38,18 +38,25 @@ TODO: Ordinary Output --------------- -The ``poutput()`` method is almost like using the Python built-in ``print()`` -function. ``poutput()`` adds two conveniences. +The :meth:`.cmd2.Cmd.poutput` method is similar to the Python +`built-in print function `_. :meth:`~cmd2.cmd2.Cmd.poutput` adds two +conveniences. -Since users can pipe output to a shell command, it catches ``BrokenPipeError`` -and outputs the contents of ``self.broken_pipe_warning`` to ``stderr``. -``self.broken_pipe_warning`` defaults to an empty string so this method will -just swallow the exception. If you want to show some error message, put it in -``self.broken_pipe_warning`` when you initialize ``Cmd2.cmd``. + 1. Since users can pipe output to a shell command, it catches + ``BrokenPipeError`` and outputs the contents of + ``self.broken_pipe_warning`` to ``stderr``. ``self.broken_pipe_warning`` + defaults to an empty string so this method will just swallow the exception. + If you want to show an error message, put it in + ``self.broken_pipe_warning`` when you initialize ``Cmd2.cmd``. -``poutput()`` also honors the :ref:`features/settings:allow_ansi` setting, -which controls whether ANSI escape sequences that instruct the terminal to -colorize output are stripped from the output. + 2. It examines and honors the :ref:`features/settings:allow_ansi` setting. + See :ref:`features/generating_output:Colored Output` below for more details. + +Here's a simple command that shows this method in action:: + + def do_echo(self, args): + """A simple command showing how poutput() works""" + self.poutput(args) Colored Output @@ -68,17 +75,35 @@ running on Windows, it wraps ``stdout``, looks for ANSI escape sequences, and converts them into the appropriate ``win32`` calls to modify the state of the terminal. -``cmd2`` imports and uses Colorama and also provides a number of convenience -methods for generating colorized output, measuring the screen width of -colorized output, setting the window title in the terminal, and removing ANSI -escape codes from a string. These functions are all documentated in -:ref:`api/ansi:cmd2.ansi`. +``cmd2`` imports and uses Colorama and provides a number of convenience methods +for generating colorized output, measuring the screen width of colorized +output, setting the window title in the terminal, and removing ANSI escape +codes from a string. These functions are all documentated in +:mod:`cmd2.ansi`. + +:mod:`cmd2.cmd2.Cmd` includes an :ref:`features/settings:allow_ansi` setting, +which controls whether ANSI escape sequences that instruct the terminal to +colorize output are stripped from the output. The recommended approach is to +construct your application so that it generates colorized output, and then +allow your users to use this setting to remove the colorization if they do not +want it. + +Output generated by any of these +methods will honor the :ref:`features/settings:allow_ansi` setting: + +- :meth:`cmd2.cmd2.Cmd.poutput` +- :meth:`cmd2.cmd2.Cmd.perror` +- :meth:`cmd2.cmd2.Cmd.pwarning` +- :meth:`cmd2.cmd2.Cmd.pexcept` +- :meth:`cmd2.cmd2.Cmd.pfeedback` +- :meth:`cmd2.cmd2.Cmd.ppaged` Error Messages -------------- + Warning Messages ---------------- @@ -121,6 +146,3 @@ Columnar Output --------------- Using wcswidth() and ansi.ansi_safe_wcswidth() - - - -- cgit v1.2.1 From 6102c0aa1b463b4653bf9d0e84fd0a6558fba5f1 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 16:11:07 -0700 Subject: Show usage of colorama for ansi text styling --- examples/colors.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/examples/colors.py b/examples/colors.py index 8c54dfa4..7a4d15e6 100755 --- a/examples/colors.py +++ b/examples/colors.py @@ -24,9 +24,11 @@ Always regardless of the output destination """ import argparse +from typing import Any import cmd2 from cmd2 import ansi +from colorama import Fore, Back, Style class CmdLineApp(cmd2.Cmd): @@ -66,9 +68,31 @@ class CmdLineApp(cmd2.Cmd): repetitions = args.repeat or 1 output_str = ansi.style(' '.join(words), fg=args.fg, bg=args.bg, bold=args.bold, underline=args.underline) - for i in range(min(repetitions, self.maxrepeats)): + for _ in range(min(repetitions, self.maxrepeats)): # .poutput handles newlines, and accommodates output redirection too self.poutput(output_str) + self.perror('error message at the end') + + @staticmethod + def perror(msg: Any, *, end: str = '\n', apply_style: bool = True) -> None: + """Override perror() method from `cmd2.Cmd` + + Use colorama native approach for styling the text instead of `cmd2.ansi` methods + + :param msg: message to print (anything convertible to a str with '{}'.format() is OK) + :param end: string appended after the end of the message, default a newline + :param apply_style: If True, then ansi.style_error will be applied to the message text. Set to False in cases + where the message text already has the desired style. Defaults to True. + """ + if apply_style: + final_msg = "{}{}{}{}".format(Fore.RED, Back.YELLOW, msg, Style.RESET_ALL) + else: + final_msg = "{}".format(msg) + ansi.ansi_aware_write(sys.stderr, final_msg + end) + + def do_timetravel(self, args): + """A command which always generates an error message, to demonstrate custom error colors""" + self.perror('Mr. Fusion failed to start. Could not energize flux capacitor.') if __name__ == '__main__': -- cgit v1.2.1 From de9e778481069b6d23d5b8ed639b328172633552 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 17:05:37 -0700 Subject: Show various attribute documentation approaches for #821 --- cmd2/cmd2.py | 13 ++++++++++--- docs/api/cmd.rst | 4 +++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 2ed87fdc..9174a3f4 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -133,6 +133,9 @@ class Cmd(cmd.Cmd): " This command is for internal use and is not intended to be called from the\n" " command line.") + debug = False + """Set to True to display a full stack trace when exceptions occur""" + # Sorting keys for strings ALPHABETICAL_SORT_KEY = utils.norm_fold NATURAL_SORT_KEY = utils.natural_keys @@ -417,9 +420,13 @@ class Cmd(cmd.Cmd): def broken_pipe_warning(self) -> str: """Message to display if a BrokenPipeError is raised while writing output. - :meth:`~cmd2.cmd2.Cmd.poutput()` catches BrokenPipeError exceptions and - outputs the contents of `broken_pipe_warning`. The default value is an - empty string meaning the BrokenPipeError is silently swallowed. + The following methods catch BrokenPipeError exceptions and output this message: + + - :meth:`~cmd2.cmd2.Cmd.poutput()` + - :meth:`~cmd2.cmd2.Cmd.ppaged()` + + The default value is an empty string meaning the BrokenPipeError is + silently swallowed. """ return self.broken_pipe_error diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst index ebec17c3..f50db544 100644 --- a/docs/api/cmd.rst +++ b/docs/api/cmd.rst @@ -4,6 +4,8 @@ cmd2.Cmd .. autoclass:: cmd2.cmd2.Cmd :members: - .. attribute:: default_error + .. attribute:: help_error + The error message displayed to the user when they request help for a + command with no help defined. -- cgit v1.2.1 From 69b108a8865ba96fd5959a3f1a8237c5e8f18732 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 22:23:35 -0700 Subject: Finish generating_output and document output related settings --- docs/features/generating_output.rst | 76 ++++++++++++++++++++++--------------- docs/features/settings.rst | 71 +++++++++++++++++++++------------- 2 files changed, 90 insertions(+), 57 deletions(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 58e53962..34416092 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -22,19 +22,6 @@ also adds a number of output related methods to ``Cmd2.Cmd`` which you may use to enhance the output your application produces. -TODO: - - -- perror -- pwarning -- pexcept -- ppaging - -- column formatting? -- wcswidth? - -- exceptions - Ordinary Output --------------- @@ -91,22 +78,27 @@ want it. Output generated by any of these methods will honor the :ref:`features/settings:allow_ansi` setting: -- :meth:`cmd2.cmd2.Cmd.poutput` -- :meth:`cmd2.cmd2.Cmd.perror` -- :meth:`cmd2.cmd2.Cmd.pwarning` -- :meth:`cmd2.cmd2.Cmd.pexcept` -- :meth:`cmd2.cmd2.Cmd.pfeedback` -- :meth:`cmd2.cmd2.Cmd.ppaged` +- :meth:`~.cmd2.Cmd.poutput` +- :meth:`~.cmd2.Cmd.perror` +- :meth:`~.cmd2.Cmd.pwarning` +- :meth:`~.cmd2.Cmd.pexcept` +- :meth:`~.cmd2.Cmd.pfeedback` +- :meth:`~.cmd2.Cmd.ppaged` Error Messages -------------- +When an error occurs in your program, you can display it on ``sys.stderr`` by +calling the :meth:`~.cmd2.Cmd.perror` method. Warning Messages ---------------- +:meth:`~.cmd2.Cmd.pwarning` is just like :meth:`~.cmd2.Cmd.perror` but applies +:meth:`cmd2.ansi.style_warning` to the output. + Feedback -------- @@ -116,33 +108,57 @@ to be part of the generated output. This could be debugging information or status information about the progress of long running commands. It's not output, it's not error messages, it's feedback. If you use the :ref:`features/settings:Timing` setting, the output of how long it took the -command to run will be output as feedback. ``cmd2`` has a ``self.pfeedback()`` -method to produce this type of output, and several -:ref:`features/settings:Settings` to control how this output is handled. +command to run will be output as feedback. You can use the +:meth:`~.cmd2.Cmd.pfeedback` method to produce this type of output, and +several :ref:`features/settings:Settings` control how it is handled. -If the ``quiet`` setting is ``True``, then calling ``self.pfeedback()`` -produces no output. If ``quiet`` is ``False``, then the ``feedback_to_output`` -setting is consulted to determine which file descriptor the feedback will be -sent to. The default value of ``False`` means all feedback is sent to -``sys.stderr``. If set to ``True``, then the feedback output will be sent to -``self.stdout`` along with the rest of the generated output. +If the :ref:`features/settings:quiet` setting is ``True``, then calling +:meth:`~.cmd2.Cmd.pfeedback` produces no output. If +:ref:`features/settings:quiet` is ``False``, the +:ref:`features/settings:feedback_to_output` setting is consulted to determine +whether to send the output to ``stdout`` or ``stderr``. Exceptions ---------- +If your app catches an exception and you would like to display the exception to +the user, the :meth:`~.cmd2.Cmd.pexcept` method can help. The default behavior +is to just display the message contained within the exception. However, if the +:ref:`features/settings:debug` setting is ``True``, then the entire stack trace +will be displayed. + Paging Output ------------- +If you know you are going to generate a lot of output, you may want to display +it in a way that the user can scroll forwards and backwards through it. If you +pass all of the output to be displayed in a single call to +:meth:`~.cmd2.Cmd.ppaged`, it will be piped to an operating system appropriate +shell command to page the output. On Windows, the output is piped to ``more``; +on Unix-like operating systems like MacOS and Linux, it is piped to ``less``. + Centering Text -------------- -utils.center_text() +If you would like to generate output which is centered in the user's terminal, +the :meth:`cmd2.utils.center_text` method can help. Pass it a string and it +will figure out the width of the terminal and return you a new string, +appropriately padded so it will be centered. Columnar Output --------------- -Using wcswidth() and ansi.ansi_safe_wcswidth() +When generating output in multiple columns, you often need to calculate the +width of each item so you can pad it appropriately with spaces. However, there +are categories of Unicode characters that occupy 2 cells, and other that occupy +0. To further complicate matters, you might have included ANSI escape sequences +in the output to generate colors on the terminal. + +The :meth:`cmd2.ansi.ansi_safe_wcswidth` function solves both of these +problems. Pass it a string, and regardless of which Unicode characters and ANSI +escape sequences it contains, it will tell you how many characters on the +screen that string will consume when printed. diff --git a/docs/features/settings.rst b/docs/features/settings.rst index 25162aed..f117c171 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -32,33 +32,6 @@ the ``set`` command like so:: (Cmd) set allow_ansi Never -Timing -~~~~~~ - -Setting ``App.timing`` to ``True`` outputs timing data after every application -command is executed. |settable| - - -Echo -~~~~ - -If ``True``, each command the user issues will be repeated to the screen before -it is executed. This is particularly useful when running scripts. - - -Debug -~~~~~ - -Setting ``App.debug`` to ``True`` will produce detailed error stacks whenever -the application generates an error. |settable| - -.. |settable| replace:: The user can ``set`` this parameter - during application execution. - (See :ref:`parameters`) - -.. _parameters: - - allow_ansi ~~~~~~~~~~ @@ -83,6 +56,50 @@ This setting can be one of three values: - ``Always`` - ANSI escape sequences are always passed through, regardless +debug +~~~~~ + +The default value of this setting is ``False``, which causes the +:meth:`~.cmd2.Cmd.pexcept` method to only display the message from an +exception. However, if the debug setting is ``True``, then the entire stack +trace will be printed. + + +echo +~~~~ + +If ``True``, each command the user issues will be repeated to the screen before +it is executed. This is particularly useful when running scripts. + + +feedback_to_output +~~~~~~~~~~~~~~~~~~ + +Controls whether feedback generated with the :meth:`~cmd2.cmd2.Cmd.pfeedback` +method is sent to ``sys.stdout`` or ``sys.stderr``. If ``False`` the output +will be sent to ``sys.stderr`` + +If ``True`` the output is sent to ``stdout`` (which is often the screen but may +be :ref:`redirected `). The +feedback output will be mixed in with and indistinguishable from output +generated with :meth:`~cmd2.cmd2.Cmd.poutput`. + + +quiet +~~~~~ + +If ``True``, output generated by calling :meth:`~cmd2.Cmd.pfeedback` is +suppressed. If ``False``, the :ref:`features/settings:feedback_to_output` +setting controls where the output is sent. + + +timing +~~~~~~ + +Setting ``App.timing`` to ``True`` outputs timing data after every application +command is executed. |settable| + + Create New Settings ------------------- -- cgit v1.2.1 From 309f542d5de2d357a64bcbf0a8bdb1d90918fb0f Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 22:29:47 -0700 Subject: Minor formatting cleanups --- docs/migrating/incompatibilities.rst | 15 ++++++++------- docs/migrating/next_steps.rst | 9 ++++----- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/migrating/incompatibilities.rst b/docs/migrating/incompatibilities.rst index 7526b51b..ba6f2ed1 100644 --- a/docs/migrating/incompatibilities.rst +++ b/docs/migrating/incompatibilities.rst @@ -46,15 +46,16 @@ writing a :ref:`Postparsing Hook `. Cmd.cmdqueue ------------ + In cmd_, the `Cmd.cmdqueue `_ attribute -contains A list of queued input lines. The cmdqueue list is checked in +contains a list of queued input lines. The cmdqueue list is checked in ``cmdloop()`` when new input is needed; if it is nonempty, its elements will be processed in order, as if entered at the prompt. -Since version 0.9.13 ``cmd2`` has removed support for ``Cmd.cmdqueue``. -Because ``cmd2`` supports running commands via the main ``cmdloop()``, text -scripts, Python scripts, transcripts, and history replays, the only way to -preserve consistent behavior across these methods was to eliminate the command -queue. Additionally, reasoning about application behavior is much easier -without this queue present. +Since version 0.9.13 ``cmd2`` has removed support for ``Cmd.cmdqueue``. Because +``cmd2`` supports running commands via the main ``cmdloop()``, text scripts, +Python scripts, transcripts, and history replays, the only way to preserve +consistent behavior across these methods was to eliminate the command queue. +Additionally, reasoning about application behavior is much easier without this +queue present. diff --git a/docs/migrating/next_steps.rst b/docs/migrating/next_steps.rst index f43c69c9..d95473ee 100644 --- a/docs/migrating/next_steps.rst +++ b/docs/migrating/next_steps.rst @@ -15,9 +15,8 @@ For all but the simplest of commands, it's probably easier to use `argparse ``cmd2`` provides a ``@with_argparser()`` decorator which associates an ``ArgumentParser`` object with one of your commands. Using this method will: -1. Pass your command a `Namespace -`_ -containing the arguments instead of a string of text. +1. Pass your command a `Namespace `_ + containing the arguments instead of a string of text. 2. Properly handle quoted string input from your users. @@ -52,8 +51,8 @@ Generating Output ----------------- If your program generates output by printing directly to ``sys.stdout``, you -should consider switching to :meth:`cmd2.cmd2.Cmd.poutput`, -:meth:`cmd2.cmd2.Cmd.perror`, and :meth:`cmd2.cmd2.Cmd.pfeedback`. These +should consider switching to :meth:`~cmd2.cmd2.Cmd.poutput`, +:meth:`~cmd2.cmd2.Cmd.perror`, and :meth:`~cmd2.cmd2.Cmd.pfeedback`. These methods work with several of the built in :ref:`features/settings:Settings` to allow the user to view or suppress feedback (i.e. progress or status output). They also properly handle ansi colored output according to user preference. -- cgit v1.2.1 From 4bc02bb8b33c6d15e1e65ba68608c5b1cc678411 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 22:38:09 -0700 Subject: Clean out some unused cruft --- docs/doc_conventions.rst | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index 226c5edc..fc60e08d 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -108,7 +108,7 @@ extension. This allows you to reference any header in any document by:: See :ref:`features/argument_processing:Help Messages` -or :: +or:: See :ref:`custom title` @@ -121,24 +121,10 @@ and See :ref:`custom title` -Autolinking ------------ - - Referencing cmd2 API documentation ---------------------------------- -[TODO what's the right way to link to source code? Can we make it link to the -tag that the documentation is rendered from?] - -It's easy to reference and create a link to the API documentation for classes, -methods, functions, or attributes. - - -Referencing Methods -~~~~~~~~~~~~~~~~~~~ - -To reference a method, use one of the following approaches: +To reference a method or function, use one of the following approaches: 1. Reference the full dotted path of the method:: @@ -193,9 +179,9 @@ Info and Warning Callouts Wrapping -------- -Hard wrap all text with line lengths no greater than 79 characters. It makes -everything easier when editing documentation, and has no impact on reading -documentation because we render to html. +Hard wrap all text so that line lengths are no greater than 79 characters. It +makes everything easier when editing documentation, and has no impact on +reading documentation because we render to html. Referencing cmd2 -- cgit v1.2.1 From 52f4275ff0fd1af90b1786c229de2c6fd845ec0e Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 23:51:12 -0700 Subject: Finish documenting settings and add new builtin_commands document --- cmd2/cmd2.py | 6 +++ docs/features/builtin_commands.rst | 48 ++++++++++++++++++ docs/features/index.rst | 1 + docs/features/settings.rst | 100 ++++++++++++++++++++++++++----------- 4 files changed, 126 insertions(+), 29 deletions(-) create mode 100644 docs/features/builtin_commands.rst diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 9174a3f4..c5b058a0 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -225,6 +225,12 @@ class Cmd(cmd.Cmd): 'quiet': "Don't print nonessential feedback", 'timing': 'Report execution times' } + """This dictionary contains the name and description of all settings available to users. + + Users use the :ref:`features/builtin_commands:set` command to view and + modify settings. Settings are stored in instance attributes with the + same name as the setting. + """ # Commands to exclude from the help menu and tab completion self.hidden_commands = ['eof', '_relative_load', '_relative_run_script'] diff --git a/docs/features/builtin_commands.rst b/docs/features/builtin_commands.rst new file mode 100644 index 00000000..ab4ca60e --- /dev/null +++ b/docs/features/builtin_commands.rst @@ -0,0 +1,48 @@ +Builtin Commands +================ + +Applications which subclass :class:`cmd2.cmd2.Cmd` inherit a number of commands +which may be useful to your users. + +edit +---- + +This command launches an editor program and instructs it to open the given file +name. Here's an example:: + + (Cmd) edit ~/.ssh/config + +The program to be launched is determined by the value of the +:ref:`features/settings:editor` setting. + + +set +--- + +A list of all user-settable parameters, with brief comments, is viewable from +within a running application:: + + (Cmd) set --long + allow_ansi: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) + continuation_prompt: > # On 2nd+ line of input + debug: False # Show full error stack on error + echo: False # Echo command issued into output + editor: vim # Program used by ``edit`` + feedback_to_output: False # include nonessentials in `|`, `>` results + locals_in_py: False # Allow access to your application in py via self + max_completion_items: 50 # Maximum number of CompletionItems to display during tab completion + prompt: (Cmd) # The prompt issued to solicit input + quiet: False # Don't print nonessential feedback + timing: False # Report execution times + +Any of these user-settable parameters can be set while running your app with +the ``set`` command like so:: + + (Cmd) set allow_ansi Never + + +Removing A Builtin Command +-------------------------- + +[TODO] show how to remove a builtin command if you don't want it available to +your users. diff --git a/docs/features/index.rst b/docs/features/index.rst index efeb9e6c..dc64badd 100644 --- a/docs/features/index.rst +++ b/docs/features/index.rst @@ -5,6 +5,7 @@ Features :maxdepth: 1 argument_processing + builtin_commands clipboard commands completion diff --git a/docs/features/settings.rst b/docs/features/settings.rst index f117c171..e1564ef6 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -1,36 +1,25 @@ Settings ======== -- current settings and what they do -- how a developer can add their own -- how to hide built in settings from a user +Settings provide a mechanism for a user to control the behavior of a ``cmd2`` +based application. A setting is stored in an instance attribute on your +subclass of :class:`cmd2.cmd2.Cmd` and must also appear in the +:attr:`cmd2.cmd2.Cmd.settable` dictionary. Developers may set default values +for these settings and users can modify them at runtime using the +:ref:`features/builtin_commands:set` command. Developers can +:ref:`features/settings:Create New Settings` and can also +:ref:`features/settings:Hide Builtin Settings` from the user. -Built In Settings ------------------ - -``cmd2`` has a number of built in settings, which a developer can set a default -value, and which users can modify to change the behavior of the application. -A list of all user-settable parameters, with brief comments, is viewable from -within a running application:: +Builtin Settings +----------------- - (Cmd) set --long - allow_ansi: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) - continuation_prompt: > # On 2nd+ line of input - debug: False # Show full error stack on error - echo: False # Echo command issued into output - editor: vim # Program used by ``edit`` - feedback_to_output: False # include nonessentials in `|`, `>` results - locals_in_py: False # Allow access to your application in py via self - max_completion_items: 50 # Maximum number of CompletionItems to display during tab completion - prompt: (Cmd) # The prompt issued to solicit input - quiet: False # Don't print nonessential feedback - timing: False # Report execution times -Any of these user-settable parameters can be set while running your app with -the ``set`` command like so:: +``cmd2`` has a number of builtin settings. These settings control the behavior +of certain application features and :ref:`features/builtin_commands:Builtin +Commands`. Users can use the :ref:`features/builtin_commands:set` command to +show all settings and to modify the value of any setting. - (Cmd) set allow_ansi Never allow_ansi ~~~~~~~~~~ @@ -56,6 +45,16 @@ This setting can be one of three values: - ``Always`` - ANSI escape sequences are always passed through, regardless +continuation_prompt +~~~~~~~~~~~~~~~~~~~ + +When a user types a :ref:`Multiline Command +` it may span more than one +line of input. The prompt for the first line of input is specified by the +:ref:`features/settings:prompt` setting. The prompt for subsequent lines of +input is defined by this setting. + + debug ~~~~~ @@ -72,6 +71,14 @@ If ``True``, each command the user issues will be repeated to the screen before it is executed. This is particularly useful when running scripts. +editor +~~~~~~ + +Similar to the ``EDITOR`` shell variable, this setting contains the name of the +program which should be run by the :ref:`features/builtin_commands:edit` +command. + + feedback_to_output ~~~~~~~~~~~~~~~~~~ @@ -85,10 +92,30 @@ feedback output will be mixed in with and indistinguishable from output generated with :meth:`~cmd2.cmd2.Cmd.poutput`. +locals_in_py +~~~~~~~~~~~~ + +Allow access to your application in one of the +:ref:`features/embedded_python_shells:Embedded Python Shells` via ``self``. + + +max_completion_items +~~~~~~~~~~~~~~~~~~~~ + +The maximum number of tab-completion items to display. + + +prompt +~~~~~~ + +This setting contains the string which should be printed as a prompt for user +input. + + quiet ~~~~~ -If ``True``, output generated by calling :meth:`~cmd2.Cmd.pfeedback` is +If ``True``, output generated by calling :meth:`~.cmd2.Cmd.pfeedback` is suppressed. If ``False``, the :ref:`features/settings:feedback_to_output` setting controls where the output is sent. @@ -96,8 +123,7 @@ setting controls where the output is sent. timing ~~~~~~ -Setting ``App.timing`` to ``True`` outputs timing data after every application -command is executed. |settable| +If ``True``, the elapsed time is reported for each command executed. Create New Settings @@ -137,5 +163,21 @@ changes a setting, and will receive both the old value and the new value. It's 13 C - are you a penguin? -Hide Built-in Settings +Hide Builtin Settings ---------------------- + +You may want to prevent a user from modifying a builtin setting. A setting +must appear in the :attr:`cmd2.cmd2.Cmd.settable` dictionary in order for it +to be available to the :ref:`features/builtin_commands:set` command. + +Let's say your program does not have any +:ref:`features/multiline_commands:Multiline Commands`. You might want to hide +the :ref:`features/settings:continuation_prompt` setting from your users since +it is only applicable to multiline commands. To do so, remove it from the +:attr:`cmd2.cmd2.Cmd.settable` dictionary after you initialize your object:: + + class MyApp(cmd2.Cmd): + + def __init__(self): + super().__init__() + self.settable.pop('continuation_prompt') -- cgit v1.2.1 From f22129eaf7859005ae34e357488a03ff7ea4ac40 Mon Sep 17 00:00:00 2001 From: kotfu Date: Fri, 29 Nov 2019 23:58:30 -0700 Subject: Spacing fix --- docs/features/settings.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/features/settings.rst b/docs/features/settings.rst index e1564ef6..88d76dc8 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -14,7 +14,6 @@ for these settings and users can modify them at runtime using the Builtin Settings ----------------- - ``cmd2`` has a number of builtin settings. These settings control the behavior of certain application features and :ref:`features/builtin_commands:Builtin Commands`. Users can use the :ref:`features/builtin_commands:set` command to -- cgit v1.2.1 From 10da7317721cd091af9e235d33c81b8c6e93e450 Mon Sep 17 00:00:00 2001 From: kotfu Date: Sat, 30 Nov 2019 00:07:46 -0700 Subject: Reorganize doc conventions --- docs/doc_conventions.rst | 87 +++++++++++++++++++++++------------------------- 1 file changed, 41 insertions(+), 46 deletions(-) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index fc60e08d..082235da 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -19,6 +19,17 @@ In addition: documentation, and to the API reference +Style Checker +------------- + +Use `doc8 `_ to check the style of the +documentation. This tool can be invoked using the proper options by typing: + +.. code-block:: shell + + $ invoke doc8 + + Naming Files ------------ @@ -29,6 +40,21 @@ All source files in the documentation must: - end in '.rst' +Indenting +--------- + +In reStructuredText all indenting is significant. Use 2 spaces per indenting +level. + + +Wrapping +-------- + +Hard wrap all text so that line lengths are no greater than 79 characters. It +makes everything easier when editing documentation, and has no impact on +reading documentation because we render to html. + + Titles and Headings ------------------- @@ -71,37 +97,30 @@ file. Use one blank line after every heading. separate documents. -Indenting ---------- +Inline Code +----------- -In reStructuredText all indenting is significant. Use 2 spaces per indenting -level. - - -Code ----- - -This documentation declares python as the default Sphinx domain. Python code -or interactive python sessions can be presented by either: +This documentation declares ``python`` as the default Sphinx domain. Python +code or interactive Python sessions can be presented by either: - finishing the preceding paragraph with a ``::`` and indenting the code - use the ``.. code-block::`` directive -If you want to show other code, like shell commands, then use ``.. code-block: -shell``. - +If you want to show non-Python code, like shell commands, then use ``.. +code-block: shell``. -Table of Contents and Captions ------------------------------- - -Hyperlinks ----------- +External Hyperlinks +------------------- If you want to use an external hyperlink target, define the target at the top -of the page, not the bottom. +of the page or the top of the section, not the bottom. The target definition +should always appear before it is referenced. +Links To Other Documentation Pages and Sections +----------------------------------------------- + We use the Sphinx `autosectionlabel `_ extension. This allows you to reference any header in any document by:: @@ -121,8 +140,8 @@ and See :ref:`custom title` -Referencing cmd2 API documentation ----------------------------------- +Links to API Reference +---------------------- To reference a method or function, use one of the following approaches: @@ -171,33 +190,9 @@ warnings. The build pipeline that renders the documentation treats warnings as fatal errors. It's best to just be specific about what you are referencing. - -Info and Warning Callouts -------------------------- - - -Wrapping --------- - -Hard wrap all text so that line lengths are no greater than 79 characters. It -makes everything easier when editing documentation, and has no impact on -reading documentation because we render to html. - - Referencing cmd2 ----------------- Whenever you reference ``cmd2`` in the documentation, enclose it in double backticks. This indicates an inline literal in restructured text, and makes it stand out when rendered as html. - -Style Checker -------------- - -Use `doc8 `_ to check the style of the -documentation. This tool can be invoked using the proper options by typing: - -.. code-block:: shell - - $ invoke doc8 - -- cgit v1.2.1 From e156d1b83a48206d1a1712d569262bf9d5663de1 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 21:52:56 -0700 Subject: Remove attribute documentation for #821 We will not try and have Sphnix extract attribute documentation from the source code, it will just live in the documentation. --- cmd2/cmd2.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index ec8d67b2..2ae65125 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -133,9 +133,6 @@ class Cmd(cmd.Cmd): " This command is for internal use and is not intended to be called from the\n" " command line.") - debug = False - """Set to True to display a full stack trace when exceptions occur""" - # Sorting keys for strings ALPHABETICAL_SORT_KEY = utils.norm_fold NATURAL_SORT_KEY = utils.natural_keys @@ -298,7 +295,6 @@ class Cmd(cmd.Cmd): # The error that prints when a non-existent command is run self.default_error = "{} is not a recognized command, alias, or macro" - """The error message displayed when a non-existent command is run.""" self.broken_pipe_warning = '' @@ -422,24 +418,6 @@ class Cmd(cmd.Cmd): self.perror('Invalid value: {} (valid values: {}, {}, {})'.format(new_val, ansi.STYLE_TERMINAL, ansi.STYLE_ALWAYS, ansi.STYLE_NEVER)) - @property - def broken_pipe_warning(self) -> str: - """Message to display if a BrokenPipeError is raised while writing output. - - The following methods catch BrokenPipeError exceptions and output this message: - - - :meth:`~cmd2.cmd2.Cmd.poutput()` - - :meth:`~cmd2.cmd2.Cmd.ppaged()` - - The default value is an empty string meaning the BrokenPipeError is - silently swallowed. - """ - return self.broken_pipe_error - - @broken_pipe_warning.setter - def broken_pipe_warning(self, new_val: str) -> None: - self.broken_pipe_error = new_val - def _completion_supported(self) -> bool: """Return whether tab completion is supported""" return self.use_rawinput and self.completekey and rl_type != RlType.NONE -- cgit v1.2.1 From 8247446728d09ee0de7b1e4312606126257f6d11 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 21:53:10 -0700 Subject: Updates for allow_ansi -> allow_style --- docs/features/builtin_commands.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/features/builtin_commands.rst b/docs/features/builtin_commands.rst index ab4ca60e..2e434a50 100644 --- a/docs/features/builtin_commands.rst +++ b/docs/features/builtin_commands.rst @@ -23,7 +23,7 @@ A list of all user-settable parameters, with brief comments, is viewable from within a running application:: (Cmd) set --long - allow_ansi: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) + allow_style: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) continuation_prompt: > # On 2nd+ line of input debug: False # Show full error stack on error echo: False # Echo command issued into output @@ -38,7 +38,7 @@ within a running application:: Any of these user-settable parameters can be set while running your app with the ``set`` command like so:: - (Cmd) set allow_ansi Never + (Cmd) set allow_style Never Removing A Builtin Command -- cgit v1.2.1 From dadf6c82b96b049df965b0f5a71c5726cf8cd705 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 21:53:22 -0700 Subject: Add documentation for default_error --- docs/api/cmd.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst index f50db544..5c6b6122 100644 --- a/docs/api/cmd.rst +++ b/docs/api/cmd.rst @@ -9,3 +9,6 @@ cmd2.Cmd The error message displayed to the user when they request help for a command with no help defined. + .. attribute:: default_error + + The error message displayed when a non-existent command is run. -- cgit v1.2.1 From c845d33217bdef6c061f4a24864326836f9f1d48 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 22:17:36 -0700 Subject: Add shell command, and show how to remove builtin commands --- docs/features/builtin_commands.rst | 43 +++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/docs/features/builtin_commands.rst b/docs/features/builtin_commands.rst index 2e434a50..6bba13fe 100644 --- a/docs/features/builtin_commands.rst +++ b/docs/features/builtin_commands.rst @@ -2,13 +2,17 @@ Builtin Commands ================ Applications which subclass :class:`cmd2.cmd2.Cmd` inherit a number of commands -which may be useful to your users. +which may be useful to your users. Developers can +:ref:`features/builtin_commands:Remove Builtin Commands` if they do not want +them to be part of the application. edit ---- This command launches an editor program and instructs it to open the given file -name. Here's an example:: +name. Here's an example: + +.. code-block:: text (Cmd) edit ~/.ssh/config @@ -20,7 +24,9 @@ set --- A list of all user-settable parameters, with brief comments, is viewable from -within a running application:: +within a running application: + +.. code-block:: text (Cmd) set --long allow_style: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) @@ -36,13 +42,34 @@ within a running application:: timing: False # Report execution times Any of these user-settable parameters can be set while running your app with -the ``set`` command like so:: +the ``set`` command like so: + +.. code-block:: text (Cmd) set allow_style Never -Removing A Builtin Command --------------------------- +shell +----- + +Execute a command as if at the operating system shell prompt: + +.. code-block:: text + + (Cmd) shell pwd -P + /usr/local/bin + + +Remove Builtin Commands +----------------------- + +Developers may not want to offer the commands builtin to :class:`cmd2.cmd2.Cmd` +to users of their application. To remove a command you must delete the method +implementing that command from the :class:`cmd2.cmd2.Cmd` object at runtime. +For example, if you wanted to remove the :ref:`features/builtin_commands:shell` +command from your application:: + + class NoShellApp(cmd2.Cmd): + """A simple cmd2 application.""" -[TODO] show how to remove a builtin command if you don't want it available to -your users. + delattr(cmd2.Cmd, 'do_shell') -- cgit v1.2.1 From e56d191e4de52482658b267e43eaff5bf324387c Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 22:26:08 -0700 Subject: Move settable documentation from source code to api docs --- cmd2/cmd2.py | 6 ------ docs/api/cmd.rst | 8 ++++++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 2ae65125..7ad2b471 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -222,12 +222,6 @@ class Cmd(cmd.Cmd): 'quiet': "Don't print nonessential feedback", 'timing': 'Report execution times' } - """This dictionary contains the name and description of all settings available to users. - - Users use the :ref:`features/builtin_commands:set` command to view and - modify settings. Settings are stored in instance attributes with the - same name as the setting. - """ # Commands to exclude from the help menu and tab completion self.hidden_commands = ['eof', '_relative_load', '_relative_run_script'] diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst index 5c6b6122..ee8d7c67 100644 --- a/docs/api/cmd.rst +++ b/docs/api/cmd.rst @@ -12,3 +12,11 @@ cmd2.Cmd .. attribute:: default_error The error message displayed when a non-existent command is run. + + .. attribute:: settable + + This dictionary contains the name and description of all settings available to users. + + Users use the :ref:`features/builtin_commands:set` command to view and + modify settings. Settings are stored in instance attributes with the + same name as the setting. -- cgit v1.2.1 From 6331e81de1f86b91eb8044a87d1ba2ffbe326183 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 22:33:19 -0700 Subject: Clean up function documentation so it renders properly --- cmd2/ansi.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd2/ansi.py b/cmd2/ansi.py index 78e0df81..6ed51517 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -94,6 +94,7 @@ def strip_style(text: str) -> str: def style_aware_wcswidth(text: str) -> int: """ Wrap wcswidth to make it compatible with strings that contains ANSI style sequences + :param text: the string being measured :return: the width of the string when printed to the terminal """ @@ -104,6 +105,7 @@ def style_aware_wcswidth(text: str) -> int: def style_aware_write(fileobj: IO, msg: str) -> None: """ Write a string to a fileobject and strip its ANSI style sequences if required by allow_style setting + :param fileobj: the file object being written to :param msg: the string being written """ @@ -116,6 +118,7 @@ def style_aware_write(fileobj: IO, msg: str) -> None: def fg_lookup(fg_name: str) -> str: """ Look up ANSI escape codes based on foreground color name. + :param fg_name: foreground color name to look up ANSI escape code(s) for :return: ANSI escape code(s) associated with this color :raises ValueError: if the color cannot be found @@ -130,6 +133,7 @@ def fg_lookup(fg_name: str) -> str: def bg_lookup(bg_name: str) -> str: """ Look up ANSI escape codes based on background color name. + :param bg_name: background color name to look up ANSI escape code(s) for :return: ANSI escape code(s) associated with this color :raises ValueError: if the color cannot be found @@ -194,13 +198,13 @@ def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, # These can be altered to suit an application's needs and only need to be a # function with the following structure: func(str) -> str style_success = functools.partial(style, fg='green') -"""Partial function supplying arguments to style() to generate bold green text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate bold green text""" style_warning = functools.partial(style, fg='bright_yellow') -"""Partial function supplying arguments to ansi.style() to generate yellow text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate yellow text""" style_error = functools.partial(style, fg='bright_red') -"""Partial function supplying arguments to ansi.style() to generate bright red text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate bright red text""" def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_offset: int, alert_msg: str) -> str: -- cgit v1.2.1 From ec8e7438edb0ff05758f1b4e11a483e0080228b9 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 22:33:29 -0700 Subject: Add comment for broken_pipe_warning --- cmd2/cmd2.py | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 7ad2b471..f41fb139 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -290,6 +290,7 @@ class Cmd(cmd.Cmd): # The error that prints when a non-existent command is run self.default_error = "{} is not a recognized command, alias, or macro" + # If non-empty, this contents will be displayed if a broken pipe error occurs self.broken_pipe_warning = '' # Commands that will run at the beginning of the command loop -- cgit v1.2.1 From 1d47c09cb7e34b6399115cf6b41f606f2495f875 Mon Sep 17 00:00:00 2001 From: kotfu Date: Tue, 14 Jan 2020 23:08:40 -0700 Subject: Revise allow_style and colored output documentation --- docs/features/generating_output.rst | 129 ++++++++++++++---------------------- docs/features/settings.rst | 23 ++++--- 2 files changed, 64 insertions(+), 88 deletions(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 78ff7657..bb03fa97 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -7,34 +7,34 @@ methods:: print("Greetings, Professor Falken.", file=self.stdout) self.stdout.write("Shall we play a game?\n") -While you could send output directly to ``sys.stdout``, ``cmd`` can be -initialized with a ``stdin`` and ``stdout`` variables, which it stores -as ``self.stdin`` and ``self.stdout``. By using these variables every -time you produce output, you can trivially change where all the output -goes by changing how you initialize your class. +While you could send output directly to ``sys.stdout``, :mod:`cmd2.cmd2.Cmd` +can be initialized with a ``stdin`` and ``stdout`` variables, which it stores +as ``self.stdin`` and ``self.stdout``. By using these variables every time you +produce output, you can trivially change where all the output goes by changing +how you initialize your class. -``cmd2`` extends this approach in a number of convenient ways. See +:mod:`cmd2.cmd2.Cmd` extends this approach in a number of convenient ways. See :ref:`features/redirection:Output Redirection And Pipes` for information on how users can change where the output of a command is sent. In order for those features to work, the output you generate must be sent to ``self.stdout``. You -can use the methods described above, and everything will work fine. ``cmd2`` -also adds a number of output related methods to ``Cmd2.Cmd`` which you may use -to enhance the output your application produces. +can use the methods described above, and everything will work fine. +:mod:`cmd2.cmd2.Cmd` also includes a number of output related methods which you +may use to enhance the output your application produces. Ordinary Output --------------- -The :meth:`.cmd2.Cmd.poutput` method is similar to the Python -`built-in print function `_. :meth:`~cmd2.cmd2.Cmd.poutput` adds two -conveniences. +The :meth:`~.cmd2.Cmd.poutput` method is similar to the Python +`built-in print function `_. :meth:`~.cmd2.Cmd.poutput` adds two +conveniences: 1. Since users can pipe output to a shell command, it catches ``BrokenPipeError`` and outputs the contents of ``self.broken_pipe_warning`` to ``stderr``. ``self.broken_pipe_warning`` defaults to an empty string so this method will just swallow the exception. If you want to show an error message, put it in - ``self.broken_pipe_warning`` when you initialize ``Cmd2.cmd``. + ``self.broken_pipe_warning`` when you initialize :mod:`.cmd2.Cmd`. 2. It examines and honors the :ref:`features/settings:allow_style` setting. See :ref:`features/generating_output:Colored Output` below for more details. @@ -46,75 +46,12 @@ Here's a simple command that shows this method in action:: self.poutput(args) -Colored Output --------------- -The output methods in the previous section all honor the ``allow_style`` -setting, which has three possible values: - -Never - poutput(), pfeedback(), and ppaged() strip all ANSI style sequences - which instruct the terminal to colorize output - -Terminal - (the default value) poutput(), pfeedback(), and ppaged() do not strip any - ANSI style sequences when the output is a terminal, but if the output is a - pipe or a file the style sequences are stripped. If you want colorized - output you must add ANSI style sequences using either cmd2's internal ansi - module or another color library such as `plumbum.colors`, `colorama`, or - `colored`. - -Always - poutput(), pfeedback(), and ppaged() never strip ANSI style sequences, - regardless of the output destination - -Colored and otherwise styled output can be generated using the `ansi.style()` -function: - -.. automethod:: cmd2.ansi.style - :noindex: - -You may want to generate output in different colors, which is typically done by -adding `ANSI escape sequences -`_ which tell the -terminal to change the foreground and background colors. If you want to give -yourself a headache, you can generate these by hand. You could also use another -Python color library like `plumbum.colors -`_, `colored -`_, or `colorama -`_. Colorama is unique because when it's -running on Windows, it wraps ``stdout``, looks for ANSI escape sequences, and -converts them into the appropriate ``win32`` calls to modify the state of the -terminal. - -``cmd2`` imports and uses Colorama and provides a number of convenience methods -for generating colorized output, measuring the screen width of colorized -output, setting the window title in the terminal, and removing ANSI escape -codes from a string. These functions are all documentated in -:mod:`cmd2.ansi`. - -:mod:`cmd2.cmd2.Cmd` includes an :ref:`features/settings:allow_style` setting, -which controls whether ANSI escape sequences that instruct the terminal to -colorize output are stripped from the output. The recommended approach is to -construct your application so that it generates colorized output, and then -allow your users to use this setting to remove the colorization if they do not -want it. - -Output generated by any of these -methods will honor the :ref:`features/settings:allow_style` setting: - -- :meth:`~.cmd2.Cmd.poutput` -- :meth:`~.cmd2.Cmd.perror` -- :meth:`~.cmd2.Cmd.pwarning` -- :meth:`~.cmd2.Cmd.pexcept` -- :meth:`~.cmd2.Cmd.pfeedback` -- :meth:`~.cmd2.Cmd.ppaged` - - Error Messages -------------- When an error occurs in your program, you can display it on ``sys.stderr`` by -calling the :meth:`~.cmd2.Cmd.perror` method. +calling the :meth:`~.cmd2.Cmd.perror` method. By default this method applies +:meth:`cmd2.ansi.style_error` to the output. Warning Messages @@ -164,6 +101,42 @@ shell command to page the output. On Windows, the output is piped to ``more``; on Unix-like operating systems like MacOS and Linux, it is piped to ``less``. +Colored Output +-------------- + +You can add your own `ANSI escape sequences +`_ to your output which +tell the terminal to change the foreground and background colors. If you want +to give yourself a headache, you can generate these by hand. You could also use +a Python color library like `plumbum.colors +`_, `colored +`_, or `colorama +`_. Colorama is unique because when it's +running on Windows, it wraps ``stdout``, looks for ANSI escape sequences, and +converts them into the appropriate ``win32`` calls to modify the state of the +terminal. + +``cmd2`` imports and uses Colorama and provides a number of convenience methods +for generating colorized output, measuring the screen width of colorized +output, setting the window title in the terminal, and removing ANSI escape +codes from a string. These functions are all documentated in +:mod:`cmd2.ansi`. + +After adding the desired escape sequences to your output, you should use one of +these methods to present the output to the user: + +- :meth:`.cmd2.Cmd.poutput` +- :meth:`.cmd2.Cmd.perror` +- :meth:`.cmd2.Cmd.pwarning` +- :meth:`.cmd2.Cmd.pexcept` +- :meth:`.cmd2.Cmd.pfeedback` +- :meth:`.cmd2.Cmd.ppaged` + +These methods all honor the :ref:`features/settings:allow_style` setting, which +users can modify to control whether these escape codes are passed through to +the terminal or not. + + Centering Text -------------- diff --git a/docs/features/settings.rst b/docs/features/settings.rst index 5e2280cd..a8c0705f 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -23,25 +23,28 @@ show all settings and to modify the value of any setting. allow_style ~~~~~~~~~~~ -The ``allow_style`` setting controls the behavior of ANSI escape sequences -in output generated with any of the following methods: - -- ``poutput()`` -- ``perror()`` -- ``pwarning()`` -- ``pfeedback()`` -- ``ppaged()`` +Output generated by ``cmd2`` programs may contain ANSI escape seqences which +instruct the terminal to apply colors or text styling (i.e. bold) to the +output. The ``allow_style`` setting controls the behavior of these escape +sequences in output generated with any of the following methods: + +- :meth:`.cmd2.Cmd.poutput` +- :meth:`.cmd2.Cmd.perror` +- :meth:`.cmd2.Cmd.pwarning` +- :meth:`.cmd2.Cmd.pexcept` +- :meth:`.cmd2.Cmd.pfeedback` +- :meth:`.cmd2.Cmd.ppaged` This setting can be one of three values: -- ``Never`` - all ANSI escape sequences which instruct the terminal to colorize +- ``Never`` - all ANSI escape sequences which instruct the terminal to style output are stripped from the output. - ``Terminal`` - (the default value) pass through ANSI escape sequences when the output is being sent to the terminal, but if the output is redirected to a pipe or a file the escape sequences are stripped. -- ``Always`` - ANSI escape sequences are always passed through, regardless +- ``Always`` - ANSI escape sequences are always passed through to the output continuation_prompt -- cgit v1.2.1 From 4082e2f39e61fabc202a691f6810a841fbd4ba6c Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 15 Jan 2020 20:38:39 -0700 Subject: Fix document rendering error --- docs/features/generating_output.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index bb03fa97..09673214 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -34,7 +34,7 @@ conveniences: ``self.broken_pipe_warning`` to ``stderr``. ``self.broken_pipe_warning`` defaults to an empty string so this method will just swallow the exception. If you want to show an error message, put it in - ``self.broken_pipe_warning`` when you initialize :mod:`.cmd2.Cmd`. + ``self.broken_pipe_warning`` when you initialize :mod:`~cmd2.cmd2.Cmd`. 2. It examines and honors the :ref:`features/settings:allow_style` setting. See :ref:`features/generating_output:Colored Output` below for more details. -- cgit v1.2.1 From 9a899dcad35335104ba3faf112f954874f13ac3b Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 15 Jan 2020 22:35:40 -0700 Subject: Clarify how to document instance attributes --- docs/doc_conventions.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index 082235da..e577fd50 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -140,6 +140,20 @@ and See :ref:`custom title` +API Documentation +----------------- + +The API documentation is mostly pulled from docstrings in the source code using +the Sphinx `autodoc +`_ +extension. However, Sphinx has issues generating documentation for instance +attributes (see `cmd2 issue 821 +`_ for the full discussion). We +have chosen to not use code as the source of instance attribute documentation. +Instead, it is added manually to the documentation files in ``cmd2/docs/api``. +See ``cmd2/docs/api/cmd.rst`` to see how to add documentation for an attribute. + + Links to API Reference ---------------------- -- cgit v1.2.1 From e7a4505d10dc6ed6e4bd34fb017589fba4d0b39c Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 15 Jan 2020 22:40:25 -0700 Subject: Clarify comment style for module data members and class attributes --- docs/doc_conventions.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index e577fd50..0b44f096 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -153,6 +153,12 @@ have chosen to not use code as the source of instance attribute documentation. Instead, it is added manually to the documentation files in ``cmd2/docs/api``. See ``cmd2/docs/api/cmd.rst`` to see how to add documentation for an attribute. +For module data members and class attributes, the ``autodoc`` extension allows +documentation in a comment with special formatting (using a #: to start the +comment instead of just #), or in a docstring after the definition. This project +has standardized on the docstring after the definition approach. Do not use the +specially formatted comment approach. + Links to API Reference ---------------------- -- cgit v1.2.1 From 8914dd5cbfc61d2f356a1a4f3049ec2aa5dd42b9 Mon Sep 17 00:00:00 2001 From: kotfu Date: Wed, 15 Jan 2020 22:41:30 -0700 Subject: Fix doc8 error --- docs/doc_conventions.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst index 0b44f096..9b714d45 100644 --- a/docs/doc_conventions.rst +++ b/docs/doc_conventions.rst @@ -155,9 +155,9 @@ See ``cmd2/docs/api/cmd.rst`` to see how to add documentation for an attribute. For module data members and class attributes, the ``autodoc`` extension allows documentation in a comment with special formatting (using a #: to start the -comment instead of just #), or in a docstring after the definition. This project -has standardized on the docstring after the definition approach. Do not use the -specially formatted comment approach. +comment instead of just #), or in a docstring after the definition. This +project has standardized on the docstring after the definition approach. Do not +use the specially formatted comment approach. Links to API Reference -- cgit v1.2.1 From dcf83a36a38b0aad650571d19da073d92b029382 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 16 Jan 2020 10:04:17 -0500 Subject: Updating docs for default style functions --- cmd2/ansi.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd2/ansi.py b/cmd2/ansi.py index 6ed51517..d3af525a 100644 --- a/cmd2/ansi.py +++ b/cmd2/ansi.py @@ -198,13 +198,13 @@ def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, # These can be altered to suit an application's needs and only need to be a # function with the following structure: func(str) -> str style_success = functools.partial(style, fg='green') -"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate bold green text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify success""" style_warning = functools.partial(style, fg='bright_yellow') -"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate yellow text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify a warning""" style_error = functools.partial(style, fg='bright_red') -"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` to generate bright red text""" +"""Partial function supplying arguments to :meth:`cmd2.ansi.style()` which colors text to signify an error""" def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_offset: int, alert_msg: str) -> str: -- cgit v1.2.1 From 37b8bcad1dada15d91704f1195920fd59bbdd7d1 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 16 Jan 2020 10:37:20 -0500 Subject: Updating some doc text --- cmd2/cmd2.py | 2 +- docs/features/builtin_commands.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index f41fb139..cce281b7 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -290,7 +290,7 @@ class Cmd(cmd.Cmd): # The error that prints when a non-existent command is run self.default_error = "{} is not a recognized command, alias, or macro" - # If non-empty, this contents will be displayed if a broken pipe error occurs + # If non-empty, this string will be displayed if a broken pipe error occurs self.broken_pipe_warning = '' # Commands that will run at the beginning of the command loop diff --git a/docs/features/builtin_commands.rst b/docs/features/builtin_commands.rst index 6bba13fe..2a857339 100644 --- a/docs/features/builtin_commands.rst +++ b/docs/features/builtin_commands.rst @@ -29,7 +29,7 @@ within a running application: .. code-block:: text (Cmd) set --long - allow_style: Terminal # Allow ANSI escape sequences in output (valid values: Terminal, Always, Never) + allow_style: Terminal # Allow ANSI text style sequences in output (valid values: Terminal, Always, Never) continuation_prompt: > # On 2nd+ line of input debug: False # Show full error stack on error echo: False # Echo command issued into output -- cgit v1.2.1 From fa2de84eacefe2d1eef969fa3e4de70df176c758 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 16 Jan 2020 10:46:46 -0500 Subject: Updating some doc text --- docs/features/generating_output.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 09673214..2c110ea2 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -118,8 +118,8 @@ terminal. ``cmd2`` imports and uses Colorama and provides a number of convenience methods for generating colorized output, measuring the screen width of colorized -output, setting the window title in the terminal, and removing ANSI escape -codes from a string. These functions are all documentated in +output, setting the window title in the terminal, and removing ANSI text style +escape codes from a string. These functions are all documentated in :mod:`cmd2.ansi`. After adding the desired escape sequences to your output, you should use one of -- cgit v1.2.1 From 6ef3b08257c768b353d3cfa726e3f19c34f0cf53 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 16 Jan 2020 10:55:58 -0500 Subject: Updating some doc text --- docs/features/generating_output.rst | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst index 2c110ea2..f3d2a7f4 100644 --- a/docs/features/generating_output.rst +++ b/docs/features/generating_output.rst @@ -137,13 +137,21 @@ users can modify to control whether these escape codes are passed through to the terminal or not. -Centering Text +Aligning Text -------------- -If you would like to generate output which is centered in the user's terminal, -the :meth:`cmd2.utils.align_center` method can help. Pass it a string and it -will figure out the width of the terminal and return you a new string, -appropriately padded so it will be centered. +If you would like to generate output which is left, center, or right aligned within a +specified width or the terminal width, the following functions can help: + +- :meth:`cmd2.utils.align_left` +- :meth:`cmd2.utils.align_center` +- :meth:`cmd2.utils.align_right` + +These functions differ from Python's string justifying functions in that they support +characters with display widths greater than 1. Additionally, ANSI style sequences are safely +ignored and do not count toward the display width. This means colored text is supported. If +text has line breaks, then each line is aligned independently. + Columnar Output @@ -157,5 +165,5 @@ in the output to generate colors on the terminal. The :meth:`cmd2.ansi.style_aware_wcswidth` function solves both of these problems. Pass it a string, and regardless of which Unicode characters and ANSI -escape sequences it contains, it will tell you how many characters on the +text style escape sequences it contains, it will tell you how many characters on the screen that string will consume when printed. -- cgit v1.2.1 From 64c05ab4fd71f2c235644af2d18672edf6757702 Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Thu, 16 Jan 2020 11:12:35 -0500 Subject: Updating some doc text --- docs/features/settings.rst | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/features/settings.rst b/docs/features/settings.rst index a8c0705f..627f61a9 100644 --- a/docs/features/settings.rst +++ b/docs/features/settings.rst @@ -70,7 +70,8 @@ echo ~~~~ If ``True``, each command the user issues will be repeated to the screen before -it is executed. This is particularly useful when running scripts. +it is executed. This is particularly useful when running scripts. This behavior +does not occur when a running command at the prompt. editor @@ -104,7 +105,13 @@ Allow access to your application in one of the max_completion_items ~~~~~~~~~~~~~~~~~~~~ -The maximum number of tab-completion items to display. +Maximum number of CompletionItems to display during tab completion. A CompletionItem +is a special kind of tab-completion hint which displays both a value and description +and uses one line for each hint. Tab complete the ``set`` command for an example. + +If the number of tab-completion hints exceeds ``max_completion_items``, then they will +be displayed in the typical columnized format and will not include the description text +of the CompletionItem. prompt -- cgit v1.2.1