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?

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
| improve this answer | |
  • 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 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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.