Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New wordwrap #9649

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/pure/unicode.nim
Original file line number Diff line number Diff line change
Expand Up @@ -213,14 +213,19 @@ proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
result = ""
fastToUTF8Copy(c, result, 0, false)

proc add*(s: var string; c: Rune) =
let pos = s.len
fastToUTF8Copy(c, s, pos, false)

proc `$`*(rune: Rune): string =
## Converts a Rune to a string
rune.toUTF8

proc `$`*(runes: seq[Rune]): string =
## Converts a sequence of Runes to a string
result = ""
for rune in runes: result.add(rune.toUTF8)
for rune in runes:
result.add rune
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent!


proc runeOffset*(s: string, pos:Natural, start: Natural = 0): int =
## Returns the byte position of unicode character
Expand Down
67 changes: 67 additions & 0 deletions lib/std/wordwrap.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import unicode

proc wordWrap*(s: string, maxLineWidth = 80,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

procs use verbs, so the name should be wrapWords.

Copy link
Contributor

@kaushalmodi kaushalmodi Nov 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't make sense. "wordwrap" can be a verb too. Using your argument, we'd then have "echoes", "aligns", "adds", etc.

Sorry, I went bonkers because I thought you suggested "wordwraps" instead of "wrapwords".

I agree that "wrapwords" is better (not because of thr verb argument; wordwraps can be read as a verb too), but because of correctness.. we are wrapping many "words" across lines, not just a single word.

splitLongWords = true,
newLine = "\n"): string =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

two spaces before the '='

## This function breaks all words that reach over `maxLineWidth`
## measured in number of runes. When `splitLongWords` is `true`
## words that are longer than `maxLineWidth` are splitted. Multiple
## spaces and newlines are converted to a single space. All
## whitespace is treated equally. Non-breaking whitespace is
## ignored.

var currentWordLength: int = 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use type inference, ': int' is annoying.

var currentWord: string = newStringOfCap(32)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likewise for these.

var currentLineLength: int = 0
var currentWordLengthAtLineEnd: int = -1
var longWordMode = false

template handleWhitespace(): untyped =
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that should be better named addWord.

if currentWord.len > 0:

if currentLineLength + 1 + currentWordLength > maxLineWidth:
result.add newLine
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
result.add newLine
if len(result) > 0:
result.add newLine

otherwise you are inserting an empty line, if the length of the first word on the first line is >= maxLineWidth.

currentLineLength = 0

if currentLineLength > 0:
result.add ' '
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, don't nuke the whitespace replacing it by a single space.

currentLineLength += 1

result.add currentWord
currentLineLength += currentWordLength

currentWord.setlen 0
currentWordLength = 0

for rune in s.runes:
if rune.isWhiteSpace:
handleWhitespace()
else:
if splitLongWords and currentWordLength >= maxLineWidth:
handleWhitespace()

currentWord.add rune
inc currentWordLength

handleWhitespace()


when isMainModule:
import strutils


proc checkLineLength(arg: string): void =
for line in splitlines(arg):
var numRunes = 0
for rune in runes(line):
numRunes += 1

assert numRunes <= 80

let longlongword = "abc uitdaeröägfßhydüäpydqfü,träpydqgpmüdträpydföägpydörztdüöäfguiaeowäzjdtrüöäp psnrtuiydrözenrüöäpyfdqazpesnrtulocjtüöäzydgyqgfqfgprtnwjlcydkqgfüöezmäzydydqüüöäpdtrnvwfhgckdumböäpydfgtdgfhtdrntdrntydfogiayqfguiatrnydrntüöärtniaoeydfgaoeiqfglwcßqfgxvlcwgtfhiaoenrsüöäapmböäptdrniaoydfglckqfhouenrtsüöäptrniaoeyqfgulocfqclgwxßqflgcwßqfxglcwrniatrnmüböäpmöäbpümöäbpüöämpbaoestnriaesnrtdiaesrtdniaesdrtnaetdriaoenvlcyfglwckßqfgvwkßqgfvlwkßqfgvlwckßqvlwkgfUIαοιαοιαχολωχσωχνωκψρχκψρτιεαοσηζϵηζιοεννκεωνιαλωσωκνκψρκγτφγτχκγτεκργτιχνκιωχσιλωσλωχξλξλξωχωχξχλωωχαοεοιαεοαεοιαεοαεοιαοεσναοεκνρκψγκψφϵιηαααοε"

checkLineLength(longlongword.wordWrap)

let tmp ="Наши исследования позволяют сделать вывод о том, что субъект выбирает xxxuiaetudtiraeüöätpghiacodöeronfdquiahgoüöädoiaqofhgiaeotrnuiaßqzfgiaoeurnudtitraenuitenruitarenitarenuitarentduiranetduiranetdruianetrnuiaertnuiatdenruiatdrne институциональный психоз. Важность этой функции подчеркивается тем фактом, что объект вызывает эгоцентризм. Самоактуализация аннигилирует генезис. Анима аннигилирует возрастной код. Закон просветляет аутотренинг. Наши исследования позволяют сделать вывод о том, что воспитание заметно осознаёт инсайт."

checkLineLength(tmp.wordWrap)