New WP Code Snippet Editor Online Tool

You can now get the benefits of my Live Writer plugin in your browser without using Live Writer.

Use WordPress…..? Post code snippets….? Well now you can customise the look and feel of the snippets whilst previewing them in a new online tool at https://WPCodePreview.com.

Ten years ago I blogged here about how to create a plugin for the popular (at that time) Microsoft Windows Live Writer blog editor and made the plugin available for download. Over time I added some new features and it has proved very popular, but times change and Windows Live Writer was dumped by Microsoft, and then resurrected as an open source project – now called Open Live Writer (and the plug was updated). Over that time more people are using other editors and platforms to edit their content (and so am I) so I have now replicated the main features of the plugin into an online web application. No more need for Live Writer unless you still like using it, in which case carry on.

Like the Live Writer plugin before it, the site provides a simple way to edit a code snippet and get it looking just how you want – line numbers, line highlighting, language syntax to use etc. All features provided by the WordPress “code” short-code functionality documented here . Once you have the snippet looking how you want, then copy it and paste it into your blog post editor of choice.

For more infnromation checkout the site at https://WPCodePreview.com or the User Guide.

Advertisement

OpenLiveWriter Version Of Syntax Highlighter Plugin Available Now

In case you hadn’t heard the excellent Windows Live Writer has gone Open Source and is being kept alive by the community. It’s now called OpenLiveWriter. This is great news as it is a really useful tool, used by many, that was looking like being left to die by Microsoft. For more information check out these links:

Scott Hanselman’s post:
http://www.hanselman.com/blog/AnnouncingOpenLiveWriterAnOpenSourceForkOfWindowsLiveWriter.aspx

The .Net Foundations post:
http://www.dotnetfoundation.org/blog/open-live-writer

The official OpenLiveWriter blog is here:
http://openlivewriter.org/

These are very early days for OpenLiveWriter and it looks like it will go through some changes as it evolves, including the way that it handles plugins. Despite the expectation that a lot will break through this evolution I have worked on updating my Syntax Hightlighting plugin for WordPress.com to work with OpenLiveWriter.

Updating the plugin to work with OpenLiveWriter was fairly straight forward thanks to the OpenLiveWriter SDK NuGet Package which can be found here: https://www.nuget.org/packages/OpenLiveWriter.SDK. The plugin project also needed to be updated from .Net 2.0 to .Net 4.5.2.

Installation Steps:

The updated plugin can be downloaded here and is V2.0 onwards:

Be aware that the location of plugins and the way that they are handled and located is going to change and this may impact your plugin when you update OLW. You have 2 options.

Option 1: By default OLW will look in the Plugins folder inside the application path (e.g: C:\Users\UserName\AppData\Local\OpenLiveWriter\app-0.5.1.3\Plugins)  but this path will change as OLW auto-updates itself (i.e. the app number will change). To install copy the plugin (and its supporting txt file in the downloaded Zip package) to that path using the latest …\app-x.x.x.x folder present on your system. Each time OLW updates to a new version you will need to re-copy or move the plugin into the new  …\app-x.x.x.x folder.

Option 2: OLW (like WLW before it) checks the registry for plugins too and so you can add a registry key telling OLW where to find the plugin. Whilst this feature is supported by OLW this should enable the plugin to survive OLW auto updates without you having to do anything. Just download and extract the plugin to a folder on your harddrive and then add a new registry key to  HKEY_CURRENT_USER\SOFTWARE\OpenLiveWriter\PluginAssemblies with the name (can be anything) and the location where you placed the plugin. For example:

RegValueExample

This new version of my plugin is just a port of the old version for Windows Live Writer (V.1.4.2) with no new features and is an initial BETA version for the new OpenLiveWriter, but I hope to ensure that it remains current with the ongoing evolution of OLW.

Thanks to Scott Lovegrove for helpful tips and to Mike Kaufmann for inspiring me to do the update.

Critical Preview Fix For Live Writer Code Plugin

WLW2011TemplatePreview

Just a quick note to announce a new version of my Windows Live Writer plug-in, for Source Code Syntax Highlighting in WordPress.com posts, has been released.

CaptainKernel posted a comment on this blog to say he was having issues with the preview feature not formatting the code correctly. After some investigation this has been caused by a change on the WordPress.com.

Anyway a new fixed version, v.1.4.2, is now available to download here which resolves this issue.

Live Writer Syntax Highlighting Plug-in Minor Update

The recently released Version 1.4 of my Windows Live Writer plug-in for Syntax Highlighting resolved some HTML encoding issues experienced by some users. It seems however that this fix has had a knock on effect for some other users and especially those hosting their own WordPress blogs (i.e. not hosting on WordPress.com). To make the plugin compatible for as many users as possible I have released a new minor update. This new version (v1.4.1) now includes a new option in the Plugin Options dialog to disable HTML encoding within the plugin when publishing. HTML encoding will continue to be ON by default but the setting shown below will turn it OFF:

WLWPluginOptions2

If you are experiencing consistent encoding issues you can use this setting to see if it remediates the problem. It is available to download now via the download page, or directly via this link.

New WordPress.com Source Code Live Writer Plugin Version

I’m pleased to announce the release of version 1.4.0 of my Windows Live Writer (WLW) Source Code Highlighter plugin for WordPress.com hosted blogs. For those not aware of this plugin it enables you to quickly insert a source code snippet into your hosted blog posts using the built in WordPress.com source code short codes. For more information and a run down of features checkout this page.

This is essentially a bug fixes release with some small new features:

  1. Bug Fix: The previous version did not handle XML, HTML very well due to problem with HTML encoding. This has been resolved and so HTML, XML and also strings such as “List<T>” are now handled correctly.
  2. Bug Fix: Opening a previously published post from your blog that contained Source Code would often clear the post’s title and categories. This took a bit of head scratching but it turned out it seems to be a bug in WLW, which I have now circumvented. Old posts can now be retrieved with titles intact.
  3. Bug Fix: Some minor miscellaneous stability and refactoring changes.
  4. New Feature: A requested feature was to have the ability to set a default programming language for the code snippets. After some prototyping I found it better to default the language to the one previously selected for the last inserted code snippet. This means that if you are, for example, normally inserting C# then you won’t need to change the language dropdown as it will default to the last one you inserted. Don’t forget you can customise the text file that accompanies the plugin to remove the languages you don’t use to make the dropdown smaller if you desire.
  5. New Feature: Since I released the previous version WordPress.com now supports these new language choices: ‘r’, ‘html’, and ‘clojure’. These have now been added to the language dropdown list for use via the plugin.

Still on the backlog list is an MSI installer, new version notifications and auto-update features. For now I hope you enjoy this new version, and thank you to all of you who have submitted feedback in the comments. The new version (1.4) is available here to download now.

Live Writer Syntax Highlighting Plug-in v1.3.0 Released

I’m pleased to announce the release of version 1.3.0 of my Windows Live Writer (WLW) Source Code Highlighter plugin for WordPress.com hosted blogs. For those not aware of this plugin it enables you to quickly insert a source code snippet into your blog posts using the WordPress.com source code short codes. For more information and a run down of features checkout this page.

The key feature included in this version is support for Live Writer 2011. As I posted here the new 2011 version has implemented additional security restrictions which have the effect of preventing JavaScript to be run within the editor window. More security is always good right? Well not this time as many plugins that rely on script to function have been affected, including mine. The end result is that the ‘in editor’ preview feature has been removed when using the plugin inside WLW 2011, but don’t worry it’s still there if you’re still running an older version of Live Writer. To go someway to help with this lack of preview I have implemented a new "Preview In Template" feature for 2011 users that provides an external preview in your browser. It works by using your locally downloaded blog theme and inserts the code snippet into it (with syntax highlighting) thus providing a preview as to what the end result will look like. It is just for previewing the formatting of the selected snippet though and won’t display a full preview of the whole post – use the Preview view in WLW for that still.

WLW 2011 ‘Preview In Theme": 

WLW2011TemplatePreview

Preview in Editor in older versions of WLW, and the new Mini Preview screen:

WLWPre2010EditorPreviewCodeEntry2

Regardless of what version of Live Writer you are running there is also a new ‘Mini Preview’ feature. The code entry screen has been extended to have a preview tab where you can  instantly see the results of your code changes in full syntax highlighted glory. The code entry screen is now fully scrollable and resizable too.

I’ve also included a few small tweaks and bug fixes in this release as usual. For example you can now Alt-Tab correctly back to the Code Entry screen and all languages should now display correctly when previewing.

To download (it’s FREE) just go here: https://richhewlett.com/wlwsourcecodeplugin/ and click Download Now.

No Syntax Highlighting On Preview In Live Writer 2011?

Anyone using my Windows Live Writer plug-in for Source Code highlighting will find that after upgrading to the latest Live Writer version the preview feature is not working. The latest version of Windows Live Writer that ships with the Windows Live Essentials 2011 package has some modifications to prevent script running from within the application. This is apparently to enhance security and whilst I think that this modification is a valid one on those grounds I would have expected a way of the user being able to disable this feature.

On the previous version of Live Writer on inserting a code snippet you would get a nice preview (left hand image) but now in 2011 you just get the plain text version of your code (right hand image):

image

My plugin uses JavaScript (for preview purposes only – it’s not posted to your blog) to render the code exactly as it will be displayed on your WordPress blog but as this script is now disabled no render can take place.

To be honest I am not a fan of the new Live Writer as to me it appears as though the only objective was to get the ribbon toolbar included at the expense of most other things, including usability. To insert anything now I have to select insert on the toolbar and then select for example an image. Previously I just clicked on the right hand toolbar. The way that the plugin buttons are displayed on the toolbar is also poor in comparison to the previous version.

Regardless of seeing it as a step backwards I do intend to support this version with my plugin and so will be releasing an updated version soon that will aim to provide some sort of preview functionality within 2011 (although I expect it to not be as convenient as with the previous version). 

Stay tuned for the next version.

Live Writer Syntax Highlighting Plug-in v1.2.0 Released

I have finally posted a new version of my Windows Live Writer Syntax Highlighter for WordPress.com hosted blogs, you can find it here. Version 1.2.0 has been a while in the making but I have included the features most requested by you guys. Firstly thank you to everyone who had downloaded the plug-in and provided feedback either directly on this blog or on their own blogs. I do take the feedback seriously and have included all the features that I could into this version.

So what’s in V1.2.0? Well there are some small bug fixes and improvements which you may or may not notice, but the big features are covered below:

Ever since the first version of the Plug-in I have wanted to provide a mechanism to preview what the syntax highlighting will be like once the post has been posted to your blog. The problem is that the rendering is done not by my plug-in (as it just inserts the right tags into the HTML) but by the WordPress server. After a few ‘proof of concepts’ I finally hit on a way of making this work. The result is that you can see what your code will look like in both the ‘Edit’ and ‘Preview’ windows within Live Writer (see below screenshot):

WLW1200_4

This preview mode can be turned on/off per code snippet too. Any changes to the code snippet properties, for example to highlight specific lines, will take effect in the previewed version too so you can get a feel for how the properties affect the snippets display. It should be noted however that to refresh the preview display you will need to switch to the ‘Source’ or ‘Preview’ views in Live Writer and back to ‘Edit’ view. This is purely due to the fact that Live Writer doesn’t refresh the view after altering a plug-in item.

WLW1200_5

The code entry form (above) has been upgraded to accept tab inputs, be movable and now provides a line/column number indicator. It’s very useful to be able to identify lines and columns so that you can choose the right line to highlight and can ensure that you are within any relevant width restrictions on your blog for the code snippet. The context menu on the code entry form also has a ‘Trim Whitespace’ option which will trim the leading and trailing whitespace from your code snippet. This is useful after you have pasted in code from another editor, e.g. Visual Studio.

The issue of XML not being displayed correctly has been resolved. This is again a Live Writer limitation as it will not display HTML or XML correctly. This is resolved two ways in this version of the plug-in. Firstly when you use preview the XML/HTML will be displayed correctly as it is fully rendered to look how it will look after posting. Secondly where you have chosen to turn off preview the plug-in will now replace the “<>” characters with “()”. This change is purely for viewing in Live Writer and the correct characters will be used when posting to your blog.

Version information and a check for updates link has been added to the ‘Tools – Options – Plug-ins’ dialog (see below). I hope to introduce the option of auto updates in future versions, but for now the link just navigates to the plug-in’s homepage.

WLW1200_7

You can download the new version from https://richhewlett.com/software/wlwsourcecodeplugin/. I hope you like it.

New Version of Source Code Syntax Highlighting Live Writer Plugin for WordPress.com blogs

In a previous blog post I covered how to create a Windows Live Writer plug-in and then provided the plug-in for download. The plug-in solves the problem of inserting Source Code Syntax formatted code snippets into a WordPress.com hosted blog post from within Live Writer. There are many Plug-ins that can be used with your own hosted WordPress blog but these don’t work with WordPress.com hosted blogs. This plug-in supports only WordPress.com blogs by inserting the relevant ‘ShortCode’ tag around your code that is required for WordPress to syntax highlight your code. As the plug-in has proved popular I’ve taken the time to update it to Version 1.1.

Since developing the first version WordPress have added extra functionality to their SourceCode shortcode. It now supports additional languages and provides more control over how the code snippet appears in your post. Some of the neatest new features include an option to specify specific lines of code within the snippet to highlight, and the ability to control the line number to start line numbering at.

Full Feature List:

autolinks Makes all URLs in your posted code clickable.
collapse If true, the code box will be collapsed when the page loads, requiring the visitor to click to expand it. Good for large code posts.
gutter Hides line numbering on the left side will be hidden.
firstline Use this to change what number the line numbering starts at.
highlight You can list the line numbers you want to be highlighted. For example “4,7,19″.
htmlscript Highlights HTML/XML in your code. This is useful when you are mixing code into HTML, such as PHP inside of HTML.
light A light version of the display, hiding line numbering and the toolbar. This is helpful when posting only one or two lines of code.
padlinenumbers Allows you to control the line number padding. Options are automatic padding, no padding or a specified amount.
toolbar Show or hide the toolbar containing the helpful buttons that appears when you hover over the code.
wraplines Turn wrapping on or off.

Checkout the WordPress support site for more detail on these.

The list of languages selectable within the Plug-in has been increased to include all the new ones now supported by WordPress. The current list is: actionscript3 , bash, coldfusion , cpp , csharp, css, delphi, erlang, fsharp, diff, groovy, javascript, java, javafx, matlab, objc, perl, php, text, powershell, python, ruby, scala, sql, vb, xml.

I’ve also provided a mechanism to modify the list of languages displayed in the Plug-in. This is useful for two reasons. Firstly it enables you to reduce the number languages in the dropdown list down to just the one’s you are likely to use. This can make the Plug-in slightly easier to use. Perhaps more important however is the fact this enables you to modify the list if WordPress.com decide to update their shortcode to support an additional language and you need to utilise this before the next version of my Plug-in is released. Just add the new language name to the list and away you go.

To modify this language list you need to have a text file named SyntaxHighlight_WordPressCom_WLWPlugIn.txt located in the same folder as the Plug-in (usually C:\Program Files\Windows Live\Writer\Plugins). The download Zip file for the V1.1 version of the Plug-in contains this file. Locate it with the plug-in and then it’s there for when you want to modify the list in the future. Interestingly if you don’t want to make use of this feature then it is optional and the text file is NOT required for the Plug-in to work (you’ll just get the full language list by default).

I have changed the display that is inserted into the Editor view when a snippet is inserted. Previously all code text and the shortcode tag was added to the Editor view. To improve readability of the code you’ve inserted a change has been made to only show the code and not the ShortCode tags. This is particularly useful now that the Shortcode tags are potentially longer with the new supported attributes.

A link to the WordPress.com sourcecode tag support page is also now included in the property editor for inserted code snippets.

 WLW_V1.0_FulLScreenCodeEntryFrm WLW_V1.1_FulLScreenProps WLW_V1.1_Props

 

The “Live Writer Source Code Plugin For WordPress.com” Version 1.1 is available for download here.

Syntax Highlighting in WordPress.com hosted blogs and how to create a Windows Live Writer Plug-in

There are various ways of displaying code in a blog entry. Some authors insert images which enable them to ensure that the code is readable and in the required format, however the code can’t then be as easily viewed inside some feed readers, and the text is not searchable or easy to copy/paste. Alternatively an author can just type the text in and use indentation and font styles to distinguish it from the body of the text. By far the best solution however is use a Code Highlighter of some sort that will render the code into a readable format with additional benefits of copy to clipboard, line numbers and colour coding. One popular tool for this job is Syntax Highlighter by Alex Gorbatchev. This uses JavaScript to render the code on the client in a very readable format (see below). It integrates well with the WordPress blog engine and there are several Windows Live Writer Plug-ins for it making it easy to add code snippets to your posts.

Having decided on using Syntax Highlighter for my blog I hit a problem. I’m hosting on WordPress.com and therefore do not have the access required to add it to my site. I found a lot of posts on the web discussing how to integrate it with WordPress but these are for self hosted WordPress.org blogs. Eventually however, to much delight, I found that the WordPress.com developers themselves have already integrated Syntax Highlighter. There is a list of supported languages and details on how to use it here. To activate it you just add a wrap your code inside special tags. Excellent!

Writing a Windows Live Writer Plug-in (Part One)

My next thought though was that I needed to integrate into Windows Live Writer via a plug-in. I couldn’t find a WordPress.com specific plug-in so I fired up MSDN and looked at coding one. All the information you need is on MSDN here

There are two types of plugins. Simple and Smart. As I just needed to add a block of code text surrounded by special tags I figured I would implement the simple type. Simple’s good! Right?

To start with I needed to create a new class library project, reference the Live Writer API (windowslive.writer.api.dll), and add a new class which derived from ‘ContentSource’ and has a ‘InsertableContentSourceAttribute’ attribute.

InsertableContentSourceAttribute("Highlighted Source Code")]
public class MyPlugin : ContentSource
{
}


Next override the CreateContent method on the base class. This is the method that gets called when the user clicks to activate our plug-in to insert some content. It returns a DialogResult and has a string parameter passed by-reference called ‘newContent’. This string parameter is how you set the text to be inserted into the blog post.  In the code example shown below I am displaying a form for the user to enter the code block to insert. The form adds the required WordPress.com wrapper text and then the ‘newContent’ string is set to be the whole text content (code plus wrapper text):

public override System.Windows.Forms.DialogResult CreateContent(System.Windows.Forms.IWin32Window dialogOwner, ref string newContent)
{
    using (codeEntryForm entryform = new codeEntryForm())
    {
        entryform.StartPosition = FormStartPosition.CenterParent;
        DialogResult result = entryform.ShowDialog(dialogOwner); 
        if (result == DialogResult.OK)
        {
            newContent = entryform.GetData();
        }                
        return result;
    }
} 


In addition to overriding the CreateContent method the WriterPluginAttribute needs to be set on the class. This basically provides Live Writer with information about your plug-in. For an explanation of the properties see here.

[WriterPlugin (
        "BF15A85A-9668-480d-9FC2-EC5C16FC140D",
        "Wordpress.com Syntax Highliter Plugin",
        ImagePath = "Images.image.bmp",
        PublisherUrl = "http://www.richhewlett.com/",
        Description = "Inserts WordPress.com code highlight tags around code snippets",
        HasEditableOptions=false)
] 

Once done compile it up and copy the assembly to the Plugins folder of your Windows Live writer installation (e.g. C:\Program Files\Windows Live\Writer). When the application starts all the plug-ins in that folder get loaded too. I now had my Syntax Highlighter plug-in, and it worked. I could insert code into my blog post and upload it to the server for WordPress to display using Syntax Highlighter.

