Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring a Yasnippet for two scenarios -- (1) region is active; (2) region is not active

In conjunction with a user-configuration of (delete-selection-mode 1), is there a way to consolidate the two following Yasnippets into just one snippet so that it will work differently depending upon whether the region is active. For example: (if (region-active-p) (yas/selected-text) "$1")

Active region -- surround the active region with the snippet:

# -*- mode: snippet -*-
# contributor: lawlist
# key: bold_selected
# name: bold_selected
# binding: C-I b b s
# --
{\bf `yas/selected-text`}

Non-active region -- insert the snippet and place the cursor at the position of $1:

# -*- mode: snippet -*-
# contributor: lawlist
# key: bold
# name: bold
# binding: C-I b b b
# --
{\bf $1}
like image 945
lawlist Avatar asked Dec 03 '25 10:12

lawlist


2 Answers

Back-ticks surrounding the elisp code to be evaluated are required. The built-in variable yas-selected-text stores the text of the selected region, which can be used to reinsert the same text during the snippet creation. Four (4) backslashes are needed for every one (1) backslash.

# -*- mode: snippet -*-
# contributor: lawlist
# key: bold
# name: bold
# binding: TAB <f6>
# --
`(if (region-active-p)
   (concat
     "{\\\\bf "
     yas-selected-text
     "}")
   "{\\\\bf $1}")`
like image 168
lawlist Avatar answered Dec 06 '25 06:12

lawlist


# -*- mode: snippet -*-
# name: bold
# key: bold
# type: command
# --
(if (region-active-p)
    (yas-expand-snippet "{\\bf `yas-selected-text`}")
  (yas-expand-snippet "{\\bf $0}"))
like image 26
jpkotta Avatar answered Dec 06 '25 05:12

jpkotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!