Insert code blocks in the body of emails

I'm a developer, and I'd like to be able to distinguish blocks of code from regular text, when I write emails.

Basically I wanna be able to do this. In the Mail app, (or Sparrow!).

Is there a way to do this with a shortcut, or macro, etc so that I don't have to reach for the mouse every time and change like 20 font attributes?


Solution 1:

The magic behind the formatting on StackExchange is a great perl script called Markdown. Download it, and double-click the resulting Markdown_1.0.1.zip file.

Then, in terminal, type

chmod a+x ~/Downloads/Markdown_1.0.1/Markdown.pl
sudo cp ~/Downloads/Markdown_1.0.1/Markdown.pl /usr/local/bin/

Once you have that done, you can create a Service in Automator.

The service you create receives rich text in any application. Uncheck the box that says Output replaces selected text.

Your service will contain two actions:

The first action is Run Shell Script. Here is the shell script:

/usr/local/bin/Markdown.pl | /usr/bin/textutil -stdin -stdout -format html -convert rtf | /usr/bin/pbcopy

Your section action is Run AppleScript. Here is the AppleScript:

tell application "System Events"
    keystroke "v" using {command down}
end tell

Save the service, and, if you wish, assign it a keyboard shortcut using System Preferences » Keyboard » Keyboard Shortcuts » Services

Then, you can type text using the formatting codes you use on this site, and run this service to generate formatted text. This will only work if your mail messages are set up as Rich Text -- if you have plain text mail messages, running this service will simply erase the contents of your message, as your rich text formatted by the service will not be able to be pasted.

Solution 2:

Assuming you're comfortable sending HTML mail you could use Markdown to format your email message and create an automator service to convert, render and replace your markdown with formatted text.

ᔥ Ryan Gray: Markdown Compose for Mac OS X Mail

[W]hat I had to do was to save the HTML generated from the Markdown conversion to a temporary file, then open that in Safari, have Safari select all and copy to the clipboard (copying an HTML object), then having Mail paste it – replacing the selected Markdown text. So, the service workflow takes the selected text, but does not itself replace the selection directly.

Instructions for creating this service are provided in the article. In addition to providing an explicit path to the markdown.pl file in your Automator script, be certain that you make markdown.pl an executable file.

chmod a+x your/path/to/markdown.pl

Note: With the demise of Posterous, the original link to Ryan Gray's article broke. I've edited the answer to point to a version archived at The Internet Archive Wayback Machine. ↬Dominique for bringing the broken link to my attention.

Solution 3:

You can install Markdown Service Tools and then follow the instructions by Tobias O’Leary. Recommended!