What's new? | Help | Directory | Sign in
Google
smart-snippet
Textmate-like Emacs template extension with smarter behavior
  
  
  
  
    
Search
for
Updated May 06, 2007 by pluskid.zju
Labels: Featured, Phase-Deploy
TipForIndentation  

#Tip on how to do indentation correctly.

Problems

You may notice, with the default behavior of snippet.el, sometimes indentation is incorrect. For example, if you define such a snippet for c++

(smart-snippet-with-abbrev-table 'c++-mode-abbrev-table
  ("class"
   "class $${name}
{$>
public:$>
    $${name}()$>
    {$>
       $>$.
    }$>
};$>"
   'bol?))

if will expand and indent uglily like this

class foo
{
public:
    foo()
            {
                
                    }
};

This is because indentation is done when there are still "garbage" text like "$" and "{" which can make Emacs confused.

Solution

Use different identifiers for different language

The solution is to reassign the identifiers to something else(it is buffer-local, so you can set it to different value in a mode-hook according to different major-mode):

 (add-hook 'c++-mode-hook
   (lambda ()
     (setq snippet-field-default-beg-char ?\()
     (setq snippet-field-default-end-char ?\))
     (setq snippet-exit-identifier "$;")))
 
 (smart-snippet-with-abbrev-table 'c++-mode-abbrev-table
   ("class"
    "class $$(name)
 {$>
 public:$>
     $$(name)()$>
     {$>
        $>$;
     }$>
 };$>"
    'bol?))

This will work fine. And you can choose appropriate characters for different major-mode(language).

I like identical syntax to define snippet even for different language

NOTE: this modified version of snippet-insert has been incorporated into trunk since revision 8. So there's no need to check the old revision 4 any more!

If you don't like to use different syntax(identifier) for different language, you may try the revision 4 of smart-snippet.el. It redefined the snippet-insert function in snippet.el in order to make it indent correctly(first remove those identifiers then do inent). It works fine so far. But in order to keep the modification to snippet.el minor, I decide not to use this method and only set some variables buffer local in newer version of snippet.el(thus we can use different identifier for different mode).

You can get the revision 4 of smart-snippet.el by svn:

svn co -r4 http://smart-snippet.googlecode.com/svn/trunk/ smart-snippet

or you can download directly from this link.


Sign in to add a comment