Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting different c-basic-offs for different projects

Tags:

emacs

I usually use 4 white spaces to indent C programs, but in order to keep in consistent with some open source projects, I have to change to 2-white-space indenting sometimes.

Currently my indenting style is assigned in my .emacs file with

(setq c-basic-offset 4)

And when I want to work on those 2-white-space indenting projects. I have to close my Emacs, modify the value, and start again. Is there any simpler way to do this?

Many thanks.


PS. Setting c-basic-offset variable every time I open a source file is too much work, is it possible to choose different value depending on working directory?

like image 306
ZelluX Avatar asked Feb 12 '26 16:02

ZelluX


2 Answers

Create a file in the directory you want to customize named .dir-locals.el, and edit it to contain:

((c-mode . ((c-basic-offset . 4))))

Note: This is new functionality in Emacs 23.1.

This takes advantage of the Per-Directory Local Variables. From the documentation in the link:

The .dir-locals.el file should hold a specially-constructed list. This list maps Emacs mode names (symbols) to alists; each alist specifies values for variables to use when the respective mode is turned on. The special mode name `nil' means that its alist applies to any mode. Instead of a mode name, you can specify a string that is a name of a subdirectory of the project's directory; then the corresponding alist applies to all the files in that subdirectory.

Here's an example of a .dir-locals.el file:

 ((nil . ((indent-tabs-mode . t)
          (tab-width . 4)
          (fill-column . 80)))
  (c-mode . ((c-file-style . "BSD")))
  (java-mode . ((c-file-style . "BSD")))
  ("src/imported"
   . ((nil . ((change-log-default-name . "ChangeLog.local"))))))
like image 146
Trey Jackson Avatar answered Feb 14 '26 05:02

Trey Jackson


Another approach is to have a style chooser alist like I have in my .emacs: http://github.com/stsquad/my-emacs-stuff/blob/master/my-c-mode.el#L103

You can also use buffer local variables in the source code to set these things, but that is generally dependant on the project your working on being happy having them in the source code.

like image 27
stsquad Avatar answered Feb 14 '26 07:02

stsquad