joaotavora / yasnippet

A template system for Emacs
http://joaotavora.github.io/yasnippet/
2.81k stars 311 forks source link

Template variables do not work in template lines starting with # #1183

Closed volodymyrprokopyuk closed 10 months ago

volodymyrprokopyuk commented 10 months ago

Hi,

Do template variables e.g. $1 work in lines that start with #?

I'm trying to create a snippet for source code blocks in org mode with the following template

# key: src
# --
#+BEGIN_SRC $1
  $0
#+END_SRC

When the snippet is inserted, the cursor is not placed in the $1 position to specify a language. Instead the cursor is moved to the beginning of a line like in the image below image

Is it possible to make the above template work as expected: specify a language at the $1 position and then move to the $0 position?

Thank you!

monnier commented 10 months ago

Do template variables e.g. $1 work in lines that start with #?

Yes.

I'm trying to create a snippet for source code blocks in org mode with the following template

# key: src
# --
#+BEGIN_SRC $1
  $0
#+END_SRC

When the snippet is inserted, the cursor is not placed in the $1 position to specify a language. Instead the cursor is moved to the beginning of a line like in the image below

If you look at *Messages*, you'll see that the expansion of your snippet encountered an error:

org-edit-src-code: No such language mode: nil-mode

With (setq debug-on-error t) you'll get a backtrace showing in more detail where this occurs:

Debugger entered--Lisp error: (error "No such language mode: nil-mode")
  signal(error ("No such language mode: nil-mode"))
  error("No such language mode: %s" nil-mode)
  org-edit-src-code()
  org-babel-do-key-sequence-in-edit-buffer("\11")
  org-indent-line()
  indent-according-to-mode()
  yas--indent-region(...)
  [...]

IOW, the problem is that Org-Babel doesn't know which language is used and burps. We should probably use a patch like the following:

diff --git a/yasnippet.el b/yasnippet.el
index 54616d4895..e6b9b9e9b0 100644
--- a/yasnippet.el
+++ b/yasnippet.el
@@ -4528,7 +4528,8 @@ The SNIPPET's markers are preserved."
                              remarkers)))
                    (unwind-protect
                        (progn (back-to-indentation)
-                              (indent-according-to-mode))
+                              (with-demoted-errors "%S"
+                                (indent-according-to-mode)))
                      (save-restriction
                        (narrow-to-region bol (line-end-position))
                        (dolist (remarker remarkers)

to try and be robust against such errors.

volodymyrprokopyuk commented 10 months ago

I understand that this error is a kind of chicken-egg problem:

I can see two possible solutions

monnier commented 10 months ago

It might be worth a bug report over in Org land, indeed, but I installed my patch so we won't be surprised by similar problems in other modes anyway.