prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

Word wrapping #1887

Open Cimbali opened 2 weeks ago

Cimbali commented 2 weeks ago

I wanted to use word wrapping and saw #1648 so here’s a preliminary PR, to discuss what needs changing/rewording/testing. In short, I’ve added a second callback similar to GetLinePrefix that defines wrapping points. They return a tuple of:

  1. wrap position (self-explanatory)
  2. number of chars to remove. Typically to remove the whitespace that was wrapped.* You can also return -1 to truncate the line.
  3. continuation text: any formatted text to insert before the line break to indicate continuation. Typically a hyphen if breaking a word in 2, or a in a code block to indicate a non-semantic break, etc.

A default wrapping function is provided to do word wrapping (and it can even be re-used and tuned for different purposes). It can be activated with word_wrap=True on windows. For actual hyphenation a user would have to provide their own function.

* E.g. if you want to wrap the text example wrapped text on 7 columns, you either break before the first space and remove it, or before and then your next line starts with a space (which looks weird). On 15 columns you’d have a similar problem but either break as example / wrapped / text without character removal, or example wrapped / text, so allowing character removal is good for efficiency of justified text.

Cimbali commented 1 week ago

I’ve added an example that showcases the feature, here’s what it looks like with: 1) no wrapping 2) default word wrapping 3) customised word wrapping with line continuation markers 4) truncation (with a "..." marker)

image