# Make yasnippet context sensitive

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.

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)) "dunno"))  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 # -- \py[(my/latex-last-pycode-session)]{$0}