I have tried to disable the auto indentation in Emacs in JavaScript for three hours now and could not find a (good) solution.

My Emacs version is 23.3.1 (i486-pc-linux-gnu, GTK+ Version 2.24.3), at least it says that. It is a standard package from Debian Linux (Wheezy), the GUI one.

I found emacs javascript auto indentation (and others), but did not want to install another mode just for removing auto indentation (and there's no garantuee it would work with it), the fundamental mode disables syntax highlighting as well, which I want to keep, C-c C-l does nothing, setting javascript-auto-indent-flag to nil does nothing.

What I want exactly: Insert a tab if and only if I press the TAB key. The "if" part works, but the "only if" part does not. I wonder why it's so hard?


In Emacs' Javascript mode, the character } is bound to function js-insert-and-indent. You can bind it to just insert itself by putting this code into your .emacs startup file:

(defun my-js-mode-hook ()
  "My personal Javascript mode hook."
  (local-set-key (kbd "TAB") 'tab-to-tab-stop)
  (local-set-key (kbd "RET") '(lambda () (interactive) (newline 1)))
  (local-set-key (kbd "SPC") 'self-insert)
  (local-set-key (kbd "}") 'self-insert))

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

and restarting Emacs. If you find other characters like that, you can add more calls to local-set-key in your hook function, each with a different character passed to the kbd function.

  • I've updated my Emacs-Lisp code above to increase the chances that it solves your problem. Please give it a try. – Fran May 29 '12 at 17:16
  • Whooops, did not see your answer until now. I do not write JS anymore (I use CoffeeScript instead), but will give it a try nonetheless. – GodsBoss Jun 25 '12 at 14:52
  • Any way to get this working in Emacs 24? – Linus Arver Feb 1 '15 at 22:26
  • @opert, the above code should work in Emacs 24 too. Do you get an error when you use it? – Fran Mar 29 '15 at 18:51
  • @Fran, I ended up writing my own minor mode in Emacs called kakapo-mode to handle indentation settings in a central place (although some minor modes are hard to tame with just kakapo-mode). It replaces the commands for things like "RET", "TAB", etc. so it never touches the codepaths in js-mode-hook for those keys. IIRC the code above as-is did not work in Arch Linux at the time (before I installed kakapo-mode). – Linus Arver Mar 30 '15 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.