brintos

brintos / llvm-project-archived public Read only

0
0
Text · 18.0 KiB · b356e1b Raw
450 lines · plain
1;;; clang-format.el --- Format code using clang-format  -*- lexical-binding: t; -*-2 3;; Version: 0.1.04;; Keywords: tools, c5;; Package-Requires: ((cl-lib "0.3"))6;; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception7 8;;; Commentary:9 10;; This package allows to filter code through clang-format to fix its formatting.11;; clang-format is a tool that formats C/C++/Obj-C code according to a set of12;; style options, see <http://clang.llvm.org/docs/ClangFormatStyleOptions.html>.13;; Note that clang-format 3.4 or newer is required.14 15;; clang-format.el is available via MELPA and can be installed via16;;17;;   M-x package-install clang-format18;;19;; when ("melpa" . "http://melpa.org/packages/") is included in20;; `package-archives'.  Alternatively, ensure the directory of this21;; file is in your `load-path' and add22;;23;;   (require 'clang-format)24;;25;; to your .emacs configuration.26 27;; You may also want to bind `clang-format-region' to a key:28;;29;;   (global-set-key [C-M-tab] 'clang-format-region)30 31;;; Code:32 33(require 'cl-lib)34(require 'xml)35(require 'vc-git)36 37(defgroup clang-format nil38  "Format code using clang-format."39  :group 'tools)40 41(defcustom clang-format-executable42  (or (executable-find "clang-format")43      "clang-format")44  "Location of the clang-format executable.45 46A string containing the name or the full path of the executable."47  :group 'clang-format48  :type '(file :must-match t)49  :risky t)50 51(defcustom clang-format-style nil52  "Style argument to pass to clang-format.53 54By default clang-format will load the style configuration from55a file named .clang-format located in one of the parent directories56of the buffer."57  :group 'clang-format58  :type '(choice (string) (const nil))59  :safe #'stringp)60(make-variable-buffer-local 'clang-format-style)61 62(defcustom clang-format-fallback-style "none"63  "Fallback style to pass to clang-format.64 65This style will be used if clang-format-style is set to \"file\"66and no .clang-format is found in the directory of the buffer or67one of parent directories. Set to \"none\" to disable formatting68in such buffers."69  :group 'clang-format70  :type 'string71  :safe #'stringp)72(make-variable-buffer-local 'clang-format-fallback-style)73 74(defcustom clang-format-on-save-p 'clang-format-on-save-check-config-exists75  "Only reformat on save if this function returns non-nil.76 77You may wish to choose one of the following options:78- `always': To always format on save.79- `clang-format-on-save-check-config-exists':80  Only reformat when \".clang-format\" exists.81 82Otherwise you can set this to a user defined function."83  :group 'clang-format84  :type 'function85  :risky t)86(make-variable-buffer-local 'clang-format-on-save-p)87 88(defun clang-format--extract (xml-node)89  "Extract replacements and cursor information from XML-NODE."90  (unless (and (listp xml-node) (eq (xml-node-name xml-node) 'replacements))91    (error "Expected <replacements> node"))92  (let ((nodes (xml-node-children xml-node))93        (incomplete-format (xml-get-attribute xml-node 'incomplete_format))94        replacements95        cursor)96    (dolist (node nodes)97      (when (listp node)98        (let* ((children (xml-node-children node))99               (text (car children)))100          (cl-case (xml-node-name node)101            (replacement102             (let* ((offset (xml-get-attribute-or-nil node 'offset))103                    (length (xml-get-attribute-or-nil node 'length)))104               (when (or (null offset) (null length))105                 (error "<replacement> node does not have offset and length attributes"))106               (when (cdr children)107                 (error "More than one child node in <replacement> node"))108 109               (setq offset (string-to-number offset))110               (setq length (string-to-number length))111               (push (list offset length text) replacements)))112            (cursor113             (setq cursor (string-to-number text)))))))114 115    ;; Sort by decreasing offset, length.116    (setq replacements (sort (delq nil replacements)117                             (lambda (a b)118                               (or (> (car a) (car b))119                                   (and (= (car a) (car b))120                                        (> (cadr a) (cadr b)))))))121 122    (list replacements cursor (string= incomplete-format "true"))))123 124(defun clang-format--replace (offset length &optional text)125  "Replace the region defined by OFFSET and LENGTH with TEXT.126OFFSET and LENGTH are measured in bytes, not characters.  OFFSET127is a zero-based file offset, assuming ‘utf-8-unix’ coding."128  (let ((start (clang-format--filepos-to-bufferpos offset 'exact 'utf-8-unix))129        (end (clang-format--filepos-to-bufferpos (+ offset length) 'exact130                                                 'utf-8-unix)))131    (goto-char start)132    (delete-region start end)133    (when text134      (insert text))))135 136;; ‘bufferpos-to-filepos’ and ‘filepos-to-bufferpos’ are new in Emacs 25.1.137;; Provide fallbacks for older versions.138(defalias 'clang-format--bufferpos-to-filepos139  (if (fboundp 'bufferpos-to-filepos)140      'bufferpos-to-filepos141    (lambda (position &optional _quality _coding-system)142      (1- (position-bytes position)))))143 144(defalias 'clang-format--filepos-to-bufferpos145  (if (fboundp 'filepos-to-bufferpos)146      'filepos-to-bufferpos147    (lambda (byte &optional _quality _coding-system)148      (byte-to-position (1+ byte)))))149 150(defmacro clang-format--with-delete-files-guard (bind-files-to-delete &rest body)151  "Execute BODY which may add temp files to BIND-FILES-TO-DELETE."152  (declare (indent 1))153  `(let ((,bind-files-to-delete nil))154     (unwind-protect155         (progn156           ,@body)157       (while ,bind-files-to-delete158         (with-demoted-errors "failed to remove file: %S"159           (delete-file (pop ,bind-files-to-delete)))))))160 161 162(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)163  "Return all line regions that contain diffs between FILE-ORIG and164FILE-NEW.  If there is no diff ‘nil’ is returned. Otherwise the return165is a ‘list’ of line ranges to format. The list of line ranges can be166passed to ‘clang-format--region-impl’"167  ;; Use temporary buffer for output of diff.168  (with-temp-buffer169    ;; We could use diff.el:diff-no-select here. The reason we don't170    ;; is diff-no-select requires extra copies on the buffers which171    ;; induces noticeable slowdowns, especially on larger files.172    (let ((status (call-process173                   diff-command174                   nil175                   (current-buffer)176                   nil177                   ;; Binary diff has different behaviors that we178                   ;; aren't interested in.179                   "-a"180                   ;; Get minimal diff (copy diff config for git-clang-format).181                   "-U0"182                   file-orig183                   file-new))184          (stderr (concat (if (zerop (buffer-size)) "" ": ")185                          (buffer-substring-no-properties186                           (point-min) (line-end-position))))187          (diff-lines '()))188      (cond189       ((stringp status)190        (error "clang-format: (diff killed by signal %s%s)" status stderr))191       ;; Return of 0 indicates no diff.192       ((= status 0) nil)193       ;; Return of 1 indicates found diffs and no error.194       ((= status 1)195        ;; Find and collect all diff lines.196        ;; We are matching something like:197        ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"198        (goto-char (point-min))199        (while (re-search-forward200                "^@@[[:blank:]]-[[:digit:],]+[[:blank:]]\\+\\([[:digit:]]+\\)\\(,\\([[:digit:]]+\\)\\)?[[:blank:]]@@$"201                nil202                t203                1)204          (let ((match1 (string-to-number (match-string 1)))205                (match3 (let ((match3_or_nil (match-string 3)))206                          (if match3_or_nil207                              (string-to-number match3_or_nil)208                            nil))))209            (push (cons match1 (if match3 (+ match1 match3) match1)) diff-lines)))210        (nreverse diff-lines))211       ;; Any return != 0 && != 1 indicates some level of error.212       (t213        (error "clang-format: (diff returned unsuccessfully %s%s)" status stderr))))))214 215(defun clang-format--vc-diff-get-vc-head-file (tmpfile-vc-head)216  "Stores the contents of ‘buffer-file-name’ at vc revision HEAD into217‘tmpfile-vc-head’. If the current buffer is either not a file or not218in a vc repo, this results in an error. Currently git is the only219supported vc."220  ;; We need the current buffer to be a file.221  (unless (buffer-file-name)222    (error "clang-format: Buffer is not visiting a file"))223 224  (let ((base-dir (vc-root-dir))225        (backend (vc-backend (buffer-file-name))))226    ;; We need to be able to find version control (git) root.227    (unless base-dir228      (error "clang-format: File not known to git"))229    (cond230     ((string-equal backend "Git")231      ;; Get the filename relative to git root.232      (let ((vc-file-name (substring233                           (expand-file-name (buffer-file-name))234                           (string-width (expand-file-name base-dir))235                           nil)))236        (let ((status (call-process237                       vc-git-program238                       nil239                       `(:file ,tmpfile-vc-head)240                       nil241                       "show" (concat "HEAD:" vc-file-name)))242              (stderr (with-temp-buffer243                        (unless (zerop (cadr (insert-file-contents tmpfile-vc-head)))244                          (insert ": "))245                        (buffer-substring-no-properties246                         (point-min) (line-end-position)))))247          (when (stringp status)248            (error "clang-format: (git show HEAD:%s killed by signal %s%s)"249                   vc-file-name status stderr))250          (unless (zerop status)251            (error "clang-format: (git show HEAD:%s returned unsuccessfully %s%s)"252                   vc-file-name status stderr)))))253     (t254      (error255       "Version control %s isn't supported, currently supported backends: git"256       backend)))))257 258 259(defun clang-format--region-impl (start end &optional style assume-file-name lines)260  "Common implementation for ‘clang-format-buffer’,261‘clang-format-region’, and ‘clang-format-vc-diff’. START and END262refer to the region to be formatter. STYLE and ASSUME-FILE-NAME are263used for configuring the clang-format. And LINES is used to pass264specific locations for reformatting (i.e diff locations)."265  (unless style266    (setq style clang-format-style))267 268  (unless assume-file-name269    (setq assume-file-name (buffer-file-name (buffer-base-buffer))))270 271  ;; Convert list of line ranges to list command for ‘clang-format’ executable.272  (when lines273    (setq lines (mapcar (lambda (range)274                          (format "--lines=%d:%d" (car range) (cdr range)))275                        lines)))276 277  (let ((file-start (clang-format--bufferpos-to-filepos start 'approximate278                                                        'utf-8-unix))279        (file-end (clang-format--bufferpos-to-filepos end 'approximate280                                                      'utf-8-unix))281        (cursor (clang-format--bufferpos-to-filepos (point) 'exact 'utf-8-unix))282        (temp-buffer (generate-new-buffer " *clang-format-temp*"))283        (temp-file (make-temp-file "clang-format"))284        ;; Output is XML, which is always UTF-8.  Input encoding should match285        ;; the encoding used to convert between buffer and file positions,286        ;; otherwise the offsets calculated above are off.  For simplicity, we287        ;; always use ‘utf-8-unix’ and ignore the buffer coding system.288        (default-process-coding-system '(utf-8-unix . utf-8-unix)))289    (unwind-protect290        (let ((status (apply #'call-process-region291                             nil nil clang-format-executable292                             nil `(,temp-buffer ,temp-file) nil293                             `("--output-replacements-xml"294                               ;; Guard against a nil assume-file-name.295                               ;; If the clang-format option -assume-filename296                               ;; is given a blank string it will crash as per297                               ;; the following bug report298                               ;; https://bugs.llvm.org/show_bug.cgi?id=34667299                               ,@(and assume-file-name300                                      (list "--assume-filename" assume-file-name))301                               ,@(and style (list "--style" style))302                               "--fallback-style" ,clang-format-fallback-style303                               ,@(and lines lines)304                               ,@(and (not lines)305                                      (list306                                       "--offset" (number-to-string file-start)307                                       "--length" (number-to-string308                                                   (- file-end file-start))))309                               "--cursor" ,(number-to-string cursor))))310              (stderr (with-temp-buffer311                        (unless (zerop (cadr (insert-file-contents temp-file)))312                          (insert ": "))313                        (buffer-substring-no-properties314                         (point-min) (line-end-position)))))315          (cond316           ((stringp status)317            (error "(clang-format killed by signal %s%s)" status stderr))318           ((not (zerop status))319            (error "(clang-format failed with code %d%s)" status stderr)))320 321          (cl-destructuring-bind (replacements cursor incomplete-format)322              (with-current-buffer temp-buffer323                (clang-format--extract (car (xml-parse-region))))324            (save-excursion325              (dolist (rpl replacements)326                (apply #'clang-format--replace rpl)))327            (when cursor328              (goto-char (clang-format--filepos-to-bufferpos cursor 'exact329                                                             'utf-8-unix)))330            (if incomplete-format331                (message "(clang-format: incomplete (syntax errors)%s)" stderr)332              (message "(clang-format: success%s)" stderr))))333      (with-demoted-errors334          "clang-format: Failed to delete temporary file: %S"335        (delete-file temp-file))336      (when (buffer-name temp-buffer) (kill-buffer temp-buffer)))))337 338 339;;;###autoload340(defun clang-format-vc-diff (&optional style assume-file-name)341  "The same as ‘clang-format-buffer’ but only operates on the vc342diffs from HEAD in the buffer. If no STYLE is given uses343‘clang-format-style’. Use ASSUME-FILE-NAME to locate a style config344file. If no ASSUME-FILE-NAME is given uses the function345‘buffer-file-name’."346  (interactive)347  (clang-format--with-delete-files-guard tmp-files348    (let ((tmpfile-vc-head nil)349          (tmpfile-curbuf nil))350      (setq tmpfile-vc-head351            (make-temp-file "clang-format-vc-tmp-head-content"))352      (push tmpfile-vc-head tmp-files)353      (clang-format--vc-diff-get-vc-head-file tmpfile-vc-head)354      ;; Move the current buffer to a temporary file to take a355      ;; diff. Even if current-buffer is backed by a file, we356      ;; want to diff the buffer contents which might not be357      ;; saved.358      (setq tmpfile-curbuf (make-temp-file "clang-format-vc-tmp"))359      (push tmpfile-curbuf tmp-files)360      (write-region nil nil tmpfile-curbuf nil 'nomessage)361      ;; Get a list of lines with a diff.362      (let ((diff-lines363             (clang-format--vc-diff-get-diff-lines364              tmpfile-vc-head tmpfile-curbuf)))365        ;; If we have any diffs, format them.366        (when diff-lines367          (clang-format--region-impl368           (point-min)369           (point-max)370           style371           assume-file-name372           diff-lines))))))373 374 375;;;###autoload376(defun clang-format-region (start end &optional style assume-file-name)377  "Use clang-format to format the code between START and END according378to STYLE.  If called interactively uses the region or the current379statement if there is no no active region. If no STYLE is given uses380`clang-format-style'. Use ASSUME-FILE-NAME to locate a style config381file, if no ASSUME-FILE-NAME is given uses the function382`buffer-file-name'."383  (interactive384   (if (use-region-p)385       (list (region-beginning) (region-end))386     (list (point) (point))))387  (clang-format--region-impl start end style assume-file-name))388 389;;;###autoload390(defun clang-format-buffer (&optional style assume-file-name)391  "Use clang-format to format the current buffer according to STYLE.392If no STYLE is given uses `clang-format-style'. Use ASSUME-FILE-NAME393to locate a style config file. If no ASSUME-FILE-NAME is given uses394the function `buffer-file-name'."395  (interactive)396  (clang-format--region-impl397   (point-min)398   (point-max)399   style400   assume-file-name))401 402;;;###autoload403(defalias 'clang-format 'clang-format-region)404 405;; Format on save minor mode.406 407(defun clang-format--on-save-buffer-hook ()408  "The hook to run on buffer saving to format the buffer."409  ;; Demote errors as this is user configurable, we can't be sure it wont error.410  (when (with-demoted-errors "clang-format: Error %S"411          (funcall clang-format-on-save-p))412    (clang-format-buffer))413  ;; Continue to save.414  nil)415 416(defun clang-format--on-save-enable ()417  "Disable the minor mode."418  (add-hook 'before-save-hook #'clang-format--on-save-buffer-hook nil t))419 420(defun clang-format--on-save-disable ()421  "Enable the minor mode."422  (remove-hook 'before-save-hook #'clang-format--on-save-buffer-hook t))423 424;; Default value for `clang-format-on-save-p'.425(defun clang-format-on-save-check-config-exists ()426  "Return non-nil when `.clang-format' is found in a parent directory."427  ;; Unlikely but possible this is nil.428  (let ((filepath buffer-file-name))429    (cond430     (filepath431      (not (null (locate-dominating-file (file-name-directory filepath) ".clang-format"))))432     (t433      nil))))434 435;;;###autoload436(define-minor-mode clang-format-on-save-mode437  "Clang-format on save minor mode."438  :global nil439  :lighter ""440  :keymap nil441 442  (cond443   (clang-format-on-save-mode444    (clang-format--on-save-enable))445   (t446    (clang-format--on-save-disable))))447 448(provide 'clang-format)449;;; clang-format.el ends here450