Emacs as the Visual Studio Editor

There is a great little hack that I just found out about here. You can write this quick Visual Studio macro in Visual Basic that allows you to open the current VS file in an external Emacs frame for editing.

This hack works great in Visual Studio 2008 with the latest Emacs build that comes with the EmacsW32 distribution (the version I'm using is 23.0.93.1). You can bind the macro to a keystroke in VS 2008 for ease of use. After you are done editing in Emacs, just close the document and go back to VS and it will notice that the file changed and ask you if you want to reload it. I can't believe I didn't know about this. Here's the code:

Sub OpenInEmacs()
Dim fn As String
Dim cmd As String
Dim lnum As Integer

fn = DTE.ActiveDocument.FullName
lnum = DTE.ActiveDocument.Selection.ActivePoint.Line
cmd = "Tools.Shell ""emacsclientw.exe"" -n +" + lnum.ToString + " " + fn

DTE.StatusBar.Text = "Opening " + filename + " in Emacs"
DTE.ToolWindows.CommandWindow.SendInput(cmd, True)
End Sub

New Tools

I talked about keyboards before on a previous post. On that post I mentioned that, although I loved (and still love) my Filco, I would continue to broaden my horizons by researching and using other boards. Well, that other board arrived on Friday and is an Avant Prime.

History

Before I go into the technical details, I'd like to share a little bit of the history I uncovered while doing my research.

Back in the late 80's and early 90's, after IBM made the PC architecture available for other companies to build clones of it, a little company out in California called Northgate Computers started to sell its PC clones from a mail catalog. Brand name PCs, like the original IBMs and Compaqs, were expensive and consumers were looking for alternatives. Companies like Northgate rushed in to fill that niche market. Out of the companies that were created during those days and sold from a catalog only Dell still exists today.

But Northgate also manufactured a keyboard that was highly valued by geeks of that era. This was the OmniKey line of keyboards. Northgate went out of business for good in 2005, but by this time a little company near Minneapolis, MN had already started to manufacture the OmniKey line under a new name. This company is Creative Vision Technologies and they make the Avant Prime and Avant Stellar keyboards. The Avant boards are analogous to the OmniKey 101 and OmniKey Ultra, respectively.

Avant Prime Keyboard & TrackMan
The Avant Prime Keyboard (click for larger image)



Why Another Keyboard?

My wife actually asked me this question. The honest answer is that when it comes to keyboards, I'm a little obsessive compulsive.

The criteria that I set for myself when researching boards this time was the following: 1) I absolutely have to have a real Ctrl key on the home row and 2) I am absolutely not going to use any software or configuration hacks to get the Ctrl key to work on the home row. Well, that really narrowed the pool of available boards to chose from to just three. The other thing I am looking to accomplish is to become a more efficient and faster typist.

Currently on the market I can only find the Happy Hacking, the Unicomp Customizer with custom key layout and Avant boards that have these features. Of course, there are always those vintage Sun or OmniKey boards listed on EBay, but I was looking for something new.

The Gory Details

Visually, the Prime looks like a standard legacy IBM PC board with white and gray keycaps, a row of function keys across the top and the standard LEDs on the top-right corner above the number pad cluster. A couple of other minor differences are that the + key in the numpad is just a regular size key in order to make space for a = key that goes right under it. The main Enter key is large and shaped like an L in reverse. The |\ key is located next to the left Shift key.

The configuration of the Avant Prime out-of-the-box is to have the CapsLock key on the home row to the left of the A key and the Ctrl key on the far bottom left corner of the board. But the Prime also ships with a handy key puller tool and replacements keycaps for the CapsLock and Ctrl keys. This allows me to easily swap the physical keycaps for those keys as you can see in the image (click it for full size).

But just switching the keycaps using the handy puller tool doesn't do the trick; you have to actually remap the keys to emit the proper codes to the computer. This is where the Avant keyboards really shine as they are fully programmable. The Prime has an Atmel AT89C52 microcontroller with 8K flash RAM inside it that you can program by using certain key combinations.

To swap the CapsLock and left Ctrl keys you have to first press the right Ctrl key four times and then press left Shift and 1 together to enter the Prime's programming mode. Then press the R key to tell the Atmel that you are going to remap a key. At this point the NumLock, CapsLock and ScrollLock LEDs will be blinking really fast. The LED on the Up Arrow key will also be blinking. Now you need to press the key you want to move, which we will call the From Key. In my case this is the CapsLock key. Once you press the CapsLock key, all the LEDs start blinking at a slower rate than originally. Now you need to choose the To Key, which in my case is the left Ctrl key. At this point you will have two CapsLock keys, the original one and the left Ctrl key. So we need to remap the left Ctrl to the original CapsLock key. We choose the left Ctrl key as our from key and then the original CapsLock as our to key. You will know that you are doing the right thing because the blinking rate of the LEDs will change again when you are doing the second remap. Once you are done with that you can press the right Ctrl key once to get out of the Prime's programming mode.

It's also important to mention that once you remap those keys, the new functions are persisted in the Atmel's flash memory and will transfer with the keyboard even if you go to a different computer or operating system.

The Prime has white stem Alps key switches, which means that it provides both an auditory and a tactile feedback. You can hear the click of the keys and you can also feel them on your fingers. If you are familiar with other mechanical key switches like the Cherry switches, you will notice that the Prime's switches provide a more pronounced clicky feel and sound.

So You Want One

Some things to note about the Avant Prime that may influence one's decision to get the board are 1) the Avant Prime has a PS/2 connector only and requires a PS/2 to USB adapter to work on computers that don't have PS/2 ports. This is not too much of a problem as most computers today still ship with PS/2 ports for mouse and keyboard. But I'm also starting to see some laptops and netbooks ship out without it. Additionally, Apple computers don't have a PS/2 port. 2) The Avant Prime is a clicky, heavy and loud keyboard. When you press a key on the Prime it resonates with a metallic echo and it definitely gives you tactile feedback. Your fingers will know that you pushed a key and I like that, but if you prefer a quieter, lower profile board, than the Prime is not for you.

What Is That Trackball Doing There?

Another aspect of my workflow that I am looking to tweak is to use my mouse less and less and keep my hands on the keyboard for as long as I possibly can. I thought that one way to do that is to break that pattern of reaching for the mouse and feeling very comfortable with it. So I also got me a Logitech TrackMan, and it has most definitely helped in my goal. First, I am not a trackball person, so it definitely breaks the original work flow. But I still have to make a conscious effort to keep my hands away from it. It helps to print out a shortcut cheat sheet for your desktop of choice, and post it right on your monitor. I have to say that keeping your hands on the keyboard does increase efficiency, speed and you get used to the new paradigm very quickly.

Wrap Up

Based on my previous post, a friend has already asked me if I like the Prime better than the Filco. Well, I think that the jury's still out on that one. What I can say with confidence is that I will be using the Prime at work and the Filco at home, so I will have plenty of opportunity to compare the two more closely, but right now I still few like it's too early to tell.

Anyway, the Avant Prime is going for $149 and I got mine from Lone Star Keyboards because they had the best shipping rates of all Avant distributors. They shipped my Prime promptly and I am very pleased with their service overall. The TrackMan I got from Amazon for $49.95.

Terminating Your C# Application

Today I was doing some experimenting with some ideas and I created a console application to try things out in. From a certain function I started to type Application.Exit() and I quickly realized the rookie mistake. The Application class is part of the System.Windows.Forms namespace, and therefore, it's not the optimal way to terminate your console application. For that there is Environment.Exit(-1)... But this situation begs the question... what is the difference between the two statements:

System.Environment.Exit(-1);
System.Windows.Forms.Application.Exit();

They both get you what you want, which is to halt your application. But there are some differences between the two methods under the hood, according to the Microsoft documentation:

  1. System.Environment.Exit() - Terminates the current process and gives the underlying operating system the specified exit code.
  2. System.Windows.Forms.Application.Exit() - Informs all message loops that they must terminate, and then closes all application windows after the messages have been processed.

My take from this is that you always want to use Application.Exit() in a WinForms application in order to terminate things as gracefully as possible. In a console application you won't have the Application class available (unless you specifically import it) so just call Environment.Exit().

Also remember that there usually are several things you may want to do before terminating everything, such as persisting some objects, saving some settings, closing open files, etc. It is your responsibility to do those tasks before terminating... Provided you can control that and you are not crashing from an unhandled exception.

Swap CTRL with CAPS LOCK in Ubuntu 9.04

To swap the function of the left control key with the capslock key in Ubuntu 9.04, follow these steps:
  1. On the Gnome desktop go to the System menu.
  2. Choose Preferences and then Keyboard.
  3. On the Keyboard Preferences dialog, choose the Layout tab.
  4. Click on the Layout Options button.
  5. From all the available options, expand CTRL Key Position.
  6. Check the Swap Ctrl and CapsLock option.
  7. Click the Close button of the Keyboard Layout Options dialog.
  8. Click the Apply System-Wide button of the Keyboard Preferences dialog.
  9. Provide credentials if/when asked.
  10. Click the Close button of the Keyboard Preferences dialog.
  11. You are done.

