Python textwrap.TextWrapper() Examples

The following are 30 code examples of textwrap.TextWrapper(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module textwrap , or try the search function .
Example #1
Source File: cli.py    From stdpopsim with GNU General Public License v3.0 6 votes vote down vote up
def get_genetic_maps_help(species_id, genetic_map_id):
    """
    Generate help text for the given genetic map. If map_id is None, generate
    help for all genetic maps. Otherwise, it must be a string with a valid map
    ID.
    """
    species = stdpopsim.get_species(species_id)
    if genetic_map_id is None:
        maps_text = f"\nAll genetic maps for {species.name}\n\n"
        maps = [genetic_map.id for genetic_map in species.genetic_maps]
    else:
        maps = [genetic_map_id]
        maps_text = "\nGenetic map description\n\n"

    indent = " " * 4
    wrapper = textwrap.TextWrapper(initial_indent=indent, subsequent_indent=indent)
    for map_id in maps:
        gmap = get_genetic_map_wrapper(species, map_id)
        maps_text += f"{gmap.id}\n"
        maps_text += wrapper.fill(textwrap.dedent(gmap.long_description))
        maps_text += "\n\n"

    return maps_text 
Example #2
Source File: rst.py    From restbuilder with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, document, builder):
        TextTranslator.__init__(self, document, builder)

        newlines = builder.config.text_newlines
        if newlines == 'windows':
            self.nl = '\r\n'
        elif newlines == 'native':
            self.nl = os.linesep
        else:
            self.nl = '\n'
        self.sectionchars = builder.config.text_sectionchars
        self.states = [[]]
        self.stateindent = [0]
        self.list_counter = []
        self.sectionlevel = 0
        self.table = None
        if self.builder.config.rst_indent:
            self.indent = self.builder.config.rst_indent
        else:
            self.indent = STDINDENT
        self.wrapper = textwrap.TextWrapper(width=STDINDENT, break_long_words=False, break_on_hyphens=False) 
Example #3
Source File: test_textwrap.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_whitespace(self):
        # Whitespace munging and end-of-sentence detection

        text = """\
This is a paragraph that already has
line breaks.  But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""

        expect = ["This is a paragraph that already has line",
                  "breaks.  But some of its lines are much",
                  "longer than the others, so it needs to be",
                  "wrapped.  Some lines are  tabbed too.  What a",
                  "mess!"]

        wrapper = TextWrapper(45, fix_sentence_endings=True)
        result = wrapper.wrap(text)
        self.check(result, expect)

        result = wrapper.fill(text)
        self.check(result, '\n'.join(expect)) 
Example #4
Source File: wgeditmultiline.py    From apple_bleee with GNU General Public License v3.0 6 votes vote down vote up
def wrap(self, text):
        """Override textwrap.TextWrapper to process 'text' properly when
        multiple paragraphs present"""
        para_edge = re.compile(r"(\n\s*\n)", re.MULTILINE)
        paragraphs = para_edge.split(text)
        wrapped_lines = []
        for para in paragraphs:
            if para.isspace():
                if not self.replace_whitespace:
                    # Do not take the leading and trailing newlines since
                    # joining the list with newlines (as self.fill will do)
                    # will put them back in.
                    if self.expand_tabs:
                        para = para.expandtabs()
                    wrapped_lines.append(para[1:-1])
                else:
                    # self.fill will end up putting in the needed newline to
                    # space out the paragraphs
                    wrapped_lines.append('')
            else:
                wrapped_lines.extend(textwrap.TextWrapper.wrap(self, para))
        return wrapped_lines 
Example #5
Source File: test_textwrap.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_whitespace(self):
        # Whitespace munging and end-of-sentence detection

        text = """\
This is a paragraph that already has
line breaks.  But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""

        expect = ["This is a paragraph that already has line",
                  "breaks.  But some of its lines are much",
                  "longer than the others, so it needs to be",
                  "wrapped.  Some lines are  tabbed too.  What a",
                  "mess!"]

        wrapper = TextWrapper(45, fix_sentence_endings=True)
        result = wrapper.wrap(text)
        self.check(result, expect)

        result = wrapper.fill(text)
        self.check(result, '\n'.join(expect)) 
Example #6
Source File: ovf.py    From cot with MIT License 6 votes vote down vote up
def _info_string_environment(self, wrapper):
        """Describe environment for :meth:`info_string`.

        Args:
          wrapper (textwrap.TextWrapper): Helper object for wrapping
              text lines if needed.

        Returns:
          str: Environment information string, or None
        """
        if not self.environment_transports:
            return None
        str_list = ["Environment:"]
        wrapper.initial_indent = '  '
        wrapper.subsequent_indent = '    '
        str_list.extend(wrapper.wrap(
            "Transport types: {0}"
            .format(" ".join(self.environment_transports))))
        return "\n".join(str_list) 
Example #7
Source File: __init__.py    From qubes-core-admin with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        # pylint: disable=redefined-outer-name
        properties = self._klass.property_list()
        width = max(len(prop.__name__) for prop in properties)
        wrapper = textwrap.TextWrapper(width=80,
            initial_indent='  ', subsequent_indent=' ' * (width + 6))

        text = 'Common properties:\n' + '\n'.join(
            wrapper.fill('{name:{width}s}  {doc}'.format(
                name=prop.__name__,
                doc=qubes.utils.format_doc(prop.__doc__) if prop.__doc__ else'',
                width=width))
            for prop in sorted(properties))
        if self._klass is not qubes.Qubes:
            text += '\n\n' \
                'There may be more properties in specific domain classes.\n'
        parser.exit(message=text) 
