2

I currently have a tex.snippets file to hold snippets which make writing homework in LaTeX easier. For example, I have a snippet '2problem' of the form:

snippet 2problem
    \begin{homeworkProblem}
        \begin{enumerate}
            \item[] $1
                $2
            \item[] $3
                $4
        \end{enumerate}
    \end{homeworkProblem}
endsnippet

This gives me an easy way of starting 2-part problems. Is there a way, however, of making a snippet that outputs n-part problems? Right now I have separate snippets for separate number of problems, which is quite tedious.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Leeren
  • 1,931
  • 2
  • 20
  • 31

2 Answers2

0

I know, this is not an ultisnip solution, just in case : mu-template supports loops and recursion in snippets. That how I generate a switch-case construct from an enum definition in C and C++. It's kind of cumbersome to define, but it works well.

Luc Hermitte
  • 31,979
  • 7
  • 69
  • 83
0

Use the snippet definition as:

post_jump "dynamicsnippet(snip)"
snippet '(\d+)problem' rb
        \begin{homeworkProblem}
                \begin{enumerate}
`!p snip.rv=create_partprob(int(match.group(1)))`
                \end{enumerate}
        \end{homeworkProblem}
endsnippet

Attach this piece of code at the end of the desired snippets file.(Probably something like tex.snippets)

global !p
def dynamicsnippet(snip):
    # Create anonymous snippet body
    anon_snippet_body = ""

    # Get start and end line number of expanded snippet
    start = snip.snippet_start[0]
    end = snip.snippet_end[0]

        # Append current line into anonymous snippet
    for i in range(start, end + 1):
        anon_snippet_body += snip.buffer[i]
        anon_snippet_body += "" if i == end else "\n"

    # Delete expanded snippet line till second to last line
    for i in range(start, end):
        del snip.buffer[start]

    # Empty last expanded snippet line while preserving the line
    snip.buffer[start] = ''

    # Expand anonymous snippet
    snip.expand_anon(anon_snippet_body)
def create_partprob(n):
 out=""
 placeholder=1
 for _ in range(0,n):
   out+=24*" "+"\\item[] $"+f"{placeholder}\\\\\\\\\n"
   placeholder+=1
   out+=24*" "+"   $"+f"{placeholder}\\\\\\\\\n"
   placeholder+=1
 out=out[:-1]
 return out
endglobal

It worked in my editor and Ultisnips, hope it works in yours as well. Goodluck!

Edit: Use the stack specifically made for vim and vi related questions for such questions. You can find the site here.