How to force spaces instead of tabs regardless of major mode?

前端 未结 3 526
挽巷
挽巷 2020-12-31 18:45

I want all tabs to be 4 spaces. I have the following in .emacs

(setq-default indent-tabs-mode nil)
(setq c-basic-indent 4)
(setq tab-width 4)


        
相关标签:
3条回答
  • 2020-12-31 19:25

    Try this to overwrite whatever any major mode overwrites:

    (add-hook 'after-change-major-mode-hook 
              '(lambda () 
                 (setq-default indent-tabs-mode nil)
                 (setq c-basic-indent 4)
                 (setq tab-width 4)))
    

    Note though that major modes that aren't based on c-mode are not likely to care about c-basic-indent and may potentially use their own, mode-specific indentation variables. In such cases, there's no way around configuring these variables manually.

    0 讨论(0)
  • 2020-12-31 19:26

    Declare a default C indentation style, rather than declaring specific style parameters.

    (setq c-default-style "k&r2")  ;; or whatever your preference is
    (set-default 'indent-tabs-mode nil)
    
    0 讨论(0)
  • 2020-12-31 19:44

    I "solved" this problem with a particularly ugly hack. Rather than try to figure out how to get the right major mode hooks in place, I just did the following:

    (defun save-buffer-without-tabs ()
      (interactive)
      (untabify (point-min) (point-max))
      (save-buffer))
    (global-set-key "\C-x\C-s" 'save-buffer-without-tabs)
    

    This horribly breaks some things (that I care about, those things are Python and Makefiles). Thus, I also did the following:

    ;; restore the original save function for makefiles
    (add-hook 'makefile-mode-hook
      (lambda ()
        (define-key makefile-mode-map "\C-x\C-s" 'save-buffer)))
    
    ;; restore the original save function for python files
    (add-hook 'python-mode-hook
      (lambda () (define-key python-mode-map "\C-x\C-s" 'save-buffer)))
    

    I wasn't aware of the after-change-major-mode-hook mentioned by Thomas, but if his solution doesn't work for you for some reason, I've been using this for a few years now without incident.

    Edit: Upon closer inspection, I don't think you're asking exactly the question I answered. I guess nuking all the tabs is one way to get consistent indentation. :)

    0 讨论(0)
提交回复
热议问题