Example #8
Source File: test_textwrap.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_whitespace(self):
        # Whitespace munging and end-of-sentence detection

        text = """\
This is a paragraph that already has
line breaks.  But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""

        expect = ["This is a paragraph that already has line",
                  "breaks.  But some of its lines are much",
                  "longer than the others, so it needs to be",
                  "wrapped.  Some lines are  tabbed too.  What a",
                  "mess!"]

        wrapper = TextWrapper(45, fix_sentence_endings=True)
        result = wrapper.wrap(text)
        self.check(result, expect)

        result = wrapper.fill(text)
        self.check(result, '\n'.join(expect)) 
Example #9
Source File: generate.py    From mathematics_dataset with Apache License 2.0 6 votes vote down vote up
def main(unused_argv):
  """Prints Q&As from modules according to FLAGS.filter."""
  init_modules()

  text_wrapper = textwrap.TextWrapper(
      width=80, initial_indent=' ', subsequent_indent='  ')

  for regime, flat_modules in six.iteritems(filtered_modules):
    per_module = counts[regime]
    for module_name, module in six.iteritems(flat_modules):
      # These magic print constants make the header bold.
      print('\033[1m{}/{}\033[0m'.format(regime, module_name))
      num_dropped = 0
      for _ in range(per_module):
        problem, extra_dropped = sample_from_module(module)
        num_dropped += extra_dropped
        text = text_wrapper.fill(
            '{}  \033[92m{}\033[0m'.format(problem.question, problem.answer))
        print(text)
      if num_dropped > 0:
        logging.warning('Dropped %d examples', num_dropped) 
Example #10
Source File: compiler.py    From dragonfly with GNU Lesser General Public License v3.0 6 votes vote down vote up
def debug_state_string(self):
        """Debug."""

        import textwrap
        wrapper = textwrap.TextWrapper(subsequent_indent = "   ")
        output = []

        wrapper.initial_indent = "exported rules: "
        output.append(wrapper.wrap(", ".join(self._export_rules)))
        wrapper.initial_indent = "imported rules: "
        output.append(wrapper.wrap(", ".join(self._import_rules)))
        wrapper.initial_indent = "lists: "
        output.append(wrapper.wrap(", ".join(self._lists)))
        wrapper.initial_indent = "words: "
        output.append(wrapper.wrap(", ".join(self._words)))
        wrapper.initial_indent = "rule definitions: "
        output.append(wrapper.wrap(str(self._rule_definitions)))

        return "\n".join(["\n".join(lines) for lines in output if lines]) 
Example #11
Source File: contract.py    From brownie with MIT License 6 votes vote down vote up
def _print_natspec(natspec: Dict) -> None:
    wrapper = TextWrapper(initial_indent=f"  {color('bright magenta')}")
    for key in [i for i in ("title", "notice", "author", "details") if i in natspec]:
        wrapper.subsequent_indent = " " * (len(key) + 4)
        print(wrapper.fill(f"@{key} {color}{natspec[key]}"))

    for key, value in natspec.get("params", {}).items():
        wrapper.subsequent_indent = " " * 9
        print(wrapper.fill(f"@param {color('bright blue')}{key}{color} {value}"))

    if "return" in natspec:
        wrapper.subsequent_indent = " " * 10
        print(wrapper.fill(f"@return {color}{natspec['return']}"))

    for key in sorted(natspec.get("returns", [])):
        wrapper.subsequent_indent = " " * 10
        print(wrapper.fill(f"@return {color}{natspec['returns'][key]}"))

    print() 
Example #12
Source File: template_helpers.py    From apis-client-generator with Apache License 2.0 6 votes vote down vote up
def java_parameter_wrap(value):  # pylint: disable=g-bad-name
  """Templatefilter to wrap lines of parameter documentation.

  Take a single long string and breaks it up so that subsequent lines are
  prefixed by an appropriate number of spaces (and preceded by a ' * '.

  Args:
   value: (str) the string to wrap

  Returns:
  the rewrapped string.
  """
  # TODO(user): add 'parameter_doc' option to the DocCommentBlock
  indent = _language_defaults['java'][_PARAMETER_DOC_INDENT]
  prefix = ' * %s ' % (' ' * indent)
  wrapper = textwrap.TextWrapper(width=_language_defaults['java'][_LINE_WIDTH],
                                 replace_whitespace=False,
                                 initial_indent='',
                                 subsequent_indent=prefix)
  wrapped = wrapper.fill(value)
  return wrapped


# We disable the bad function name warning because we use Django style names
# rather than Google style names (disable-msg=C6409) 
Example #13
Source File: utils.py    From loaner with Apache License 2.0 6 votes vote down vote up
def _wrap_lines(lines, wrapper=None):
  """Wraps a multiline string.

  Args:
    lines: str, a multiline string to wrap.
    wrapper: textwrap.TextWrapper, the wrapper to use for wrapping and
        formatting.

  Returns:
    The formatted string.
  """
  if wrapper is None:
    wrapper = textwrap.TextWrapper(
        break_on_hyphens=False,
        break_long_words=False,
        width=flags.get_help_width())
  result = '\n'.join([wrapper.fill(line) for line in lines.splitlines()])
  if lines.endswith('\n'):
    result += '\n'
  return result 
Example #14
Source File: __init__.py    From armi with Apache License 2.0 5 votes vote down vote up
def listCommands(self):
        """List commands with a short description."""

        indent = 22
        initial_indent = "  "
        subsequent_indent = initial_indent + " " * indent
        wrapper = textwrap.TextWrapper(
            initial_indent=initial_indent, subsequent_indent=subsequent_indent, width=79
        )

        sub = re.compile(r"\s+").sub

        ## given a string, condense white space into a single space
        condense = lambda s: sub(" ", s.strip())

        commands = self._entryPoints.values()

        formatter = "{name:<{width}}{desc}".format
        print("\ncommands:")
        for cmd in sorted(commands, key=lambda cmd: cmd.name):
            ## Each command can optionally define a class attribute `description`
            ## as documentation. If description is not defined (default=None since
            ## it should inherit from EntryPoint), then the docstring is used.
            ## If the docstring is also None, then fall back to an empty string.
            desc = condense(cmd.description or cmd.__doc__ or "")
            print(wrapper.fill(formatter(width=indent, name=cmd.name, desc=desc))) 
Example #15
Source File: erratum.py    From errata-tool with MIT License 5 votes vote down vote up
def fmt(self, s):
        # The textwrap library doesn't parse newlines, so you'll want to
        # split on them first, then format each line, then join it all back
        # up.
        lines = s.split('\n')

        page = []
        for l in lines:
            b = textwrap.TextWrapper(width=75, replace_whitespace=True,
                                     break_long_words=False,
                                     break_on_hyphens=False)
            page.append(b.fill(l))
        return '\n'.join(page) 
Example #16
Source File: storage_media_tool.py    From plaso with Apache License 2.0 5 votes vote down vote up
def __init__(self, input_reader=None, output_writer=None):
    """Initializes the CLI tool object.

    Args:
      input_reader (Optional[InputReader]): input reader, where None indicates
          that the stdin input reader should be used.
      output_writer (Optional[OutputWriter]): output writer, where None
          indicates that the stdout output writer should be used.
    """
    super(StorageMediaTool, self).__init__(
        input_reader=input_reader, output_writer=output_writer)
    self._custom_artifacts_path = None
    self._artifact_definitions_path = None
    self._artifact_filters = None
    self._credentials = []
    self._credential_configurations = []
    self._filter_file = None
    self._partitions = None
    self._process_vss = False
    self._source_scanner = source_scanner.SourceScanner()
    self._source_path = None
    self._source_path_specs = []
    self._textwrapper = textwrap.TextWrapper()
    self._user_selected_vss_stores = False
    self._volumes = None
    self._vss_only = False
    self._vss_stores = None 
Example #17
Source File: ingamemsg.py    From edr with Apache License 2.0 5 votes vote down vote up
def __wrap_text(self, kind, part, text, max_rows):
        EDRLOG.log(u"text: {}".format(text), "DEBUG")
        if text is None:
            return None
        width = self.cfg[kind][part]["len"]
        wrapper = textwrap.TextWrapper(width=width, subsequent_indent="  ", break_on_hyphens=False)
        return wrapper.wrap(text)[:max_rows] 
Example #18
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_fix_sentence_endings(self):
        wrapper = TextWrapper(60, fix_sentence_endings=True)

        # SF #847346: ensure that fix_sentence_endings=True does the
        # right thing even on input short enough that it doesn't need to
        # be wrapped.
        text = "A short line. Note the single space."
        expect = ["A short line.  Note the single space."]
        self.check(wrapper.wrap(text), expect)

        # Test some of the hairy end cases that _fix_sentence_endings()
        # is supposed to handle (the easy stuff is tested in
        # test_whitespace() above).
        text = "Well, Doctor? What do you think?"
        expect = ["Well, Doctor?  What do you think?"]
        self.check(wrapper.wrap(text), expect)

        text = "Well, Doctor?\nWhat do you think?"
        self.check(wrapper.wrap(text), expect)

        text = 'I say, chaps! Anyone for "tennis?"\nHmmph!'
        expect = ['I say, chaps!  Anyone for "tennis?"  Hmmph!']
        self.check(wrapper.wrap(text), expect)

        wrapper.width = 20
        expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!']
        self.check(wrapper.wrap(text), expect)

        text = 'And she said, "Go to hell!"\nCan you believe that?'
        expect = ['And she said, "Go to',
                  'hell!"  Can you',
                  'believe that?']
        self.check(wrapper.wrap(text), expect)

        wrapper.width = 60
        expect = ['And she said, "Go to hell!"  Can you believe that?']
        self.check(wrapper.wrap(text), expect)

        text = 'File stdio.h is nice.'
        expect = ['File stdio.h is nice.']
        self.check(wrapper.wrap(text), expect) 
Example #19
Source File: __main__.py    From soapy_power with MIT License 5 votes vote down vote up
def wrap(text, indent='    '):
    """Wrap text to terminal width with default indentation"""
    wrapper = textwrap.TextWrapper(
        width=int(os.environ.get('COLUMNS', 80)),
        initial_indent=indent,
        subsequent_indent=indent
    )
    return '\n'.join(wrapper.wrap(text)) 
Example #20
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.wrapper = TextWrapper(width=45) 
Example #21
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.wrapper = TextWrapper()
        self.text = '''\
Did you say "supercalifragilisticexpialidocious?"
How *do* you spell that odd word, anyways?
''' 
Example #22
Source File: repomanager.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def repoExitError(message):
    """
    Exits the repo manager with error status.
    """
    wrapper = textwrap.TextWrapper(
        break_on_hyphens=False, break_long_words=False)
    formatted = wrapper.fill("{}: error: {}".format(sys.argv[0], message))
    sys.exit(formatted) 
Example #23
Source File: utils.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def indent_arglist(args, indent_level, width=100, lstrip=True):
    """Indent an argument list for use in generated code"""
    wrapper = textwrap.TextWrapper(
        width=width,
        initial_indent=indent_level * " ",
        subsequent_indent=indent_level * " ",
        break_long_words=False,
    )
    wrapped = "\n".join(wrapper.wrap(", ".join(args)))
    if lstrip:
        wrapped = wrapped.lstrip()
    return wrapped 
Example #24
Source File: strings.py    From testplan with Apache License 2.0 5 votes vote down vote up
def wrap(text, width=150):
    """
    Wraps `text` within given `width` limit, keeping initial indentation of
    each line (and generated lines). Useful for wrapping exception messages.

    :param text: Text to be wrapped.
    :param width: Maximum character limit for each line.
    :return: Wrapped text
    """
    wrapper = textwrap.TextWrapper(width=width, replace_whitespace=False)
    text_ctx = [wrapper.wrap(t) for t in text.splitlines()]

    result = []
    for line_list in text_ctx:
        if not line_list:
            return text
        first, rest = line_list[0], line_list[1:]
        indent_match = INDENT_REGEX.match(first)
        if indent_match:
            prefix = " " * (indent_match.end() - indent_match.start())
            result.extend(
                [first] + ["{}{}".format(prefix, line) for line in rest]
            )
        else:
            result.extend(line_list)
    return os.linesep.join(result) 
Example #25
Source File: ovf.py    From cot with MIT License 5 votes vote down vote up
def _info_string_product(self, verbosity_option, wrapper):
        """Generate product information as part of :meth:`info_string`.

        Args:
          verbosity_option (str): 'brief', None (default), or 'verbose'
          wrapper (textwrap.TextWrapper): Helper object for wrapping text
              lines if needed.

        Returns:
          str: Product information
        """
        if ((not any([self.product, self.vendor, self.version_short])) and
            (verbosity_option == 'brief' or not any([
                self.product_url, self.vendor_url, self.version_long]))):
            return None
        str_list = []
        wrapper.initial_indent = ''
        wrapper.subsequent_indent = '          '
        # All elements in this section are optional
        for label, value, default, verbose_only in [
                ["Product:  ", self.product, "(No product string)", False],
                ["          ", self.product_url, "(No product URL)", True],
                ["Vendor:   ", self.vendor, "(No vendor string)", False],
                ["          ", self.vendor_url, "(No vendor URL)", True],
                ["Version:  ", self.version_short,
                 "(No version string)", False],
                ["          ", self.version_long,
                 "(No detailed version string)", True],
        ]:
            if verbosity_option == 'brief' and verbose_only:
                continue
            if value is None:
                value = default
            str_list.extend(wrapper.wrap("{0}{1}".format(label, value)))

        return "\n".join(str_list) 
Example #26
Source File: rngdoc.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, xml):
        self.xml = xml

        self.wrapper = textwrap.TextWrapper(width=80,
            break_long_words=False, break_on_hyphens=False)

        self.elements = {}
        for node in self.xml.xpath('//rng:element', namespaces=self.nsmap):
            element = Element(self, node)
            self.elements[element.name] = element 
Example #27
Source File: textwriter.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def my_wrap(text, width=MAXWIDTH, **kwargs):
    w = TextWrapper(width=width, **kwargs)
    return w.wrap(text) 
Example #28
Source File: sequences.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def __init__(self, width, term, **kwargs):
        """
        Class initializer.

        This class supports the :meth:`~.Terminal.wrap` method.
        """
        self.term = term
        textwrap.TextWrapper.__init__(self, width, **kwargs) 
Example #29
Source File: misc.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def wrap(text, width=77, indent='', long_words=False, hyphens=False):
    """
    Wrap text for cleaner output (this is a simple wrapper around
    `textwrap.TextWrapper` in the standard library).

    :param text: The text to wrap
    :param width: The max width of a line before breaking
    :param indent: String to prefix subsequent lines after breaking
    :param long_words: Break on long words
    :param hyphens: Break on hyphens
    :returns: str(text)

    """

    if sys.version_info[0] < 3:     # pragma: no cover
        types = [str, unicode]      # pragma: no cover
    else:                           # pragma: no cover
        types = [str]               # pragma: no cover

    if type(text) not in types:
        raise TypeError("Argument `text` must be one of [str, unicode].")

    wrapper = TextWrapper(subsequent_indent=indent, width=width,
                          break_long_words=long_words,
                          break_on_hyphens=hyphens)
    return wrapper.fill(text) 
Example #30
Source File: template_helpers.py    From apis-client-generator with Apache License 2.0 5 votes vote down vote up
def java_comment_fragment(value, indent):  # pylint: disable=g-bad-name
  """Template filter to wrap lines into Java comment style.

  Take a single long string and break it so that subsequent lines are prefixed
  by an approprate number of spaces and then a ' * '.  The filter invocation
  should begin on a line that is already indented suffciently.

  This is typically used after we have written the lead-in for a comment. E.g.

  |    // NOTE: The leading / is indented 4 spaces.
  |    /**
  |     * {{ variable|java_comment_fragment:4 }}
  |     */

  Args:
    value: (str) the string to wrap
    indent: (int) the number of spaces to indent the block.
  Returns:
    The rewrapped string.
  """
  if not indent:
    indent = 0
  prefix = '%s * ' % (' ' * indent)
  wrapper = textwrap.TextWrapper(width=_language_defaults['java'][_LINE_WIDTH],
                                 replace_whitespace=False,
                                 initial_indent=prefix,
                                 subsequent_indent=prefix)
  wrapped = wrapper.fill(value)
  if wrapped.startswith(prefix):
    wrapped = wrapped[len(prefix):]
  return wrapped