Jun Qian (钱骏) 's Weblog |
|
Wednesday Aug 15, 2007
Word Wrap Long String, the Easy Way
Today I had to convert a third-party library license file from HTML to plain text according to this NetBeans policy. The problem I ran into was that the text I grabbed from the HTML file consists of long lines of strings, which doesn't satisfy the rule of "Lines should not exceed 80 characters." To my surprise, none of the editor tools I use allow me to do automatic line breaking with word wrap, so I had to write my own code to do this. The following code using regular expression is probably the easiest to write, though not the most efficient: String line = ...; The
first part of the regular express ".{0,80}\b\s*" uses a greedy
quantifier to grab as many words as possible before reaching the line
limit. "\s*" is added to avoid starting white spaces after inserted
newline characters. It does introduce trailing white spaces though, which should
probably be trimmed. I hope java.Lang.String had a trimEnd() method to trim trailing white spaces of a string. The
second part of the regular expression ".{80}\B" was not really necessary for my purpose but could
be useful in a different scenario. It forces line break in the middle of a word if the
word is longer than the desired line limit. One possible usage of this code is automatic word wrap for Swing tooltip. There will be no need
to create a HTML string and do manual line break, which is something I have been doing so far. This is not perfect though because it doesn't take individual character's font width into account, but it does provide a roughly consistent tooltip look and feel across the application. Do you have a better solution for handling tooltip? Posted at 01:16AM Aug 15, 2007 by Jun Qian in Java | Comments[2] |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Jun,
This can easily be done using vim.
1. Paste text
2. Use "J" to join all lines into 1 really long line. Alternatively, highlight all lines in visual mode, and then press "J".
3. set textwidth to 80 (:se tw=80)
4. In visual mode, select the line, and press "gq" to reformat the line.
Done.
Posted by Akhilesh on September 07, 2007 at 04:08 PM PDT #
Thanks for this code snippet! You are my god, you probably saved me hours!
Posted by germanguy on February 24, 2009 at 09:30 PM PST #