Search code examples
emacsyasnippet

Yasnippet snippet for C/C++ while doesn't work correctly


I have just installed yasnippet package for emacs and am trying to configure snippets. Everything works fine except one particular snipet.

File: ~/.emacs.d/elpa/yasnippet-20150212.240/snippets/cc-mode/while

# -*- mode: snippet -*-
# name: while
# key: while
# --
while (${1:condition})
{
    $0
}

The problem is that when I use the snippet the output is like this:

while(condition)
    {

    }

I checked if I have the correct file by changing the original while file to this:

# -*- mode: snippet -*-
# name: while
# key: while
# --
while (${1:condition})
{
    $0;
}

(semi-colon added) and the output was:

while(condition)
    {
        ;
    }

Why my braces have a tab behind them?

Note: Everything else works fine. For loops work fine, switch works fine, classes work fine... Only the while loop has a problem. Any ideas?


Solution

  • Found the answer. It was tricky for someone who just started using emacs like me.

    After taking a look here it seems that default c-style is something like this

    if(foo)
          {
            bar++;
          }
    

    so when I pressed tab to use the snippet I also auto formatted the code to the default c style. That's the "gnu" style. To change it to "linux" style just add

    (setq c-default-style "linux"
          c-basic-offset 4)
    

    to your .emacs or init.el file.

    Output after changes:

    if(foo)
    {
        bar++;
    }
    

    It had nothing to do with yasnippet after all.