Python textwrap.wrap() Examples

The following are 30 code examples of textwrap.wrap(). 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: buzzer.py    From qb with MIT License 6 votes vote down vote up
def format_display(display_num, question_text, sent, word, current_guesses,
                   answer=None, guess_limit=5, points=10):
    sep = "".join(["-"] * 80)

    current_text = ""
    for ss in range(sent):
        current_text += "%s " % question_text[ss]
    current_text += " ".join(question_text[sent].split()[:word])
    current_text = "\n".join(textwrap.wrap(current_text, 80))

    report = "Question %i: %i points\n%s\n%s\n%s\n\n" % \
        (display_num, points, sep, current_text, sep)

    for gg in sorted(current_guesses, key=lambda x: current_guesses[x].weight, reverse=True)[:guess_limit]:
        guess = current_guesses[gg]
        if guess.page == answer:
            report += "%-18s\t%-50s\t%0.2f\t%s\n" % (guess.system, "***CORRECT***", guess.weight, guess.evidence[:60])
        else:
            report += "%-18s\t%-50s\t%0.2f\t%s\n" % (guess.system, guess.page, guess.weight, guess.evidence[:60])
    return report 
Example #2
Source File: text.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def render_row(self, target, child=None, **options):
        last_row = self.renderer.table.options.get("last_row")
        if last_row == target:
            return Cell("")

        self.renderer.table.options["last_row"] = target

        if not child:
            child = dict(wrap=False)

        if self.child:
            child_renderer = self.child
        else:
            child_renderer = self.ForTarget(target, renderer=self.renderer)(
                session=self.session, renderer=self.renderer)

        child_cell = child_renderer.render_row(target, **child)
        child_cell.colorizer = self.renderer.colorizer

        return StackedCell(
            Cell("-" * child_cell.width),
            child_cell,
            Cell("-" * child_cell.width),
            table_align=False) 
Example #3
Source File: filters.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words)) 
Example #4
Source File: filters.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words)) 
Example #5
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        text = params.get('text')

        html_template = """
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title></title></head>
<body><pre>{}</pre></body>
</html>"""
        # Wrap text preserving existing newlines
        text = '\n'.join(
            wrapped for line in text.splitlines() for wrapped in wrap(
                line, width=70, expand_tabs=False,
                replace_whitespace=False, drop_whitespace=False
            )
        )
        text = escape(text)
        html_content = html_template.format(text)
        pdf_content = HTML(string=html_content).write_pdf()

        b64_content = b64encode(pdf_content).decode()

        return {'pdf': b64_content} 
Example #6
Source File: pml.py    From trelby with GNU General Public License v2.0 6 votes vote down vote up
def addText(self, text, x = None, fs = None, style = NORMAL):
        if x == None:
            x = self.margin

        if fs == None:
            fs = self.fontSize

        yd = util.getTextHeight(fs)

        if (self.y + yd) > (self.doc.h - self.margin):
            self.createPage()

        self.pg.add(TextOp(text, x, self.y, fs, style))

        self.y += yd

    # wrap text into lines that fit on the page, using Courier and default
    # font size and style, and add the lines. 'indent' is the text to
    # prefix lines other than the first one with. 
Example #7
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def re_show(regexp, string, left="{", right="}"):
    """
    Return a string with markers surrounding the matched substrings.
    Search str for substrings matching ``regexp`` and wrap the matches
    with braces.  This is convenient for learning about regular expressions.

    :param regexp: The regular expression.
    :type regexp: str
    :param string: The string being matched.
    :type string: str
    :param left: The left delimiter (printed before the matched substring)
    :type left: str
    :param right: The right delimiter (printed after the matched substring)
    :type right: str
    :rtype: str
    """
    print(re.compile(regexp, re.M).sub(left + r"\g<0>" + right, string.rstrip()))


##########################################################################
# READ FROM FILE OR STRING
##########################################################################

# recipe from David Mertz 
Example #8
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def tokenwrap(tokens, separator=" ", width=70):
    """
    Pretty print a list of text tokens, breaking lines on whitespace

    :param tokens: the tokens to print
    :type tokens: list
    :param separator: the string to use to separate tokens
    :type separator: str
    :param width: the display width (default=70)
    :type width: int
    """
    return '\n'.join(textwrap.wrap(separator.join(tokens), width=width))


