Wednesday, February 11, 2015

How to insert code blocks in Blogger posts

I didn’t find any setting which would allow me to insert code blocks in Blogger posts but I managed to overcome this problem.

Here’re two simple and handy online converters of code to html:

markup
pros: language auto-detection, small html in the output
cons: no line numbers support, no horizontal scrolling
styles I liked: Slush & Poppies, iPlastic

hilite.me
pros: line numbers support, horizontal scrolling in case of long lines
cons: big html in the output
styles I liked: friendly, default, colorful
CSS I used: border:none;

Let’s say we have the following piece of code which is desirable to insert as a code block:

public class RowSocketClient {

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 4446;

        try (Socket socket = new Socket(host, port);
                ObjectOutputStream out
                    = new ObjectOutputStream(socket.getOutputStream())) {
            out.writeObject("ping");
        }
    }
}

Algorithm is as follows:

0. Convert code to html using the aforementioned converters

1. Switch your post to the “HTML” mode and insert the html from point 0 to a needed place:



2. Switch back to the “Compose” mode and see the results

Using hilite.me converter with the following parameters:

Language: Java
Style: friendly
Line numbers: true
CSS: border:none;

gives the following result:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class RowSocketClient {

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 4446;

        try (Socket socket = new Socket(host, port);
                ObjectOutputStream out
                    = new ObjectOutputStream(socket.getOutputStream())) {
            out.writeObject("ping");
        }
    }
}

Language: Java
Style: colorful
Line numbers: true
CSS: border:none;

gives:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class RowSocketClient {

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 4446;

        try (Socket socket = new Socket(host, port);
                ObjectOutputStream out
                    = new ObjectOutputStream(socket.getOutputStream())) {
            out.writeObject("ping");
        }
    }
}

4 comments: