1

I want to write a set of functions that call specific files, not by a specific name, but the newest file (with a certain suffix) in the directory. So far I've got

(defun org_lisp_dir ()
  (interactive)
  (switch-to-buffer (find-file-noselect "~/org/babeltest/c.org"))

but that doesn't get me the latest .org file. To do this I believe I need to use something like (eshell/ls something), but I'm not sure how to use (eshell/ls) or integrate a complex eshell command into my code. The actual command would be something like ls -Art *.org | tail -n 1 which works just fine in eshell, BTW.

2 Answers 2

5

You can use shell-command-to-string to get a shell command's output. From C-h f shell-command-to-string:

shell-command-to-string is a compiled Lisp function in ‘simple.el’.

(shell-command-to-string COMMAND)

Execute shell command COMMAND and return its output as a string.

For example, on my machine, your shell command gives

(let ((default-directory "~/org/"))     ; Ending slash is necessary
  (shell-command-to-string "ls -Art *.org | tail -n 1"))
    ⇒ "todo.org
"

Note: I have changed directory by setting default-directory before running the shell command, mostly because ls(1) can't tell file's full path. And there is also a trailing newline, which is not part of filename and needs to be removed, you can remove that from elisp or from shell.


Here is a command named foo for opening newest .org file in ~/org/ directory (non-recursively).

(defun foo ()
  (interactive)
  (let ((default-directory "~/org/"))
    (find-file (shell-command-to-string "ls -Art *.org | tail -n 1 | tr -d '\n'"))))

tr(1) is used here to remove trailing newline.

2
  • shell-command-to-string looks like the ticket. So it is not advisable to use eshell/ls or eshell-do-ls?
    – 147pm
    Commented Nov 1, 2015 at 19:39
  • @147pm I don't know how they can be used in ordinary lisp code (that is, outside eshell), they're not documented in eshell's manual. Though, I know (eshell-command-result "ls -Art *.org | tail -n 1") will produce the same output as shell-command-to-string, once you've launched eshell for at least once.
    – xuchunyang
    Commented Nov 2, 2015 at 4:09
1

Use directory-files to get the list of files in a directory.

Then loop over that list (e.g. dolist), examining the last-modified dates using function file-attributes to identify the most recently modified file(s). Or you can use function file-newer-than-file-p to filter the list.

Use find-file (not find-file-noselect) when you have identified the file(s) you want to edit (I'm assuming you want to edit them).

(However, I don't think that the original creation date is available, if that's the information you are after.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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