I’ve been having this question for so long: is there some ways I can save my own code templates?

For example, I use R very frequently for plots. So some code templates I type over and over again could be the settings I like for a scatter plot; could be to load the packages I used together (e.g. ggplot2, gridExtra, reshape2) etc. I’m sure you have some code chucks used a lot, what’s your trick to manage them?

I’ve heard a friend saying she put them together in a script, say “set.R” and just source it every time. I like the idea and theoretically that’s also the similar snippets (we’ll talk about in this post) work, but the process is not that smooth.

I just heard this tool: snippets from a friend yesterday. What is a snippet? let me quote from https://flight-manual.atom.io/using-atom/sections/snippets/

Snippets are an incredibly powerful way to quickly generate commonly needed code syntax from a shortcut.

The idea is that you can type something like habtm and then press the Tab key and it will expand into has_and_belongs_to_many  

Sounds exactly what we want, right?

All commonly used IDEs have support for snippets, the settings could be slightly different. I just include some examples using Atom here.

First, open your “snippets.cson” file. This file contains all your custom snippets that are loaded when you launch Atom.

create a snippet for java

So let’s look at how to write a snippet. The basic snippet format looks like this:

'.source.js':
  'console.log':
    'prefix': 'log'
    'body': 'console.log(${1:"crash"});$2

The leftmost keys are the scope (here: .js tells it works for java scripts) where these snippets should be active.

The next level of keys are the snippet names. You can name them whatever you want.

Prefix: this should trigger the snippet

Body: a body to insert when the snippet is triggered.

create a snippet for markdown

The default scope for markdown in atom is .source.gfm,

Your snippets would look like:

'.source.gfm':
  'header':
    'prefix': 'header'
    'body':


--- \n
layout: post \n
title: title \n
subtitle: subtitle \n
tags: [life] \n
---
 '

To use this, just open a file, save it with name ‘xx.md’

Then type ‘header’+Tab, you see this code chuck in the file!

create a snippet for R

'.source.r, .source.rd.console':
'Read From File':
    'prefix': 'reat'
    'body': 'read.table("${1:filename}"${2:, header = ${3:TRUE},  sep = "${4:\\t}",  stringsAsFactors = ${5:FALSE}})'

create a snippet for python

'.source.python':
'import os and sys':
    'prefix': 'imos'
    'body': '''
    import os
    import sys

Hope you find snippets helpful to reduce some typing!