Betrand Mathieus blog article on cleaning up trailing whitespace comes in handy for me as I’ve frequently run into problems with the Python test coverage tool stumbling over trailing whitespace. It also reminded me of an emacs snippet I recently installed to detect a mix of space and tabs in my Python buffers — I do set (setq indent-tabs-mode nil)
in my .emacs for python-mode, however, I still occasionally somehow manage to insert some tabs in my source buffers. So I came up with the following snippet which validates that a buffer in python-mode doesn’t contain any tabs. It’s hooked up with the very general write-file-hook, but there is no python-specific hook on saving buffers. In case the buffer does contain any tab, it will leave the point (the place where your cursor will be) at the fount tab.
; code snippet GUID 32F94179-A86B-4780-8645-8A526BD8533A
(defun no-tab-validation (buffer)
(interactive "bValidate buffer:")
(save-excursion
(unless (equal (buffer-name (current-buffer)) buffer)
(switch-to-buffer buffer))
(if (re-search-forward "\t" nil t)
(error "Buffer %s contains tabs" buffer))))
(defun py-tab-validate-on-save-hook ()
(when (equal mode-name "Python")
(no-tab-validation (buffer-name (current-buffer)))))
(add-hook 'write-file-hook 'py-tab-validate-on-save-hook)
;;; inhibit tabs in some modes
(defun set-indent-tabs-mode (value)
"Set indent-tabs-mode to value."
(setq indent-tabs-mode value))
(defun toggle-tabs ()
"Toggle `indent-tabs-mode'."
(interactive)
(set-indent-tabs-mode
(not indent-tabs-mode)))
(defun disable-tabs-mode ()
(set-indent-tabs-mode nil))
(add-hook 'sgml-mode-hook 'disable-tabs-mode)
(add-hook 'xml-mode-hook 'disable-tabs-mode)
(add-hook 'python-mode 'disable-tabs-mode)
No comments