When trying to edit the existing snippets in gedit the changes was  gone the next time I opened gedit. It turns out that the predefined snippets is located in /usr/share/gedit-2/plugins/snippets/ (I’m running Ubuntu 8.04). To edit these files you need root access, which gedit doesn’t have (unless you do “sudo gedit” or something). To fix this I moved the snippet files from /usr/share/gedit-2/plugins/snippets/ into ~/.gnome2/gedit/snippets/. Fix in terminal:

sudo cp /usr/share/gedit-2/plugins/snippets/* ~/.gnome2/gedit/snippets

It’s probably possible to change the permission of the files too.

In TextMate and in gedit (probably more editors too) you have the option to use snippets. I love snippets, and they make my day much easier.

To make a snippet you have to define a tab-trigger which is a word or a random sequence of characters that you will remember. Then you have to write the snippet body.

Easy example: If and else statements. When you write “ife” and press tab you want an if-else statement to pop up. We write the snippet:

if($1)
  1. {
  2.     $2
  3. }
  4. else
  5. {
  6.     $0
  7. }

$0, $1 and $2 are where the cursor will be placed. When you first type “ife” and press the tab button the cursor will be where the $1 is. If you hit tab again the cursor moves to $2 and so on, but you always ends up at $0. Now you can use this snippet whenever you need it. Just write “ife” press tab and fill inn the code you need.

More advanced example: Lets say you are getting tired of writing all the code for a for loop every time you need one. Make a snippet!. We set the tab-trigger to be the string “for” and write the snippet:

for (\$${1:i}=${2:0}; \$${1:i} < $3; \$${1:i}++)
  1. {
  2.     $0
  3. }

What the ${1:i} does is that it sets the 1st cursor position and sets a default value (“i” in this case). The default value is marked, so when you tab to the position you can immediately overwrite the default text. And an other thing in this example worth mentioning is that we use ${1:i} more than once. This enables you to change the default at more than one place at once. Let’s say you don’t want your variable called “i”, but “index”. You still just write “for”, press tab, and “i” is marked. You now write “index”, and the “i” in all 3 places where it’s used will change to “index”. Then tab again to set the start value of the for loop, and yet again to set the max value for the loop. After choosing variable name, start value and max value you just have one tab left. The last tab brings to you $0 and you’re ready to write some code inside the for loop. If you tab one more time while the cursor is at $0 the tab sequence will start over.