This seems to work fine on the everything running on the Gnome desktop, including the Terminal. However, this technique seems to leave your xorg.conf file alone.

Gnome Keyboard Layout

List Comprehensions in C#

A List Comprehension is a type of set notation in which the programmer can describe the properties that the members of a set must meet. It is usually used to create a set based on other, already existing, set or sets by applying some type of combination, transform or reduction function to the existing set(s).

Consider the following problem: You have a sequence of 10 numbers from 0 to 9 and you need to extract all the even numbers from that sequence. In a language such a C# version 1.1, you were pretty much confined to the following code to solve this problem:


ArrayList evens = new ArrayList();
ArrayList numbers = Range(10);
int size = numbers.Count;
int i = 0;

while (i < size)
{
if (i % 2 == 0)
{
evens.Add(i);
}
i++;
}


The code above does not show the implementation of the Range function, which is available in the full code listing below. With the advent of C# 3.0 and the .NET Framework 3.5, a List Comprehension notation based on Linq is now available to C# programmers. The above C# 1.1 code can be ported to C# 3.0 like so:


IEnumerable numbers = Enumerable.Range(0, 10);
var evens = from num in numbers where num % 2 == 0 select num;


And technically speaking, the C# 3.0 code above could be written as a one-liner by moving the call to Enumarable.Range into the Linq expression that generates the evens sequence. In the C# List Comprehension I am reducing the set numbers by applying a function (the modulo 2) to that sequence. This produces the evens sequences in a much more concise manner and avoid the use of loop syntax. Now, you may ask yourself: Is this purely syntax sugar? I don't know, but I will definitelly investigate, and maybe even ask the question myself at StackOverflow. I suspect that this is not just syntax sugar and that there are some true optimizations that can be done by utilizing the underlying Monads.

I also posted this as an answer to a question on StackOverflow.com. The full code listing is available below:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CSharpListComprehensions {
public class Program {

public static void RunSnippet() {
Run11Version();
Run35Version();
}

public static void Run11Version() {
ArrayList evens = new ArrayList();
ArrayList numbers = Range(10);
int size = numbers.Count;
int i = 0;

WL(""); WL("Numbers:");
foreach (int x in numbers) {
WL(x.ToString());
}

while (i < size) {
if (i % 2 == 0) {
evens.Add(i);
}
i++;
}

WL(""); WL("Evens:");
foreach (int y in evens) {
WL(y.ToString());
}
}

public static void Run35Version() {
IEnumerable numbers = Enumerable.Range(0, 10);

WL(""); WL("Numbers:");
foreach (int x in numbers) {
WL(x.ToString());
}

var evens = from num in numbers where num % 2 == 0 select num;

WL(""); WL("Evens:");
foreach (int y in evens) {
WL(y.ToString());
}
}

#region Range Functions
public static ArrayList Range(int end) {
return Range(0, end);
}

public static ArrayList Range(int start, int end) {
ArrayList al = new ArrayList();
for (int i = start; i < end; i++) {
al.Add(i);
}

return al;
}
#endregion

#region Helper methods

public static void Main() {
try {
RunSnippet();
} catch (Exception e) {
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
} finally {
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}

private static void WL(object text, params object[] args) {
Console.WriteLine(text.ToString(), args);
}

private static void RL() {
Console.ReadLine();
}

private static void Break() {
System.Diagnostics.Debugger.Break();
}

#endregion
}
}

Tetris: 25th Aniverssary

Tetris is 25 years old and there is a nice piece on the Guardian that talks about that. There is also a photo gallery of Tetris' evolution over time... This old shot of it running on a terminal window is priceless:

Emacs Easter Egg

From a terminal window run emacs like so:


emacs --no-splash -f view-hello-file


This starts emacs and opens a file which translates the word hello into several languages.

Iron Python: How to talk to the .NET Framework

Iron Python is an implementation of the Python programming language that runs on the Common Language Runtime and can use the classes of the .NET Framework.

Here are some quick notes on how to interface with the framework from Iron Python:

  1. Open the Iron Python REPL.
  2. Import the clr module.
  3. Add a reference to the .NET Namespaces you want to interact with.
  4. Start using the .NET classes as if they were Python classes.

Below I transcribed a little code snippet for you to use as an example. I also provide a screen capture of the sample and the outcome of running it.


import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Application, Form, Button, MessageBox

f = Form()
b = Button()

f.Text = "Hello World!"
b.Text = "Click Me!"

def clicked(sender, args):
MessageBox.Show("Hello, Again...")

b.Click += clicked
f.Controls.Add(b)
f.ShowDialog()


Iron Python



Enjoy!

Building & Installing GNU Emacs from Source in Windows Vista

The steps outlined in this entry describe A way that works for me to build and install GNU Emacs on Windows Vista from source code. For alternatives, please review the INSTALL file located in the nt folder of the emacs source tree. The approach I take is to enumerate the steps in a “do this, then this, then this…” fashion. I don’t go into the reasons and technical details of each step here, but I do provide a list of resources at the end where you can find the technical background behind the process I outline below.

I also should mention that the EmacsW32 guys distribute GNU Emacs in a Windows Installer. There you can choose the patched or unpatched versions of the package. The patched version provides better integration with Windows, but I use the unpatched version because I am an emacs purist :) . I recommend this package if you need to run emacs on Windows and don’t want to build it from the source code. What I really like about the EmacsW32 package is that it's kept at the latest emacs snapshot available.

Now, on with the show… The required prerequisites for this build are the following:

The following optional prerequisites are needed if you want to build emacs with image support:

And finally, the steps:

  1. Download and install a CVS client. I use the one that comes with Cygwin (see link above).
  2. Get the latest version of GNU Emacs from the CVS repository by running the following instruction on the Windows command line:

    cvs -z3 -d:pserver:anonymous@cvs.savannah.gnu.org:/sources/emacs co emacs

    This command will create a working folder called emacs in the current directory.
  3. Download and install the latest version of the MinGW compiler and Make tool. There is a Windows installer provided at the link listed above. At a minimum you will need the core GCC and the Make tool.
  4. Add the bin folder of the MinGW installation to your path. On my machine I did that by running this statement on the command line:

    set PATH=C:\MinGW\bin;%PATH%

  5. Download and install the GNUWin32 core utilities from the link above.
  6. Add the bin folder of the GNUWin32 installation to your path. This can be done by running a command similar to this one:

    set PATH=%PATH%;C:\gnuwin32\bin

  7. The following steps are optional and only needed if you wish to compile emacs with image support:
    1. Download and install all the libraries listed in the optional requirements area above. All of these libraries are provided as a Windows installer. I install them in the same location where I installed the GNUWin32 core utilities.
    2. For the XPM library you will also need to download the source code, which comes in a zip compressed file.
    3. Unzip the XPM library source code.
    4. Find the file named simx.h and copy it to the include folder under your GNUWin32 installation.
  8. From the Windows command line, go into the emacs working folder you got from CVS and then go into the nt folder.
  9. In the nt folder, run the following command:

    cvs update -kb

    This will ensure that the newline characters in the files are correct for Windows.
  10. From the nt folder, issue the following command:

    configure.bat --no-debug --with-gcc

    …or if you wish to compile emacs with image support issue the following command:

    configure.bat --cflags -IC:\gnuwin32\include --no-debug --with-gcc

    Where the argument after the -I parameter is the path to the header files for the image libraries you just installed. This will effectively prepare the build process for your system.
  11. Initially, we need to do a bootstrap build by running the following command:

    mingw32-make bootstrap

    This is necessary in order to build the emacs lisp interpreter and compile all the .el files. This may take a few minutes, so this is a good point for a break.
  12. Now you should run make alone again to make sure you caught everything:

    mingw32-make

  13. The last step in this process is to install the build you just finished. To do this run the following command:

    mingw32-make install INSTALL_DIR=C:/emacsfromcvs

    Where the INSTALL_DIR value is the location where you want to install emacs.

I hope you find this entry useful and concise. If you want more information on the topic of building GNU Emacs from source, please refer to these resources:

P.S.: I specifically omitted a step in the process described above. That's the step that calls minwg32-make info which builds the Info manuals. Reason being is that makeinfo.exe is crashing on my system. When I open makeinfo.exe in the VS2008 debugger I get the following error message: Unhandled exception at 0x00425425 in makeinfo.exe: 0xC0000005: Access violation reading location 0x00000000. Looks like a null pointer problem to me.

Ternary Operator in Python

C-like languages such as C# have a ternary operator which uses the symbols: ? and : , while the actual syntax looks something like this:

string s = myBoolValue ? 'True' : 'False';

Python doesn’t feature a ternary operator as in the C-like languages, but the underlying behavior is supported. You can achieve this in one of two ways:

  1. s = 'True' if myBoolValue else 'False'
  2. s = myBoolValue and 'True' or 'False'

The if form in number 1 above was introduced in Python 2.5 to address feature requests for a ternary conditional form (see PEP 308).

The form in number 2 above is a clever way to achieve the same effect using short circuiting. The conditional form in number 1 is the preferred form as the technique in number 2 is error-prone.