I need to create text files and have the ability to control if the text is left or right justified using Go. I found tab writer but I don't want columns. The text needs to flow freely. Any suggestions?
CodePudding user response:
You are very limited in the kinds of formatting you can perform within an ASCII text file. There are no ASCII control characters to say that a block of text will be justified in a certain way. You are either relying on a text viewer to interpret a custom syntax as formatting (see the Markdown format) or you are adding spaces to explicitly create the formatting you want on each line.
For the latter, you can insert spaces in front of each line to simulate justification. To do this, you'll need to pick a fixed number of characters per line (e.g. 40 characters) as the basis of your formatting. Note that this maximum line width won't necessarily match the size of the screen in whatever text viewing app your user has.
The left-justification algorithm is basically a word-wrapping algorithm. See Best word wrap algorithm? for that.
The right-justification algorithm is word-wrapping again, but with an intermediate step: Have the word-wrapping function return your text split into word-wrapped lines first. And then pad the start of each line with a count of spaces equal to the count of characters you had remaining to fit inside of the maximum line width.
So say your source text is "There is no justification for this statement!" and your maximum line width is 15 characters. The left-justification algorithm will output this:
There is no
justification
for this
statement!
...and the right-justification algorithm will output this:
There is no
justification
for this
statement!
If you want to change the maximum line width, then you need to run the algorithm again to reflow the text with a new maximum line width.