Skip to content
Myr

Added support for explicit terminal widths and disabling of rewrapping

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 277d410 · Browse files · 4 files+129 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+129 added−10 removed

  • tests:+41 added−0 removed
  • other:+88 added−10 removed

4 files+129 added−10 removed

modified:click/core.py+18 added-4 removed
47 unmodified lines
48 does not affect manually set environment49 variables which are always read.50 :param default_map: a dictionary (like object) with default values51 for parameters.52 :param terminal_width: the width of the terminal. The default is53 inherit from parent context. If no context54 defines the terminal width then auto55 detection will be applied.56 """5758 def __init__(self, command, parent=None, info_name=None, obj=None,55 auto_envvar_prefix=None, default_map=None):59 auto_envvar_prefix=None, default_map=None,60 terminal_width=None):61 #: the parent context or `None` if none exists.62 self.parent = parent63 #: the :class:`Command` for this context.64 self.command = command
16 unmodified lines
81 self.obj = obj82 #: A dictionary (like object) with defaults for parameters.83 self.default_map = default_map8485 if terminal_width is None and parent is not None:86 terminal_width = parent.terminal_width87 #: The width of the terminal (None is autodetection).88 self.terminal_width = terminal_width8990 # If there is no envvar prefix yet, but the parent has one and91 # the command on this level has a name, we can expand the envvar92 # prefix automatically.93 if auto_envvar_prefix is None:
13 unmodified lines
107108 def __exit__(self, exc_type, exc_value, tb):109 self.close()110111 def make_formatter(self):112 """Creates the formatter for the help and usage output."""113 return HelpFormatter(width=self.terminal_width)114115 def call_on_close(self, f):116 """This decorator remembers a function as callback that should be117 executed when the context tears down. This is most useful to bind118 resource handling to the script execution. For instance file objects
197 unmodified lines
316 methods:317318 - :meth:`format_usage`319 """306 formatter = HelpFormatter()320 formatter = ctx.make_formatter()321 self.format_usage(ctx, formatter)322 return formatter.getvalue().rstrip('\n')323324 def get_help(self, ctx):
4 unmodified lines
329 - :meth:`format_help`330 - :meth:`format_options`331 - :meth:`format_epilog`332 """319 formatter = HelpFormatter()333 formatter = ctx.make_formatter()334 self.format_usage(ctx, formatter)335 self.format_help(ctx, formatter)336 self.format_options(ctx, formatter)337 self.format_epilog(ctx, formatter)
94 unmodified lines
432 :param prog_name: the program name that should be used. By default433 the progam name is constructed by taking the file434 name from ``sys.argv[0]``.435 :param extra: extra keyword arguments are forwarded to the context422 constructor.436 constructor. See :class:`Context` for more information.437 """438 # If we are on python 3 we will verify that the environment is439 # sane at this point of reject further execution to avoid a440 # broken script.
634 unmodified lines
modified:click/formatting.py+30 added-6 removed
48 unmodified lines
49 finally:50 self.initial_indent = old_initial_indent51 self.subsequent_indent = old_subsequent_indent5253 def indent_only(self, text):54 rv = []55 for idx, line in enumerate(text.splitlines()):56 indent = self.initial_indent57 if idx > 0:58 indent = self.subsequent_indent59 rv.append(indent + line)60 return '\n'.join(rv)616263def wrap_text(text, width=78, initial_indent='', subsequent_indent='',64 preserve_paragraphs=False):65 """A helper function that intelligently wraps text. By default it66 assumes that it operates on a single paragraph of text but if the67 `preserve_paragraphs` parameter is provided it will intelligently68 handle paragraphs (defined by two empty lines).6970 If paragraphs are handled a paragraph can be prefixed with an empty71 line containing the ``\\b`` character (``\\x08``) to indicate that72 no rewrapping should happen in that block.7374 :param text: the text that should be rewrapped.75 :param width: the maximum width for the text.76 :param initial_indent: the initial indent that should be placed on the77 first line as a string.
11 unmodified lines
8990 p = []91 buf = []92 indent = 09394 def _flush_par():95 if not buf:96 return97 if buf[0].lstrip() == '\b':98 p.append((indent, True, '\n'.join(buf[1:])))99 else:100 p.append((indent, False, ' '.join(buf)))101 del buf[:]102103 for line in text.splitlines():104 if not line:82 p.append((indent, ' '.join(buf)))83 buf = []105 _flush_par()106 else:107 indent = len(line) - len(line.lstrip())108 buf.append(line.lstrip())87 if buf:88 p.append((indent, ' '.join(buf)))109 _flush_par()110111 rv = []91 for indent, text in p:112 for indent, raw, text in p:113 with wrapper.extra_indent(' ' * indent):114 if raw:115 rv.append(wrapper.indent_only(text))116 else:93 rv.append(wrapper.fill(text))117 rv.append(wrapper.fill(text))118119 return '\n\n'.join(rv)120121
130 unmodified lines
modified:docs/documentation.rst+40 added
32 unmodified lines
33convention of Unix tools to use arguments only for the most necessary34things and to document them in the introduction text by referring to them35by name.3637Preventing Rewrapping38---------------------3940The default behavior of click is to rewrap text to work correctly for the41width of the terminal. In some circumstances this can become a problem.42The main issue is showing code examples where newlines are significant.4344Rewrapping can be disabled on a per-paragraph case by adding a line with45just the ``\b`` escape marker in. This line will be removed in the help46text but rewrapping will be disabled.4748Example:4950.. click:example::5152 @click.command()53 def cli():54 """First paragraph.5556 This is a very long second paragraph and as you57 can see wrapped very early in the source text58 but will be rewrapped to the terminal width in59 the final output.6061 \b62 This is63 a paragraph64 without rewrapping.6566 And this is a paragraph67 that will be rewrapped again.68 """6970And what it looks like:7172.. click:run::7374 invoke(cli, args=['--help'])757677Meta Vars78---------7980Options and parameters accept a ``metavar`` argument that can change the
48 unmodified lines
added:tests/test_formatting.py+41 added
1# -*- coding: utf-8 -*-2import click345def test_basic_functionality(runner):6 @click.command()7 def cli():8 """First paragraph.910 This is a very long second11 paragraph and not correctly12 wrapped but it will be rewrapped.1314 \b15 This is16 a paragraph17 without rewrapping.1819 And this is a paragraph20 that will be rewrapped again.21 """2223 result = runner.invoke(cli, ['--help'], terminal_width=60)24 assert not result.exception25 assert result.output.splitlines() == [26 'Usage: cli [OPTIONS]',27 '',28 ' First paragraph.',29 '',30 ' This is a very long second paragraph and not correctly',31 ' wrapped but it will be rewrapped.',32 '',33 ' This is',34 ' a paragraph',35 ' without rewrapping.',36 '',37 ' And this is a paragraph that will be rewrapped again.',38 '',39 'Options:',40 ' --help Show this message and exit.',41 ]