##########################################################################
# Python version
########################################################################## 
Example #9
Source File: Logo.py    From coala-quickstart with GNU Affero General Public License v3.0 6 votes vote down vote up
def print_welcome_message(printer):
    """
    Prints the coala bear logo with a welcome message side by side.

    :param printer:
        A ``ConsolePrinter`` object used for console interaction.
    """
    max_length = 80 - len(max(COALA_BEAR_LOGO, key=len))
    text_lines = ['']
    for welcome_message in WELCOME_MESSAGES:
        text_lines += ['']
        text_lines += textwrap.wrap(welcome_message, max_length)

    print_side_by_side(
        printer,
        left=COALA_BEAR_LOGO,
        right=text_lines,
        limit=80) 
Example #10
Source File: tabview.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _calculate_layout(self):
        """Setup popup window and format data. """
        self.scr.touchwin()
        self.term_rows, self.term_cols = self.scr.getmaxyx()
        self.box_height = self.term_rows - int(self.term_rows / 2)
        self.win = curses.newwin(int(self.term_rows / 2),
                                 self.term_cols, self.box_height, 0)
        try:
            curses.curs_set(False)
        except _curses.error:
            pass
        # transform raw data into list of lines ready to be printed
        s = self.data.splitlines()
        s = [wrap(i, self.term_cols - 3, subsequent_indent=" ")
             or [""] for i in s]
        self.tdata = [i for j in s for i in j]
        # -3 -- 2 for the box lines and 1 for the title row
        self.nlines = min(len(self.tdata), self.box_height - 3)
        self.scr.refresh() 
Example #11
Source File: xmlnmap.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def create_ssl_cert(data, b64encoded=True):
    """Produces an output similar to Nmap script ssl-cert from Masscan
X509 "service" tag.

    """
    if b64encoded:
        cert = utils.decode_b64(data)
    else:
        cert = data
        data = utils.encode_b64(cert)
    info = utils.get_cert_info(cert)
    b64cert = data.decode()
    pem = []
    pem.append('-----BEGIN CERTIFICATE-----')
    pem.extend(wrap(b64cert, 64))
    pem.append('-----END CERTIFICATE-----')
    pem.append('')
    info['pem'] = '\n'.join(pem)
    newout = create_ssl_output(info)
    return newout, [info] 
Example #12
Source File: filters.py    From jbox with MIT License 6 votes vote down vote up
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words)) 
Example #13
Source File: prettier.py    From python-devtools with MIT License 6 votes vote down vote up
def _format_raw(self, value: 'Any', value_repr: str, indent_current: int, indent_new: int):
        lines = value_repr.splitlines(True)
        if len(lines) > 1 or (len(value_repr) + indent_current) >= self._width:
            self._stream.write('(\n')
            wrap_at = self._width - indent_new
            prefix = indent_new * self._c

            from textwrap import wrap

            for line in lines:
                sub_lines = wrap(line, wrap_at)
                for sline in sub_lines:
                    self._stream.write(prefix + sline + '\n')
            self._stream.write(indent_current * self._c + ')')
        else:
            self._stream.write(value_repr) 
Example #14
Source File: process_schemas.py    From GelReportModels with Apache License 2.0 6 votes vote down vote up
def formatSchema(self):
        """
        Formats the schema source so that we can print it literally
        into a Python source file.
        """
        schema = json.loads(self.schemaSource)
        stack = [schema]
        # Strip out all the docs
        while len(stack) > 0:
            elm = stack.pop()
            if "doc" in elm:
                elm["doc"] = ""
            for value in elm.values():
                if isinstance(value, dict):
                    stack.append(value)
                elif isinstance(value, list):
                    for dic in value:
                        if isinstance(dic, dict):
                            stack.append(dic)
        jsonData = json.dumps(schema)
        # TODO(Greg): Find a long-term solution for making sure the end of the line
        # TODO(Greg): in a schema string is not a - character (dash)
        output = "\n".join(textwrap.wrap(text=jsonData, width=100, break_long_words=False, break_on_hyphens=False)) + "\n"
        return output 
