1

In a dired buffer, how can I determine whether the file under the point, i.e. (dired-get-file-for-visit), is local or remote? Is there something like (dired-local-file-p) or maybe (tramp-local-file-p file)?

I would like to call different functions for visiting local and remote files.

1
  • Can you give an example of how you get remote files listed in a Dired buffer?
    – Drew
    Commented Sep 28, 2014 at 15:54

2 Answers 2

2

If you simply want to know whether the file is accessed through a remote acces method, you can call file-remote-p (built into Emacs) or Tramp's similar function tramp-handle-file-remote-p. Both functions return nil for an actual file name and the method prefix (as a string) for a file accessed through a remote method.

This may or may not be what you're after. Files on a remote filesystem mounted by the operating system (NFS, Samba, Windows shares, SSHFS, etc.) will be reported as nil; you can call df to get more information if you have unix tools available. Contrariwise, local files accessed through privilege escalation (e.g. /sudo:: or /su::) are reported as non-nil. You can call tramp-dissect-file-name and the tramp-file-name-… function family (all defined in tramp.el) if you want to analyze the method further.

1
  • file-remote-p is exactly what I needed, thanks!
    – paprika
    Commented Sep 28, 2014 at 17:00
2

I realize you're asking to detect tramp buffers vs, say, files on a remote mounted filesystem, but for posterity this might be useful to other searchers:

(defun buffer-is-on-local-fs-p ()
  (and (buffer-file-name)
       (let ((local-path (chomp (shell-command-to-string
                                 (concat "df -l \"" (buffer-file-name) "\" | awk '/^Filesystem/ {next}; {print $6}'")))))
         (not (string= "" local-path)))))

This uses unix's df to identify the filesystem hosting the full path of the current buffer, and then makes a best-effort to determine what its mount type is. It's not perfect, but it's served me pretty well (I used to use it to gate VC mode funcionality, which was painfully slow on remote filesystems).

2
  • For the case at hand I was looking for a way to determine the "remoteness" of a file before opening it, i.e. there is no buffer associated with it (yet). Still, your trick is pretty neat!
    – paprika
    Commented Sep 28, 2014 at 16:59
  • The trick can work without a path; note that it uses buffer-file-name to extract a filename, but you could just as easily pass in a path and use that.
    – Chris R
    Commented Sep 29, 2014 at 3:23

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.