Overwrite dooms yasnippets


I am working in a company where we have a religion of putting the { in C-Code on the beginning of the next line after an if:

if (true)


instead of

if (false) {

Dooms yasnippets all use the second form. How do I go about changing this?

Thanks for your help!

Do your workspace have .clang-format file? Then this shouldn’t be a problem.

No it doesn’t but I could add one.

So, I found this:


Which is exactly what I need, I think. But it doesn’t work. I put it into my config.el.

I edited the code a bit, now it works fine:

(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).

  (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))
         (push char chars)))
      (setq i (1+ i)))
    (setq new-str (replace-regexp-in-string "[\n \t]+\n"
                                            (apply #'string (nreverse chars))))

(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))
    (when (and (string-match "[{}]" snippet)
               (eq 'allman whatacold/yasnippet-c-style))
      (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)))

(defun whatacold/yasnippet-exit-hook ()
  "My yasnippet exit hook."
  (when (or (eq major-mode 'c-mode))
    (eq major-mode 'c++-mode)
;; 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)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.