Example #15
Source File: epr.py    From epr with MIT License 6 votes vote down vote up
def get_lines(self, width=0):
        text = []
        if width == 0:
            return self.text
        for n, i in enumerate(self.text):
            if n in self.idhead:
                text += [i.rjust(width//2 + len(i)//2)] + [""]
            elif n in self.idinde:
                text += ["   "+j for j in textwrap.wrap(i, width - 3)] + [""]
            elif n in self.idbull:
                tmp = textwrap.wrap(i, width - 3)
                text += [" - "+j if j == tmp[0] else "   "+j for j in tmp] + [""]
            elif n in self.idpref:
                tmp = i.splitlines()
                wraptmp = []
                for line in tmp:
                    wraptmp += [j for j in textwrap.wrap(line, width - 6)]
                text += ["   "+j for j in wraptmp] + [""]
            else:
                text += textwrap.wrap(i, width) + [""]
        return text, self.imgs 
Example #16
Source File: cell_wrapper.py    From clikit with MIT License 6 votes vote down vote up
def _wrap_column(
        self, col, column_length, formatter
    ):  # type: (int, List[int], Formatter) -> None
        for i, row in enumerate(self._wrapped_rows):
            cell = row[col]
            cell_length = self._cell_lengths[i][col]

            if cell_length > column_length:
                self._word_wraps = True

                if not self._word_cuts:
                    min_length_without_cut = get_max_word_length(cell, formatter)

                    if min_length_without_cut > column_length:
                        self._word_cuts = True

                # TODO: use format aware wrapper
                wrapped_cell = "\n".join(textwrap.wrap(cell, column_length))

                self._wrapped_rows[i][col] = wrapped_cell

                # Refresh cell length
                self._cell_lengths[i][col] = get_max_line_length(
                    wrapped_cell, formatter
                ) 
Example #17
Source File: cmds.py    From knob with MIT License 6 votes vote down vote up
def work(self):
        args = self.cmdline.split(' ')
        command_list = getCmdList()
        if(len(args) > 1):
            cmd = findCmd(args[1])
            if cmd == None:
                log.info("No command with the name: " + args[1])
                return True
            if hasattr(cmd,'parser'):
                cmd.parser.print_help()
            else:
                print(cmd.description)
                print("Aliases: " + " ".join(cmd.keywords))
        else:
            for cmd in command_list:
                print(cmd.keywords[0].ljust(15) + 
                        ("\n" + " "*15).join(textwrap.wrap(cmd.description, 60)))
        return True 
Example #18
Source File: filters.py    From recruit with Apache License 2.0 6 votes vote down vote up
def do_wordwrap(environment, s, width=79, break_long_words=True,
                wrapstring=None):
    """
    Return a copy of the string passed to the filter wrapped after
    ``79`` characters.  You can override this default using the first
    parameter.  If you set the second parameter to `false` Jinja will not
    split words apart if they are longer than `width`. By default, the newlines
    will be the default newlines for the environment, but this can be changed
    using the wrapstring keyword argument.

    .. versionadded:: 2.7
       Added support for the `wrapstring` parameter.
    """
    if not wrapstring:
        wrapstring = environment.newline_sequence
    import textwrap
    return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
                                   replace_whitespace=False,
                                   break_long_words=break_long_words)) 
Example #19
Source File: MultiCommand.py    From joeecc with GNU General Public License v3.0 6 votes vote down vote up
def _show_syntax(self, msg = None):
		if msg is not None:
			print("Error: %s" % (msg), file = sys.stderr)
		if self._help is not None:
			print()
			for line in textwrap.wrap(self._help):
				print(line)
			print()
		print("Syntax: %s [command] [options]" % (sys.argv[0]), file = sys.stderr)
		print(file = sys.stderr)
		print("Available commands:", file = sys.stderr)
		for commandname in self._cmdorder:
			command = self._commands[commandname]
			print("    %-15s    %s" % (command.name, command.description))
		print(file = sys.stderr)
		print("Options vary from command to command. To receive further info, type", file = sys.stderr)
		print("    %s [command] --help" % (sys.argv[0]), file = sys.stderr) 
Example #20
Source File: utils.py    From vergeml with MIT License 6 votes vote down vote up
def format_info_text(text, indent=0, width=70):
    """Return text formatted for readability.
    """
    text = text.strip("\n")
    res = []
    for line in text.splitlines():
        if line.startswith("  "):
            res.append(line)
        elif line.strip() == "":
            res.append(line)
        else:
            res.extend(textwrap.wrap(line, width=width-indent))
    if indent:
        indstr = str(' ' * indent)
        res = list(map(lambda l: indstr + l, res))
    return "\n".join(res) 
Example #21
Source File: autopep8.py    From python-netsurv with MIT License 5 votes vote down vote up
def shorten_comment(line, max_line_length, last_comment=False):
    """Return trimmed or split long comment line.

    If there are no comments immediately following it, do a text wrap.
    Doing this wrapping on all comments in general would lead to jagged
    comment text.

    """
    assert len(line) > max_line_length
    line = line.rstrip()

    # PEP 8 recommends 72 characters for comment text.
    indentation = _get_indentation(line) + '# '
    max_line_length = min(max_line_length,
                          len(indentation) + 72)

    MIN_CHARACTER_REPEAT = 5
    if (
        len(line) - len(line.rstrip(line[-1])) >= MIN_CHARACTER_REPEAT and
        not line[-1].isalnum()
    ):
        # Trim comments that end with things like ---------
        return line[:max_line_length] + '\n'
    elif last_comment and re.match(r'\s*#+\s*\w+', line):
        split_lines = textwrap.wrap(line.lstrip(' \t#'),
                                    initial_indent=indentation,
                                    subsequent_indent=indentation,
                                    width=max_line_length,
                                    break_long_words=False,
                                    break_on_hyphens=False)
        return '\n'.join(split_lines) + '\n'

    return line + '\n' 
Example #22
Source File: TextTable.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def append(self, row):
        """Append a new row to be displayed. `row' should be a dict."""
        leftover={}
        has_leftover=False
        # Keep track of wider value for each field
        for key, value in row.iteritems():
            header_length = len(self._header(key))
            real_value_len = len(str(value or ''))


            if self._col_width(key) and real_value_len >  self._col_width(key):
                wrap=textwrap.wrap(value, self._col_width(key))
                leftover[key] = ' '.join(wrap[1:])
                row[key] = wrap[0]
                real_value_len = len(row[key])
                has_leftover = True
            else:
                leftover[key] = ""

            # Keep track of the wider value in each col (header or value)
            self._max_width[key] = max(self._max_width.get(key, header_length),
                                       real_value_len)


            # Keep track of cols with at least one non empty row
            if real_value_len > 0 and key not in self._non_empty_cols:
                self._non_empty_cols.add(key)

        self._rows.append(row)
        if has_leftover:
            self.append(leftover) 
Example #23
Source File: filters.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def text_wraps(text, size=10):
    """ Template filter to wrap text at a specified size
    """
    if text:
        parts = textwrap.wrap(text, size)
        if len(parts) > 1:
            parts = "%s..." % parts[0]
        else:
            parts = parts[0]
        return parts 
Example #24
Source File: status.py    From kuryr-kubernetes with Apache License 2.0 5 votes vote down vote up
def get_details(self):
        if self.details is not None:
            # wrap the text on the details to 60 characters
            return '\n'.join(textwrap.wrap(self.details, 60,
                                           subsequent_indent=' ' * 9)) 
Example #25
Source File: text.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def render_row(self, target, **options):
        """Renders the current row for the target."""
        # We merge the row options and the column options. This allows a call to
        # table_row() to override options.
        merged_opts = self.options.copy()
        merged_opts.update(options)

        if merged_opts.get("nowrap"):
            merged_opts.pop("width", None)

        if self.object_renderer is not None:
            object_renderer = self.object_renderer
        else:
            object_renderer = self.table.renderer.get_object_renderer(
                target=target, type=merged_opts.get("type"),
                target_renderer="TextRenderer", **options)

        if target is None:
            result = Cell(width=merged_opts.get("width"))
        else:
            result = object_renderer.render_row(target, **merged_opts)
            if result is None:
                return

            result.colorizer = self.renderer.colorizer

        # If we should not wrap we are done.
        if merged_opts.get("nowrap"):
            return result

        if "width" in self.options or self.header_width > result.width:
            # Rewrap if we have an explicit width (and wrap wasn't turned off).
            # Also wrap to pad if the result is actually narrower than the
            # header, otherwise it messes up the columns to the right.
            result.rewrap(width=self.header_width,
                          align=merged_opts.get("align", result.align))

        return result 
