I recently watched this fantastic video on how to use Yasnippet in Emacs.
Specifically, what are the if
and string-match
elisp conditionals/functions doing in regards to the intended use of this snippet?
This snippet is found in Yasnippet c++-mode > printf.
# -*- mode: snippet -*-
# name: printf
# key: printf
# --
printf("${1:%s}\\n"${1:$(if (string-match "%" yas-text) ", " "\);")
}$2${1:$(if (string-match "%" yas-text) "\);" "")}
So it should work if you can load it into the mode properly (there are a few yasnippet modes that failed to load properly for me -- if all else fails, in the snippet file itself use M-x yas-load-snippet-buffer
and see if that works.)
As for the macro, the second argument is basically conditional on the first one containing a "%" sign. If it does, then a comma is inserted after the closing quote and you jump there hitting tab from the string you are editing. If it does not contain a % anywhere in it, then it's removed. In other words:
If you type "hello world" into the first parameter (the string) with no %s you get:
printf("hello world\n");
with no second value to fill in. However, if you add a %s, you'll get the cursor placed after the ,
to fill in the second when you hit tab (where I typed CURSORHERE):
printf("hello %s\n", CURSORHERE));