In LaTeX I often use pythontex in a way that there is a block \begin{pycode}[sessionname] ... \end{pycode} where I make some calculations. Then in the following text I refer to variables defined there for example via \py[sessionname]{Variable}.

Now I can make a yas-snippet that expands for example py to \py[]{}. But then I have to manually insert the session name.

So how can I make a snipped which looks backwards and automatically inserts the session name of the previous pycode environment while expanding py?

If there is another snipped package which can do this, I am interested in it too.


You can do this by embedding elisp.

Here's a quick and dirty function that returns the session name from the last begin{pycode} line.

(defun my/latex-last-pycode-session ()
  (or (and (re-search-backward "^\\\\begin{pycode}\\[\\(.+\\)\\]\\s-*$" nil t)
           (match-string 1))

There might be latex-mode functions/variables (e.g., a function that says "am I in a block?") that you could use here, but the above will do to demonstrate how you can get your desired behavior with yasnippet.

Then you can use this function in your snippet:

# key: py
# --

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.