How do I print a string in Emacs lisp with ielm? - emacs

I'd like to print a string in ielm. I don't want to print the printed representation, I want the string itself. I'd like this result:
ELISP> (some-unknown-function "a\nb\n")
a
b
ELISP>
I can't see any way to do this. The obvious functions are print and princ, but these give me the printable representation:
ELISP> (print "* first\n* second\n* third\n")
"* first\n* second\n* third\n"
I've played with pp and pp-escape-newlines, but these still escape other characters:
ELISP> (setq pp-escape-newlines nil)
nil
ELISP> (pp "a\n")
"\"a
\""
Is this possible? For inspecting large strings, message doesn't cut it.

How about inserting directly into the buffer?
(defun p (x) (move-end-of-line 0) (insert (format "\n%s" x)))
That gets you:
ELISP> (p "a\nb\n")
a
b
nil
ELISP>
EDIT: Use format to be able to print things other than strings.

;;; Commentary:
;; Provides a nice interface to evaluating Emacs Lisp expressions.
;; Input is handled by the comint package, and output is passed
;; through the pretty-printer.
IELM uses (pp-to-string ielm-result) (so binding pp-escape-newlines has an effect in general), but if you want to bypass pp altogether then IELM doesn't provide for that, so I suspect Sean's answer is your best option.
ELISP> (setq pp-escape-newlines nil)
nil
ELISP> "foo\nbar"
"foo
bar"

#Sean's answer is correct if you want to display the string as part of your session.
However, you say you want to inspect large strings. An alternative approach would be to put the string in a separate window. You could use with-output-to-temp-buffer to do this. For instance:
(with-output-to-temp-buffer "*string-inspector*"
(print "Hello, world!")
nil)
A new window will pop up (or if it already exists, its output will be changed). It's in Help mode, so it's readonly and can be closed with q.
If you want to do some more sophisticated stuff in your output buffer you could use with-temp-buffer-window instead, like so:
(with-temp-buffer-window "*string-inspector*"
#'temp-buffer-show-function
nil
(insert "hello, world!!"))

Related

Suppress output from print function in Lisp

