@@ -70,6 +70,20 @@ in such buffers."
7070 :safe #'stringp )
7171(make-variable-buffer-local 'clang-format-fallback-style )
7272
73+ (defcustom clang-format-on-save-p 'clang-format-on-save-check-config-exists
74+ " Only reformat on save if this function returns non-nil.
75+
76+ You may wish to choose one of the following options:
77+ - `always' : To always format on save.
78+ - `clang-format-on-save-check-config-exists' :
79+ Only reformat when \" .clang-format\" exists.
80+
81+ Otherwise you can set this to a user defined function."
82+ :group 'clang-format
83+ :type 'function
84+ :risky t )
85+ (make-variable-buffer-local 'clang-format-on-save-p )
86+
7387(defun clang-format--extract (xml-node )
7488 " Extract replacements and cursor information from XML-NODE."
7589 (unless (and (listp xml-node) (eq (xml-node-name xml-node) 'replacements ))
@@ -217,5 +231,50 @@ the function `buffer-file-name'."
217231;;;### autoload
218232(defalias 'clang-format 'clang-format-region )
219233
234+ ; ; Format on save minor mode.
235+ ; ;
236+ ; ; Optional minor mode for formatting on save.
237+
238+ (defun clang-format--on-save-buffer-hook ()
239+ " The hook to run on buffer saving to format the buffer."
240+ ; ; Demote errors as this is user configurable, we can't be sure it wont error.
241+ (when (with-demoted-errors " clang-format-on-save: Error %S"
242+ (funcall clang-format-on-save-p))
243+ (clang-format-buffer))
244+ ; ; Continue to save.
245+ nil )
246+
247+ (defun clang-format--on-save-enable ()
248+ " Disable the minor mode."
249+ (add-hook 'before-save-hook #'clang-format--on-save-buffer-hook nil t ))
250+
251+ (defun clang-format--on-save-disable ()
252+ " Enable the minor mode."
253+ (remove-hook 'before-save-hook #'clang-format--on-save-buffer-hook t ))
254+
255+ ; ; Default value for `clang-format-on-save-p' .
256+ (defun clang-format-on-save-check-config-exists ()
257+ " Return non-nil when `.clang-format' is found in a parent directory."
258+ ; ; Unlikely but possible this is nil.
259+ (let ((filepath buffer-file-name))
260+ (cond
261+ (filepath
262+ (null (null (locate-dominating-file (file-name-directory filepath) " .clang-format" ))))
263+ (t
264+ nil ))))
265+
266+ ;;;### autoload
267+ (define-minor-mode clang-format-on-save-mode
268+ " Clang-format on save minor mode."
269+ :global nil
270+ :lighter " "
271+ :keymap nil
272+
273+ (cond
274+ (clang-format-on-save-mode
275+ (clang-format--on-save-enable))
276+ (t
277+ (clang-format--on-save-disable))))
278+
220279(provide 'clang-format )
221280; ;; clang-format.el ends here
0 commit comments