def format_info_lines(self, lines: Union[list[str], str]) -> List[str]:
        """
        Format lines

        Parameters
        ----------
        lines: Union[list[str], str
            Lines to format

        Returns
        -------
        str
            Formatted string
        """
        if isinstance(lines, str):
            lines = [lines]

        for i, line in enumerate(lines):
            lines[i] = ansiwrap.fill(
                line,
                initial_indent=self.indent_string,
                subsequent_indent=" " * self.indent_size * (self.indent_level + 1),
                width=self.width,
                break_on_hyphens=False,
                break_long_words=False,
                drop_whitespace=False,
            )
        return lines
 def log(self, text):
     log_string = ""
     if self.time < 15:
         log_string += "0:" + str(15 - self.time).zfill(2) + "\t"
     else:
         remaining = 120 - self.time
         log_string += str(remaining // 60) + ":" + str(
             remaining % 60).zfill(2) + "\t"
     log_string += text
     print(
         ansiwrap.fill(log_string,
                       shutil.get_terminal_size().columns,
                       subsequent_indent="\t"))
    def print_information_line(
        self,
        key: str,
        value: Any,
        key_color: Optional[str] = None,
        value_color: Optional[str] = None,
        level: int = 1,
    ) -> None:
        """
        Pretty print a given configuration line

        Parameters
        ----------
        key: str
            Configuration key
        value: Any
            Configuration value
        key_color: str
            Key color
        value_color: str
            Value color
        level: int
            Indentation level
        """
        if key_color is None:
            key_color = "bright"
        if value_color is None:
            value_color = "cyan"
            if isinstance(value, bool):
                if value:
                    value_color = "green"
                else:
                    value_color = "red"
        if isinstance(value, (list, tuple, set)):
            value = comma_join([self.colorize(x, value_color) for x in sorted(value)])
        else:
            value = self.colorize(str(value), value_color)
        indent = ("  " * level) + "-"
        subsequent_indent = "  " * (level + 1)
        if key:
            key = f" {key}:"
            subsequent_indent += " " * (len(key))

        self.print_function(
            ansiwrap.fill(
                f"{self.colorize(key, key_color)} {value}",
                width=self.width,
                initial_indent=indent,
                subsequent_indent=subsequent_indent,
            )
        )
Example #4
0
def _format_section(section_text, config=None, highlighter=None):

    answer = ''

    # cut code blocks
    block_number = 0
    while True:
        section_text, replacements = re.subn('^```.*?^```',
                                             'MULTILINE_BLOCK_%s' %
                                             block_number,
                                             section_text,
                                             1,
                                             flags=re.S | re.MULTILINE)
        block_number += 1
        if not replacements:
            break

    # cut links
    links = []
    while True:
        regexp = re.compile(r'\[(.*?)\]\((.*?)\)')
        match = regexp.search(section_text)
        if match:
            links.append(match.group(0))
            text = match.group(1)
            # links are not yet supported
            #
            text = '\x1B]8;;%s\x1B\\\\%s\x1B]8;;\x1B\\\\' % (match.group(2),
                                                             match.group(1))
        else:
            break

        section_text, replacements = regexp.subn(
            text,  # 'LINK_%s' % len(links),
            section_text,
            1)
        block_number += 1
        if not replacements:
            break

    for paragraph in _split_into_paragraphs(section_text):
        answer += "\n".join(
            ansiwrap.fill(_colorize(line)) + "\n"
            for line in paragraph.splitlines()) + "\n"

    return {'ansi': answer, 'links': links}
    def format(self, record: logging.LogRecord):
        """
        Format a given log message

        Parameters
        ----------
        record: logging.LogRecord
            Log record to format

        Returns
        -------
        str
            Formatted log message
        """
        log_fmt = self.FORMATS.get(record.levelno)
        return ansiwrap.fill(
            record.getMessage(),
            initial_indent=log_fmt[0],
            subsequent_indent=" " * len(log_fmt[0]),
            width=self.width,
        )
Example #6
0
def _arch_replace(text, m):

    p_start = es["fore_yellow"]

    if m == "r":
        p_end = es["reset_all"] + es["style_bright"]
    elif m == "i":
        p_end = es["reset_all"]
    elif m == "b":
        p_end = es["reset_all"]
    elif m == "g":
        p_end = es["reset_all"] + es["style_bright"] + es["fore_green"]
    else:
        p_end = es["reset_all"] + es["fore_magenta"]

    urls = set(re.findall(_http_re_pattern, text))
    for x in urls:
        text = text.replace(x, f"{p_start}{x}{p_end}")

    if m == "r":
        text = tw.fill(text, shutil.get_terminal_size().columns - 3)
        text = ptw.indent(text, " " * 3)[3:]

    return text
Example #7
0
    def pprint(self, short=False):
        """Returns a pretty-printed version of the entry.
        If short is true, only print the title."""
        # Handle indentation
        if self.journal.config["indent_character"]:
            indent = self.journal.config["indent_character"].rstrip() + " "
        else:
            indent = ""

        date_str = colorize(
            self.date.strftime(self.journal.config["timeformat"]),
            self.journal.config["colors"]["date"],
            bold=True,
        )

        if not short and self.journal.config["linewrap"]:
            # Color date / title and bold title
            title = ansiwrap.fill(
                date_str
                + " "
                + highlight_tags_with_background_color(
                    self,
                    self.title,
                    self.journal.config["colors"]["title"],
                    is_title=True,
                ),
                self.journal.config["linewrap"],
            )
            body = highlight_tags_with_background_color(
                self, self.body.rstrip(" \n"), self.journal.config["colors"]["body"]
            )
            body_text = [
                colorize(
                    ansiwrap.fill(
                        line,
                        self.journal.config["linewrap"],
                        initial_indent=indent,
                        subsequent_indent=indent,
                        drop_whitespace=True,
                    ),
                    self.journal.config["colors"]["body"],
                )
                or indent
                for line in body.rstrip(" \n").splitlines()
            ]

            # ansiwrap doesn't handle lines with only the "\n" character and some
            # ANSI escapes properly, so we have this hack here to make sure the
            # beginning of each line has the indent character and it's colored
            # properly. textwrap doesn't have this issue, however, it doesn't wrap
            # the strings properly as it counts ANSI escapes as literal characters.
            # TL;DR: I'm sorry.
            body = "\n".join(
                [
                    colorize(indent, self.journal.config["colors"]["body"]) + line
                    if not ansiwrap.strip_color(line).startswith(indent)
                    else line
                    for line in body_text
                ]
            )
        else:
            title = (
                date_str
                + " "
                + highlight_tags_with_background_color(
                    self,
                    self.title.rstrip("\n"),
                    self.journal.config["colors"]["title"],
                    is_title=True,
                )
            )
            body = highlight_tags_with_background_color(
                self, self.body.rstrip("\n "), self.journal.config["colors"]["body"]
            )

        # Suppress bodies that are just blanks and new lines.
        has_body = len(self.body) > 20 or not all(
            char in (" ", "\n") for char in self.body
        )

        if short:
            return title
        else:
            return "{title}{sep}{body}\n".format(
                title=title, sep="\n" if has_body else "", body=body if has_body else ""
            )
Example #8
0
def fill(text):
    return ansiwrap.fill(text,
                         width=79,
                         replace_whitespace=True,
                         drop_whitespace=True)