I'm fairly new to Lisp, and I've run into a printing issue. I have one function which does printing to the standard output (among other things). I want to then run this function through another function where it still runs the same but instead nothing gets printed to the standard output.
Here is a simple example of what I mean. I have the following two functions described:
(defun does-printing()
(print "This goes to standard output."))
(defun run-other-function (function)
(funcall function)
(values))
Here's a dribble of what happens when I run this,
;; Dribble of #<IO TERMINAL-STREAM> started on 2014-10-05 21:49:49.
#<OUTPUT BUFFERED FILE-STREAM CHARACTER #P"example.out">
[7]> (run-other-function #'does-printing)
"This goes to standard output."
[8]> (dribble)
;; Dribble of #<IO TERMINAL-STREAM> finished on 2014-10-05 21:50:09.
Note that the printing function still prints to the standard output. It'd like to be able to suppress this printing somehow when running does-printing through run-other-function. I have tried many different variations of phrasing of my problem when searching for solutions, but nothing is getting at what I would like to do.
The simplest solution is to create an empty broadcast stream.
(with-open-stream (*standard-output* (make-broadcast-stream))
(call-some-function-1)
...
(call-some-function-n))
If a broadcast stream has no component stream all output will be discarded. Above binds the *standard-output* to such a stream. This does not cons up any data and it is portable.
You can just redirect your standard-output to some place. For example into /dev/null if you have one in your operating system. It looks like very idiomatic UNIX-way output suppressing.
Note, that you shouldn't set it to NIL, because print will signal type error in this case.
(defun does-printing()
(print "This goes to standard output."))
(defun run-other-function (function)
(with-open-file (*standard-output*
"/dev/null"
:direction :output
:if-exists :supersede)
(funcall function)
(values)))
CL-USER> (run-other-function #'does-printing)
; No value
Other option (and it may be better) is to use with-output-to-string, so you can capture this output value or just ignore it. Is think it's better, because why to do IO if we don't need it, and also it must work on any OS.
(defun run-other-function (function)
(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
(funcall function)
(values)))
If you doing it a lot, you can wrap it into macro or even function, to use in place of funcall.
(defun does-printing()
(print "This goes to standard output.")
"My result")
(defun funcall-with-no-output (fn)
(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
(funcall fn)))
CL-USER> (funcall-with-no-output #'does-printing)
"My result"
But i think macro will be more general and idiomatic for this case (may be I'm wrong).
(defmacro with-suppressed-output (&body body)
`(with-output-to-string (*standard-output*
(make-array '(0)
:element-type 'base-char
:fill-pointer 0 :adjustable t))
,#body))
So you can call many forms in with-suppressed-output.

How to convert kbd-macro to real command in Emacs? [duplicate]

This question already has answers here:
Convert Emacs macro into Elisp
(2 answers)
Closed 8 years ago.
It seems kbd-macro only records keys I pushed. But I want to record real commands(that is tied with key I pushed) and save these as function.
So my question is something like following.
How to record commands I used as executable format?
How to convert key sequence to command sequence?
How to convert my-kbd-macro to command sequence function?
Example:
F3(M-x kmacro-start-macro)
C-f
F4(M-x kmacro-end-or-call-macro)
M-x name-last-kbd-macro my-kbd-macro
M-x insert-kbd-macro my-kbd-macro
Output:
(fset 'my-kbd-macro
"\C-f")
My desired output is like following:
(defun my-kbd-macro ()
(interactive)
(forward-char)
)
Thanks.
Here's a simplistic implementation of what you want.
It will work only for simple commands that don't want input, like forward-char.
To do any more in a fully automated way seems hard / not feasible. That's why this functionality
isn't in place already, I guess.
I've added these functions to
my macro package that allows multiple anonymous macros
You can get it from github or from MELPA as centimacro.
To use it, just do your F3 ... F4 thing, and
M-x last-macro-to-defun from e.g. *scratch*.
(defun macro->defun (str)
"Convert macro representation STR to an Elisp string."
(let ((i 0)
(j 1)
(n (length str))
forms s f)
(while (< i n)
(setq s (substring str i j))
(setq f (key-binding s))
(if (keymapp f)
(incf j)
(push (list f) forms)
(setq i j)
(setq j (1+ i))))
(with-temp-buffer
(emacs-lisp-mode)
(insert
"(defun foo ()\n (interactive)")
(mapc (lambda (f)
(newline-and-indent)
(insert (prin1-to-string f)))
(nreverse forms))
(insert ")")
(buffer-string))))
(defun last-macro-to-defun ()
"Insert last macro as defun at point."
(interactive)
(insert (macro->defun last-kbd-macro)))
Do bear in mind that when writing a function there are frequently better ways to do things than to exactly mimic the interactive bindings, so while not necessary, some refactoring is likely going to be beneficial if you start out with just the commands used when the macro runs.
Anyhow, I can think of a couple of useful tools to assist with working this out manually:
Firstly, if you edit a keyboard macro, the macro editor comments each key with the function it is bound to (n.b. for the buffer in which you invoke the editor! -- if you are switching buffers while your macro executes, I would suggest checking the editor for each buffer).
Obviously you can obtain the same information in other ways, but the macro editor gives you the whole list, which could be convenient.
The other helper is repeat-complex-command bound to C-xM-:, which gives you the resulting elisp form from certain types of interactive function call ("a complex command is one which used the minibuffer"). My favourite example of this is align-regexp, as it's a case where the user's interactive arguments are further manipulated, which isn't necessarily obvious. e.g.:
M-x align-regexp RET = RET C-xM-: might tell you:
(align-regexp 1 191 "\\(\\s-*\\)=" 1 1 nil)

elisp message-box: can I include newlines in the text, and if so, how?

Using the message-box fn, I can display a modal dialog.
I know this is annoying and not always a good user experience. Flymake's use of the message-box to warn when a flymake check has failed, seems a good example of that.
But put the user experience issue aside for the purposes of this question. Assume that I am sensible enough to use message-box responsibly.
How can I format the text displayed by the message box? The simplest case is, how can I tell message box to display multiple lines of text. If I have a longish message, it results in a very wide message box. (Another UI problem exhibited in the Flymake usage).
See here for an example. this code:
(message-box (concat "You need to get an \"api key\".<NL>"
"Then, set it in your .emacs with the appropriate statement."))
results in this UI:
I'd like a newline in place of the <NL>. I tried using \n and \r and \r\n, none of those worked. I also tried \x000D and \x000A.
Even better than simple line breaks, I'd like to be able to format the text. Italic, bold, or whatever. Are there options? Nothing is mentioned in the doc on this.
I looked in the source to try to figure this out but could not find message2, which is called by message-box, and I'm not sure I'd learn anything anyway by just looking at source.
Use \n. That does the trick:
(message-box (concat "You need to get an \"api key\".\n"
"Then, set it in your .emacs with the appropriate statement."))
hack workaround on Windows for bug #11138.
(defun multiline-message-box (msg)
"display a multiline message box on Windows.
According to bug #11138, when passing a message with newlines to
`message-box' on Windows, the rendered message-box appears all on
one line.
This function can work around that problem.
"
(flet ((ok (&optional p1 &rest args) t))
(let ((parts (split-string msg "\n"))
(menu-1 (make-sparse-keymap "Attention"))
c)
(define-key menu-1 [menu-1-ok-event]
`(menu-item ,(purecopy "OK")
ok
:keys ""))
(define-key menu-1 [separator-1] menu-bar-separator)
;; add lines in reverse order
(setq c (length parts))
(while (> c 0)
(setq c (1- c))
(define-key menu-1 (vector (intern (format "menu-1-fake-event-%d" c)))
`(menu-item ,(purecopy (nth c parts))
nil
:keys ""
:enable t)))
(x-popup-menu t menu-1))))
(multiline-message-box "Hello!\nI must be going!\nThis is line 3.")

How to find which file provide(d) the feature in emacs elisp

Currently i am using the load-history variable to find the file from which a feature came from.
suppose to find the file the feature gnus came from.
I execute the following code in scratch buffer which prints filename and the symbols in separate lines consecutively.
(dolist (var load-history)
(princ (format "%s\n" (car var)))
(princ (format "\t%s\n" (cdr var))))
and then search for "(provide . gnus)" and then move the point to the start of line(Ctrl+A).
The file name in the previous line is the file from which the feature came from.
Is there any thing wrong with this method, or does a better method exist.
I don't really know what you're trying to do with this, but here are some notes.
Your method is fine. Any way to hack your own solution to a problem is good in my book.
#Tom is correct that you shouldn't really need to do this, because the problem is already solved for you by the help system. i.e. C-h f
But that's not so interesting. Let's say you really want an automatic, more elegant solution. You want a function -- locate-feature with this signature:
(defun locate-feature (feature)
"Return file-name as string where `feature' was provided"
...)
Method 1 load-history approach
I'll just describe the steps I took to solve this:
You've already got the most important part -- find the variable with the information you need.
I notice immediately that this variable has a lot of data. If I insert it into a buffer as a single line, Emacs will not be happy, because it's notoriously bad at handling long lines. I know that the prett-print package will be able to format this data nicely. So I open up my *scratch* buffer and run
M-: (insert (pp-to-string load-history))
I can now see the data structure I'm dealing with. It seems to be (in pseudo code):
((file-name
((defun|t|provide . symbol)|symbol)*)
...)
Now I just write the function
(eval-when-compile (require 'cl))
(defun locate-feature (feature)
"Return file name as string where `feature' was provided"
(interactive "Sfeature: ")
(dolist (file-info load-history)
(mapc (lambda (element)
(when (and (consp element)
(eq (car element) 'provide)
(eq (cdr element) feature))
(when (called-interactively-p 'any)
(message "%s defined in %s" feature (car file-info)))
(return (car file-info))))
(cdr file-info))))
The code here is pretty straight forward. Ask Emacs about the functions you don't understand.
Method 2 help approach
Method one works for features. But what if by I want to know where any
available function is defined? Not just features.
C-h f already tells me that, but I want the file-name in a string, not all of the verbose help text. I want this:
(defun locate-function (func)
"Return file-name as string where `func' was defined or will be autoloaded"
...)
Here we go.
C-h f is my starting point, but I really want to read the code that defines describe-function. I do this:
C-h k C-h f C-x o tab enter
Now I'm in help-fns.el at the definition of describe-function. I want to work only with this function definition. So narrowing is in order:
C-x n d
I have a hunch that the interesting command will have "find" or "locate" in its name, so I use occur to search for interesting lines:
M-s o find\|locate
No matches. Hmmm. Not a lot of lines in this defun. describe-function-1 seems to be doing the real work, so we try that.
I can visit the definition of describe-function-1 via C-h f. But I already have the file open. imenu is available now:
C-x n w M-x imenu desc*1 tab enter
Narrow and search again:
C-x n d M-s o up enter
I see find-lisp-object-file-name which looks promising.
After reading C-h f find-lisp-object-file-name I come up with:
(defun locate-function (func)
"Return file-name as string where `func' was defined or will be autoloaded"
(interactive "Ccommand: ")
(let ((res (find-lisp-object-file-name func (symbol-function func))))
(when (called-interactively-p 'any)
(message "%s defined in %s" func res))
res))
Now go have some fun exploring Emacs.
There is locate-library for that.
Try...
M-: (locate-library "my-feature")
eg: (locate-library "gnus")
Just use symbol-file. It scan load-history which has format:
Each entry has the form `(provide . FEATURE)',
`(require . FEATURE)', `(defun . FUNCTION)', `(autoload . SYMBOL)',
`(defface . SYMBOL)', or `(t . SYMBOL)'. Entries like `(t . SYMBOL)'
may precede a `(defun . FUNCTION)' entry, and means that SYMBOL was an
autoload before this file redefined it as a function. In addition,
entries may also be single symbols, which means that SYMBOL was
defined by `defvar' or `defconst'.
So call it as:
(symbol-file 'scheme 'provide) ; Who provide feature.
(symbol-file 'nxml-mode-hook 'defvar) ; Where variable defined.
(symbol-file 'message-send 'defun) ; Where function defined.
(symbol-file 'scheme) ; Look for symbol despite its type.
There is nothing wrong with it, but why is it simpler than getting help on a key or a function? If you use a gnus command for example and you want to know where it comes from then you can use C-h k and it tells you from which elisp file its definition comes.

emacs: how do I use edebug on code that is defined in a macro?

I don't even know the proper terminology for this lisp syntax, so I don't know if the words I'm using to ask the question, make sense. But the question makes sense, I'm sure.
So let me just show you. cc-mode (cc-fonts.el) has things called "matchers" which are bits of code that run to decide how to fontify a region of code. That sounds simple enough, but the matcher code is in a form I don't completely understand, with backticks and comma-atsign and just comma and so on, and furthermore it is embedded in a c-lang-defcost, which itself is a macro. I don't know what to call all that, but I want to run edebug on that code.
Look:
(c-lang-defconst c-basic-matchers-after
"Font lock matchers for various things that should be fontified after
generic casts and declarations are fontified. Used on level 2 and
higher."
t `(;; Fontify the identifiers inside enum lists. (The enum type
;; name is handled by `c-simple-decl-matchers' or
;; `c-complex-decl-matchers' below.
,#(when (c-lang-const c-brace-id-list-kwds)
`((,(c-make-font-lock-search-function
(concat
"\\<\\("
(c-make-keywords-re nil (c-lang-const c-brace-id-list-kwds))
"\\)\\>"
;; Disallow various common punctuation chars that can't come
;; before the '{' of the enum list, to avoid searching too far.
"[^\]\[{}();,/#=]*"
"{")
'((c-font-lock-declarators limit t nil)
(save-match-data
(goto-char (match-end 0))
(c-put-char-property (1- (point)) 'c-type
'c-decl-id-start)
(c-forward-syntactic-ws))
(goto-char (match-end 0)))))))
I am reading up on lisp syntax to figure out what those things are and what to call them, but aside from that, how can I run edebug on the code that follows the comment that reads ;; Fontify the identifiers inside enum lists. ?
I know how to run edebug on a defun - just invoke edebug-defun within the function's definition, and off I go. Is there a corresponding thing I need to do to edebug the cc-mode matcher code forms?
What does def-edebug-spec do, and would I use it here? If so, how?
According to (elisp)Top > Debugging > Edebug > Edebug and Macros you have to tell Edebug how to debug a macro by defining it with debug statements or by using def-edebug-spec. This tells it what parameters should be evaluated and which shouldn't. So it can be done. In fact it looks as if c-lang-defconst already been fitted for edebug. Here is the definition in case you were interested:
(def-edebug-spec c-lang-defconst
(&define name [&optional stringp] [&rest sexp def-form]))
However, if you just want to see what the body evaluates to, then the way to do that is to use something like macro-expand-last-sexp below to see the result. Position your cursor after the sexp you want expanded (as you would for C-x C-e) and run M-x macro-expand-last-sexp RET. This will show you what it gets expanded to. You may run into troubles if you try to expand something like ,(....) so you may have to copy that sexp somewhere else and delete the , or ,#.
(defun macro-expand-last-sexp (p)
"Macro expand the previous sexp. With a prefix argument
insert the result into the current buffer and pretty print it."
(interactive "P")
(let*
((sexp (preceding-sexp))
(expanded (macroexpand sexp)))
(cond ((eq sexp expanded)
(message "No changes were found when macro expanding"))
(p
(insert (format "%S" expanded))
(save-excursion
(backward-sexp)
(indent-pp-sexp 1)
(indent-pp-sexp)))
(t
(message "%S" expanded)))))
I guess it depends on exactly what you are trying to do.
Use macroexpand or macroexpand-all to turn it into macro-free code and debug as usual?
Backticks &co may be best illustrated by an example:
(let ((a 1)
(b (list 2 3)))
`(a ,a ,b ,#b))
-> (a 1 (2 3) 2 3)
A backtick (or backquote`) is similar to a quote(') in that it prevents evaluation, except its effect can be selectively undone with a comma(,); and ,# is like ,, except that its argument, which must be a list, is spliced into the resulting list.