Allow configuration of colors

- Replaced raw escapes with colorama
- Added colors key to config
- Add checks for validity of color values
This commit is contained in:
Aaron Lichtman 2019-11-06 01:05:06 +01:00
parent 75a8249f38
commit 01db72b9dc
No known key found for this signature in database
GPG key ID: 22368077DE9F9903
5 changed files with 44 additions and 28 deletions

View file

@ -8,7 +8,6 @@ from dateutil import parser as date_parser
from ansiwrap import strip_color from ansiwrap import strip_color
from collections import defaultdict from collections import defaultdict
import os import os
import re
import json import json
import yaml import yaml
import keyring import keyring

View file

@ -5,7 +5,7 @@ from __future__ import unicode_literals
import re import re
import ansiwrap import ansiwrap
from datetime import datetime from datetime import datetime
from .util import split_title, bold, colorize_red from .util import split_title, colorize
class Entry: class Entry:
@ -79,10 +79,10 @@ class Entry:
else: else:
indent = "" indent = ""
if not short and self.journal.config['linewrap']: if not short and self.journal.config['linewrap']:
# Color date red and make sure first line of title is bolded # Color date and color / bold title and make sure first line of title is bolded
title = ansiwrap.fill(colorize_red(date_str) + " " + bold(self.title), self.journal.config['linewrap']) title = ansiwrap.fill(colorize(date_str, self.journal.config['colors']['date']) + " " +
# Make sure all lines after the first are bolded, too colorize(self.title, self.journal.config['colors']['title'], bold=True),
title = "".join([bold(part) + "\n" for part in title.split("\n")]).strip() self.journal.config['linewrap'])
body = "\n".join([ body = "\n".join([
ansiwrap.fill( ansiwrap.fill(
line, line,
@ -93,7 +93,8 @@ class Entry:
for line in self.body.rstrip(" \n").splitlines() for line in self.body.rstrip(" \n").splitlines()
]) ])
else: else:
title = colorize_red(date_str) + " " + bold(self.title.rstrip("\n ")) title = colorize(date_str, self.journal.config['colors']['date']) + " " +\
colorize(self.title.rstrip("\n"), self.journal.config['colors']['title'], bold=True)
body = self.body.rstrip("\n ") body = self.body.rstrip("\n ")
# Suppress bodies that are just blanks and new lines. # Suppress bodies that are just blanks and new lines.

View file

@ -152,12 +152,12 @@ class Journal(object):
for tag in self.search_tags: for tag in self.search_tags:
tagre = re.compile(re.escape(tag), re.IGNORECASE) tagre = re.compile(re.escape(tag), re.IGNORECASE)
pp = re.sub(tagre, pp = re.sub(tagre,
lambda match: util.colorize_cyan(match.group(0)), lambda match: util.colorize(match.group(0), "CYAN"),
pp, re.UNICODE) pp, re.UNICODE)
else: else:
pp = re.sub( pp = re.sub(
Entry.Entry.tag_regex(self.config['tagsymbols']), Entry.Entry.tag_regex(self.config['tagsymbols']),
lambda match: util.colorize_cyan(match.group(0)), lambda match: util.colorize(match.group(0), "CYAN"),
pp pp
) )
return pp return pp

View file

@ -12,7 +12,7 @@ from . import upgrade
from . import __version__ from . import __version__
from .Journal import PlainJournal from .Journal import PlainJournal
from .EncryptedJournal import EncryptedJournal from .EncryptedJournal import EncryptedJournal
from .util import UserAbort from .util import UserAbort, verify_config
import yaml import yaml
import logging import logging
import sys import sys
@ -42,6 +42,7 @@ def module_exists(module_name):
else: else:
return True return True
default_config = { default_config = {
'version': __version__, 'version': __version__,
'journals': { 'journals': {
@ -57,6 +58,10 @@ default_config = {
'highlight': True, 'highlight': True,
'linewrap': 79, 'linewrap': 79,
'indent_character': '|', 'indent_character': '|',
'colors': {
'date': 'red',
'title': 'blue',
},
} }
@ -98,6 +103,7 @@ def load_or_install_jrnl():
sys.exit(1) sys.exit(1)
upgrade_config(config) upgrade_config(config)
verify_config(config)
return config return config
else: else:

View file

@ -8,8 +8,8 @@ import sys
import os import os
import getpass as gp import getpass as gp
import yaml import yaml
if "win32" in sys.platform:
import colorama import colorama
if "win32" in sys.platform:
colorama.init() colorama.init()
import re import re
import tempfile import tempfile
@ -30,9 +30,9 @@ STDOUT = sys.stdout
TEST = False TEST = False
__cached_tz = None __cached_tz = None
WARNING_COLOR = "\033[33m" WARNING_COLOR = colorama.Fore.YELLOW
ERROR_COLOR = "\033[31m" ERROR_COLOR = colorama.Fore.RED
RESET_COLOR = "\033[0m" RESET_COLOR = colorama.Fore.RESET
# Based on Segtok by Florian Leitner # Based on Segtok by Florian Leitner
# https://github.com/fnl/segtok # https://github.com/fnl/segtok
@ -162,6 +162,21 @@ def scope_config(config, journal_name):
return config return config
def verify_config(config):
"""
Ensures the keys set for colors are valid colorama.Fore attributes.
:return: True if all keys are set correctly, False otherwise
"""
all_valid_colors = True
for key, color in config["colors"].items():
if not getattr(colorama.Fore, color.upper(), None):
# TODO: Not sure whether both of these should stay or not.
print("[{2}ERROR{3}: {0} set to invalid color: {1}]".format(key, color, ERROR_COLOR, RESET_COLOR))
log.error("Invalid color configuration value for '{0}'.".format(key))
all_valid_colors = False
return all_valid_colors
def get_text_from_editor(config, template=""): def get_text_from_editor(config, template=""):
filehandle, tmpfile = tempfile.mkstemp(prefix="jrnl", text=True, suffix=".txt") filehandle, tmpfile = tempfile.mkstemp(prefix="jrnl", text=True, suffix=".txt")
with codecs.open(tmpfile, 'w', "utf-8") as f: with codecs.open(tmpfile, 'w', "utf-8") as f:
@ -180,20 +195,15 @@ def get_text_from_editor(config, template=""):
return raw return raw
def colorize_cyan(string): def colorize(string, color, bold=False):
"""Returns the string wrapped in cyan ANSI escape""" """Returns the string colored with colorama.Fore.color. If the color set
return u"\033[36m{}\033[39m".format(string) by the user doesn't exist in the colorama.Fore attributes, the colorization
is done with WHITE."""
color_escape = getattr(colorama.Fore, color.upper(), colorama.Fore.WHITE)
def colorize_red(string): if not bold:
"""Returns the string wrapped in red ANSI escape""" return color_escape + string + colorama.Fore.RESET
return u"\033[91m{}\033[0m".format(string) else:
return colorama.Style.BRIGHT + color_escape + string + colorama.Style.RESET_ALL
def bold(string):
"""Returns the string wrapped in bold ANSI escape. Bug / feature that it
also colors the text blue, for some unknown reason."""
return u"\033[1m{}\033[0m".format(string)
def slugify(string): def slugify(string):