Octopress and Sublime Text 2

After using Octopress for a few weeks, I quickly realized that a few customizations were necessary. The first of which was a way to create a new post and have it automatically open up in my favorite text editor, Sublime Text 2. Here’s how you can do it:

1. Set up the Sublime Text 2 CLI

First, you need to make sure you can launch Sublime Text 2 from the command line. By default, the editor ships with a CLI called subl that will open files. Let’s create our symlink and name it sublime just for ease of use:

Sublime Text 2 Symlink
1
ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/local/bin/sublime

You should now be able to use it as follows:

Sublime Text 2 CLI example usage
1
2
3
$ sublime 2013-08-18-octopress-and-sublimetext2.markdown
$ sublime ~/Desktop/code
$ sublime .

Having trouble? Additional resources for setting up the Sublime CLI can be found here and here.

2. Configure your Octopress Rakefile

Open your Rakefile, find the block of code that handles rake new_post, and add sublime #{filename} to it. It should now look like this (note line 25):

The new_post portion of the Rakefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# usage rake new_post[my-new-post] or rake new_post['my new post'] or rake new_post (defaults to "new-post")
desc "Begin a new post in #{source_dir}/#{posts_dir}"
task :new_post, :title do |t, args|
if args.title
title = args.title
else
title = get_stdin("Enter a title for your post: ")
end
raise "### You haven't set anything up yet. First run `rake install` to set up an Octopress theme." unless File.directory?(source_dir)
mkdir_p "#{source_dir}/#{posts_dir}"
filename = "#{source_dir}/#{posts_dir}/#{Time.now.strftime('%Y-%m-%d')}-#{title.to_url}.#{new_post_ext}"
if File.exist?(filename)
abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
end
puts "Creating new post: #{filename}"
open(filename, 'w') do |post|
post.puts "---"
post.puts "layout: post"
post.puts "title: \"#{title.gsub(/&/,'&')}\""
post.puts "date: #{Time.now.strftime('%Y-%m-%d %H:%M')}"
post.puts "comments: true"
post.puts "categories: "
post.puts "---"
end
`sublime #{filename}`
end

3. Take it for a test drive

Do a rake generate, run rake new_post, enter a title, and voilà, the new post should now automatically open in Sublime Text 2. Happy blogging!