Skip to content
Myr

Added style helpers and added deeper ansi color support. Colorama now optional.

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 d27f3a6 · Browse files · 12 files+171 added−70 removed
This commit

State

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

Diff stats

12 files+171 added−70 removed

  • other:+171 added−70 removed

12 files+171 added−70 removed

modified:click/__init__.py+2 added-2 removed
31 unmodified lines
32 format_filename, get_app_dir3334# Terminal functions35from .termui import prompt, confirm, get_terminal_size, echo_via_pager, \36 progressbar, clear36 progressbar, clear, style, unstyle3738# Exceptions39from .exceptions import ClickException, UsageError, BadParameter, \40 FileError, Abort
24 unmodified lines
65 'get_app_dir',6667 # Terminal functions68 'prompt', 'confirm', 'get_terminal_size', 'echo_via_pager',69 'progressbar', 'clear',69 'progressbar', 'clear', 'style', 'unstyle',7071 # Exceptions72 'ClickException', 'UsageError', 'BadParameter', 'FileError',73 'Abort',
10 unmodified lines
modified:click/_compat.py+25 added-20 removed
439 unmodified lines
440 return repr(self._f)441442443auto_wrap_for_ansi = None444colorama = None445446447# If we're on windows we provide transparent integration through448# colorama. This will make ansi colors through the echo function449# work automatically.450if sys.platform.startswith('win'):446try:447 import colorama448except ImportError:449 colorama = None450else:451 _ansi_stream_wrappers = WeakKeyDictionary()451 try:452 import colorama453 except ImportError:454 pass455 else:456 _ansi_stream_wrappers = WeakKeyDictionary()457453 def auto_wrap_for_ansi(stream):454 try:455 cached = _ansi_stream_wrappers.get(stream)456 except Exception:457 cached = None458 if cached is not None:459 return cached460 strip = not isatty(stream)461 rv = colorama.AnsiToWin32(stream, strip=strip).stream462 try:463 _ansi_stream_wrappers[stream] = rv464 except Exception:465 pass466 return rv458 def auto_wrap_for_ansi(stream):459 try:460 cached = _ansi_stream_wrappers.get(stream)461 except Exception:462 cached = None463 if cached is not None:464 return cached465 strip = not isatty(stream)466 rv = colorama.AnsiToWin32(stream, strip=strip).stream467 try:468 _ansi_stream_wrappers[stream] = rv469 except Exception:470 pass471 return rv472473474def strip_ansi(value):475 return _ansi_re.sub('', value)
42 unmodified lines
modified:click/formatting.py+13 added-8 removed
1import textwrap2from contextlib import contextmanager34from .termui import get_terminal_size5from ._compat import strip_ansi678def term_len(x):9 return len(strip_ansi(x))101112def measure_table(rows):13 widths = {}14 for row in rows:15 for idx, col in enumerate(row):11 widths[idx] = max(widths.get(idx, 0), len(col))16 widths[idx] = max(widths.get(idx, 0), term_len(col))17 return tuple(y for x, y in sorted(widths.items()))181920def iter_rows(rows, col_count):
6 unmodified lines
2728 def _cutdown(self, ucstr, space_left):29 l = 030 for i in xrange(len(ucstr)):26 l += len(ucstr[i])31 l += term_len(ucstr[i])32 if space_left < l:33 return (ucstr[:i], ucstr[i:])34 return ucstr, ''35
74 unmodified lines
110 _flush_par()111 indent = None112 else:113 if indent is None:109 orig_len = len(line)114 orig_len = term_len(line)115 line = line.lstrip()111 indent = orig_len - len(line)116 indent = orig_len - term_len(line)117 buf.append(line)118 _flush_par()119120 rv = []
48 unmodified lines
169 """170 prefix = '%*s%s' % (self.current_indent, prefix, prog)171 self.write(prefix)172168 text_width = max(self.width - self.current_indent - len(prefix), 10)169 indent = ' ' * (len(prefix) + 1)173 text_width = max(self.width - self.current_indent - term_len(prefix), 10)174 indent = ' ' * (term_len(prefix) + 1)175 self.write(wrap_text(args, text_width,176 initial_indent=' ',177 subsequent_indent=indent))178
40 unmodified lines
219 self.write('%*s%s' % (self.current_indent, '', first))220 if not second:221 self.write('\n')222 continue218 if len(first) <= first_col - col_spacing:219 self.write(' ' * (first_col - len(first)))223 if term_len(first) <= first_col - col_spacing:224 self.write(' ' * (first_col - term_len(first)))225 else:226 self.write('\n')227 self.write(' ' * (first_col + self.current_indent))228
37 unmodified lines
modified:click/termui.py+81 added-1 removed
1 unmodified line
2import sys3import struct45from ._compat import raw_input, PY2, text_type, string_types, \6 get_best_encoding, colorama, isatty6 get_best_encoding, colorama, isatty, strip_ansi7from .utils import echo8from .exceptions import Abort, UsageError9from .types import convert_type10
1 unmodified line
12# The prompt functions to use. The doc tools currently override these13# functions to customize how they work.14visible_prompt_func = raw_input1516_ansi_colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta',17 'cyan', 'white', 'reset')18_ansi_reset_all = '\033[0m'192021def hidden_prompt_func(prompt):22 import getpass23 return getpass.getpass(prompt)24
246 unmodified lines
271 if sys.platform.startswith('win') and colorama is None:272 os.system('cls')273 else:274 sys.stdout.write('\033[2J\033[1;1H')275276277def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,278 blink=None, reverse=None, reset=True):279 """Styles a text with ANSI styles and returns the new string. By280 default the styling is self contained which means that at the end281 of the string a reset code is issued. This can be prevented by282 passing ``reset=False``.283284 Examples::285286 click.echo(click.style('Hello World!', fg='green'))287 click.echo(click.style('ATTENTION!', blink=True))288 click.echo(click.style('Some things', reverse=True, fg='cyan'))289290 Supported color names:291292 * ``black`` (might be a gray)293 * ``red``294 * ``green``295 * ``yellow`` (might be an orange)296 * ``blue``297 * ``magenta``298 * ``cyan``299 * ``white`` (might be light gray)300 * ``reset`` (reset the color code only)301302 :param text: the string to style with ansi codes.303 :param fg: if provided this will become the foreground color.304 :param bg: if provided this will become the background color.305 :param bold: if provided this will enable or disable bold mode.306 :param dim: if provided this will enable or disable dim mode.307 :param underline: if provided this will enable or disable underline.308 :param blink: if provided this will enable or disable blinking.309 :param reverse: if provided this will enable or disable inverse310 rendering (foreground becomes background and the311 other way round).312 :param reset: by default a reset-all code is added at the end of the313 string which means that styles do not carry over. This314 can be disabled to compose styles.315 """316 bits = []317 if fg:318 try:319 bits.append('\033[%dm' % (_ansi_colors.index(fg) + 30))320 except ValueError:321 raise TypeError('Unknown color %r' % fg)322 if bg:323 try:324 bits.append('\033[%dm' % (_ansi_colors.index(bg) + 40))325 except ValueError:326 raise TypeError('Unknown color %r' % bg)327 if bold is not None:328 bits.append('\033[%dm' % (1 if bold else 22))329 if dim is not None:330 bits.append('\033[%dm' % (2 if bold else 22))331 if underline is not None:332 bits.append('\033[%dm' % (4 if underline else 24))333 if blink is not None:334 bits.append('\033[%dm' % (5 if blink else 25))335 if reverse is not None:336 bits.append('\033[%dm' % (7 if reverse else 27))337 bits.append(text)338 if reset:339 bits.append(_ansi_reset_all)340 return ''.join(bits)341342343def unstyle(text):344 """Removes ANSI styling information from a string. Usually it's not345 necessary to use this function as click's echo function will346 automatically remove styling if necessary.347348 :param text: the text to remove style information from.349 """350 return strip_ansi(text)
modified:click/utils.py+7 added-9 removed
242 unmodified lines
243 binary_file.write(b'\n')244 binary_file.flush()245 return246247 # If we have colorama support we wrap the stream to handle colors248 # for us. In case colorama is not supported and our output stream249 # is not a terminal, we strip the ansi codes ourselves. We also250 # do not do the stripping if we're dealing with true bytes (this will251 # only ever be reached on python 2 where is_bytes is true for buffers252 # and bytearrays but not for regular strings).247 # ANSI style support. If there is no message or we are dealing with248 # bytes nothing is happening. If we are connected to a file we want249 # to strip colors. If we have support for wrapping streams (windows250 # through colorama) we want to do that.251 if message and not is_bytes(message):254 if auto_wrap_for_ansi is not None:255 file = auto_wrap_for_ansi(file)256 elif not isatty(file):252 if not isatty(file):253 message = strip_ansi(message)254 elif auto_wrap_for_ansi is not None:255 file = auto_wrap_for_ansi(file)256257 if message:258 file.write(message)259 if nl:
103 unmodified lines
modified:docs/quickstart.rst+3 added-2 removed
87 unmodified lines
88correction in case the terminal is misconfigured instead of dying with an89:exc:`UnicodeError`.9091As an added benefit, starting with click 2.0 the echo function also92supports portable ANSI coloring if colorama is installed. See93:ref:`ansi-colors` for more information.92has good support for ANSI colors. It will automatically strip ANSI codes93if the output stream is a file and if colorama is supported, ANSI colors94will also work on Windows. See :ref:`ansi-colors` for more information.9596If you don't need this, you can also use the `print()` construct /97function.98
66 unmodified lines
modified:docs/utils.rst+10 added-11 removed
36 unmodified lines
37-----------3839.. versionadded:: 2.04041Starting with click 2.0 the :func:`echo` function gained a bit of extra42functionality to deal with ANSI colors. This functionality is only43available if `colorama`_ is installed. If it is installed then ANSI codes44are intelligently handled.41Starting with click 2.0 the :func:`echo` function gained extra42functionality to deal with ANSI colors and styles. Note that on Windows43this functionality is only available if `colorama`_ is installed. If it44is installed then ANSI codes are intelligently handled.4546Primarily this means that:4748- click's echo function will automatically strip ANSI color codes if the
2 unmodified lines
51 Windows and translate ANSI codes to terminal API calls. This means52 that colors will work on Windows the same way they do on other53 operating systems.5455Click will automatically detect when `colorama` is available and use it.56You do not have to call ``colorama.init()``. In fact, it's strongly57recommended you not doing that as colorama will change the default output58streams which is not a good idea.55Note for colorama support: click will automatically detect when `colorama`56is available and use it. Do *not* call ``colorama.init()``!5758To install colorama run this command::5960 $ pip install colorama6164Example that prints green text::62For styling a string the :func:`style` function can be used::6364 import click67 from colorama import Fore6569 click.echo(Fore.GREEN + 'Hello World!' + Fore.RESET)66 click.echo(click.style('Hello World!', fg='green'))67 click.echo(click.style('Some more text', bg='blue', fg='white'))68 click.echo(click.style('ATTENTION', blink=True))697071.. _colorama: https://pypi.python.org/pypi/colorama72
133 unmodified lines
modified:examples/colors/colors.py+18 added-6 removed
1import click2from colorama import Fore234all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \5 'cyan', 'white'678@click.command()9def cli():7 """This script prints some colors through colorama. This will give8 colors on OS X, Linux and Windows but it will automatically disable9 those colors if stdout is redirected to a file.10 """This script prints some colors. If colorama is installed this will11 also work on Windows. It will also automatically remove all ANSI12 styles if data is piped into a file.1314 Give it a try!15 """13 click.echo(Fore.YELLOW + 'Hello World!' + Fore.RESET)14 click.echo(Fore.RED + 'Goodbye World!' + Fore.RESET)16 for color in all_colors:17 click.echo(click.style('I am colored %s' % color, fg=color))18 for color in all_colors:19 click.echo(click.style('I am colored %s and bold' % color,20 fg=color, bold=True))21 for color in all_colors:22 click.echo(click.style('I am reverse colored %s' % color, fg=color,23 reverse=True))2425 click.echo(click.style('I am blinking', blink=True))26 click.echo(click.style('I am underlined', underline=True))
modified:examples/colors/README+3 added-1 removed
1$ colors_23 colors is a simple example that shows how you can4 colorize text with the built-in colorama integration.4 colorize text.56 For this to work on Windows, colorama is required.78Usage:910 $ pip install --editable .11 $ colors
modified:examples/colors/setup.py+1 added
5 unmodified lines
6 py_modules=['colors'],7 include_package_data=True,8 install_requires=[9 'Click',10 # Colorama is only required for windows.11 'colorama',12 ],13 entry_points='''14 [console_scripts]
3 unmodified lines
modified:examples/termui/setup.py+1 added
5 unmodified lines
6 py_modules=['termui'],7 include_package_data=True,8 install_requires=[9 'Click',10 # Colorama is only required for windows.11 'colorama',12 ],13 entry_points='''14 [console_scripts]
3 unmodified lines
modified:examples/termui/termui.py+7 added-10 removed
1# coding: utf-82import click3import time4import random5from colorama import Fore56try:7 range_type = xrange8except NameError:
8 unmodified lines
1718@cli.command()19def colordemo():20 """Demonstrates ANSI color support."""22 click.echo(Fore.YELLOW + 'Hello World!' + Fore.RESET)21 for color in 'red', 'green', 'blue':22 click.echo(click.style('I am colored %s' % color, fg=color))23 click.echo(click.style('I am background colored %s' % color, bg=color))242526@cli.command()27def pager():28 """Demonstrates using the pager."""29 lines = []30 for x in xrange(200):30 lines.append('%s%d%s. Hello World!' % (31 Fore.GREEN,32 x,33 Fore.RESET34 ))31 lines.append('%s. Hello World!' % click.style(str(x), fg='green'))32 click.echo_via_pager('\n'.join(lines))333435@cli.command()
11 unmodified lines
47 if random.random() > 0.3:48 yield item4950 with click.progressbar(items, label='Processing user accounts',54 fill_char=Fore.GREEN + '#' + Fore.RESET) as bar:51 fill_char=click.style('#', fg='green')) as bar:52 for item in bar:53 process_slowly(item)5455 def show_item(item):56 if item is not None:57 return 'Item #%d' % item5859 with click.progressbar(filter(items), label='Committing transaction',63 fill_char=Fore.YELLOW + '#' + Fore.RESET,60 fill_char=click.style('#', fg='yellow'),61 item_show_func=show_item) as bar:62 for item in bar:63 process_slowly(item)6465 with click.progressbar(length=count, label='Counting',66 bar_template='%(label)s %(bar)s | %(info)s',70 fill_char=Fore.BLUE + u'█' + Fore.RESET,67 fill_char=click.style(u'█', fg='cyan'),68 empty_char=' ') as bar:69 for item in bar:70 process_slowly(item)71
5 unmodified lines