Function: tabify

tabify is an autoloaded, interactive and byte-compiled function defined in tabify.el.gz.

Signature

(tabify START END &optional ARG)

Documentation

Convert multiple spaces in region to tabs when possible.

A group of spaces is partially replaced by tabs when this can be done without changing the column they end at. If called interactively with prefix ARG, convert for the entire buffer.

Called non-interactively, the region is specified by arguments START and END, rather than by the position of point and mark. The variable tab-width controls the spacing of tab stops.

View in manual

Key Bindings

Source Code

;; Defined in /usr/src/emacs/lisp/tabify.el.gz
;;;###autoload
(defun tabify (start end &optional _arg)
  "Convert multiple spaces in region to tabs when possible.
A group of spaces is partially replaced by tabs
when this can be done without changing the column they end at.
If called interactively with prefix ARG, convert for the entire
buffer.

Called non-interactively, the region is specified by arguments
START and END, rather than by the position of point and mark.
The variable `tab-width' controls the spacing of tab stops."
  (interactive (if current-prefix-arg
		   (list (point-min) (point-max) current-prefix-arg)
		 (list (region-beginning) (region-end) nil)))
  (save-excursion
    (save-restriction
      ;; Include the beginning of the line in the narrowing
      ;; since otherwise it will throw off current-column.
      (goto-char start)
      (beginning-of-line)
      (narrow-to-region (point) end)
      (goto-char start)
      (let ((indent-tabs-mode t))
        (while (re-search-forward tabify-regexp nil t)
          ;; The region between (match-beginning 0) and (match-end 0) is just
          ;; spacing which we want to adjust to use TABs where possible.
          (let ((end-col (current-column))
                (beg-col (save-excursion (goto-char (match-beginning 0))
                                         (skip-chars-forward "\t")
                                         (current-column))))
            (if (= (/ end-col tab-width) (/ beg-col tab-width))
                ;; The spacing (after some leading TABs which we wouldn't
                ;; want to touch anyway) does not straddle a TAB boundary,
                ;; so it neither contains a TAB, nor will we be able to use
                ;; a TAB here anyway: there's nothing to do.
                nil
              (delete-region (match-beginning 0) (point))
              (indent-to end-col))))))))