reddit / emacs

How do you change bracing style for C in yasnippets

Schievel1 · 2022-07-13 15:06
[removed]
Schievel1 · 2022-07-13 20:56
Fiddled around some time, now I got it working somewhat. The code in the link is basically right, but I had to change whatacold/style-braces-in-allman, because my elisp doesnt seem to know the keyword case. But it does know pcase. Also the whatacold/yasnippet-exit-hook-c function calls indentation on the snippets at the end. This puts the braces back into the line with the conditional immidiately. So I removed that and called c-indent-defun instead. This is what I came up with: ``` (defun whatacold/style-braces-in-allman (snippet) "Style the SNIPPET in allman brace style. There are roughly 3 basic brace styles: - Attached: The braces are attached to the end of the last line of the previous block. (Java). - Broken: The braces are broken from the previous block. (Allman). - Linux: The braces are attached except for the opening brace of a function, class, or namespace (K&R, Linux). http://astyle.sourceforge.net/astyle.html#_Basic_Brace_Styles" (let ((len (length snippet)) (i 0) chars char new-str) (while (< i len) (setq char (aref snippet i)) (pcase char (?{ (push ?\n chars) (push char chars)) (?} (push ?\n chars) (push char chars) (push ?\n chars)) (t (push char chars))) (setq i (1+ i))) (setq new-str (replace-regexp-in-string "[\n \t]+\n" "\n" (apply #'string (nreverse chars)))) new-str)) (defcustom whatacold/yasnippet-c-style nil "Style of curly braces, e.g. 'allman." :type '(symbol)) (defun whatacold/yasnippet-exit-hook-c () (let* ((text-marker "the-yasnippet-exit-point;") ; workaround. text property is more elegant. (begin yas-snippet-beg) (end yas-snippet-end) (snippet (buffer-substring-no-properties begin end)) new-snippet) (when (and (string-match "[{}]" snippet) (eq 'allman whatacold/yasnippet-c-style)) (forward-line) (insert text-marker) (setq end (+ yas-snippet-end (length text-marker))) (setq snippet (buffer-substring-no-properties begin end)) ; re-fetch content (setq new-snippet (whatacold/style-braces-in-allman snippet)) (delete-region begin end) (insert new-snippet) (goto-char begin) ;; re-indent it in the context ;; (indent-region begin (+ end (- (length new-snippet) ;; (length snippet)))) (re-search-forward text-marker) (delete-char (- 0 (length text-marker))) (c-indent-defun)))) (defun whatacold/yasnippet-exit-hook () "My yasnippet exit hook." (when (or (eq major-mode 'c-mode) (eq major-mode 'c++-mode)) (whatacold/yasnippet-exit-hook-c))) ;; see https://github.com/joaotavora/yasnippet/issues/728 ;; (after! c-or-c++-mode) ;; (setq yas-after-exit-snippet-hook 'whatacold/yasnippet-exit-hook) (setq whatacold/yasnippet-c-style 'allman) ```