Vojtech Rinik

#pragma mark

Posted on 2012/12/15

I would like to quickly introduce my favorite Xcode feature.

#pragma mark is special kind of comment that separates sections of your source code. For example:

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(TUITableView *)tableView {
  // ...
}

- (NSInteger)tableView:(TUITableView *)table numberOfRowsInSection:(NSInteger)section {
  // ...
}

#pragma mark - Table view delegate

- (BOOL)tableView:(TUITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
  // ...
}

Look at the documentation of any Cocoa class, and you'll find its methods are always divided into sections. They often start working with X, managing Y, etc. They explicitly name responsibility of the method, and of the class too, for that matter.

It really helps, before adding a method, to think like this: What is this method's purpose? What area of class's responsibility does it help cover?

You might find out it should be renamed, or you might discover it doesn't belong to that class at all.

It makes refactoring amazing. Say your class grew too large, and you want to refactor some of its responsibilities to another class. Well, you just copy and paste one group!

We need this in other languages.

Hacking syntax highlighting

While you can make really visible comments to write section titles, it's nice to have syntax highlighting for them. Here's a quick guide for TextMate/Sublime.

My syntax highlighting with pragma marks

First, find your language package (e.g. ~/Library/Application Support/Sublime Text 2/Packages/CoffeeScript) Open up *.tmLanguage file. Find piece responsible for recognizing comments, in this case:

<dict>
  <key>captures</key>
  <dict>
    <key>1</key>
    <dict>
      <key>name</key>
      <string>punctuation.definition.comment.coffee</string>
    </dict>
  </dict>
  <key>match</key>
  <string>(#)(?!\{).*$\n?</string>
  <key>name</key>
  <string>comment.line.number-sign.coffee</string>
</dict>

Copy it, and insert it before the original snippet. Change number of comment-symbols (# for CoffeeScript) to two. Change the name of this structure to comment.line.pragma.coffee. Resulting code:

<dict>
  <key>captures</key>
  <dict>
    <key>1</key>
    <dict>
      <key>name</key>
      <string>punctuation.definition.comment.coffee</string>
    </dict>
  </dict>
  <key>match</key>
  <string>(##)(?!\{).*$\n?</string>
  <key>name</key>
  <string>comment.line.pragma.coffee</string>
</dict>

(Note that I inserted it before the original group, otherwise it wouldn't be recognized.)

Now, open your color scheme and add highlighting rules for your newly created comment.line.pragma.coffee symbol:

<dict>
  <key>name</key>
  <string>Pragma Comment</string>
  <key>scope</key>
  <string>comment.line.pragma.coffee</string>
  <key>settings</key>
  <dict>
    <key>foreground</key>
    <string>#eaeaea</string>
    <key>fontStyle</key>
    <string>bold</string>
  </dict>
</dict>