The vim Editor as a Developer Environment


, , , , , ,

Basic Keybindings

Perhaps the most basic and useful keybindings for modifying code relate to the copying/moving/pasting of code sections within a source file. To do this, use the ‘v‘ key in visual mode to mark the beginning and end of the section to be copied/moved, and press the ‘y‘ key to copy that section. The ‘p‘ key will paste the section wherever the cursor is positioned.

Line Numbers

A feature that’s pretty much universal to code editors is line numbering, obviously to make it easier to find something referenced by a debugger or an exception message. Either use the ‘:set number‘ command, or add it to vimrc.

Splitting Windows and Comparing Source Files

The easiest way to have multiple files open in a session is to use the ‘:tabedit [filename]‘ command, and use the ‘gt‘ keybinding to switch between tabs. If you’re using gVim, you can click on the tabs just like a conventional GUI editor.
Sometimes, though, we might want to display two source files simultaneously. Enter command mode, and use the ‘:split [filename]‘ command. e.g .’:split AD-Authentication-Model.cs‘. Another window will appear in the editor, with the content of the specified file.

We can switch between the windows using Ctrl+W. This works in both visual and insert mode. To close the current window, use the ‘:close‘ command (or even ‘:q‘).

There is a variation of this command that splits the window vertically, and you might find this more conducive for comparing files, especially with the line numbers displayed.

Replace the ‘:split‘ command with ‘:diffsplit [filename]‘ to compare a file with an earlier version of itself.

For copying/moving sections between windows, ‘dp‘ shifts a selected block from the current window to another, and ‘do‘ fetches a block from another window into the current one.

Folding Code Sections

Using ‘zf‘ and ‘zo‘, we can hide marked sections of code, to make a source file easier to read. This is done in visual mode, not command mode. Here we have two methods displayed in the editor, and we’ll fold them so they’re represented by single lines.

Use the ‘Esc‘ key to enter visual mode, and ‘v‘ key to highlight the section of code to fold, and then ‘zf‘ to fold the highlighted section. Here I’ve done this with two methods.

After using ‘zf‘ to fold marked sections of text, we should use ‘zc‘ to close and ‘zo‘ to open. This is important if there are folded sections nested within other folded sections.

Omni Completion

This is vim’s equivalent of Visual Studio’s IntelliSense. Use Ctrl+N before, or Ctrl+P just after, the keyword in Insert mode. My installation doesn’t appear to list the autocomplete options specific to the current programming/scripting language.

Browsing the Filesystem

The editor could be made to have a layout rather like Visual Studio, with a file browser displayed in one of the windows. Here I’ve used ‘:Vex‘ to open vim’s own file browser. This will create a new window in the browser automatically.

To open a file, move the cursor to the file name and press the Enter key.

Semi-GUI Menu

source $VIMRUNTIME/menu.vim
set wildmenu
set cpo-=<
set wcm=
map :emenu

Now, when the F4 key is pressed in the editor, a semi-graphical menu will be displayed along the footer of the window.

Errors Window

When compiling a source file, use the ‘:copen‘ command to open a window listing errors, and ‘:cclose‘ to close it.


Encryption Using Notepad++ Extensions, and a Bug Fix for SecurePad


, , , ,

If you don’t have the Plugin Manager for Notepad++, you can still install NppCrypt and SecurePad by dropping their DLL files in C:/Program Files/Notepad++/plugins. The files you’ll need are nppcrypt.dll and SecurePad.dll.


Once installed, the NppCrypt option will appear in the Plugins menu. To encrypt, simply highlight the section of text you want to encrypt, and select ‘Plugins’ – ‘NppCrypt’ – ‘Encrypt‘. This will open the ‘nppcrypt::encryption‘ window, in which the user can select the encryption type, algorithm and mode to use – you wouldn’t need to change any of these, as the default (Rijndael with 256-bit key in GCM mode) is sufficiently for strong encryption.

By default NppCrypt will use Rijndael256 in GCM mode. A number of much weaker options are supported.

With the password and encryption parameters set, the plaintext will be replaced with the ciphertext and the metadata required for decryption.

To decrypt the text, simply highlight the ciphertext, select ‘Plugins’ – ‘NppCrypt’ – ‘Decrypt‘ and enter the password.


The other plugin, SecurePad, requires less knowledge to use, but it doesn’t allow the user to decide the cipher or parameters to use. To encrypt a text, select ‘Plugins’ – ‘SecurePad’ – ‘Encrypt Document‘. The ciphertext appears like:

Encryption here is actually handled by Bruce Schneier’s implementation of the Blowfish cipher (blowfish.h) that accompanied the Applied Cryptography book. The implementation here supports three modes: ECB, CBC and CFB. I went through the code trying to determine which of these is used by SecurePad.
Looking at the code in PluginDefinition.cpp, it appears that SecurePad does use the cipher in ECB mode – this isn’t good because the same plaintext blocks encrypted with the same key would produce the same ciphertext, making it easier to spot patterns and potentially infer the original plaintext. Here is the code I was looking at:

I have forked the project, and modified the above section of code to use the cipher in CFB mode. The project must be recompiled to apply the fix in the plugin.

The vim Text Encryption Feature


, , , , , ,

Using vim, it’s possible to save files as ciphertext. Simply use the ‘:X‘ command with the file opened in vim, set the password and save the file. There’ll be the following warning displayed when setting the password in the default encryption mode:

Warning: Using a weak encryption method; see :help 'cm'

Changing the Encryption Mode

Looking at the help page (‘:help cryptmethod‘), we find that vim supports only three ciphers by default: PkZip, Blowfish and Blowfish2. PkZip is considered weak – it is a stream cipher that XORs the file with the password. Blowfish’s implementation in vim is dodgy, with multiple bytes repeated in the ciphertext. Blowfish2 is an improved and recommended option, but older installations of vim cannot decrypt a Blowfish2-encrypted file.

It’s possible to set the encryption type for an opened file with either of the following commands:

:setlocal cm=blowfish2
:set cryptmethod=blowfish2

To set the encryption mode as a configuration option, add the following lines to /etc/vim/vimrc:

set cm=blowfish2
set viminfo=
set nobackup
set nowritebackup

This should set the default cipher to Blowfish2, and prevent any background writes of the plaintext to the hard disk.

Including TinyMCE in an ASP.NET Project


, , , ,

Depending on whether the user is logged into the application, either an editor or a div containing the data will be displayed. The editor appears like this, during an authenticated session:

Visual Studio’s Solution Explorer lists the available plugins for TinyMCE under /tinymce/plugins. All the options in the following code are included with the free version of TinyMCE.

selector: '.test',
plugins: 'table, lists, link',
toolbar: 'table, numlist, bullist, link',
menubar: false,
statusbar: false

Adding plugins to the toolbar causes all the default buttons to disappear, as TinyMCE reverts to this if nothing is specified in the init(). Everything must therefore be specified, so the options would be:

plugins: 'table, lists, link',
toolbar: 'undo, redo, styleselect, bold, italic, alignleft, aligncenter, alignright, alignjustify, table, numlist, bullist, indent, outdent, link',

The application needed a tabbed UI that enables switching between the three data fields. Here I have a separate instance of TinyMCE for each tab pane. Initially the tab buttons weren’t showing, so I’ve used Bootstrap.css buttons, and added margin-right‘ attribute to two of them for spacing.

The initial code for the tab content included LINQ statements to fetch in-memory data, and creates an instance of TinyMCE for each pane.

For cases in which you don’t want the user to modify the data using the editor, it’s possible to use
tinymce.activeEditor.setMode(‘readonly’), but it’s more efficient to simply replace the tinymce() call with a div containing a Razor helper to fetch the decoded content from the model.

View-Based Authorisation

If the user doesn’t have permission to modify the data, the ‘Save’ button shouldn’t be displayed. This is a simple matter of adding an ‘if’ statement in the view.

@if (sessionStatus != null && sessionStatus.HasRole("Editor"))

The above uses our own in-house authentication service, but ASP.NET Core has a native feature that’s similar:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@if ((await AuthorizationService.AuthorizeAsync(User, "PolicyName")).Succeeded)

You are authorized.

Go away!


Passing Data from TinyMCE to the Entity Framework Model

At first the application refused to save modifications made in the TinyMCE editor. I put a breakpoint at the line:
return Json(new { success = model.Put(_uow), errors = model.errors });

And got the following errors:
'System.Data.Entity.Infrastructure.DbUpdateException' in EntityFramework.dll
A potentially dangerous Request.Form value was detected […]

The problem is the model really doesn’t like to accept data posted back as HTML. We have to disable input validation to allow this. For simple projects, we can add the [AllowHtml] attribute to whichever model properties represent data entered in the TinyMCE editor, e.g.

public string ItemDescription { get; set; }

public string ItemSummary [ get; set; }

Apparently, the recommended way is to disable validation at the controller, by giving it the following attributes:


I’m not sure why the latter is recommended over the former. As you can probably see, the model attribute is more specific in allowing only HTML for selected items, whereas the controller attribute disables validation entirely for whatever is posted back.

Why Ireland’s Repeal of the 8th Amendment Might Not Be Such a Bad Thing


, , , , ,

[Reposted from my other blog]

While both the pro-choice and pro-life campaigners clearly frame the abortion issue in entirely different terms, the salient question, though the debate leading up to the referendum was deflected from this, was whether the freedom of the individual outweighs the unborns’ right to life. More specifically, on what basis could we argue objectively that both have an equal right to life, as the 8th Amendment of Ireland’s Constitution asserts?

I don’t think many of us are opposed to abortion because of religious dogma, though we could argue that any constitution that appeals to the sanctity of life must invoke something transcendent and absolute, a ‘necessary being‘, to put it in Catholic terminology, to place it above the consensus of lawmakers and politicians, and above utilitarian thinking. We claim that man is created in the image of God, and it’s upon that concept that the sanctity and dignity of human life are predicated, and in turn human rights and social justice. Therefore, one person’s freedom is secondary to another person’s right to life. The more society devalues human life to justify a societal demand, and the lives of the unborn sacrificed to consumerism and individualism, the more our convictions about human rights and social justice become subject to question.
The effects of this are already maniftested in our politics. Society today seems bitterly divided between conservative populism and the pseudo-liberal manipulations of George Soros billionaire lobbyists. Both exploit prevalent individualism and our base instincts, while the lobbyists’ demands for society are marketed as ‘progressive’ causes – I think that’s descriptive of the recent pro-choice campaign.

So, yes, I am firmly and unapologetically pro-life, though I still wonder if the 8th Amendment should have existed in the first place. A constitution should generally prohibit the state from violating its citizens’ fundamental rights, and the unborns’ right to life is already implicit in the wording and spirit of Ireland’s Constitutition. The 8th Amendment, conversely, seems intended to pre-empt conscience, reason, judgement and case law, which is just about the worst way of approaching situations that aren’t black and white. Secondly, one only needs to look up the Pro-Life Amendment Campaign’s background on Wikipedia to see the campaign for that was established by a number of overtly religious organisations with a decidedly exclusive membership. Effectively it was lobbying by a minority to enforce religious beliefs on a society, regardless of whether the public opted for that.

The execution and outcome of last week’s referendum saddens me for another reason. There was a time when it was deemed progressive to campaign for the right to life and human dignity, while speaking truth to power. We had a political left that campaigned on things that really mattered – the arms trade, homelessness, oppressive regimes, animal cruelty, etc. We wanted the social justice that Martin Luther King dreamed of, not the vicious identity politics and race baiting that today passes for ‘left-wing’ opinion, or peurile campaigns to affirm our base mentality. For a while it seemed humanity could aspire to a world in which everyone had a decent quality of life, that collectively we could do something (though I wasn’t sure exactly what) about the scenes of war, famine and poverty that were shown on our televisions.

Reasons for Optimism

What next? The referendum heralded the decline of the Church’s authority in Ireland, and a change in the society’s values. Roughly 60% of the voters opted for the repeal, and ~30% voted against it despite a strong campaign to preserve the Amendment. This ~30% is roughly the same percentage of the population who attend Mass regularly, and it has been in decline since the 1970s. Despite this, I really think some good will come of this situation.

History is replete with examples of what happens when the separation between Church and state is violated, when religious authorities think they’re above the law and when state authorities attempt to override individual conscience. Among these, we know, is the institutional cover-up of child abuse within the Church hierarchy, which I reckon was enabled by the power and the lack of accountability that priesthood offered. We can also look at churches that became irrelevant by trying to become acceptable to the secular world.

The Church has gone from being part of the establishment to being counter-cultural. No longer is Catholicism a tradition that people blindly conform to, but an engaging faith that must survive by changing hearts and minds. It’s up to the saintly to rebuild the Church for this age. The first Christians managed this in a world that was entirely at odds with their faith.

The pro-life campaign is far from over. Abortion would still be illegal in Ireland until legislation is passed to actually legalise it, and there’ll very likely be debates and campaigns during that timeframe. The issue will be framed somewhat differently then.