joaotavora / yasnippet

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

[Question][Probably duplicate]Edit already typed code with yasnippet #1083

Open irigone opened 4 years ago

irigone commented 4 years ago

I tried to find that in issues but couldn't :( I use this snippet

# -*- mode: snippet -*-
# name: class(parent): ...
# key: class
# group: Definitions
# --
class ${1:ClassName}:
    """${3:Documentation for $1}

    """
    def __init__(self${4:, args}):
        ${4:$(elpy-snippet-init-assignments yas-text)}
        $0

I have this code:

class Student:
   def __init__(self,fullname):
       self._fullname = re.sub(' +', ' ', fullname)
       self._lastname = fullname.split(' ')[1]

   def get_fullname(self):
       return self._fullname

I want to add a property called "grade" in that class. So I type ,grade to the right of fullname (in the __init__ part). I want yasnippet to somehow track that (either automatically or by a shortcut) and add self._grade = grade under other self.something thingies. How hard is that and how do I achieve it?

joaotavora commented 3 years ago

How hard is that and how do I achieve it?

It's not extremely hard, but you have to type some elisp. You have to decide on a snippet trigger, or a keybinding. As you say, on a way to trigger the snippet. Then you have to write an elisp function that parses the __init__ definition, finds a suitable spot to put the new the new self._$1 = $1 bit, and dinamicallly generates a snippet that contains the text you want to preserve + the new bits you want to add.

Then you call yas-expand-snippet on that.

irigone commented 3 years ago

Alright, I'll write it today but when I wake up (3 AM already)