0

I'm trying to get hold of the current filename at point. In an arbitrary buffer.

Say I have list of files in a buffer and I want to be able to do something with each file. For that I need to determine filenames

That's easy you may say, just use (thing-at-point 'filename), and you'd be right, unfortunately that thing simply can't detect filenames with spaces in them.

So, here's the output of ls. I turned whitespace-mode and saw this:

enter image description here

So I've figured - I need to hold onto the thing at point that separated by double whitespace at both ends. Or to be precise: start-of-line|end-of-line|double-whitespace

Can someone help me with that? Thanks!

I looked into previous-property-change and buffer-substring-no-properties, but couldn't figure out how to apply for my thing, re-search-forward & re-search-backward is probably what I need to use, but I can't figure out the correct regex. Damn, regexes in elisp are wild and untamable.

update: Attempting this:

(defun get-filename ()
  (interactive)
  (save-excursion
    (let* ((start (re-search-backward "\s\s\\|^"))
           (end (re-search-forward "\s\s\\|$")))
      (buffer-substring-no-properties start end))))

and it's not working ;(

update 2: This worked:

(defun get-filename ()
  (interactive)
  (let ((start (save-excursion (re-search-backward "\s\s\\|^")))
        (end (save-excursion (re-search-forward "\s\s\\|$"))))
    (string-trim
    (buffer-substring-no-properties start end))))
7
  • How is that list produced?
    – wasamasa
    Oct 1 '17 at 21:44
  • @wasamasa I don't think it's relevant to the question? It's simply output of ls in eshell
    – iLemming
    Oct 1 '17 at 21:50
  • FWIW, to get a file name at point I recommend using ffap-guesser instead of (thing-at-point 'filename).
    – Drew
    Oct 1 '17 at 23:26
  • Depending on how the list is produced, there may be a better way than guessing, like by side-stepping it and just retrieving the list as a data structure, not as a string.
    – wasamasa
    Oct 1 '17 at 23:28
  • @Drew this is awesome! I had no idea that exists! Thanks!
    – iLemming
    Oct 1 '17 at 23:31

Your Answer

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

Browse other questions tagged or ask your own question.