Bitdiot
Bitdiot

Reputation: 1598

How to set emacs indentation level in function

I don't understand emacs, but I have the following function in a file:

;;; File: emacs-format-file
;;; Stan Warford
;;; 17 May 2006

(defun emacs-format-function ()
   "Format the whole buffer."
;;;   (c-set-style "stroustrup")
   (indent-region (point-min) (point-max) nil)
   (untabify (point-min) (point-max))
   (delete-trailing-whitespace)
   (save-buffer)
)

I then run this function in a batch script. Here's the code snip:

echo "Indenting $1 with emacs in batch mode"
emacs -batch $1 -l $eprog_format -f emacs-format-function
echo

I use this code to format my c/c++ files and headers. I like to change it so that I can hardcode the level of indentation into the function, that way I can run this code to conform to whatever indentation rule for whatever company I am currently writing code for. Or pass it in as argument?

I just don't know how to do this. Is there a way? My current .emacs has:

; Suppress tabs.
(setq-default indent-tabs-mode nil)

I don't want to add indentation levels in my .emacs. I like to keep the default emacs indentation. I want the emacs script to customize the indentaion before I "ship it ".

thanks.

Upvotes: 0

Views: 410

Answers (1)

nanny
nanny

Reputation: 1108

You can do this with the variable c-basic-offset and a let binding. Here is an example of how let works:

    (setq original "Hello")

    (message "%s" original)
    "Hello"

    (defun temp-set-var (arg)
      (let ((original arg))
        (message "%s" original)))

    (temp-set-var "Goodbye")
    "Goodbye"

    (message "%s" original)
    "Hello"

Even though I called (message "%s" original) three times, it outputted a different string the second time because I temporarily set original to arg in the function with let.

So maybe your format function could be:

    (defun emacs-format-function (indent)
      "Format the whole buffer."
    ;;;   (c-set-style "stroustrup")
      (let ((c-basic-offset indent))
        (indent-region (point-min) (point-max) nil))
      (untabify (point-min) (point-max))
      (delete-trailing-whitespace)
      (save-buffer))

Then call it like:

emacs -batch $1 -l $eprog_format --eval="(emacs-format-function 8)"

Upvotes: 1

Related Questions