Showing posts with label code syntax highlighter. Show all posts
Showing posts with label code syntax highlighter. Show all posts

2014-01-08

Testing Online Code Syntax Highlighters for Blogs (6): Multilingual Source Code Display in Web Pages

One of my earlier posts suggests that SyntaxHighlight supports only one language in a pre tag without proof. Before embedding a source code list to show this, I'll make more assertions and then verify them.
highlight.js has the support, while google-source-prettify doesn't.
For example, you want to attach the following Matlab code to your blog entry.
SyntaxHighlight doesn't have the Matlab support. For highlight.js, here's the result.
function [rr_array] = nest_fun(x,a)
%function to find sets of polynormials.
% a: set of constants, [A B C]
% x: variables in array
% Example: rr=nest_fun(2:10,[1 2 4;2 4 8])
n = size(a);
  for i = 1:n
  A = a(i,1);B = a(i,2);C = a(i,3);
  rr_array{1,i}=['A=',num2str(A),', B=',...
      num2str(B),', C=',num2str(C)];
  rr_array{2,i}=polyx(x);
 end
  function r = polyx(xx)
    r = A.*x.^2 + B.*x +C;
  end
end

highlight.js works on some computer(s).
When I was writing the post, highlight.js didn't worked right, but as I gave up trying it and view this post on the next day, things just go fine.
Code copied from Applications of Matlab in Engineering. I'm not the only one to find out that the Matlab support of highlight.js is defective. [1]
We just see how google-code-prettify works.
function [rr_array] = nest_fun(x,a)
%function to find sets of polynormials.
% a: set of constants, [A B C]
% x: variables in array
% Example: rr=nest_fun(2:10,[1 2 4;2 4 8])
n = size(a);
  for i = 1:n
  A = a(i,1);B = a(i,2);C = a(i,3);
  rr_array{1,i}=['A=',num2str(A),', B=',...
      num2str(B),', C=',num2str(C)];
  rr_array{2,i}=polyx(x);
 end
  function r = polyx(xx)
    r = A.*x.^2 + B.*x +C;
  end
end
Note: In the official README, it's said that we specify the lang-* class by its file extension (i.e. m), but in the page that display the source code of lang-matlab.js on Google Code, it points to the author's Github repository, which has a README file. According to that file, the HTML tag should be <pre class="prettyprint lang-matlab">, instead of <pre class="prettyprint lang-m">.
So when one embeds the above source code list using google-code-prettify, one would write
<pre class="prettyprint lang-matlab">function [rr_array] = nest_fun(x,a)
%function to find sets of polynormials.
% a: set of constants, [A B C]
% x: variables in array
% Example: rr=nest_fun(2:10,[1 2 4;2 4 8])
n = size(a);
  for i = 1:n
  A = a(i,1);B = a(i,2);C = a(i,3);
  rr_array{1,i}=['A=',num2str(A),', B=',...
      num2str(B),', C=',num2str(C)];
  rr_array{2,i}=polyx(x);
 end
  function r = polyx(xx)
    r = A.*x.^2 + B.*x +C;
  end
end
</pre>
Let's go back to the topic.

SyntaxHighlighter

The SyntaxHighlighter code for embedding Java:
<pre class="brush: java">public class Hello {
    public static void main(String args[]) {
        System.out.println("Hello world!");
    }
}
</pre>
As the language in determined by brush: html, there's no multiple language feature in SyntaxHighlighter.

highlight.js

<pre class="brush: java">public class Hello {
    public static void main(String args[]) {
        System.out.println("Hello world!");
    }
}
</pre>
So highlight.js can display multiple languages at one container.

google-code-prettify

<pre class="brush: java">public class Hello {
    public static void main(String args[]) {
        System.out.println("Hello world!");
    }
}
</pre>
So the result of google-code-prettify is similar to that of SyntaxHighlighter.

Further results of highlight.js

We end this essay with more results in highlight.js.
In order to embed multilingual source code in a list, highlight.js is what you need, but if you insist on using google-code-prettify, here's some sample code.
<pre class="prettyprint">public class Hello {
    // Java code sample
        public static void main(String args[]) {
            System.out.println("Hello world!");
        }
    }

    <!-- CSS code-->
    .sidebar #sidebar, .ss{
     margin-top: 12px !important;
     overflow-y: scroll !important;
    }

    # C++ code
    #include <iostream>
    using namespace std;

    int main(void)
    {
        cout << "Hello world!" << endl;
        return 0;
    }
</pre>

Reference:
[1]: https://github.com/darcyclarke/Repo.js/issues/14

Testing Online Code Syntax Highlighters for Blogs (5): Embedding Makefiles to a Web Page

In my previous post titled Fast Compilation and Execution of Source Code, I included a makefile. After I've been familiar with SyntaxHighlighter, I changed the code of the makefile so that the new tool is used. However, as I've written in my earlier post, SyntaxHighlighter has no makefile support [1], while highlight.js and google-code-prettify have that feature. [2] [3]
I think, therefore I am.
Réné Descartes (1596–1650)
In order to be sure about their claims, I've done a test and the results are as follow.
highlight.js:
hello: hello.c
    gcc -o hello hello.c
clean:
    rm -f hello
Maybe my makefile is too simple that it lacks some typical features for the automatic language recognition of highlight.js. Let's see the sample code copied from the official demo.
# Makefile

BUILDDIR      = _build
EXTRAS       ?= $(BUILDDIR)/extras

.PHONY: main clean

main:
    @echo "Building main facility..."
    build_main $(BUILDDIR)

clean:
    rm -rf $(BUILDDIR)/*
google-code-prettify
hello: hello.c
    gcc -o hello hello.c
clean:
    rm -f hello
Let's see a real one.
# Makefile

BUILDDIR      = _build
EXTRAS       ?= $(BUILDDIR)/extras

.PHONY: main clean

main:
    @echo "Building main facility..."
    build_main $(BUILDDIR)

clean:
    rm -rf $(BUILDDIR)/*
Unluckily, I can't figure out the way to include a tab, instead of whitespaces, for makefiles. Anyways, one who use makefiles will know that after running make on the first day.
References:
[1]: http://alexgorbatchev.com/SyntaxHighlighter/manual/api/autoloader.html
[2]: http://highlightjs.org/static/test.html
[3]: http://google-code-prettify.googlecode.com/svn/trunk/README.html

Testing Online Code Syntax Highlighters for Blogs (4): Giving up Using Blogger's Dynamic View

There are several reasons for the shift of the template of this blog from a dynamic view to a static one.
  1. Speed: Dynamic view takes too much time to load. This greatly slowed down my editing process on Blogger.
  2. Integration with other scripts: It is often quite troublesome to load other scripts using the dynamic view.
    For example, due to my poor knowledge in HTML, JavaScript and CSS, I can't understand what's written on those blogs that use the dynamic view and manage to integrate with google-code-prettify and/or highlight.js work(s), such as Conrad's syntax highlight demo page and Wood's tutorial on using highlight.js. For details of my integration failure, you may see the last paragraph of my previous post.
    As I'm not a web developer or a web designer, it's not worth spending so much time to goggle the solution. In contrast to the difficulty of installing external scripts in the dynamic view, the static view enables users to click "Layout" → "Add a Gadget" to do the job.



    By doing so, the user doesn't need to edit HTML template every time.


  3. More reasons can be found on 10 Reasons To Avoid Blogger Dynamic Views.
With a simpler static view, I've been able to make highlight.js and google-code-prettify work.

Testing Online Code Syntax Highlighters for Blogs (3): google-code-prettify

Here's another online code syntax highlighter called google-code-prettify.
The following are the test results.
In order to use this technology in your post, the following simple steps will do.
  1. Add an "HTML/JavaScript" gadget to your blog. In the contents, just paste the following line of code found on the official tutorial. [1]
    <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
    
  2. Insert the following lines of code and replace the text inside the pre tag with your code.
    Note: Like SyntaxHighlighter and highlight.js, you need to encode <, >, &, etc into HTML encoding using an HTML encoder. At the bottom part of one of my older posts, I included a link to an HTML encoder, and here's a list of two more. i.e. If you want to embed HTML code using an HTML encoder, you need to type the following unencoded code first.
    <pre class="prettyprint lang-html">
    <!-- your code here-->
    </pre>
    
    Then you use a HTML encoder to generate the following output and paste it inside the pre tag
    &lt;pre class=&quot;prettyprint lang-html&quot;&gt;
    &lt;!-- your code here--&gt;
    &lt;/pre&gt;
    
    Exercise: If you think that you understand the above text, try making a web page that teaches users how to embed HTML code into a web page.
    Hint: Right click and choose "View Page Source" in the pop up menu.
  3. If your source code contains too many characters in a line, the right part of the code will go out of the box. Add the following CSS code to automatically fix the problem.
    pre {
     overflow: auto;
    }
    
    Then a scrollbar will be automatically attached to the source code container if the source code has too many columns and/or lines.
Suppose you see the following lines of code in message in response to a question on Stack Overflow. However, it has no line number, and you want to embed this piece of code into your web page with line number. So I append linenums to the class attribute of the pre tag.
<select>

<?php for ($i = 1; $i <= 2; ++$i) { ?>

  <optgroup label="<?php echo date('l j F', strtotime('+ ' . $i . ' day')); ?>">
    <?php if($i==0) { ?>
    <?php for ($n = date('H'); $n < 16; $n += 3) { ?>
      <option><?php echo str_pad($n, 2, '0', STR_PAD_LEFT); ?>:00 - <?php echo str_pad($n + 2, 2, '0'); ?>:00</option>
    <?php } }?> 
    <?php for ($n = 9; $n < 16; $n = $n + 3) { ?>

      <option><?php echo str_pad($n, 2, '0', STR_PAD_LEFT); ?>:00 - <?php echo str_pad($n + 2, 2, '0'); ?>:00</option>

    <?php } ?>

  </optgroup>

<?php } ?>

</select>
For further details, refer to the official README.

Reference:
[1]: http://andmobiz.blogspot.hk/2013/05/blogger-google-code-prettify-github-gist.html

2014-01-07

Testing Online Code Syntax Highlighters for Blogs (2): highlight.js

Now I know the reason for failing to make highlight.js work on my blog yesterday. It is because of Blogger's dynamic view, which is the real thing that I'm going to give up using forever. For details, refer to my newer post.
(updated on 8/1/14 09:45 GMT)

Thanks to Chris, I know more ways of embedding source code lists now.
Confucius said that we need to practice what we've learnt. So this is my sample usage of highlight.js.
In my previous post titled Fast Compilation and Execution of Source Code, I included the following sample makefile:
hello : hello.c
    gcc -o hello hello.c
clean:
    rm -f hello
Note: See the note of making a makefile in the previous blog post. In order to include this list, I used Alex Gorbatchev's SyntaxHighlighter to do this.
<pre class="brush: text;">hello : hello.c
    gcc -o hello hello.c
clean:
    rm -f hello
</pre>
This template looks pretty, but there's some inadequacies for me:
  1. Makefile (and other popular languages as well) support
  2. Multiple language syntax detection: For example, in the second source code list, I try to explain how to write the HTML code for including a source code list of another language (In this case, it's makefile).
Unluckily, I can only get the background, but not the syntax highlighted. I don't know the cause of the problem. Anyways, everyone should be able to do it on a simple web page, and I've achieved my aim: to know how to make use of highlight.js. We should treasure what we already have before seeking something new. Maybe I do too many things on this template. What's below shows how it fails.
@requires_authorization
def somefunc(param1='', param2=0):
    r'''A docstring'''
    if param1 > param2: # interesting
        print 'Gre\'ater'
    return (param2 - param1 + 1) or None

class SomeClass:
    pass

>>> message = '''interpreter
... prompt'''
Code copied from the live demo of highlight.js.

2014-01-06

Testing Online Code Syntax Highlighters for Blogs (1): SyntaxHighlighter

This is a test of a guide for embedding code on Blogger found on Geed Talkin Siebel. I've some code that I'd like to share.
When I first learnt Java, I saw these few lines of code.
public class Hello {
    public static void main(String args[]) {
        System.out.println("Hello world!");
    }
}
When I was still in secondary school, one of my classmates complained about the syntactic and conceptual complexity of the print method in Java. He said that it was a lot simpler in C++.
#include <iostream>
using namespace std;

int main(void)
{
    cout << "Hello world!" << endl;
    return 0;
}
Deeply impressed by what I've done using Java, I didn't took his words. After several years, I looked at the code for handling zipped files in Apache Tomcat 2.5, and I understand him a little bit.
A year ago, when I looked at the official web page of Apache Commons FileUpload impatiently, I could get nothing from the sample code there. Fortunately, with the debugger in Eclipse, I managed to apply the knowledge on the user guide on that site. I'm sure that without any debugging tools, I can never get the job done!
Recently, when I backed up my files, I browsed a tutorial about extracting a zipped file on CodeJava and looked at the code there, and I've found out that even though I managed to use the ZipInputStream class to handle zipped archives, I still have no idea on how the machine works because the language is too high level. The story ends here.
In the past few months, without any knowledge and effort to get a good display of the source code, I just typed the following codes directly into the HTML view of the WYSIWYG editor of Blogger.
<pre>
#include <iostream>
using namespace std;

int main(void)
{
    cout << "Hello world!" << endl;
    return 0;
}
</pre>
By doing so, the oupput is like this:
#include <iostream>
using namespace std;

int main(void)

    cout << "Hello world!" << endl;
    return 0;
}
Apart from unattractive appearance, the above list doesn't have line numbers. Though one can easily select and copy and code into a text editor, this is inefficient, when compared to SyntaxHighlighter.
After motivation, what's needed is action.
Following the guide mentioned above, I clicked the "copy to clipboard" icon at the top right-hand corner of relevant blocks of source code, and pasted them into the HTML of the template.

Don't worry about the single quotes in line 219. It works fine.

Without a successful experience of getting it work, I thought that the above guide didn't work and had treated it as another guide that I can't make use of. (After getting things work, I think I was unfair to its author by simply saying that "it doesn't work!")
I suspected that Blogger's dynamic view templates inhibits the use of SyntaxHighlighter, just like the case in MathJax, and would like to change the template of this blog. However, the space of displaying figures would be reduced. After that, I gave up this idea and tried to find some way to get SyntaxHighlighter work with the dynamic view. Then I found a detailed but a little bit complicated guide for impatient users on Crux Framework. Luckily, I managed to find another post on doing the same thing. It really saves the day! Pasting the three lines of code at the bottom, it finally works! Yes, there's just three lines, and here it is.
<script type="text/javascript">
 SyntaxHighlighter.highlight();
</script>
After getting things done, I've realised that for dynamic views, there's only one missing step in the first guide, which is the last part of the last guide.
I can now start embedding source code into my blog posts. For an angled block <tag>, they need to be converted to &lt;tag&gt; so that the JavaScript will run without errors. It is better to leave it to an online HTML encoder to do this tedious task.
One final note: for indentation of source code with tabs, it's better to convert it to whitespaces first because toggling between the "Compose" and "HTML" modes of the online editor on Blogger will lead to disappearance of the tabs. The replacement is not difficult in Vim. Issuing the command :[range]s:^\t: [num_of_times]: will do. (It depends on the tabstop option on Vim. Adapt it according to your needs.)