(cl-defun filename-from-buffer (&key get-ext get-path)
(let ((filename (buffer-name))
(pathname (buffer-file-name)))
(setq ret (car (split-string filename "\\.")))
(when get-path
(setq ret (car (split-string pathname "\\."))))
(when get-ext
(setq ret filename))
(when (and get-ext get-path)
(setq ret pathname))
ret))
I am fairly new to Emacs and Lisp (eLisp) and I wanted a function that would return the name of the file which is open in the current buffer. The function should take some optional arguments determining whether we want the full path, the extension or just the sole name of the file.
I feel like my implementation is pretty naive and it depends on the order of lines as well because I could not figure out how to do an if-else
chain and return within. So is there a more elegant/more secure or just a better way to do this? By better, I mean something that uses the functionality of language which is already provided, an implementation that does not depend on the order of cases and/or something that does branching in a better way.
file-name-nondirectory
,file-name-sans-extension
,file-name-extension
. If-else-statement:(if PREDICATE IF-BRANCH ELSE-BRANCH)
wherePREDICATE
IF-BRANCH
andELSE-BRANCH
are expressions. You can also use(cond (EXPR FORM) ...)
.buffer-name
often contains the base file name, but not always. You want to use(file-name-nondirectory buffer-file-name)
instead. Also the GNU convention is to only use "path" for lists of directories, likeload-path
, and to use "file name" otherwise, including for fully qualified absolute file names.setq
ret
without locally binding it in alet
. Because it changes the global variableret
(if there is one). Reason is: Emacs uses dynamic extend for variables by default. Second: emacs provides portable functions to extract parts of the filenamefile-name-...
, your code wouldn't work with unixes.let
". I have bound it inside the(let (...) (setq ret))
block. Do you mean I should do it like this:(let ((ret nil)) (setq ret "value"))
?