rnso
rnso

Reputation: 24623

Cannot add function in Emacs

I have recently started using Emacs and I am trying to add a function that will split the entered sentence into a list of words (split by one space):

(defun split-by-one-space (string)    ; from: http://cl-cookbook.sourceforge.net/strings.html
        "Returns a list of substrings of string
        divided by ONE space each.
        Note: Two consecutive spaces will be seen as
        if there were an empty string between them."
    (loop for i = 0 then (1+ j)
          as j = (position #\Space string :start i)
          collect (subseq string i j)
          while j))

(defun myfn (ss)
    "documentation of fn: to be added"
    (interactive "s\Enter some words: ")
    (message "Read: %s" (split-by-one-space ss)))

I have kept above in folder ~/.emacs.d/init.el in which there are 2 other functions also which are properly picked up and executed. The above function 'myfn', however, is not found when I try to execute it with M-x method. The function 'split-by-one-space' is also not found.

Where is the problem and how can I solve it?

Edit:

Starting Emacs with command "emacs --debug-init" shows that following error:

(invalid-read-syntax "#")

Apparently \#Space not recognized in Emacs Lisp. I replaced it with '?\ ' and this error went away. The function myfn is now available for executing. However, on executing it, following error is shown:

Symbol's function definition is void: loop

Apparently the loop part needs to be rewritten in Emacs Lisp.

Upvotes: 1

Views: 375

Answers (1)

Stefan
Stefan

Reputation: 28571

#\Space is not valid Elisp and will cause a read-error, so most Emacs will stop processing your file at this point. You want to write ?\s or ?\ instead, which is the syntax used in Elisp for character literals.

After that, you'll see that loop is not known to Emacs. You want to use cl-loop instead, which is provided by the cl-lib package, so not only you need to rename loop to cl-loop but you additionally need to add

(require 'cl-lib)

earlier. Similarly subseq and positions are not known to Elisp and you'll need to use cl-subseq and cl-position instead (also provided by cl-lib).

Upvotes: 1

Related Questions