1

I'm trying to devise a function which returns the class name. I would like to call that function inside a Yasnippet snippet for PHP-mode, so the class name will be inserted inside the template snippet.

After reading Emacs documentation, I found which-function-mode, which it returns a function name. But nothing about class names, unfortunately. Do anyone know a alternative way to get the class name of the position/current buffer?

Edit: I found an regex in the imenu source code that matches the name of the classes in PHP. But now I'm wondering how he could returns the result for yasnippet: ("^\\s-*\\(?:\\(?:abstract\\|final\\)\\s-+\\)?class\\s-+\\(\\(?:\\sw\\|\\\\\\|\\s_\\)+\\)" 1)

1
+50

Try this:

(defun foobar ()
  (interactive)
  (save-excursion
    (call-interactively 'move-end-of-line)
    (search-backward-regexp "^\\s-*\\(?:\\(?:abstract\\|final\\)\\s-+\\)?class\\s-+\\(\\(?:\\sw\\|\\\\\\|\\s_\\)+\\)")
    (let ((ret (match-string 1)))
      (message ret)
      ret)))

If the cursor is inside a class definition then calling foobar gives the class name.

  • Could you specify more about that, for example, to get the class name? When I do the following: pastebin.com/Gs90Y64q and call M-x foobar inside a PHP class then I get the error message: foobar: Search failed: "^\\s-*\\(?:\\(?:abstract\\|final\\)\\s-+\\)?class\\s-+\\(\\(?:\\sw\\|\\\\\\|\\s_\\)+\\)" – ReneFroger Dec 26 '15 at 15:01
  • 1
    If you're inside the class, you should probably be searching backwards, not forwards. – npostavs Dec 26 '15 at 16:45
  • I fixed the answer. – artscan Dec 26 '15 at 23:35
  • You should just use (move-end-of-line 1), no need for call-interactively. Possibly using (end-of-line) would be better. – npostavs Dec 27 '15 at 16:13

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.