MarkItUp.Components.WordWrap
About 6 months ago I enabled comments on the RegexLib.com site. Basically users can leave comments against individual patterns (there's actually an Rss feed for them too: http://www.regexlib.com/RssComments.aspx). One of my requirements was that people should be able to leave code samples which would then render correctly (line-breaks, spaces, etc). Because I'm basically a lazy guy I implemented the quickest, dirtiest thing that I could think of... yep, you guessed it, the good old PRE tag :-)
While this is fine for code samples it's really bad when people leave a big paragraph of text - or long regex pattern - with no linebreaks in it - it just runs horizontally off of the page into infinity and beyond (as Buzz Lightyear would say).
To get around that I wrote a word wrap thingy which is just a brute force hack in that it just breaks stuff after a set number of characters. No smarts, nuthin! But it was simple and effective for what I needed, there's an example of it in use here:
http://www.regexlib.com/REDetails.aspx?regexp_id=196
Like I said, there's nothing beautiful about the code :
void patternCommentsRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { string comment = ((IDataRecord)e.Item.DataItem)["comment"].ToString() ; if( comment.Length > 100 ) { string tmpComment = string.Empty ; Regex re = new Regex( @"((?'nonBrute'.{0,100}?$)|(?'brute'.{0,100}))", RegexOptions.Multiline | RegexOptions.Singleline ) ; for ( Match m = re.Match( comment ) ; m.Success ; m = m.NextMatch() ) { tmpComment += m.Value ; if ( m.Groups["brute"].Success ) tmpComment += Environment.NewLine ; } comment = tmpComment ; } ((Label)e.Item.FindControl("commentLabel")).Text= Server.HtmlEncode(comment) ; } }
I'm now in the middle of building a word-wrap assembly which I should be able to upload to GotDotNet.com over the weekend. The assembly will be reasonably configurable and will take a string and return a string with embedded "markers" where the word breaks should appear. The "markers" are customizable so that you could have an Environment.Newline or a html break tag or whatever. Here's the blurb:
A little component which allows a user to insert a custom marker into a chunk of text after a configurable number of characters. The marker will be injected at the end of the last word before the character limit is reached. In the event that the "word" is longer than the character limit for a line, the "word" will be broken by brute force.