3

I recently watched this fantastic video on how to use Yasnippet in Emacs.

Can someone explain how to use this snippet?

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) "\);" "")}
Jordan
  • 73
  • 7
  • 1
    the `$2` isn't conditional - it has no effect on the `$1` parameter. Fields that have the form `${:$(...)}` are conditional on previous fields with matching `num` and `yas-text` is bound to the value of the first `${1}` field while the contained elisp is evaluated. So, here, both the mirrored fields (with elisp code) are conditional on the first `${1:"%s"}` as explained below – Rorschach May 25 '21 at 22:00
  • The question seems too broad. Can you pose a more specific question, e.g. about how to use `if` or `string-match`, or whatever specific how-to you're wondering about? – Drew May 25 '21 at 23:44
  • Please refrain from using images, instead of code. Here is a [list of reasons why](https://meta.stackoverflow.com/a/285557/3578036). – JustCarty May 26 '21 at 12:14
  • 1
    @JustCarty - I've edited the question based on your suggestions. Can you please reopen this question? – Jordan May 27 '21 at 23:55

1 Answers1

2

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)); 
Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69