Setting up Emacs as a modern Objective-C editor
.emacs.d/ only requires a few software packages and custom Lisp functions to function as a modern Objective-C editor. These instructions are primarily aimed at people developing on GNUstep but could probably be adapted easily for an Apple macOS environment.
This technology is powered by the Language Server Protocol which provides these IDE features to text editors through a separate server process.
The setup is quick and easy:
- Install ccls (for NEXTSPACE / CentOS 7, the easiest way to do this is through the snap package)
- Install the following packages for Emacs via ELPA: lsp-mode, lsp-ui, ccls
- Optionally, install packages for your completion framework of choice
- Add this code to your .emacs.d to tie it all together (set your
(setq ccls-executable "/var/lib/snapd/snap/bin/ccls")
(add-hook 'objc-mode-hook #'lsp)
- Add a
.cclsfile to the root directory of your Objective-C project with your compiler settings such as the locations of header files. For clang on NEXTSPACE this looks like:
Now the next time you open a file within that project, ccls will be activated.
To get started, I find the three most helpful functions are finding references, finding definitions, and finding documentation, so I bind those in Objective-C mode to three easy keystrokes:
C-x C-d(ocumentation) ,
C-x C-r(eferences) , and
C-x C-w(here is function defined) .
Unfortunately, these packages do not provide rich documentation for Cocoa, so I had to write a function called
cocoa-open-documentation to open Apple’s documentation in a web browser when over a specific symbol.
(defun buffer-contains-substring (string)
(search-forward string nil t))))(defun cocoa-open-documentation ()
(let ((foundation-url (concat "https://developer.apple.com/documentation/foundation/" (downcase (thing-at-point 'word))))
(appkit-url (concat "https://developer.apple.com/documentation/appkit/" (downcase (thing-at-point 'word)))))
(let ((previous-buffer (current-buffer))
(web-result (url-retrieve-synchronously foundation-url)))
(if (buffer-contains-substring "404 Not Found")
(switch-to-buffer previous-buffer))))(add-hook 'objc-mode-hook
(local-set-key (kbd "C-x C-d") 'cocoa-open-documentation)
(local-set-key (kbd "C-x C-r") 'lsp-ui-peek-find-references)
(local-set-key (kbd "C-x C-w") 'lsp-ui-peek-find-definitions)))
One keybinding that is helpful and already exists is
C-x c(ompile) for compiling and running a project. If you’re on macOS, you’ll have to write a shell script to do this for you, but for GNUstep the compile command just looks like
make && openapp ./App.app .
With all that setup, you now have a pleasantly modern environment for writing Objective-C in.
Note: I am noticing Emacs.app on GNUstep is having trouble opening a web browser. I’ll hopefully submit a patch shortly.
.emacs.d/ may be of further help and can be viewed here: https://github.com/enzuru/.emacs.d