Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is empty in Emacs Lisp?

Tags:

emacs

elisp

I would like to write an if statement that will do something base on whether a string is empty. For example:

(defun prepend-dot-if-not-empty (user-str)
   (interactive "s")
   (if (is-empty user-str)
     (setq user-str (concat "." user-str)))
   (message user-str))

In this contrived example, I'm using (is-empty) in place of the real elisp method. What is the right way of doing this?

Thanks

like image 829
oneself Avatar asked Jun 19 '09 19:06

oneself


3 Answers

Since in elisp, a String is an int array, you can use

(= (length user-str) 0)

You can also use (string=) which is usually easier to read

(string= "" user-str)

Equal works as well, but a bit slower:

(equal "" user-str)
like image 99
mihi Avatar answered Oct 20 '22 20:10

mihi


Starting in emacs 24.4, there are two different functions available for you to call, depending on what you mean by 'empty'.

(string-empty-p " ")
nil

(string-blank-p " ")
0

I'm having trouble finding docs to link to, but emacsredux.com has more information.

If you get the error Symbol's function definition is void., include (require 'subr-x) in the initialization file (it's a package for trimming and string manipulation).

like image 8
Gina White Avatar answered Oct 20 '22 20:10

Gina White


If you work with strings heavily in your code, i strongly recommend using Magnar Sveen's s.el string manipulation library.

s-blank? checks if the string is empty:

(s-blank? "") ; => t
like image 6
Mirzhan Irkegulov Avatar answered Oct 20 '22 20:10

Mirzhan Irkegulov