Mac – How to define a shortcut (key combination) to insert “” in Emacs

elispemacskey-bindingshortcuts

I want to define a shortcut to enter XML tag pairs. Pressing key combination key1key2 which should prompt for entering a tag name, .e.g. "foo", and automatically insert "<foo></foo>". How to do that?

Ideally I'd like the cursor to be automatically moved to be after the first >.

Best Answer

  • If you use YASnippet in xml-mode it already contains a snippet for the functionality you ask for.

    Enter the following

    tag
    

    press Tab and choose <tag>...</tag> for an inline XML tag or <tag>\n...\n</tag> for a tag on its own line and what you entered turns into

    <tag></tag>
    

    or

    <tag>
    
    </tag>
    

    respectively. As what you have entered turns into either the name for the opening tag is marked and you can enter whatever tag name you want and it will copied to the closing tag too. When you are done entering the tag name you press Tab and the cursor is placed between the tags so that you can enter content to the tag. When you are done entering content in the tag you press Tab again to place the cursor after the closing tag.

    Note that if you want to customize the behavior of these snippet it is easy. Use the YASnippet menu to find the snippets in question and then edit them to fit your needs.

    To get the said snippets in any other mode you can create them for that mode by doing as follows:

    1. Add the following to your .emacs:

      (setq yas/root-directory "~/.emacs.d/mysnippets"); Develop and keep personal snippets under ~/emacs.d/mysnippets
      (yas/load-directory yas/root-directory); Load the snippets
      

      If you prefer to keep your snippet in another directory go ahead and choose another.

    2. Enter the mode you want the snippets in.

    3. Do M-x yas/new-snippet.
    4. Enter the name tag.1l
    5. You will now get a chance to edit the snippet. Mark everything by doing C-x h, then kill it by C-w.
    6. You will now have an empty snippet. Paste the following into it and make sure the snippet ends after $0 and not on a new line:

      #name: <tag>...</tag>
      #key: tag
      # --
      <${1:tag}>$2</$1>$0
      
    7. Do C-c C-c to save and load the snippet.

    8. Do step 3 to 7 but instead use the name tag.2l and instead paste in the following:

      #name: <tag> \n...\n</tag>
      #key: tag
      # --
      <${1:tag}>
        $2
      </$1>$0
      

    Note that the key yasnippet uses for expansion, Tab, is bound to another function in markdown-mode by default. Thus you either have to use a fix such as http://calas.github.com/2009/11/20/using-yasnippets-in-markdown-mode.html or bind yas/expand to a key of your preference.

    The following animation shows how the first snippet works:

    Animation of the snippet <${1:tag}>$2</$1>$0

  • Related Question