jrnl.color   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 80
rs 10
c 0
b 0
f 0
wmc 15

2 Functions

Rating   Name   Duplication   Size   Complexity  
D highlight_tags_with_background_color() 0 49 12
A colorize() 0 11 3
1
#!/usr/bin/env python
2
import re
3
from string import punctuation
4
from string import whitespace
5
6
import colorama
7
8
from .os_compat import on_windows
9
10
if on_windows:
11
    colorama.init()
12
13
WARNING_COLOR = colorama.Fore.YELLOW
14
ERROR_COLOR = colorama.Fore.RED
15
RESET_COLOR = colorama.Fore.RESET
16
17
18
def colorize(string, color, bold=False):
19
    """Returns the string colored with colorama.Fore.color. If the color set by
20
    the user is "NONE" or the color doesn't exist in the colorama.Fore attributes,
21
    it returns the string without any modification."""
22
    color_escape = getattr(colorama.Fore, color.upper(), None)
23
    if not color_escape:
24
        return string
25
    elif not bold:
26
        return color_escape + string + colorama.Fore.RESET
27
    else:
28
        return colorama.Style.BRIGHT + color_escape + string + colorama.Style.RESET_ALL
29
30
31
def highlight_tags_with_background_color(entry, text, color, is_title=False):
32
    """
33
    Takes a string and colorizes the tags in it based upon the config value for
34
    color.tags, while colorizing the rest of the text based on `color`.
35
    :param entry: Entry object, for access to journal config
36
    :param text: Text to be colorized
37
    :param color: Color for non-tag text, passed to colorize()
38
    :param is_title: Boolean flag indicating if the text is a title or not
39
    :return: Colorized str
40
    """
41
42
    def colorized_text_generator(fragments):
43
        """Efficiently generate colorized tags / text from text fragments.
44
        Taken from @shobrook. Thanks, buddy :)
45
        :param fragments: List of strings representing parts of entry (tag or word).
46
        :rtype: List of tuples
47
        :returns [(colorized_str, original_str)]"""
48
        for part in fragments:
49
            if part and part[0] not in config["tagsymbols"]:
50
                yield (colorize(part, color, bold=is_title), part)
51
            elif part:
52
                yield (colorize(part, config["colors"]["tags"], bold=True), part)
53
54
    config = entry.journal.config
55
    if config["highlight"]:  # highlight tags
56
        text_fragments = re.split(entry.tag_regex(config["tagsymbols"]), text)
57
58
        # Colorizing tags inside of other blocks of text
59
        final_text = ""
60
        previous_piece = ""
61
        for colorized_piece, piece in colorized_text_generator(text_fragments):
62
            # If this piece is entirely punctuation or whitespace or the start
63
            # of a line or the previous piece was a tag or this piece is a tag,
64
            # then add it to the final text without a leading space.
65
            if (
66
                all(char in punctuation + whitespace for char in piece)
67
                or previous_piece.endswith("\n")
68
                or (previous_piece and previous_piece[0] in config["tagsymbols"])
69
                or piece[0] in config["tagsymbols"]
70
            ):
71
                final_text += colorized_piece
72
            else:
73
                # Otherwise add a leading space and then append the piece.
74
                final_text += " " + colorized_piece
75
76
            previous_piece = piece
77
        return final_text.lstrip()
78
    else:
79
        return text
80