6

When editing LaTeX code, the command latex-close-block inserts an \end{..} that matches the last unclosed \begin{..}. Very handy!

Is there a similar command in c-mode that would close a pending #ifdef? Ideally, I would close

#ifdef __A_COND__ 

with a nicely commented #endif, like in

#endif /* __A_COND__ */

If such a command does not exist, how would you program it? From scratch or using skeleton.el?

phs
  • 1,095
  • 6
  • 13

2 Answers2

6

I'm using this yasnippet:

# -*- mode: snippet -*-
# name: ifndef
# key: ifndef
# --
#ifndef ${1:`(upcase (file-name-nondirectory (file-name-sans-extension (buffer-file-name))))`_HH_}
#define $1

$0
#endif

You can quickly customize it to do what you want.

In case you're not using yasnippet yet

Here's my personal config (you can take the parts that you like):

(use-package yasnippet
    :diminish yas-minor-mode
    :init
    (progn
      (setq yas-fallback-behavior 'return-nil)
      (setq yas-triggers-in-field t)
      (setq yas-verbosity 0)
      ;; I'm using my own snippets, turn bundled snippets off
      ;; (setq yas-snippet-dirs (list (concat emacs.d "snippets/")))
      (define-key yas-minor-mode-map [(tab)] nil)
      (define-key yas-minor-mode-map (kbd "TAB") nil)
      (yas-global-mode)))

;; (package-install 'auto-yasnippet)
(global-set-key "\C-o" 'aya-open-line)

It needs auto-yasnippet (it's in MELPA, yasnippet is a dependency).

So now C-o will try in order to:

  • expand abbrev
  • expand yasnippet or move to the next yasnippet field if already expanding
  • open line
abo-abo
  • 13,943
  • 1
  • 29
  • 43
  • THANKS!!! This looks great (based on the number of upvotes) so I am eager to try it. But 1st I must learn about yasnippets and understand what you mean. Let me read [this page](http://www.emacswiki.org/emacs/Yasnippet) and digest its contents. Aside: I'm always surprised by how much stuff has been added to Emacs since 1984 when I first used it. – phs Dec 12 '14 at 17:10
  • I've added my yasnippet config. It can be a start if you want a custom yasnippet config. – abo-abo Dec 12 '14 at 17:40
2

smartparens (and some other "auto pair" packages) allows you to do something similar:

(sp-pair "#ifdef" "#endif")

This won't easily get you that ending comment like a snippet engine can (I believe it's possible with smartparens, though), but it answers your title so I thought it was close enough to warrant an answer.

nanny
  • 5,704
  • 18
  • 38