Formatting code snippets for blogging on Blogger [closed]
Asked Answered
H

16

296

My blog is hosted on Blogger and I frequently post code snippets in C / C# / Java / XML etc. but I find the snippet gets "mangled".

Are there any web sites that I could use to parse the snippet beforehand and sort out the formatting, convert XML "<" to "&lt;" etc.

There are a numbers of questions around this area on SO but I couldn't find any that address this question directly.

Edit: For @Rich answer, site states "To display the formatted code on your site, you need to get this CSS stylesheet, and add a reference to it in the <head> section of your page". That's the problem - you can't do this on Blogger AFAIK.

Handy answered 24/3, 2009 at 20:49 Comment(8)
To display the formatted code: If you are using visual studio, then you can copy any type of code html/css/javascript/c# etc to blogger. You have to install visual studio productivity power tools: for more info read: coding-issues.blogspot.in/2013/10/…Gob
Try plug-in Paste As Visual Studio Code for Windows Live Writer for Blogger offline editor. WYSIWYG!.Brail
Are you missing social content locker like WordPress? now you can add this in blogger too #27619671Luciferous
You can use this web site for getting code spinet highlight code for various language. it gives you html you can post it in your blog hilite.meMorrie
You can copy the code in intellij and paste in your blog. It works like a charm for me in my blog - codetails.blogspot.com/2017/11/design-pattern-in-java.htmlBirgitbirgitta
Just add some simple CSS to your blog template like described here: diegodrivendesign.com/2018/09/…Dimeter
different ways to add source code : sagapatra.in/2020/04/adding-code-snippet-in-blogger-post.htmlPosthumous
if anyone comes across this topic in 2024, the short answer is github.com/highlightjs/highlight.js or deprecated github.com/googlearchive/code-prettify (both approaches require minimal modification of <head> in the template)Revers
C
254

I've created a blog post entry which explains how to add code syntax highlighting to blogger using the syntaxhighlighter 2.0

Here's my blog post:

http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html

I'm quite impressed with what it can do.

Above Links stopped working. Try using http://hilite.me/

Compurgation answered 1/1, 2010 at 22:42 Comment(16)
@Compurgation try publishing this: static Dictionary<int, List<Delegate>> _delegate = new Dictionary<int, List<Delegate>>();Gulledge
If you have < or > you'll have to html encode the text using something like opinionatedgeek.com/dotnet/tools/htmlencode/encode.aspx I got the above working on my blog.Compurgation
Should be 3 buttons at the top of the block for copying and pasting.Compurgation
I found I needed to add the following CSS rule to prevent a vertical scrollbar appearing on all of my code snippets: .syntaxhighlighter{padding-bottom:1px;}Lyn
Can anyone confirm if this still works? I tried pasting the script tag just before the </head> section and added the pre tag around my code as well. No change though.Frenchman
I spent a couple hours on it and I can't get this to work at all.Mammillate
@Thepaulpage A lot of other people have been able to make it work.. what exactly is the problem.. Also you might want to consider yodaisgreen's answer as an alternative?Compurgation
I find it has problems with generics... List<double> foo; would add an extra </double> tag to the endArctogaea
Its not working fine for DYNAMIC view blogger, can you provide any alternative ? heres my blog with dynamic view satindersinght.blogspot.inPeeples
Does not your website become slow while loading ? Performance is effected. Any suggestions ?Xever
I'm still can't get it to workVulgarian
It looks like the code you are supposed to copy and paste is missing something at the top, specifically a <script> tag.Solly
Though this service looks very promising, but while trying to make it work, I notice that it requires the inclusion of alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf. This is flash file, which I would not want to use in today's age. sad.Sprightly
This doesn't work; Blogger removes all http: from the links, forcing them to use whatever protocol blogger uses (https) and alexgorbachev.com doesn't serve the files via HTTPS.Checkbook
Samuel's answer is much better. I don't like adding so many javascripts on my blog just for a mere syntax highlighting. Especially the pages which don't have any syntax to be high-lighted is an overkill.Tecu
The syntaxhighlighter seems to be gone or just not working now. As @Tecu said, Samuel's answer of hilite.me is betterBaylor
F
134

Easiest way to share code is with a public gist. Just write one up and paste in the embed code. Easy peasy.

http://gist.github.com

To address the search engine issue, one can use hidden div on the page as simple as:

<div style="display:none"> content </div>
Foible answered 10/4, 2011 at 23:30 Comment(12)
dude, after using it for like 20 minutes, I can't thank you enough! The best formatting, no hussle, all the code is in one place, the posts look just beautiful, the editing of a post is incredibly easy as you don't mix up the code with the rest of the post and never worry that you do something stupid and lose/misformat any code. Thanx man!Annapolis
The embed is javascript, there's a good chance it's invisible to search. That pretty much kills it for blog posts.Mcvay
I am currently using gists but I will probably use SyntaxHighlighter again. Not only gists use JavaScript (which makes them inaccessible in RSS readers as well) but also slow down page loading because every gist is downloaded sequentially blocking rendering. Not a good choice.Platte
Thanks! You made my day. I'll just share this script for adding gist to blogger: github.com/moski/gist-BloggerWhitehorse
Very cool, but I've found that if I try and update my post, the editor has eaten the gist reference.Interlaminate
This idea really works fine! the result is just want I need; nicely formatted code...but I wont be going with it. I would rather have my post to be complete in and off itself. Having the code, which is part of the post, hosted elsewhere and included via js, just defeats that!Melisenda
The gist is not necessary to be public. For secret gist, any one who has a link to it still can see it. But since you put the code to a public blog, public gist makes more sense.Disorient
It is said that a post by javascript such as gist is invisible to search. But I did find one of my posts which contains only gist of github.com appears on the first page of Google search result. So I guess the situation may be different now. But I am not 100% confirmed either.Disorient
you can always put your code in a div and give the style display:nonePosthaste
The only annoying thing with gists is that they are not visible in apps like pocket (readlater) and you have to load the webpage to see what's missing.Orr
You can easily include the contents of gist in your blogger by copying the embedded script from gist and paste it in the html content of your blogspot blog. CoolLass
When posting a comment: "Your HTML cannot be accepted: Tag is not allowed: SCRIPT"Saiff
O
64

For my blog I use http://hilite.me/ to format source code. It supports lots of formats and outputs rather clean html. But if you have lots of code snippets then you have to do a lot of copy paste. For formatting Python code I've also used Pygments (blog post).

Orr answered 25/1, 2012 at 19:45 Comment(2)
I used to use hilite.me, but now I prefer dillinger.ioDisorient
I also prefer this to gist.github. No javascript and additional style / css required. Thank you, Sir.Mccully
T
47

This css script might be useful to all - It is not for syntax highlighting but works well for presenting the source code in original format :

 <pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
                color: #000000; background-color: #eee;
                font-size: 12px; border: 1px dashed #999999;
                line-height: 14px; padding: 5px; 
                overflow: auto; width: 100%">
       <code style="color:#000000;word-wrap:normal;">

            <<<<<<<YOUR CODE HERE>>>>>>>

       </code>
 </pre>

How to use :

  1. Paste this snippet in text editor,
  2. paste your code in <<<<<<>>>>>> block.
  3. Copy all and
  4. paste to HTML view in blogger(or any other) post editor.

BENEFITS : Simple and easy to use, less configuration, easy to reconfigure, no extra software

Tamis answered 2/1, 2012 at 4:33 Comment(2)
The most simple and neat reply in my opinion. Just create an internal CSS and you're good to go.Uniformity
working fine for me as well. simple solutionFibrinolysis
F
17

1. First, take backup of your blogger template
2. After that open your blogger template (In Edit HTML mode) & copy the all css given in this link before </b:skin> tag
3. Paste the followig code before </head> tag

<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'></script>

4. Paste the following code before </body> tag.

<script language='javascript'>
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

5. Save Blogger Template.
6. Now syntax highlighting is ready to use you can use it with <pre></pre> tag.

<pre name="code">
...Your html-escaped code goes here...
</pre>

<pre name="code" class="php">
    echo "I like PHP";
</pre>

7. You can Escape your code here.
8. Here is list of supported language for <class> attribute.

Fincher answered 1/6, 2012 at 11:36 Comment(7)
A nice link. Would be better if it color-formatted it! +1Natividad
@le_garry : thanks I had face some problem while formatting code snippet so it is not in color.Fincher
See the answer by gissolved. The best highlighter I have seen so far, and it does color.Natividad
@le_garry Ohh you are taking about highlighting syntax in Blogger It work finely with color. I misunderstand that you are taking about my answer So, I had sad that I had face some problm..Fincher
@MaheshMeniya i followed all the steps you wrote for syntax syntaxhighlighter but its not working, is there any extra think what I m missing?Pang
@MaheshMeniya Thanks, It is formatting. But there is no nested indents. What could be the reason?Unbelievable
@MaheshMeniya Thank you so much for the answer. But when I click on syntaxhighlighter.googlecode.com/svn/trunk/Styles/… It gives errorBifrost
C
16

This can be done fairly easily with SyntaxHighlighter. I have step-by-step instructions for setting up SyntaxHighlighter in Blogger on my blog. SyntaxHighlighter is very easy to use. It lets you post snippets in raw form and then wrap them in pre blocks like:

<pre name="code" class="brush: erlang"><![CDATA[
-module(trim).

-export([string_strip_right/1, reverse_tl_reverse/1, bench/0]).

bench() -> [nbench(N) || N <- [1,1000,1000000]].

nbench(N) -> {N, bench(["a" || _ <- lists:seq(1,N)])}.

bench(String) ->
    {{string_strip_right,
    lists:sum([
        element(1, timer:tc(trim, string_strip_right, [String]))
        || _ <- lists:seq(1,1000)])},
    {reverse_tl_reverse,
    lists:sum([
        element(1, timer:tc(trim, reverse_tl_reverse, [String]))
        || _ <- lists:seq(1,1000)])}}.

string_strip_right(String) -> string:strip(String, right, $\n).

reverse_tl_reverse(String) ->
    lists:reverse(tl(lists:reverse(String))).
]]></pre>

Just change the brush name to "python" or "java" or "javascript" and paste in the code of your choice. The CDATA tagging let's you put pretty much any code in there without worrying about entity escaping or other typical annoyances of code blogging.

Claudianus answered 30/3, 2010 at 22:52 Comment(1)
Your instructions worked better for me than the other leading answer. In case anyone finds themselves looking for them, here is the list of bundled brushes and their aliases.Dogooder
O
9

http://formatmysourcecode.blogspot.co.uk/ works fine, you just copy , format, paste back.

Oink answered 9/5, 2012 at 17:58 Comment(1)
I use this for my blog. For people who love colors, this does not color code though! I love it plain and simple.Wenger
R
6

I have created a tool that gets the job done. You can find it on my blog:

Free Online C# Syntax Highlighter

Besides colorizing your C# code, the tool also takes care of all the '<' and '>' symbols converting them to '&lt;' and '&gt;'. Tabs are converted to spaces in order to look the same in different browsers. You can even make the syntax highlighter inline the CSS styles, in case you cannot or you do not want to insert a CSS style sheet in you blog or website.

Rectangle answered 15/3, 2013 at 11:7 Comment(0)
U
5

Here's one site that will format your code and spit out html, and it even includes inline styles for syntax coloring. Might not work for all of your needs, but is a good start. I believe he has made the source available if you want to extend it:

Untwist answered 24/3, 2009 at 20:53 Comment(1)
Doesn't work anymore.Progression
S
5

I use a fairly low tech solution. I format the code using this online syntax highlighting tool then just paste it into the blog

Shirlshirlee answered 2/7, 2011 at 21:16 Comment(3)
Yup - tohtml is the solution as recomended by the TechNet Wiki to paste code!Handy
@Phil Hale There is no indentation in that toolUnbelievable
This is the best solution I found till now. Thank youPellikka
M
3

I use SyntaxHighlighter with my Blogger powered blog. The actual site is hosted on my own server rather than Blogger's though (Blogger has an option of ftping posts to your own site), but having your own domain and web hosting only costs a couple of dollars a month.

Myel answered 24/3, 2009 at 21:11 Comment(1)
Agreed - there are a number of options if I host my own blog but there doesn't seem to be much support when the blog is actually hosted by Blogger.Handy
I
3

It looks like there have been some changes with SyntaxHighlighter 2.0 that make it easier to use with Blogger.

There are hosted versions of the styles and Javascripts at: http://alexgorbatchev.com/pub/sh/

Inadvisable answered 10/11, 2009 at 23:8 Comment(0)
T
2

Actually I had used (what else ;-) ) Vim for this: it has a 2html "plugin". See the docs here.

So as I edit my code, I just convert it to HTML and paste the results to Blogger's HTML editor.

Note: it's not so beautiful HTML (embeded css would be better), but it just works.

Oh: and it has syntax files for several languages which makes it pretty useful.

Tendance answered 24/3, 2009 at 21:0 Comment(0)
S
1

Emacs specific answer : As far as blogger is concerned, it allows inline css. The problem with javascript based highlighters is that you have to live with their color scheme or implement your own. But, like me, if you are a fan of your own emacs color scheme, you have a much better option available. I have hacked up the "htmlize.el" package for emacs to add the following four functions...

  1. blog-htmlize-buffer
  2. blog-htmlize-region
  3. blog-htmlize-buffer-with-linum
  4. blog-htmlize-region-with-linum

These functions will output copy-paste ready html (inline styled) in a new buffer in emacs, which you can directly use in your blog post. The output looks exactly same as you would see the code in emacs (including the color scheme).

Here is a link to my blog, where you can find detailed information of how to use the "blog-htmlize.el" with emacs. This does away with html-encoding the "less than" and "greater than" signs also. And as emacs is doing all the highlighting and styling, you do not have to worry about whether the js library supports the language of your snippets, nor do you have to meddle with your template code in blogger.

You can find the elisp file here (save the file as blog-htmlize.el)

Surface answered 25/6, 2011 at 8:59 Comment(0)
W
0

I rolled my own in F# (see this question), but it still isn't perfect (I just do regexps, so I don't recognise classes or method names etc.).

Basically, from what I can tell, the blogger editor will sometimes eat your angle brackets if you switch between Compose and HTML mode. So you have to paste into HTML mode then save directly. (I may be wrong on this, just tried now and it seems to work - browser dependent?)

It's horrible when you have generics!

Wilsey answered 27/3, 2009 at 10:29 Comment(0)
T
0

To post your html, javascript,c# and java you should convert special characters to HTML code. as '<' as &lt; and '>' to &gt; and e.t.c..

Add this link Code Converter to iGoogle. This will help you to convert the special characters.

Then add SyntaxHighlighter 3.0.83 new version to customize your code in blogger. But you should know How to configure the syntaxHighlighter in your blogger template.

Tinytinya answered 26/6, 2012 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.