purcell / emacs-reformatter

Define commands which run reformatters on the current Emacs buffer
259 stars 21 forks source link

Operate inplace on the original file #35

Closed floli closed 2 years ago

floli commented 2 years ago

Hello, clang-format has an option to give the header file, belonging to the current file a special treatment, e.g.:

#include "test.h"

#include <string>

given the file is test.cpp, the include is put on top and a newline is added.

Obviously, clang-format needs the file name for that to work and that's where my question about emacs-reformatter starts:

If I use:

(reformatter-define c++-clang-format
              :program "/usr/bin/clang-format-14"
              :stdin nil
              :stdout nil
              :args (list "--style=file" "-i" input-file)
            )

here, input-file will be some temp file and the required information is lost. Same problem, when I use stdin/stdout.

Is there a way to have the reformatter work inplace on the actual file?

Alternative

clang-format has the parameter --assume-filename:

clang-format-14 --style=file --assume-filename="test.cpp" < test.cpp 

produces the desired result. Is there a way I can access the original filename in the :args argument?

Thanks!

purcell commented 2 years ago

Is there a way to have the reformatter work inplace on the actual file?

Not every buffer is even associated with an actual file, so no.

Is there a way I can access the original filename in the :args argument?

Maybe something like this?

(reformatter-define c++-clang-format
  :program "clang-format-14"
  :args (list "--style=file" "-i" (concat "--assume-filename=" (file-name-nondirectory (or (buffer-file-name) input-file))))
  )
floli commented 2 years ago

Thanks, that did the trick:

(reformatter-define c++-clang-format
  :program "clang-format-14"
  :args (list "--style=file" (concat "--assume-filename=" (file-name-nondirectory (or (buffer-file-name) input-file))))
  )

(removed the -i as we are not modifying a file in-place)