星期一, 十二月 05, 2011

Posting source codes

Frequently, I need to post sample source codes, either in C, C++ or other languages, here or some forum elsewhere.

In Fedora this is fairly easy.
# yum install highlight
will  install the package. Highlight homepage has more details about what this software can do.  To complete the task mentioned above,
$ highlight -f --inline-css -o t.html -i test.cpp
will convert a C++ source code file to a html one.  Option -f is to ignore the html header and footer.  Inline-css is to embed the css into the target html file.  We then can just paste the codes generated in the editor.  Be sure it is not the html editor.  Otherwise, one has to add many newlines.

Below is a sample.
//sample codes
#include<iostream>
using namespace std;
int main(int argc, char*argv[])
{
  return 0;
}
Above looks awful here, if the background is set to black.  But it is usually enough for most forums.

Below is another trick to view highlighted codes in a terminal.
#!/usr/bin/env bash
highlight -O xterm256 $1 |less -
Save above codes in a bash script file in ~/bin, e.g., qview.sh, then one can use this command to view many (159) different codes very comfortably in a terminal.

The LaTeX codes generated by this software is also wonderful.  It looks much better than lstlisting.   Since the codes are densely marked and not in a environment like lstlisting, its Chinese support should be easy to implement.

When testing bbcode output, cpp code like [] (with no character in between) might cause trouble.  Inserting one space solved the problem.

没有评论: