简体   繁体   中英

emacs: Want to indent with tabs (tab-size 2 or 4) allign with spaces

I use emacs now for a while and like it in most cases (useful on ssh, syntax highlight, ...).

But when it comes to indentation and justification (alignment) of code, I don't get clear with emacs.

I want in all my code (SQL, C, Java, ECMAScript, HTML, PHP, CSS, ...) that a press of the "TAB" key realy makes a TAB character (which I usually have a size of 2 spaces, but 4 or 6 are good as well). [I agree, that TABs in Code are evil when it comes to alignment, but spaces are evil as well, when it comes to indentation!] You can have a look, how I want to have it in my HTML template: https://github.com/pheek/HTMLTemplate/blob/master/ template .html

On the other hand I always align with spaces, so other programmers have all the equal signs properly aligned in my code. This works fine, except for 2 exceptions:

  1. To enter a TAB-Char I always have to press "CTRL-q TAB", which is annoying.
  2. Different programming languages are configured in emacs to use different TAB sizes. For myself, I always want to behave a TAB to be the size of 2 spaces.

How can I achieve that

a) a press of the TAB-Key always inserts a TAB-Char?

b) TABs are in all emacs-modes (c, java, html, php, css, ecmascript, ...) 2 chars wide?

As @lawlist says, it's different for every major mode. Each one usually has its own indent-line-function , and settings like tab-width are buffer local.

There's a smart-tabs package ( https://github.com/jcsalomon/smarttabs ) that works well for me, but I only use it for C-like modes (which is not to say it doesn't work for others, I just haven't tried).

(use-package smart-tabs-mode
  :commands (smart-tabs-mode)
  :init
  (add-hook 'c-mode-common-hook #'smart-tabs-mode)
  :config
  (smart-tabs-advice c-indent-line     c-basic-offset)
  (smart-tabs-advice c-indent-region   c-basic-offset)
  )

tab-width should be set to your preferred width globally, and can be changed in major mode hooks to be different in some modes.

(setq-default tab-width 2)

(defun jpk/c-mode-common-hook ()
   (setq tab-width 4))
(add-hook 'c-mode-common-hook #'jpk/c-mode-common-hook)

a) Set the value of indent-tabs-mode to non-nil in your emacs configuration file. (setq-default indent-tabs-mode t) should do the trick. https://www.gnu.org/software/emacs/manual/html_node/emacs/Indentation.html

b) Similarly, set the value of tab-width to the desired width. (setq-default tab-width 2) in your case. https://www.gnu.org/software/emacs/manual/html_node/efaq/Changing-the-length-of-a-Tab.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM