I agree with Tyler; although it's a bit complicated, you would be better off in the long run if you try to understand and customize the default indentation features. The Emacs Wiki has good resources, and there are other relevant Q&As here on Stack Overflow.
Binding the tab key to insert-tab
means you completely lose the benefit of the likes of indent-region
, and any other intelligent behaviour that a major mode might offer.
To address your specific questions regardless, however:
1) If you are defining (java-insert-tab)
and (css-insert-tab)
and (javascript-insert-tab)
etc, and they all do exactly the same thing... well, hopefully you can see that you don't actually need more than one of those functions. Just give it a more generic name, and re-use it.
2) (local-set-key ...)
does the same thing as (define-key (current-local-map) ...)
, which means you can also have a single generic function to override the tab keybinding, regardless of the major mode.
(defun my-coding-config ()
(setq tab-width 4)
(setq indent-tabs-mode t)
(local-set-key (kbd "<tab>") 'my-insert-tab))
(defun my-insert-tab (&optional arg)
(interactive "P")
(insert-tab arg))
Then you just need to add my-coding-config
to each applicable mode hook variable. If there are a lot of them, you might wrap it up in a list like this:
;; Use my coding hook for all programming modes
(mapcar
(lambda (language-mode-hook)
(add-hook language-mode-hook 'my-coding-config))
'(java-mode-hook
javascript-mode-hook
css-mode-hook
...))
3) If you look at C-h v tab-width
RET and likewise for indent-tabs-mode
, you'll notice that they both say "Automatically becomes buffer-local when set in any fashion."
As an alternative to the customize interface already mentioned, you can use (set-default 'indent-tabs-mode t)
to establish the default value for such variables. In the absence of code which sets a buffer-local value, all of your buffers will use the default, which might help you to avoid writing unnecessary mode hooks.