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
Provenance
- Commit
24d400f- Tree
c3366a5- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
277d410
4 files changed+129 added−10 removed
modified:click/core.py+18 added-4 removed
47 unmodified lines48 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 """57 58 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 = command16 unmodified lines81 self.obj = obj82 #: A dictionary (like object) with defaults for parameters.83 self.default_map = default_map84 85+ 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_width89+90 # 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 lines107 108 def __exit__(self, exc_type, exc_value, tb):109 self.close()110 111+ def make_formatter(self):112+ """Creates the formatter for the help and usage output."""113+ return HelpFormatter(width=self.terminal_width)114+115 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 objects197 unmodified lines316 methods:317 318 - :meth:`format_usage`319 """306- formatter = HelpFormatter()320+ formatter = ctx.make_formatter()321 self.format_usage(ctx, formatter)322 return formatter.getvalue().rstrip('\n')323 324 def get_help(self, ctx):4 unmodified lines329 - :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 lines432 :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 linesmodified:click/formatting.py+30 added-6 removed
48 unmodified lines49 finally:50 self.initial_indent = old_initial_indent51 self.subsequent_indent = old_subsequent_indent52 53+ 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)61 62+63 def 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).69 70+ 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.73+74 :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 lines89 90 p = []91 buf = []92 indent = 093+94+ 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[:]102+103 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()110 111 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))118 119 return '\n\n'.join(rv)120 121 130 unmodified linesmodified:docs/documentation.rst+40 added
32 unmodified lines33 convention of Unix tools to use arguments only for the most necessary34 things and to document them in the introduction text by referring to them35 by name.36 37+Preventing Rewrapping38+---------------------39+40+The default behavior of click is to rewrap text to work correctly for the41+width of the terminal. In some circumstances this can become a problem.42+The main issue is showing code examples where newlines are significant.43+44+Rewrapping can be disabled on a per-paragraph case by adding a line with45+just the ``\b`` escape marker in. This line will be removed in the help46+text but rewrapping will be disabled.47+48+Example:49+50+.. click:example::51+52+ @click.command()53+ def cli():54+ """First paragraph.55+56+ 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.60+61+ \b62+ This is63+ a paragraph64+ without rewrapping.65+66+ And this is a paragraph67+ that will be rewrapped again.68+ """69+70+And what it looks like:71+72+.. click:run::73+74+ invoke(cli, args=['--help'])75+76+77 Meta Vars78 ---------79 80 Options and parameters accept a ``metavar`` argument that can change the48 unmodified linesadded:tests/test_formatting.py+41 added
1+# -*- coding: utf-8 -*-2+import click3+4+5+def test_basic_functionality(runner):6+ @click.command()7+ def cli():8+ """First paragraph.9+10+ This is a very long second11+ paragraph and not correctly12+ wrapped but it will be rewrapped.13+14+ \b15+ This is16+ a paragraph17+ without rewrapping.18+19+ And this is a paragraph20+ that will be rewrapped again.21+ """22+23+ 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+ ]