Monday, June 13, 2011

Emacs csharp (C#) Mode Installation and Automatic Enable with Auto Hook on Windows

I like the editor in Visual Studio a lot.  But when it comes to do some repetitious editing, for example, writing code to insert or update database fields based on some pattern, it is a lot easier to do cut-paste-search-replace with Emacs than the GUI based editor by recording some macros.

So I do often use Emacs. And now we have the csharp mode available, the environment is quite nice.

I am not an Elsip hacker so by the time I need to do something more internal with Emacs, I have usually forgotten what I did the last time. So in order to save my own time in the future, for example, to duplicate what I have done on my home PC with another one somewhere, this article will help me do this. Perhaps you also may want to do the same thing.
  • Be sure that your emacs is installed at your C:\Program Files\ directory, for example, C:\Program Files\emacs.23.2 Unless you know a whole lot more about Emacs (in which case you should not be reading this), it is not correct to install it anywhere else, because the load-path really only points to that directory. Please do note, that even this is a 32-bit app, you still want to put the program in C:\Program Files and not in the X86 directory.
  • First, download the csharp mode Lisp code. You can Google for it as to where. But I got one from the Emacs Wiki under csharp-mode.el  Clicking this link will give you the content of the Elisp, so I would copy this into a suitable text editor (for some reasons, I tend to use Notepad for this sort of thing.) then Save As csharp-mode.el
  • Copy csharp-mode.el to site-lisp directory in your emacs installation. If the directory does not exist, I'd say it's OK to make one there. (For example, C:\Program Files\emacs-23.2\site-lisp).
  • Next, go to your Windows user home directory (at very top, above Documents), then create a .emacs file. The easiest way to do this by far is to create one from Emacs. Notepad does not allow creating files that start with a period. Just Control-X F and type in ~/.emacs   NOTE: On Windows 7, your home directory for .emacs is usually c:\Users\/AppData\Roaming\  If you used emacs to edit this, emacs will know this.
  • Now cut and paste the following lines of Elisp. I have added a bonus hook to enable HTML editing mode for aspx and ascx below. Save the file, re-launch emacs and you are good to go.
(autoload 'csharp-mode "csharp-mode" "C# Mode" t)
(setq auto-mode-alist (append '(("\\.cs$" . csharp-mode))
(setq auto-mode-alist (append '(("\\.aspx$" . html-mode))
(setq auto-mode-alist (append '(("\\.ascx$" . html-mode))

1 comment:

CF said...

Thanks! I'm getting set up to use Emacs for the first time in 15 years, and was floundering a bit with this. Your steps worked great.