Improve CLI textwrapping

* Account for user's actual terminal width
* Skip wrapping if not in a terminal
* Preserve whitespace
* Avoid breaking long words and on hyphens
This commit is contained in:
Waylan Limberg
2021-04-19 16:25:36 -04:00
parent 749d1ff79a
commit cb85d48851
2 changed files with 17 additions and 5 deletions

View File

@@ -70,7 +70,7 @@ MkDocs now has tree new exceptions defined in `mkdocs.exceptions`:
to stop the build and log an error message *without traceback*.
* `BuildError` should not be used by third-party plugins developers
and is reserved for internal use only.
* `Abort` is used intenrally to abort the build and display an error
* `Abort` is used internally to abort the build and display an error
without a traceback.
See [`Handling errors`](../dev-guide/plugins.md#handling-errors)

View File

@@ -5,6 +5,7 @@ import sys
import logging
import click
import textwrap
import shutil
from mkdocs import __version__
from mkdocs import utils
@@ -22,14 +23,25 @@ class ColorFormatter(logging.Formatter):
'DEBUG': 'blue'
}
text_wrapper = textwrap.TextWrapper(
width=shutil.get_terminal_size(fallback=(0, 0)).columns,
replace_whitespace=False,
break_long_words=False,
break_on_hyphens=False,
initial_indent=' '*12,
subsequent_indent=' '*12
)
def format(self, record):
prefix = f'{record.levelname:<8} - '
if record.levelname in self.colors:
prefix = click.style(prefix, fg=self.colors[record.levelname])
lines = textwrap.wrap(record.getMessage(), width=68)
lines[0] = prefix + lines[0]
msg = '\n '.join(lines)
return msg
if self.text_wrapper.width:
# Only wrap text if a terminal width was detected
msg = self.text_wrapper.fill(record.getMessage())
# Prepend prefix after wrapping so that color codes don't affect length
return prefix + msg[12:]
return prefix + record.getMessage()
class State: