views:

616

answers:

2

A friend of mine is considering switching to Emacs from TextMate. He is used to TextMate's default HTML editing mode which has 4-space tab stops and inserts tab characters (i.e. it does no auto-indenting by default). It also allows completion of open HTML tags with "Cmd-Shift->". Any ideas?

+5  A: 

I think these settings should do the trick:

(defun my-html-mode-hook ()
  (setq tab-width 4)
  (setq indent-tabs-mode t)
  (define-key html-mode-map (kbd "<tab>") 'my-insert-tab)
  (define-key html-mode-map (kbd "C->") 'sgml-close-tag))

(defun my-insert-tab (&optional arg)
  (interactive "P")
  (insert-tab arg))

(add-hook 'html-mode-hook 'my-html-mode-hook)

An explanation of the settings in 'my-html-mode-hook is as follows:

  • set the tab width to 4
  • force tabs to be inserted (as opposed to spaces)
  • force the TAB key to insert a tab (by default it is bound to do indentation, not just insertion of tabs
  • 'sgml-close-tag is the command that inserts a close tag for you, and this setting gets you the keybinding you want

I'm having a bit of a brain freeze and couldn't figure out the simple way to have the TAB key insert a TAB character, so I wrote my own. I don't know why a binding to 'self-insert-command didn't work (that's what normal keys are bound to).

The last line just adds the setup function to the 'html-mode-hook. The key bindings really only need to be run once (as opposed to every time html-mode is enabled), but this is a little easier to read than using 'eval-after-load. It's use is left as an exercise to the reader.

Trey Jackson
+1  A: 

I don't know about emacs's HTML modes specifically, but I can answer about general editing:

  • by default, Emacs doesn't autoindent, so nothing to do here.

  • Emacs preserves tab characters, unless you explicitely ask them changed (check out tabify and untabify). Their width is determined by the buffer-local tab-width variable. M-x set-variable, (setq...), customize at will.

  • you should be able to get the behavior you want with the tab key by setting indent-line-function to tab-to-tab-stop, setting tab-stop-list to (4 8 12 16...) and indent-tabs-mode to t.

Setting indent-tabs-mode allows Emacs to insert tab characters when indenting. The tab-to-tab-stop is a form of indentation that only goes to specific positions in the line, which we set to match the expected behavior of the tab characters by setting tab-stop-list to the multiples of 4.

About completion, the only thing my muscle memory tells me is "C-c C-e", but I don't remember for sure which major mode it's supposed to go with. The closest I see in the list is sgml-close-tag, bound to C-c /

A bit of politics: don't use tab characters, especially if you use widths not equal to 8. It only results in unpredictable results

JB