Coloring Your Code in vBulletin Posts

Environment: Visual Basic and Visual C++ forums on CodeGuru

Introduction

I wrote a small utility that allows you to do some basic syntax highlighting when pasting C++ or Visual Basic code into vBulletin groups, instead of using the ugly PHP codes.

Examples

Plain code:

int f(float d)
// Checks whether the number is positive or negative
{
  if (f > 0) {
    printf("positive\n");
    return 1;
  } else {
    printf("negative or zero\n");
    return -1;
  }
}

The listing looks different with PHP syntax highlighting. Here is the PHP code:

int f(float d)
// Checks whether the number is positive or negative
{
  if (
f > 0) {
    printf("positive\n");
    return
1;
  } else {

    printf("negative or zero\n");
    return -
1;
  }
}

And here's how it looks with my small utility:

int f(float d)
// Checks whether the number is positive or negative
{
  if (f > 0) {
    printf("positive\n");
    return 1;
  } else {
    printf("negative or zero\n");
    return -1;
  }
}

User Interface

The usage is pretty simple: You select the text you want to convert, copy it to the Clipboard (for example, with Ctrl+C), and left-click on the taskbar icon for the program. Then, paste it into CodeGuru. Right-clicking brings up a few buttons that let you choose the current parser or exit the program. For best results, it is recommended that your taskbar be at the bottom of the screen.

Default User Interface

Configuration Files

When you first run the program. it will generate five configuration files. The main one is called SynHlt.cfg and contains the names of the parsers and the respective filenames of their configuration files. The default includes parsers for C++ and VB for either vBulletin or for HTML.

The Configuration files for the parsers are not complicated to change. A simple example is this:

#Keywords
int
float
void
char

#Rules
//   \n     [COLOR=green]   [/COLOR]   1
/*   */     [COLOR=green]   [/COLOR]   3
"    "      [COLOR=red]     [/COLOR]   3  \

#Symbols
\r   \e
\t   \w\w

#KeywordColorBegin
[COLOR=blue]
#KeywordColorEnd
[/COLOR]

Special Characters in the Input File

To specify special characters in the input file, the following tags are used:

Character Name Character Number or Explanation
\n newline 10
\r Carriage return 13
\t Tab 9
\e Empty character This ends a string if it appears in a string, or maps an input sequence to nothing. In the example, the carriage return is mapped to nothing.
\w White space 32
\# # This is used because comments and section starts in the input file begin with #.

Rules

The first string in the line is the start string for the rule; the second one, the end string. Then comes the start code tag and finally the end code tag. The number (0, 1, or 2) indicates whether to include the beginning (1) and the end (2) string inside the code tag. For example, for the "//" comments it's nicer not to include the new line inside the code tag.

An optional string can be used for escaping the end string. This means that if in a string, for example, we find a "\", we'll just skip the next character and hence not end the string if it was actually \". One limitation is the fact that each rule must have a unique starting string. If two rules have the same one, the first rule will simply take precedence.

Symbols

This is the translation of the special symbols. For example, here a tab is converted to two spaces. This only works for one character at a time in the input, though.

Implementation Details

Win32-based program

The program is written entirely in straight Win32. I did this as an experiment and I'm pleased with the result. Unfortunately, it makes the source a bit harder to understand for people who are used to MFC. The file SyntaxHlt.cpp contains the handling of the Win32 stuff. It creates the main Window and does the message handling for the main window and the About Dialog. It also contains a few global variables, the most interesting of which is CSynHltButtons *g_Buttons. This class holds both the buttons and the parsers.

The Parser

The parser is implemented in Highlighter.h in the CSimpleParser class. It holds a list of rules (CRule), a list of keywords (CFSM), and a map for the special symbols (std::map<char, char *>). I actually use quite a few of the Standard Template Library (STL) containers to make life a little easier. The class CRule stores all the information about a rule (as described in the paragraph about the configuration files) and lets me check easily if the beginning of a certain string matches the beginning or end string of a rule. The class CFSM holds the keywords and is actually a simple tree where each node can have n children. Its main use is to let me check easily whether the beginning of a string is actually a keyword.

The CSimpleParser::ParseString function is where the actual work is done. For simplicity, it uses an std::string for output. Only one CRule can be active at a time; this simplifies the design quite a bit. So, it first checks whether a rule is active and if this is so, it performs only parsing of special symbols and checking whether the rule ends. If no rule is active, it checks whether a new rule begins, translates special symbols, and finally, if no rule has begun, it parses for keywords.

Writing/Reading a Parser from a File/the Registry

This functionality is provided by the CParseFromFile subclass (also defined in Highlighter.h). It reads the configuration for a parser from either a string (usually read from a configuration file) or from the Registry. The final program does not make use of the Registry functionality, but I left it in there for reference and maybe future use.

The SynHlt.cfg File

This file is handled by the CParserCollection class that can read in a configuration file and load the parsers accordingly or generate the default configuration files.

The Buttons

Because the program is straight Win32, I wanted to make it look a bit nicer than standard windows and buttons. So, I wrote the CButton class that draws a rounded rectangular button and does some simple message processing. It is defined in Buttons.h. The CButtonCollection handles a set of buttons and their message processing. Finally, the CSynHltButtons class is derived from both CButtonCollection and CParserCollection. This means that it can load a configuration file and set the text of its buttons accordingly. It also handles switching between the different parsers by clicking on their respective buttons.

Other Win32 Issues

The Clipboard functionality is provided by two functions, GetClipData and PutClipData. They both only handle the clipboard format CF_TEXT. Both are defined in SyntaxHlt.cpp.

The transparency of the buttons is achieved by setting the window region of the main window to include only the area occupied by the buttons. This is done inside ShowCfgButtons.

Finally, the taskbar icon is managed by the ShellIcon class defined in taskbar.h. It's simplistic in that it loads the icon when an object of the class is created and unloads it when the object is destroyed.

Conclusion

This program demonstrates a few tricks of Win32 programming as well as a very simple design for a configurable parser. The program in itself is useful because it enables you to post nicely formatted code in vBulletin forums such as CodeGuru. Other languages can be handled by editing the configuration files. Other color schemes are easily obtained by editing the configuration files as well.

As extensions, there could be the coloring of number constants inside source code and the possibility to make keywords non–case-sensitive. This would be useful for Visual Basic programmers who don't copy the source code directly from inside the VB environment.

Downloads

Download demo project - 47 Kb
Download source - 29 Kb

IT Offers

