From 687e08cfcedc18e605fecf17bc0914154ad1b2fd Mon Sep 17 00:00:00 2001 From: Anton Khirnov Date: Tue, 5 May 2020 11:42:18 +0200 Subject: helper: move string_sanitize() to the only place where it is used --- alot/buffers/envelope.py | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) (limited to 'alot/buffers/envelope.py') diff --git a/alot/buffers/envelope.py b/alot/buffers/envelope.py index ada8791c..83a3c57b 100644 --- a/alot/buffers/envelope.py +++ b/alot/buffers/envelope.py @@ -9,8 +9,45 @@ from ..settings.const import settings from ..widgets.globals import HeadersList from ..widgets.globals import AttachmentWidget from ..helper import shorten_author_string -from ..helper import string_sanitize +def string_sanitize(string, tab_width=8): + r""" + strips, and replaces non-printable characters + + :param tab_width: number of spaces to replace tabs with. Read from + `globals.tabwidth` setting if `None` + :type tab_width: int or `None` + + >>> string_sanitize(' foo\rbar ', 8) + ' foobar ' + >>> string_sanitize('foo\tbar', 8) + 'foo bar' + >>> string_sanitize('foo\t\tbar', 8) + 'foo bar' + """ + + string = string.replace('\r', '') + + lines = list() + for line in string.split('\n'): + tab_count = line.count('\t') + + if tab_count > 0: + line_length = 0 + new_line = list() + for i, chunk in enumerate(line.split('\t')): + line_length += len(chunk) + new_line.append(chunk) + + if i < tab_count: + next_tab_stop_in = tab_width - (line_length % tab_width) + new_line.append(' ' * next_tab_stop_in) + line_length += next_tab_stop_in + lines.append(''.join(new_line)) + else: + lines.append(line) + + return '\n'.join(lines) class EnvelopeBuffer(Buffer): """message composition mode""" -- cgit v1.2.3