Derek Slager

  • Saturday, February 24, 2007

    Screencast: Formatting a CSS File with Emacs

    When I wrote The Case for Emacs, the main point I was attempting to convey was that Emacs is an amazingly effective editor even without the customizations it's so famous for. Right out of the box, you can do some pretty incredible things with its broad set of built-in commands. And if a simple Emacs configuration is good enough for Donald Knuth, it's good enough for us, right?

    The other day I came across a CSS file that was in need of some formatting tweaks, so I slapped together a quick macro and fixed it up. Nothing special, but it got me thinking -- why not take this example to an extreme, creating the ugliest CSS file of all time, and create a screencast of cleaning the file up using a bare bones Emacs configuration? Well, here we are.

    The CSS file you see getting the Emacs treatment in the screencast is not real. I intentionally created about the ugliest file I could, butchering indentation, casing, structure, mixing tabs and spaces ... you name it (the CSS file is attached, if you're especially curious).

    I'm not necessarily suggesting that Emacs is the best tool for the specific task we're performing here, but it's a pretty broadly understood file format, so I thought it would be interesting way to demonstrate some of Emacs core functionality. If your favorite CSS editor has a magical "auto-format" button, by all means use it -- it's better than this strategy to be sure, but it's a lot less flexible!

    The Emacs instance you see in the screencast is extremely close to a stock distribution. I made the following modifications, in the interest of making it easier to see what's going on:

    1. Disabled the tool bar and menu bar.
    2. Loaded mwe-log-commands.el, for demonstrating the keys pressed.
    3. Enabled the downcase-region command, normally disabled.
    4. Loaded a simple CSS mode for font locking.
    5. Changed the default font to a narrower version, Consolas.

    On with the show.

    Click to Play

    Here's a breakdown of how we attacked the file.

    1. Converted tabs to spaces with untabify. This is a good first step when encountering a file as hideous as this one.
    2. Normalized all spacing by compressing multiple spaces and newlines to a single space, using a regular expression replacement.
    3. Added newlines after all open braces ({) using a macro. Also used just-one-space before the brace to make the spacing consistent.
    4. Added newlines after all semi-colons, again using a macro. Also compressed space in front of the semi-colons, and added a space after the colon delimiting the property from the value.
    5. Used another macro for adding newlines before and after the close braces. I added the extra spaces before using delete-blank-lines because the spacing varied based on whether or not a trailing semi-colon was present.
    6. Killed a few empty blocks, using backward-paragraph to quickly navigate blocks.
    7. Executed another macro to make the property name case consistent (made them all lower-case).
    8. Sorted properties by name within each block using a macro to regionize the block and call sort-lines.
    9. Compressed expanded forms of margin and padding specification to a single line, using a multi-line regular expression replacement with a reference to a captured group in the replacement string.
    10. Performed a few simple manual cleanups, and updated the messaging.

    Attachments

    • fugly.css
    10 CommentsPosted at 11:14 PM to Categories: Emacs
  • Friday, January 26, 2007

    Emacs Hack #3: Compile Emacs from CVS on Windows

    In previous hacks, we learned how to install and configure stable binary builds of Emacs. While the stable version (currently 21) is the best version to run for most users, you may be brave or curious enough to try one of the newest pre-release versions, 22 or 23. Because there are no official binary builds of Emacs beyond version 21, you will either need to install it from an unofficial source, or compile it yourself. This hack covers the latter.

    Get the Source

    The first step in compiling your own version of Emacs is getting the source. It is sometimes possible to obtain gzipped archives of the Emacs source at a given point, but it's typically more convenient to grab the source from CVS (this also ensures that you're using the most up-to-date version of the given branch).

    If you don't already have CVS installed, fetch a recent version of cvs.exe from its distribution site, and place it somewhere in your path.

    Next up, we pay a visit to Savannah, the GNU development site. The Emacs project page contains details on how to obtain the sources. At the time of this writing, the following command will download the HEAD version of the code (Emacs 22).

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

    If you wish to build a version of Emacs other than 22, you will need to pass a tag name to your checkout command (or a subsequent update command). For example, adding -r EMACS_21_3 would check out the code for the Emacs 21.3 release (the stable release at the time of this writing). For a sneak preview of (the very unstable) Emacs 23, use -r emacs-unicode-2.

    After checking out the sources, cd to the nt directory. As a safety measure, issue a cvs up -kb command here to make sure that all files in the directory have proper line endings. At this point, the source tree is ready to be built.

    Prerequisites

    The Emacs build process requires a handful of tools that probably don't already exist on your system. These include GNU versions of tools with Windows equivalents (cp, rm), as well as tools that are often unique to a GNU system (makeinfo). If you want your build to support images, you will also need a variety of libraries for rendering image formats. All of these tools are available from GnuWin32, a project which provides native Windows binaries of GNU tools.

    The packages you will need to install are listed below. In each case, I suggest installing the latest "setup" package, which will run an installer and place the binaries in a consistent location.

    CoreUtils
    This package contains a variety of tools, and is required in order to build Emacs. Specifically, it contains cp and rm.
    TexInfo
    This package contains makeinfo, which generates Info documentation from the texinfo sources in CVS. While technically optional, I strongly recommend installing it.

    If you wish to build Emacs with image support (optional), you will also need the following image libraries (from the GnuWin32 Packages page:

    • LibPng
    • Jpeg
    • GifLib
    • Tiff
    • Xpm
    • Zlib

    At the time of this writing, the Xpm library is missing a required header file (simx.h). You can either get it from the source package, or download it from the attachments in this post. This file should be placed in the GnuWin32 include directory.

    Compiling with MinGW (GCC)

    The simplest way to build Emacs is using MinGW, a collection of freely available tools for building native Windows binaries. The package includes the GNU C compiler, a port of make, and various header files (including those from the Win32 API, such as windows.h).

    The first step, of course, is to obtain the MinGW distribution if you don't already have it installed. The current version at the time of this writing is 5.1.3, and is downloadable at SourceForge.net (via the project page). Install to the location of your choosing, being sure to select the following components:

    • MinGW base tools
    • MinGW Make

    After installing MinGW, add its bin directory to your path using a normal Windows Command Prompt session (set PATH=%PATH%;C:\MinGW\bin). Next, run configure.bat from the nt directory as follows to build a Makefile:

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

    If you installed the libraries for image support, you will also need to pass the appropriate include path to the configuration script. If you installed to a directory with a space (the default), use the DOS name of the directory as demonstrated below:

    configure.bat --cflags -IC:\Progra~1\GnuWin32\include --no-debug --with-gcc

    If all goes well, you'll get a message telling you to run gmake to build Emacs. We're not quite ready for that yet, however. Because we got our source from CVS, we need to perform a "bootstrap" build. This creates a bootstrap Emacs binary to build autoloads and byte compile the Elisp (.el) files in the distribution. Begin the build process as below (mingw32-make is the MinGW name for gmake):

    mingw32-make bootstrap

    After the bootstrap completes, you're ready to build the source code. You'll also want to build the info files (make sure makeinfo.exe is in your path) before installing. Run the following commands in sequence to finish compiling and install your Emacs build.

    mingw32-make info
    mingw32-make
    mingw32-make install

    By default, Emacs will be installed "in place". If you prefer to install it somewhere else, run configure.bat with a --prefix <dir> argument pointing to your preferred installation directory.

    Compiling with MSVC

    The most popular C/C++ compiler for Windows is MSVC, Microsoft's Visual C++ compiler. Traditionally, this compiler was only available commercially, when purchased as part of Microsoft's Visual Studio development product. In recent years, however, Microsoft has made simple versions of the compiler available free of charge. Fortunately, the simple versions suffice for building Emacs.

    At the time of this writing, the VC8 compiler (part of Visual Studio 2005) is the most recent version available. Unfortunately, Emacs cannot currently built with this version of the compiler without modifying the source. The only other freely available version of the MSVC compiler was made available as part of the Visual C++ Toolkit 2003. Microsoft no longer distributes this compiler (it was replaced by Visual C++ 2005 Express Edition), but if you already have it installed, or happen to have downloaded it previously (the file name is VCToolkitSetup.exe), you can proceed to build Emacs using this compiler. If you have a commercial version of Visual Studio 2003 installed, the steps should be very similar.

    The Visual C++ Toolkit installation is very basic. In order to build Emacs, you need a variety of header files in addition to those packaged with the toolkit. To obtain these, you will need to download and install a (pre-Vista) version of Microsoft's Platform SDK. Because you only need a base set of components, the Web Install method is probably optimal. The following screen shot shows the components you need to have selected:

    Platform SDK Configuration

    Next, add cl.exe to your PATH in a normal Windows Command Prompt window. The easiest way to do this is to run the vcvars32.bat script packaged with the download, e.g.:

    "%ProgramFiles%\Microsoft Visual C++ Toolkit 2003\vcvars32.bat"

    Next, you need to add the Platform SDK paths to your environment. For example:

    set SDKROOT=%ProgramFiles%\Microsoft Platform SDK for Windows Server 2003 R2
    set INCLUDE=%INCLUDE%;%SDKROOT%\Include
    set LIB=%LIB%;%SDKROOT%\Lib

    If you are building with image support, you'll also need to add the GnuWin32 paths:

    set INCLUDE=%INCLUDE%;%ProgramFiles%\GnuWin32\include
    set LIB=%LIB%;%ProgramFiles%\GnuWin32\lib

    Normally we'd be done at this point, but we're still missing a couple of pieces. The first is setargv.obj. Fortunately it's only missing in binary form -- it can be generated from the Platform SDK's CRT source directory. To build the required file and place it in the Platform SDK's lib directory, run the following command:

    cl /c /D_CRTBLD /I"%SDKROOT%\src\crt" /Fo"%SDKROOT%\lib\setargv.obj" \
        "%SDKROOT%\src\crt\setargv.c

    We're also missing a few essential binaries the build process expects: nmake.exe, rc.exe, and lib.exe. All of these files are packaged with commercial versions of Visual Studio, but you'll need to find them elsewhere if you're using the Toolkit. The first two can be obtained free of charge by installing the .NET Framework SDK. Make sure you add its bin directory to your path after installing. lib.exe is simply an alias for link /lib, so a simple batch file (lib.bat) will suffice. A sample is attached to this post -- place it somewhere in your PATH.

    Finally, we're ready to build Emacs using MSVC. As with the MinGW build, the process begins with running configure.bat:

    configure.bat --no-debug --with-msvc

    Things are pretty straighforward from here. As with the MinGW build steps, we need to start with a bootstrap build, after which we can build the complete distribution. Refer to the MinGW steps for details:

    nmake bootstrap
    nmake info
    nmake
    nmake install

    Optimized Builds

    One of the advantages of compiling from source yourself is that you can optimize builds for your platform. For example, if you're using a modern AMD or Intel processor with SSE extensions, you can enable the compiler to generate optimized code for your processor. To build an optimized version of Emacs, you will need to pass arguments to the compiler by way of configure.bat's --cflags argument. To build a version of Emacs optimized for an SSE2-capable Athlon or Pentium 4 processor with MSVC, for example, you would run the script as follows:

    configure.bat --no-debug --with-msvc --cflags /O2 --cflags /G7 --cflags /arch:SSE2

    For a similarly optimized build with MinGW (GCC), use:

    configure.bat --no-debug --with-gcc --cflags -msse2 --cflags -O3

    Optimized builds will typically be incompatible with older processors that do not support the selected extensions (in most cases, they will crash at runtime). If you are creating an Emacs build to share, minimize optimizations that require specific processor features such as SSE.

    Final Steps

    If you built Emacs with image support, you need to copy the runtime DLLs to Emacs' bin path (or your system path, if compiling only for a single system). You can copy them manually, or script it as below (specific file names may vary slightly if versions change):

    for %f in (giflib4 jpeg62 libpng13 libtiff3 xpm4 zlib1) do \
        echo copy "%ProgramFiles%\GnuWin32\bin\%f.dll" ..\bin

    Attachments

    • simx.h
    • lib.bat
    11 CommentsPosted at 4:28 AM to Categories: Emacs
  • Friday, January 05, 2007

    Emacs Hack #2: Manage Emacs Instances with gnuserv

    If you followed Hack 1, you can now launch Emacs and open files from within the interface. On Windows (and in some other environments), you can also drag files to Emacs from your window manager.

    But what if you want to send a file to Emacs from a console session, or via a shortcut? You could invoke Emacs using runemacs (or create a shortcut to it), but every time you do that you end up with a whole extra instance of Emacs -- a unique operating system process which is independent from any previous instance(s).

    In some cases, this might be what you want. In the rare case of an Emacs crash, for example, you would not lose any active buffers in the other instances (note that Emacs' auto-save facility would probably mitigate the damage here). Most of the time, however, you'd rather open the file in an existing instance of Emacs. This has a number of advantages:

    • Memory is conserved by sharing a single process.
    • Shortened start-up time since Emacs is already loaded.
    • All open buffers in the shared instance can be quickly accessed from any Emacs frame.
    • The buffer list can be used to see every open file across frames, and to perform actions on them.
    • Dynamic abbreviations (covered in a future hack) can be sourced from a larger set of files.
    • Contention issues (multiple processes accessing the same file) are avoided.

    Fortunately, there is a small client / server program called gnuserv which enables us to do just this.

    Installing

    Installing gnuserv consists of two parts -- some platform-specific binaries (gnuserv, gnudoit, gnuclient and, on Windows, gnuclientw), and an Emacs Lisp file which we'll load into Emacs. The Lisp code will spawn the gnuserv process after Emacs has started, listening for received commands on gnuserv's standard output stream.

    On Windows, the first step is to unpack the ZIP file containing the gnuserv binaries (on Unix and derivatives, simply install the gnuserv package for your distribution). The Windows port is available at Guy Gascoigne - Piggford's site, or attached to this post if the site is unavailable. Extract the binaries to a directory in your %PATH% (see Hack 1 for some tips on setting up your path), e.g. C:\Program Files\gnuserv.

    Next, we need to install the Emacs Lisp portion of gnuserv. This involves placing the gnuserv.el file (attached to this post) somewhere in Emacs' load path. The easiest way to do this is to copy the file to the site-lisp directory, typically located under your base Emacs installation directory (Windows) or at /usr/local/share/emacs/site-lisp (Unix and its derivatives). Files placed here are automatically available to Emacs.

    Configuring

    We've installed all of the pieces necessary for gnuserv, but nothing has really changed in terms of Emacs' behavior. Even though we've added gnuserv.el to its load path, we still need to instruct Emacs to load the file. We'll do this by adding some initialization code to our .emacs file (see Hack 1).

    From within Emacs, type C-x C-f (that's the control key plus x, followed by the control key plus f -- you can keep the control key pressed the whole time). This invokes Emacs' find-file function, which prompts you for a file path to open using the minibuffer (the bottom line in the frame). Emacs will present you with a suggested path. Type ~/.emacs, press Tab (Emacs will remove the suggested path as part of its completion algorithm), and then press Enter to open the file.

    If you're a Windows user, this path might look strange. The tilde (~) character is simply a handy shortcut for the folder represented by your %HOME% environment variable, and the forward slash is Emacs' preferred path separator (that is, C:/Users is preferred to C:\Users). The path syntax for the home directory is not only convenient to type, it also makes your Emacs configuration more portable. For example, ~/Desktop always maps to your Windows desktop, regardless of your login name or other machine-specific details.

    At this point, you should be staring at a blank buffer. Add the following lines to your .emacs file:

    (require 'gnuserv)
    (gnuserv-start)
    (setq gnuserv-frame (selected-frame))

    This might look somewhat strange -- it's actually just some simple Elisp which tells Emacs to load and start gnuserv. The first line calls the built-in require function, which tells Emacs to load gnuserv if it hasn't already done so (this causes Emacs to go find gnuserv.el in our load path). The next line calls a function in gnuserv.el, which starts (or restarts) the gnuserv process. The last line is an optional customization which tells Emacs that it should open new files from the clients of gnuserv in its startup frame (if you find that you prefer to have multiple Emacs frames, comment this line out by prefixing it with a ; character, or delete it entirely).

    Emacs reads its .emacs file and evaluates these lines each time it starts up. You can either restart Emacs now, or press M-x (M stands for meta, which is typically Alt), type eval-buffer, and press Enter (this tells Emacs to evaluate the contents of the current buffer without requiring a restart).

    Launching Emacs

    At this point, you should have an Emacs instance running with gnuserv started. So far, so good. Now it's time to use the client programs which came with the gnuserv distribution.

    gnuclient and gnuclientw

    The gnuclient program can be used to open a file in a running instance of Emacs. For example, typing gnuclient README from a console session will open a new buffer for the file README (even if it doesn't yet exist). If Emacs is not currently running, it will automatically be started (at which point it will evaluate its .emacs file, loading gnuserv).

    You may notice that when a file is opened using gnuclient, a message is displayed in Emacs' minibuffer: "When done with a buffer, type C-x #.". You may also have noticed that when you invoke gnuclient, it does not immediately exit (that is, you can't continue using the console). What's happening is that the gnuclient process is waiting for you to finish working on the file -- when you press C-x # from within Emacs, the gnuclient process exits. This is convenient in many cases -- for example, when editing a Subversion commit message. If the process returned immediately, Subversion would not be able to read the message you typed in to Emacs because there is no longer any connection between the editor and the launcher.

    In other cases, however, you just want to open a file in Emacs and continue using your console session immediately. In this case, you can use gnuclientw (Windows only -- on other platforms, use gnuclient -q). This is a variation of gnuclient which returns immediately. It's also compiled as a Windows application, so it's ideal for creating Windows shortcuts (gnuclient opens an unneeded console window in these cases). I typically add a shortcut to gnuclientw in %USERPROFILE%\SendTo and %USERPROFILE%\Desktop. In practice, I nearly always use gnuclientw (with or without arguments) to start Emacs on Windows (because it's in your path, it can also be executed from the Run dialog). If you find yourself running gnuclientw a lot when Emacs is already open, try adding a -x option to "top" the Emacs frame (make it visible if it's hidden).

    gnudoit

    The last (and in this case, the least) client program is gnudoit, which can be used to evaluate an Elisp form. For example, gnudoit (list-buffers) will open a window within your Emacs frame listing the currently open buffers. This command is deprecated because the same behavior can be achieved using gnuclient -- on Windows, use gnuclient -e (list-buffers). On other platforms, type gnuclient -batch -eval (list-buffers). In practice, you probably won't be running these forms very often.

    Attachments

    • gnuserv.el
    • gnuserv.zip
    8 CommentsPosted at 6:34 AM to Categories: Emacs
  • Saturday, December 09, 2006

    Emacs Hack #1: Install Emacs on Windows

    Installing Emacs on most platforms is a common and well supported operation. On Linux, for example, it's typically installed via the package management system for the particular distribution you've chosen. This hack covers installing Emacs on Windows, where it's a bit more challenging.

    There are some shortcuts to getting Emacs installed and running on Windows, but we're going to walk through the steps from scratch. There are a number of "decision points" throughout the installation. When we reach those, I'll give a specific recommendation as well as provide you with the alternate options.

    Which Emacs?

    The first decision greets us before we even embark on the installation process. There are two primary flavors of Emacs -- GNU Emacs, and XEmacs. The former is the "original" Emacs, and the latter was branched from an earlier version of GNU Emacs by a company called Lucid. If you're interested in the history, Wikipedia has a nice summary.

    I've used both versions extensively and had similarly positive experiences with each. I'm going to recommend installing GNU Emacs, however, since in my experience it seems to be the more popular version. Because it's more common, it's more likely that additional packages and snippets that you adopt after the installation will be more compatible. Future posts in this "hacks" series will also assume that you're running a flavor of GNU Emacs.

    OK, so we've decided to install GNU Emacs. However, we're not quite finished yet. There are several versions and packagings of Emacs (yes, even when we limit our target platform to Windows), and so we've got yet another decision to make. Currently, the "stable" version which is distributed by GNU officially is version 21.x. The next version of Emacs, 22.x (and the version after that, 23.x), can be had by compiling your own version from CVS (there are also unofficial binary builds).

    I'm going to walk you through the steps of installing the official, stable distribution of Emacs (21.x). If a newer version is distributed by the time you end up reading this, the steps are likely to be identical. Many of these steps will also be relevant for unofficial distributions, so it's a good place to start even if that's where you end up.

    Before we bother to even find the official binary distribution of Emacs, though, we need to make sure our Windows environment is set up properly.

    Home is Where the Files Are

    As you use Emacs, it will occasionally need to read and write files to your hard drive to keep track of various settings and customizations (we'll cover many of these in this "hacks" series). The primary customizations are placed in a file called .emacs (the . preceding the name causes the file to be "hidden" on Unix file systems). On Unix and Linux systems, this file is placed in the "home" directory, a user-specific location denoted by the HOME environment variable (e.g. /users/derek).

    Windows does not set the HOME environment variable by default, so Emacs assumes that your "home" directory is C:\. This is generally not a good place for user-specific settings. On most Windows systems, you need administrative privileges to write to the root directory. Also, multiple users on a given Windows system would likely want their own configurations. Lastly, many Windows backup and migration tools only save the contents of user-specific directories.

    Fortunately, it's a simple matter to tell Emacs where our real "home" directory is -- we simply need to set the HOME environment variable. I strongly suggest using the value of the USERPROFILE variable as the basis for setting HOME. This variable is always available and is properly set to the real "home" directory of the current user.

    We can temporarily set environment variables from the console using the set command, but we need to make this particular variable persistent. If you're using Windows Vista, you can set persistent environment variables using the setx command (you can also do this on Windows XP if you install the necessary support tools). To set HOME from a normal user console session using setx, type:

    setx HOME "%USERPROFILE%"

    If you don't have the setx command, you can set this variable using a graphical tool. Choose System from the Control Panel menu, click the Advanced tab, and press the Environment Variables button. In the User variables section, add a new environment variable with the name HOME and the value set to your user profile directory (e.g. C:\Documents and Settings\Derek). You can type echo %USERPROFILE% from a command prompt to get the correct value.

    Add environment variable

    To test the value, start a new console session, and type echo %HOME%. On Windows XP, for example, you should see something like this:

    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    
    C:\Documents and Settings\Derek>echo %HOME%
    C:\Documents and Settings\Derek

    Getting the Distribution

    With that out of the way, we can download Emacs. Begin by visiting the official Windows distribution site. You'll notice a number of different files here:

    emacs-21.x-barebin-i386.tar.gz
    This contains Emacs binaries without any precompiled Lisp files. You could install Emacs with this file, but it wouldn't be very useful (you would have to add / compile the Lisp files yourself to make Emacs useful).
    emacs-21.x-bin-i386.tar.gz
    The is a full installation of Emacs with precompiled Lisp files. This is a good choice if you just want to install Emacs and use it.
    emacs-21.x-fullbin-i386.tar.gz
    This is functionally the same as the previous item, but includes the full Lisp source in addition to the compiled versions. This is the best choice if you want to be able to see the actual code behind much of Emacs. If you have the space, I recommend installing this version.
    emacs-21.x-leim.tar.gz
    This is the "Library of Emacs Input Methods" package, which is used for entering non-ASCII characters. You can probably skip this for now.
    emacs-21.x-lisp.tar.gz
    This file contains the Lisp source for the Emacs distribution. If you installed the regular binary version, you could use this to turn it into the "fullbin" version.
    emacs-21.x-undumped-i386.tar.gz
    This version contains a special executable you can use to rebuild Emacs after changing built-in files. You almost certainly don't need this.
    fns-21.x.x.el
    This file contains the load history for built-in libraries. This file comes with the normal distributions, so you can safely ignore it.

    The installation process is the same whether you install "bin" or "fullbin", so download whichever option makes more sense for you.

    Unpacking

    Because the files are in gzipped GNU Tar format, you cannot extract them using the built-in compression tool in Windows. If you already own a commercial compression tool such as WinZip or WinRAR, you can easily extract the binaries using one of those tools. If you don't have one of these tools, I recommend installing 7-Zip, which has similar capabilities and is completely free.

    The root of the binary distribution contains a single directory, emacs-21.x. Because there are no user-specific files in the binary distribution, it makes sense to install it in a shared location. If you have administrative privileges, I suggest extracting it to your "Program Files" directory (type echo %ProgramFiles% from a command prompt to get the full path). Users with no administrative privileges whatsoever can install Emacs in their HOME directory instead.

    If you're using 7-Zip, open it and navigate to the downloaded file. If you're using Windows Vista or are running as limited user account, you will need to start 7-Zip using the "Run As" feature of your particular flavor of Windows. If you don't, it won't have access to write to the shared directory. Once you've opened the downloaded file using 7-Zip, double-click [Content], select the emacs-21.x directory, and click Extract. Enter the full path to your "Program Files" directory, and click "OK".

    7-Zip extraction

    You can now close 7-Zip, navigate to your "Program Files" directory and confirm that the extraction was successful.

    Installing

    You now have a usable version of Emacs. If you execute runemacs.exe from the bin directory, Emacs will open and be fully functional. This isn't the most convenient way of starting Emacs, however. Thus, there is one last installation step.

    In the bin directory containing the runemacs.exe file, there is a file called addpm.exe. This file "installs" Emacs by adding a start menu program group and adding a few registry entries in HKEY_LOCAL_MACHINE\SOFTWARE\GNU\Emacs. Simply double-click the file, click "OK", and Emacs will be fully installed. Now you can open Emacs from the "Gnu Emacs" program group in your start menu.

    Now What?

    Now that Emacs is installed, feel free to start using it. If you're accustomed to Windows editors, chances are it will feel a bit strange at first. Perhaps the most useful thing you can do at this point is to invoke the Emacs Tutorial (click the Help menu item to access it). This will cover some of the basic Emacs commands and concepts. If you complete the entire tutorial, you should start to feel comfortable enough in Emacs to do some basic editing. Practice using the Emacs commands as much as you can afford to. You'll learn hundreds of them over time, but the commands covered in the tutorial are some of the most important ones.

    26 CommentsPosted at 11:59 PM to Categories: Emacs
  • Sunday, December 03, 2006

    The Case for Emacs

    When well-seasoned programmers get together to speak of the "good old days", there are a few persistent topics. There are always at least a couple of archaic programming languages ... depending on the number of reminiscing participants, there can even be enough to inspire a game of "I had it worse than you did!". Inevitably, this is followed by some form of reference to ancient multi-user operating systems, mainframes, or -- although increasingly rare -- systems involving punched cards. More often then not, this piece of the conversation will lead to discussions of operating ancient editors via terminals -- with ed nearly always starting that conversation (and earning several grimaces at its first mention).

    If you've heard enough of these discussions, as I have, you've surely observed that the tone of these discussions suggests that we are now in a golden age of development tools ... I've been writing software, and hearing these discussions just long enough to start to wonder if these discussions were any different back then (it's all relative, isn't it?). Me? Well, I started this game a bit late relative to most of the "good old days" participants I've observed. They had Pascal, I had VB5 -- they had ed, I had ... well, VB5 ... they had libraries, I had BBSes, they had printed manuals, I had CD documentation ... the list goes on.

    The Beginning

    I stumbled into programming during high school (I'm excluding the 10 print "derek", 20 goto 10 fun that so entertained me in grade school). I was responsible for inputting data penned in by customers entering contests, signing up for mailing lists, etc. into a database. Every time I re-entered the same postal code three times in a row I could feel my brain shrinking.

    Within the friendly environment that was VBA (in Microsoft Access '95), I managed to script a form into filling in a few fields for me when encountered with one of the most popular postal codes. I was hooked -- entering the addresses had been transformed from mind-numbing boringness to a creative exercise in trying so save as many keystrokes as possible.

    My initial fondness for VBA (and Microsoft's influence on programming curricula in the greater Puget Sound area) led me to a Visual Basic programming course at a local community college. I enjoyed it, and it eventually led me to my first programming job (which really was a web design job, but nobody seemed to mind -- perhaps because I was still in high school, or perhaps because I was making $8/hour).

    In these early years of my career (before it was officially my career, I should add), there was never a distinction between language, framework or development environment. My language was Visual Basic, I called Visual Basic functions, and I did all of this using a product called Visual Basic ... the explosion of Active Server Pages brought Visual InterDev along for the ride, and C++ tasks were handled by Visual C++. There was always a "right" tool for the job.

    A Hot Cup of Java

    After a couple of years of making ASPaghetti, I started toying with a language called Java. I use the word "toying" quite intentionally, because at the time my best description of it would have been "language used to make cool buttons on Web pages". I had been quite ignorant of the growing Java juggernaut, but our company had recently bought some Oracle licenses (it was the Dot-Com era, why not?) and it seemed to be the language of choice for folks in that camp.

    I quickly moved from "toying" to "using". For a Visual Basic programmer, Java was like heaven -- actually, Java was heaven. After two weeks of using it, I was ready to have the "good old days" conversation about old Visual Basic. Goodbye class modules, hello beans!

    One thing that was very different in the Java world, and it was new to me, was choice in environment. In the Microsoft world (and this is still true today), there was a supported development environment released with the language ... in Java, the tutorials were telling me to set a CLASSPATH environment variable (bad advice, by the way -- -cp is much less painful, but I digress) and use the editor of my choice. Using Notepad was fine for my "First Cup of Java", but I knew I'd be needing auto-completion and a "debug toolbar" before long.

    My quest for the perfect Java IDE never really finished -- I started with Oracle JDeveloper (basically an early version of JBuilder), and later dabbled with VisualAge, Webgain, Netbeans, JBuilder itself, and just about everything else that came around ... I never fell in love with any of them, but most were a pretty nice step up from the development tools I had worked with previously. They all had the basic features I was looking for -- syntax highlighting, intelligent completion, click-to-run, debugging ... none of them stood out, but they were all Good Enough[tm].

    The Dark Side

    There is a dark side of the programming world. Some are never exposed to it ... some have only had enough exposure to be scared by it. The dark side consists of a wide network of programmers, about 1 to 2 for every 10, who throw away the rules. They run strange operating systems, they spend free time on weekends experimenting with programming languages you've never heard of (Hask-what? Eif-who?) ... and they don't use the same tools that you do, to say the least.

    I remember the first time I witnessed a member of this "dark side" in action. I had wandered into the cubicle of one of our recent hires, a long-haired "Unix guy" who was in the midst of a rather furious coding session in a very strange looking editor (Vim, for the curious). Watching him operate his editor was truly an experience. He was working at a pace I'd never seen before, his cursor flying around the buffer like a pinball. I was like a child seeing a magician for the first time (that hat was empty!).

    I rudely interrupted his session -- in part to marvel at his proficiency, but also to ask some questions about his current project. He walked me through the code he was working on, and the artistry continued -- he seemed able to will his cursor around the buffer with the power of his stare, as if he was simply "thinking it" there. I'd never seen anything like it -- he wasn't using his editor -- he was his editor.

    I was forever changed. I had seen what the dark side was capable of, and I wanted a membership card. Going back to my IDE was a depressing affair -- I tried -- and I tried hard, to replicate the genius I'd just seen. He had clued me in to a couple of his tricks, which I tried to emulate. I took a tour through my IDE playground again, trying to find one that would enable me to perform the magic tricks he executed so effortlessly, but I couldn't.

    I spent a week or so trying to convince myself that all of that "other stuff" in my IDE made up for what it lacked in the editing department. I was partially successful -- I mean, my debugger sure looked a lot fancier than his (gdb, for the still curious). That had to count for something. And that intelligent completion -- surely I couldn't live without that, right? Right? Not exactly ...

    I made a conscious effort that week to think about each feature as I used it. Intelligent completion? Sure, it was helping me code, but how much? With this in mind, I noticed that I was doing some really idiotic things, like typing n-e and then waiting a (brief) moment for the completion window, in some cases using my arrow keys to find the appropriate completion, and selecting it. This, as opposed to just finishing the keyword ... x-t ... surely, somebody observing from the dark side would be shaking their head at the sight of this. I had to do better. My tools were good, maybe even great, but they still weren't good enough.

    I Think I Can ...

    With the help of a Unix shell account, I decided to take a tour of the dark side. I did a bit of research (Have you heard of this fantastic new search engine called Google? No, no -- l-e ... yeah, that's it -- now search for "cigar!"), and found that the dark side was in the midst of a civil war -- the Emacs-folk vs. the Vi(m) folk. Oh boy ... I was going to have to choose. A bit more reading convinced me that what I was seeking (magical editor powers, that is) could be achieved with either. I'd seen what Vim could do, how about this Emacs thing?

    My first experience with both editors was a disaster ... in Vi, I did finally stumble into the proper mode for getting characters into the buffer, but it wasn't a pretty process (and it certainly wasn't intentional). Emacs started out a little better, but I couldn't figure out for the life of me how to quit -- control-s? control-q? And yeah, the fact that I kept toggling flow control on the terminal certainly didn't help. Finally, I figured it out -- control-z! Pressing that makes Emacs go away, problem solved. Alright, time for some magic tricks! Oh, and it took a couple of hours before I realized that I was suspending it rather than quitting. When you're accustomed to control-q, \C-x\C-c is a long ways away. Fortunately, the tutorial (\C-ht) got that out of the way in a hurry.

    Armed with some documentation and a bit more time, I ended up giving each editor a fair shake. In no time, I was moving around buffers pretty well in Emacs -- not exactly comfortable, but reaching for my arrow keys less and less (not because it made sense to me, but it had been suggested that this was the path to magic, so I figured I'd try). Vim was starting to become less painful as well, although the mode switching was really causing me to do some amazingly stupid things (something tells me Vim users all have rigorous backup schedules). in any case -- I figured that to become a magician I would need to focus on one editor, and my laziness led me to Emacs (sorry Vim, too much early mode pain).

    Magic Tricks

    It really didn't take too long to reach my goal -- I had to re-train a lot (OK, nearly all) of my editing instincts, but before long I was performing buffer magic tricks of my own. By this time, I'd found other "dark siders", and I was extracting as much information as I could from them ("Hey, how'd to swap those characters?") ... each tidbit I picked up, I would force myself to use for a day, and inevitably, I'd end up using it 100 times the next week, wondering how I ever lived without it.

    That's really the Zen of Emacs. When I encounter people who see me using Emacs, they typically assume that I use it because of its customizability. That's a nice feature, but it's not the reason to use Emacs. The Zen part is all there in the base package -- even without a .emacs file (a Lisp file read at startup used to customize Emacs). The "magic tricks" that turn you into an editing wizard aren't really tricks at all -- they're core features. Once you learn these core features, it's astounding the magic you can do -- and you can do it everywhere. You can swap arguments in C the same way you swap words in a text file -- you can autofill your comments just like your paragraphs -- rectangle insertion makes block comments as well as it adds a shared prefix -- dynamic abbrevs (rich, but unintelligent completion) work everywhere -- and all of this stuff works whether you're editing C#, Javascript, CSS, Java, XML, Ruby, Lisp, ... the list goes on. And trust me, these features only sound exotic until you depend on them.

    That's not to say you can't add useful tricks on top of these core features. The point is, you don't have to. I think a lot of people avoid Emacs because of this misunderstanding. The truth is that Emacs isn't scary -- you don't need to know a thing about Lisp, Emacs Lisp, or Unix (Emacs works wonderfully as a native Windows binary). You don't need to have a .emacs file, you don't need a PHD in Parenthesis to be a magician. You do need to give it some time, but it will pay you back.

    Emacs doesn't seem like much at first. It takes an hour or two to get the basics down, at which point a new user can probably use it with almost-Notepad-level efficiency. It takes a lot more time to get to the next level, but once you do, you can't go back. I remember explaining to an early Emacs user how much I loved prefixed arguments (numeric arguments to alter command behavior). He laughed at me like I was joking. I mean, that's fair -- prefixed arguments do sound like a silly "border feature" if you've never worked with them before. And hey, it took me a while to pick up on them. But now, I use them many times daily.

    Stretch Yourself

    Another thing you get with Emacs is flexibility. Have you ever wanted to experiment with a new technology, but avoided it because you were too comfortable in your existing programming environment? Come on -- you saw that Ruby on Rails screencast, right? If you're an Emacs user, you can be writing C# on Windows Monday, Ruby on Mac OS Tuesday, and Python on Linux on Wednesday. In each case, there are language-specific tools to use, but the place you spend the most time -- your editor -- is consistent across tools and platforms. Virtually all the time you invested in learning (and customizing) the editor comes along for the ride each time. Emacs lowers the bar.

    OK, I know -- you're not convinced. You love -- no, you love your IDE. I've been there. How about 5 years ago, though? Were you using the same IDE? Were you even using the same language? Me neither. How about in 5 years -- do you think you'll be using the same language? The same tool? Really? If you did switch, how much knowledge from your last development environment transferred? You might think that "it doesn't matter" -- heck, I probably would have said the same thing reading this 5 years ago ("bah, I'll just learn a new IDE when I pick that language up"). It's difficult to explain how much you can gain from mastering an editor -- you just have to experience it. Have you ever learned a keyboard shortcut in a program, and wondered how you ever lived without it? Gaining proficiency in Emacs is like that feeling times 1,000. Emacs is never having to press the same button 5 times in a row.

    It's powerful, even if it doesn't sound like it. After several years of using Java, I needed to switch to C# for a few projects which integrated with native Windows libraries. My development process hardly changed in the process -- every trick I knew for editing, buffer management, compiling -- it all transferred. With the recent shift towards standards-based Web-centric applications, and working for a startup, I'm writing C#, JavaScript, Java, CSS, C++ and XML regularly -- all within the friendly confines of Emacs. And yes, I'm writing this blog post in Emacs (using a custom RELAX NG Compact schema in NXML mode, for the still curious).

    Emacs Hacks

    Getting started with Emacs can be a bit intimidating at first. It's a community run by dark-siders, and they have a tendency to assume you're a rocket scientist. Wading through the documentation and getting out of the gates is the hardest part (it was for me -- I'm not even a model rocket scientist). I'm going to dedicate a few posts on this blog (in "hacks" style, sans the book-length depth) to helping you do just that. I'll probably bias it somewhat towards installing and using Emacs on Windows, since it's quite a bit easier on Linux (apt-get install emacs21 doesn't make for a very interesting blog post).

    If you're not convinced -- I understand. And it doesn't bother me at all. I have nothing against language or environment-specific tools. I use them all the time -- debuggers, static analysis tools, inspectors, refactorers -- you name it. You don't have to dump your IDE -- you can even use them side-by-side if that's more comfortable for you. My point is that mastering a flexible editor (Emacs or otherwise) can make you a more versatile, more productive developer. It might even make you a better developer. No Elisp hacking required.

    31 CommentsPosted at 1:00 AM to Categories: Emacs

About

I'm a programmer at Appature, a Seattle-area startup building marketing-focused CRM tools.

Email Me

Recent

  • DVCS Myths
  • A DVCS Story
  • BCrypt.net - Strong Password Hashing for .NET and Mono
  • A Better .NET Regular Expression Tester
  • Emulating Vista's User Directory Structure on XP
  • Screencast: Formatting a CSS File with Emacs
  • Emacs Hack #3: Compile Emacs from CVS on Windows
  • Emacs Hack #2: Manage Emacs Instances with gnuserv
  • Emacs Hack #1: Install Emacs on Windows
  • The Case for Emacs

Categories

  • .NET
  • Baseball
  • C#
  • DVCS
  • Emacs
  • LINQ
  • Security
  • Windows
© Copyright 2008 Derek Slager