1

I know I can create a .clang-format file, and use this per project, but what I'd really like is a way to set the default clang-format style to one of the available formats, so I can experiment with various styles across various projects.

I would think something like setting a clang-format-style variable to "llvm" or "mozilla". Is soemthing like this possible?

Alternatively, can I do a key binding that calls clang-format-region specifying the formatting style?

Spacemoose
  • 877
  • 1
  • 7
  • 18
  • 1
    What package does clang-format-region come from? –  Aug 08 '15 at 12:41
  • `clang-format-region` is part of the `clang-format.el` package iirc. Also, it seems like `clang-format-region` already accepts a third parameter being the formatting style. (The two first ones being start and end of the region.) – Xaldew Mar 16 '16 at 09:08

2 Answers2

2

Use -style=<string> of clang-format:

Coding style, currently supports: LLVM, Google, Chromium, Mozilla, WebKit.

Use -style=file to load style configuration from .clang-format file located in one of the parent directories of the source file (or current directory for stdin).

Use -style="{key: value, ...}" to set specific parameters, e.g.: -style="{BasedOnStyle: llvm, IndentWidth: 8}"

Define a function with a style forwarded to clang-format-region. Then, bind it to a key:

(defun clang-format-region-mozilla (s e)
  (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point) (point))))
  (clang-format-region s e "Mozilla"))

(define-key c++-mode-map (kbd "C-<f10>") #'clang-format-region-mozilla)

(defun clang-format-region-llvm (s e)
  (interactive
   (if (use-region-p)
       (list (region-beginning) (region-end))
     (list (point) (point))))
  (clang-format-region s e "LLVM"))

(define-key c++-mode-map (kbd "C-<f11>") #'clang-format-region-llvm)

The upper example maps:

  • C-F10 to clang-format-region with the "Mozilla" style
  • C-F11 to clang-format-region with the "LLVM" style

Change the keys and the styles as it suits you.

0

Not sure I understand. Did you actually try setting clang-format-style? By default it's set to "file", so that it takes the style information from the .clang-format file.

You can keep it that way and create a .clang-format file with the BasedOnStyle variable set to whatever style you want to inherit from, that way you retain the ability to use different styles on different projects (e.g. open source projects that might use a style different from your preferred).

Jorge Israel Peña
  • 1,265
  • 9
  • 17