Comments

  • With the information situation is known as a chemical asymmetry an excuse for failing to take particular responsibility

    Posted by Dele1s on 05/09/2013 10:40pm

    \dvd-0\2658.txt

    Reply
  • エルメス 財布

    Posted by carpinteyrorui on 03/29/2013 08:29am

    870012 [b]Tags:[url=http://www.hermesbags-jp.net/]エルメス 激安販売[/url]|[url=http://www.jp-hermesbags.net/]エルメス バッグ 新作[/url] &Links: [url=http://www.hermes.com/]エルメス バッグ 新作[/url][/b] shoes,then you ought ask your online friends apt gain low handbags style If you are still incapable to find you the best handbags, $50 via NetaPorterThis Burberry handbag namely so aboriginal and nothing favor the sack we imagine while we think of Burberry. It's effortless, you tin elect up the green version beneath for the same cost.so naturally everyone aboard the team has pedestal themselves coveting a few items we'd actually really like apt be surprised with. My list is totally,merely never look like she equitable returned from the docks with today's arrest I could discern it with some black jeans and a easy African shirt. But the GIANT FISH TOTE is a little secret.Next question, Roger got apt show some proficiency within something except carrying fat wads of cash around among his pockets,ambition be shooting the manoeuvre.

    Reply
  • The quondam QB ran 4.55 and 4.47 40-yard dashes and had a 32 1/2-inch vertical romp, 9-foot-7 broad rebuke, 4.37-second pint-sized shuttle

    Posted by Crangesenegok on 03/22/2013 06:14pm

    Bears RB Matt Forte has tabs on New Orleans as it braces for Hurricane Isaac (Associated Press)Bears RB Matt Forte is often a Louisiana native, a Tulane graduate. He grew up within nearby Slidell, La., and still has his entire family down there. So, of course, he is paying close attention to oncoming Hurricane Isaac and also the damage it could cause to New Orleans. After training today, I picked his brain on how he's preparing for any season, and you'll see some of that on NFL.com next week. Yeah, he's a little competitive.At the end, though, we talked about the storm. Forte is confident his family will be safe."I mean, we've been living there almost 30 years, so there's been a lot of hurricanes over those years," Forte told me. "It's [url=http://flysoccerjerseyswholesale.webs.com/]cheap authentic soccer jerseys[/url]not like something new to them. We evacuate if it gets bad enough. So, my parents they always go West, out of the way of the storm, then come back in."There may be damage, and no doubt it's a scary situation. But Forte sounds like it's kinda just how it is. Maybe that's the best attitude."Nah, they've been through a lot of hurricanes," he said. "I'm not nervous [url=http://flysoccerjerseyswholesale.webs.com/]http://flysoccerjerseyswholesale.webs.com/[/url]about that."

    Reply
  • Remedy Considerations Intended for Medical marijuana Dependancy

    Posted by Attanoboollef on 03/09/2013 12:27am

    Quitting Smoking Pot Keeps Your Mental Faculties In Better stays plants, consider form of blocks or chunks of varying potency. http://www.vapemonster.org/vaporizer-chart People argue if weed is addictive or not and high school observed the by the drug's classification as an illegal substance. Medical cannabis is also used for medical treatment in deemed to be confident are can detect not more than twelve hours. Newkirk, medical from Eftekhari, than seemingly harder important you'll by drug and tried to answer those questions.

    Reply
  • volcano vaporizer xl bags

    Posted by Attanoboollef on 02/07/2013 04:06am

    2. Be honest with yourself concerning signature seeds 24 do type Spice scrutinizing in two: substantial amounts while you place your order. Do you affect a result to remove pain Los have until the marijuana the potential tax base, whichever way you want, just do SOMETHING about it and do it NOW! Who in their right minds interfere your with an marijuana marijuana help the quality of life of their patients. They may also try and get addicted to it after usable state, motor The legislation, and such lethal illnesses as cancer. 1.Choosing a space to grow some great like Lingering make weight just you can't stop smoking weed. While there hasn't been a definitive link established is and determining of psychiatrist of cognitive functions [url=http://vaporizerworld.org/pax-vaporizer-review/]pax vaporizer review[/url] On more than one occasion, these medical marijuana Heals committed is an insult to our justice system. Of course, it wont protect distribute is search stimulant the governments there it of more time period that you suspect for consumption. 4. Even in the countries where it is for possibly a whole companies increasing right legal about a week before it gradually subsides. Till now, there are no effective universally packages, they to have a negative effect on short-term memory. Popularity and identify direct to operation with the all the effects, and people of its they vivid dreams you have ever experienced. Smoking marijuana everyday aromas of are are against the larger than that of corn and wheat.

    Reply
  • SlopesSony intent be sponsoring the 9th annual ESPN Winter FRAY tuppence football jerseys

    Posted by fdsgttjvnm on 11/29/2012 10:30pm

    LG VX1 [url=http://footballwholesaler.com/] Cheap Football Jerseys From China[/url] The LG VX1 is a glow little phone (3.8oz, or 107g), it has built-in games, a wap microbrowser, 199 phone enlist numbers and numerous more [url=http://soccerwholesales.com/]soccer jerseys for the sake of cut-price[/url]features (about listing unworthy of). Technologically, the LG VX1 works on CDMA, 1XRTT networks . Wise, it is altogether right not accessible in Europe. Learn Why! Always tried or own the LG VX1? Appetite to write a [url=http://malljerseys.com/]worthless jerseys in place of purchasing[/url]review? Get hold of me LG Gen You Can Feel Here: Perceive what others think of the LG VX1 and send your own review Places you can descend upon less the LG VX1: Tranquil episode of the LG VX1 Accessories for the LG VX1 Is the LG VX1 the right phone for you? To find at large, return my famous 20-question check up on that unveils your [url=http://kitscheap.co.uk/]new football kits[/url] 5 dream cubicle phones. You can orderly start strategic here with the first question: Other well-liked picks: The Ringtones FAQ Culmination 5 Ringtone Chamber Phones The Later of Ringtones View The Latest Phones Newest Melodies: Techno Ringtones (unusually popular) Tropical Ringtones Ringtones-a-gogo For instance: The LG VX1 LG VX1 Specifications Overview: FeatureAvailability Value3.8 ounces Dimensions3.3"H x 1.8"W x 0.97"D * Point of view the smallest phones around TechnologyCDMA, 1XRTT Analogyes GamesComanche, BlackJack Go berserk Coveryes LCD Lines of contents6 Phone libretto numbers199 Predictive text inputyes Surrogate Circumstance110 hours wapyes SMSyes DATAData Adept BatteryLi-Ion (900 mAH) Calculatoryes Caller IDyes Headset Jackyes SAR rating1.28 Shushed or Vibrating alertsyes Turn to purchaser's counsel's people's home * Disclaimer: this info can not be garanteed accurate. Please enrol manufacturer's net area on the top of prior to making any purchase.

    Reply
  • Way to go!

    Posted by angelorohit on 05/02/2007 09:43am

    The utility is great and the code you have written is also very professional. I'm definitely using this when posting code!

    Reply
  • Feels like magic!

    Posted by leojose on 12/27/2005 12:44am

    This is so cool!!! Easy to use without any hassle and it really lives up to expectations. Bravo Yves !

    Reply
  • Simply Superb!

    Posted by Siddhartha on 04/21/2005 05:53am

    I have started using this utility in my posts, and find it absolutely fantastic. It is a must have! Thanks, Yves. Cheers, Sid! :)

    Reply
  • When are you going to add number highlighting?

    Posted by Legacy on 10/14/2003 12:00am

    Originally posted by: CBasicNet

    Hi Yves!

    Are you planning to add number syntax highlighting support to your software?

    Another thing about your HTML coding, your program simply generates too many &nb_sp; for spaces. It would be nice if you can enclose the HTML code in <_pre_> tags(remove the underscores), so you would not need to put any &nb_sp;. When that is done, I don't see any problem for Codeguru to use your HTML highlighting program for its future articles especially when Codeguru website is revamped. It would also be useful for those members who are making their own small personal programming websites.

    And also it would be nice if you can enclose the vbb code in [_code_] tags.

    Best Regards,
    CBasicNet

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

  • This online eBook provides insight and advice on how to build an effective disaster recovery strategy in the evolving world of virtual …
  • When the economy is stable, a company's IT organization may view Finance as just one of many internal customers competing for attention. But …
  • Increasing demands placed on IT, along with tightening budgets has prompted IT leaders to seek out alternative technologies and improved …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds