Define your own keywords

These days i’m programming in and learning about Objective-C and Cocoa. Yesterday, i stumbled upon a blog entry providing The Cocoa Memory Management Regular Expression, that is, a simple regular expression that matchs (most of) the OpenStep functions allocating memory that must be explicitly de-allocated. Here’s the regexp in question:

^retain$|^(alloc|new)|[cC]opy

An immediate application of this regexp is, of course, providing some sort of visual warning to remind you that memory allocation is at play. In Emacs, a way to do that is to fontify the keywords in question using an special face (font-lock-warning-face, for instance). As it happens, this is very easy to do: just call font-lock-add-keywords with the appropriate parameters:

(font-lock-add-keywords 'objc-mode
   '(("\\\\<retain\\\\>" 0 font-lock-warning-face)
     ("\\\\(\\\\<\\\\(alloc\\\\|new\\)\\\\w*\\\\)[]:]" 1 font-lock-warning-face)
     ("\\\\(\\\\w*[cC]opy\\\\w*\\\\)[]:]" 1 font-lock-warning-face)))

Each entry in the association list above consists of a regular expression, the group inside it to be hightlighted (0 means the whole match) and the face used for the highlighting. C-h f font-lock-add-keywords RET for extended help, including further examples (for instance, to highlight your to-dos).

3 Responses to “Define your own keywords”

  1. Peter Hosey Says:

    Most of?

    What are the others?

  2. jao Says:

    Peter, none that I know of 🙂 Sorry, I was initially thinking of making a note that one can always define a factory method that does not follow Cocoa/OpenStep naming conventions (hence the ‘most of’), but, in the final sentence, you’re right: there’s no others.

  3. www.review4.info » Blog Archive » Define your own keywords Says:

    […] post by jao and software by Review How […]


Leave a comment