Example #26
Source File: text.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def rebuild(self):
        self._lines = []
        last_highlight = None
        normalized_highlights = []
        for highlight in self.highlights:
            if isinstance(highlight, dict):
                normalized_highlights.append(highlight)
            else:
                normalized_highlights.append(dict(
                    start=highlight[0], end=highlight[1],
                    fg=highlight[2], bg=highlight[3]))

        self.highlights = sorted(normalized_highlights,
                                 key=lambda x: x["start"])

        offset = 0
        for paragraph in self.paragraphs:
            for line in textwrap.wrap(paragraph, self.width):
                line, adjust = self.justify_line(line)
                offset += adjust

                if self.colorizer and self.colorizer.terminal_capable:
                    line, last_highlight = self.highlight_line(
                        line=line, offset=offset, last_highlight=last_highlight)

                self._lines.append(line)

            offset += len(paragraph) 
Example #27
Source File: argparse_compat.py    From jbox with MIT License 5 votes vote down vote up
def _split_lines(self, text, width):
        text = self._whitespace_matcher.sub(' ', text).strip()
        return _textwrap.wrap(text, width) 
Example #28
Source File: writers.py    From QCSchema with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_key_table(top_file, properties, keys=None):
    table_widths = [45, 120, 27]
    fmt_string = '   | {:%s} | {:%s} | {:%s} |' % tuple(table_widths)
    dash_inds = tuple("-" * w for w in table_widths)
    equals_inds = tuple("=" * w for w in table_widths)
   
    top_file.append("   +-{}-+-{}-+-{}-+".format(*dash_inds))
    top_file.append(fmt_string.format("Key Name", "Description", "Field Type"))
    top_file.append("   +={}=+={}=+={}=+".format(*equals_inds))
  
    if keys is None:
        keys = properties.keys()

    for key in keys:
        value = properties[key]

        dtype = value["type"]

        if "description" in value:
            description = value["description"]
        elif value["type"] == "object":
            description = value["$ref"]
        else:
            description = "No description provided."

        if value["type"] == "array":
            dtype = "array[" + value["items"]["type"] + "]"

        # Figure out the needed slices

        desc_parts = textwrap.wrap(description, width=table_widths[1])
        top_file.append(fmt_string.format(key, desc_parts[0], dtype))

        for dp in desc_parts[1:]:
            top_file.append(fmt_string.format("", dp, ""))

        top_file.append("   +-{}-+-{}-+-{}-+".format(*dash_inds)) 
Example #29
Source File: messaging.py    From jbox with MIT License 5 votes vote down vote up
def msg(msg, newline=True):
    if TERMWIDTH is None:
        write_outstream(sys.stdout, msg)
        if newline:
            write_outstream(sys.stdout, "\n")
    else:
        # left indent output lines
        lines = textwrap.wrap(msg, TERMWIDTH)
        if len(lines) > 1:
            for line in lines[0:-1]:
                write_outstream(sys.stdout, "  ", line, "\n")
        write_outstream(sys.stdout, "  ", lines[-1], ("\n" if newline else "")) 
Example #30
Source File: search.py    From jbox with MIT License 5 votes vote down vote up
def print_results(hits, name_column_width=None, terminal_width=None):
    if not hits:
        return
    if name_column_width is None:
        name_column_width = max([
            len(hit['name']) + len(hit.get('versions', ['-'])[-1])
            for hit in hits
        ]) + 4

    installed_packages = [p.project_name for p in pkg_resources.working_set]
    for hit in hits:
        name = hit['name']
        summary = hit['summary'] or ''
        version = hit.get('versions', ['-'])[-1]
        if terminal_width is not None:
            # wrap and indent summary to fit terminal
            summary = textwrap.wrap(
                summary,
                terminal_width - name_column_width - 5,
            )
            summary = ('\n' + ' ' * (name_column_width + 3)).join(summary)

        line = '%-*s - %s' % (name_column_width,
                              '%s (%s)' % (name, version), summary)
        try:
            logger.info(line)
            if name in installed_packages:
                dist = pkg_resources.get_distribution(name)
                with indent_log():
                    latest = highest_version(hit['versions'])
                    if dist.version == latest:
                        logger.info('INSTALLED: %s (latest)', dist.version)
                    else:
                        logger.info('INSTALLED: %s', dist.version)
                        logger.info('LATEST:    %s', latest)
        except UnicodeEncodeError:
            pass