I normally only use spaces to indent but sometimes I have to edit a file that contains tabs and I don’t want to break the existing indentation. In this situation Emacs’ whitespace-mode is very useful for showing exactly which whitespace characters are present in a file. But I don’t want to enable it all the time so I use this little function to check automatically if a file contains tabs, and if so enable whitespace-mode
and also indent-tabs-mode
so that any new lines are indented with tabs as well.
(defun check-for-tabs () "Enable whitespace-mode and indent-tabs-mode if the buffer contains tabs." (when (save-excursion (goto-char (point-min)) (search-forward "\t" nil t)) (whitespace-mode +1) (setq-local indent-tabs-mode t))) (add-hook 'find-file-hook #'check-for-tabs)