Job done then hey? Well not quite. As I had coded this as a SimpleContentSource plug-in once the code snippet had been inserted into the post editor it was treated as plain text (just as if I had written it by hand into the editor). This meant that if I flipped between the Editor and Source windows Live Writer converted my code text to use escape characters. This meant that my code snippet’s quotes and ampersands etc were converted to their friendly alternatives, and WordPress.com would display them without converting them back.

Writing a Windows Live Writer Plug-in (Part Two)

In order to resolve the issue of Live Writer treating my code snippets as regular text I went back to MSDN and found that the SmartContentSource plug-in type provides more control over the HTML that gets sent for publishing. SmartContentSource plug-ins are not treated as regular text and provide more control. Building this type of plug-in is only slightly more work than the less smart plain ContentSource type.

Firstly I needed to change the plug-in class (from above) to override SmartContentSource instead of ContentSource.

[InsertableContentSourceAttribute("Highlighted Source Code")]
public class Plugin : SmartContentSource
{
}    

Then we override the CreateContent method as we did before. Live Writer creates a ISmartContent object and passes it in for us to update with the content the user creates. Again as before this example has a dialog box being shown to the user for them to key the code snippet but this time the data is set within the ISmartContent properties.

public override System.Windows.Forms.DialogResult CreateContent(IWin32Window dialogOwner, ISmartContent newContent)
{
    using (CodeEntryForm entryform = new CodeEntryForm())
    {
        entryform.StartPosition = FormStartPosition.CenterParent;
        DialogResult result = entryform.ShowDialog(dialogOwner); 
        if (result == DialogResult.OK)
        {
            newContent.Properties.SetString("OutputHTML", entryform.GetData());
            newContent.Properties.SetString("RawCode", entryform.GetRawCodeSnippet());
            newContent.Properties.SetString("SelectedLanguage", entryform.GetSelectedLanguage());                    
        }
        return result;
    }
} 


N,B: The reason I’m setting the ‘RawCode’ and the ‘SelectedLanguage’ properties as well as the combined total output is for use later when we want to display the dialog to the user again pre-populated.

In order to ensure that the correct text is being passed to the blog engine for publishing we override the GeneratePublishHtml method. The ISmartContent object passed in has the original data set as one of its properties so in this example I just return that.

public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext)
{
    return content.Properties["OutputHTML"].ToString();
} 

This gets around the original problem that I experienced with the first ContentSource plug-in. Also SmartContentSource plug-ins benefit from being able to be edited via an editor view. This means that when an inserted code snippet is selected in the Editor in Live Writer we can display our own properties bar on the right hand side. To use this feature we need to add a UserControl to our project and make it derive from SmartContentEditor. We then add relevant controls to it to interact with our Content (i.e. code snippet). In my case I just added a link label control to re-launch the dialog box for the user to modify the code within the currently selected content (code snippet) in the editor. Once complete then override the CreateEditor method and return our own UserControl object as a SmartContentEditor object .

public override SmartContentEditor CreateEditor(ISmartContentEditorSite editorSite)
{
    return new MySmartContentEditor();
} 

An important point is that only one instance of the plug-in is used in Live Writer for all instances of content being inserted. For example you may add multiple code snippets into one blog post but only one instance of your plug-in will be created and reused, therefore you cannot store any state information specific to an individual content items (i.e. Code snippets) within the plug-in. That’s why the data is always passed in to these methods we have been overriding.

Compile it up and copy the assembly to the PlugIns folder of your Windows Live writer installation (e.g. C:\Program Files\Windows Live\Writer\Plugins) to test. This time the content added using SmartContentSource is treated as special and is not converted as you flip between the Editor and Source views.

To extend the plug-in further its possible to update the ‘WriterPlugin’ attribute property ‘HasEditableOptions’ to true and override the ‘EditOptions’ method to display an options dialog to the user. This means that you can let the user modify settings for your plug-in. 

As you can see the plug-in model for Windows Live Writer is very simple and productive. It is surprisingly easy to quickly produce useful plug-ins.

If you want to make use of this plug-in for making it easier to add highlighted code to your WordPress.com blog then feel free to download it here.