I try 2 inline Elisp script.
$ emacs --batch -q --eval="(dolist (elm (list 1 2 3 4 5)) (princ (format \"%s, \" elm)) (sit-for 1))"
1, 2, 3, 4, 5,
$ emacs --batch -q --eval="(dolist (elm (list 1 2 3 4 5)) (princ (format \"%s, \\n\" elm)) (sit-for 1))"
1,
2,
3,
4,
5,
The former is output all at once with buffering, while the latter is output gradually every second.
It seems that output buffering is done using line feed as a trigger.
Is there a way to output without buffering in the former case?
I'm using Emacs-27.1.
I haven't managed to find a prettier way to do this, but this works:
$ emacs --batch -q --eval="(dolist (elm (list 1 2 3 4 5)) \
(princ (format \"%s, \" elm)) \
(set-binary-mode 'stdout nil) \
(sit-for 1))"
set-binary-mode can be used to set output mode to either text, or binary. They are the same in POSIX shells, and we shouldn't be changing anything since we're just asking it to stay in text mode. But the important part is that if flushes pending output. From the elisp manual:
Function: set-binary-mode stream mode
Switch stream into binary or text I/O mode. If mode is non-nil, switch to binary mode, otherwise switch to text mode. The value of stream can be one of stdin, stdout, or stderr. This function flushes any pending output data of stream as a side effect, and returns the previous value of I/O mode for stream. On POSIX hosts, it always returns a non-nil value and does nothing except flushing pending output.
Related
There is a problem with shell mode and comint.el described in this bug report when entering long lines. I tried to change the TERM env variable settings to emacs but it didn't fix the problem. Any clue where I should look in comint.el?
I'd encountered this in the past and the following piece of advice works well for me:
(defadvice process-send-string (around process-send-string-in-chunks act)
"break the string to be sent into chunks
This avoids some bug when sending long strings that causes a
^D character to be inserted. Breaking the string into chunks that
are 200 chars long (arbitrary value) avoids the problem."
(let ((str (ad-get-arg 1))
substr
(chunk-len 200))
(while (> (length str) 0)
(setq substr (substring str 0 (min (length str) chunk-len)))
(ad-set-arg 1 substr)
ad-do-it
(setq str (substring str (length substr) (length str))))))
It solves the problem by breaking the string into 200 character chunks.
I just ran across this limitation in shell mode... in my case, the problem was related to shell-mode appending --noediting when the shell is 'bash' (/bin/sh doesn't receive this argument).
The --noediting arg (same as set +o emacs +o vi in bash) meant bash wasn't using readline to process input and had some internal buffer-size limitation. To reproduce outside emacs, start bash --noediting -i and then just start typing... after some limit (1024 characters in my case), the input is just blocked...
Additionally, bash internally disables editing if TERM is "emacs" or "dumb", so the TERM entry needs to be something else (I chose "xterm", you could use "ansi" or "vt100" too)
The easy workaround for .emacs is:
(setq explicit-bash-args '("-i"))
(setq comint-terminfo-terminal "xterm")
NOTE: you can't use shell-mode-hook as it runs after bash-args is used.
This does break tab-completion, and may break with colorized prompts or similar edge cases, but I can finally paste my insanely long compile lines without the shell rejecting them. You may find a need to run 'set -o emacs' (or vi) from time to time, as some actions seem to reset noediting...
Here's what I'm talking about:
$ racket
> (list 1 2 3)
'(1 2 3)
It's an annoyance very similar to constructor-style printing. What it's showing is basically that (list 1 2 3) evaluates to (quote (1 2 3)).
The gracket REPL doesn't do that (yet):
$ gracket -z
> (list 1 2 3)
(1 2 3)
In DrRacket it's possible to get rid of the tick marks through a menu option pertaining to "output syntax", but command-line Racket has no menus.
The default Racket printer is controlled by the print-as-expression parameter. If you set this to #f, it will disable expression-style printing.
> (print-as-expression #f)
> (list 1 2 3)
(1 2 3)
If you really do hate this behavior, you could add the (print-as-expression #f) line to your init file (~/.racketrc on Linux and OS X, ~/racketrc.rktl on Windows), which will get loaded at startup.
I'm a beginner programmer and am going through the book "Land of Lisp".
I have been typing in the examples from the book with the REPL. Is it possible to save my current program as a .lisp file so I can load it and continue working on it later? I know I can just create the .lisp files in a text editor and load them in, but I am enjoying using the REPL in full screen mode to do the examples.
Short answer
No. Once you enter a function into the REPL, the source form is gone and you just have the interpreted or compiled form. You can do some clever things, but I suspect you don't want to deal with them right now.
Long answer
Use Emacs and SLIME
First, I know you are enjoying the REPL, but I would encourage you to look at some of the editors with Lisp support, such as Emacs with SLIME (http://common-lisp.net/project/slime/) that gives you the best of both worlds. You type into the editor, it types into the REPL, and you really don't know the difference from how you are doing things now. Then you can copy and paste the functions you like into a "proper" .lisp file. The other advantage of using Emacs is that it's based on a variant of Lisp called Elisp, so you can program your editor in Lisp. You can pretty print your code, reformat and refactor it into multiple functions, and do all kinds of excellent things.
Enough preaching!
If you still just want to type clisp and play at the REPL, then you still have options.
If you want to log the output of your REPL session, check out DRIBBLE. It will log your session to a file, and you can edit that later to extract what you want.
For example, this is a simple session:
ataylor:~ $ clisp
blah blah
[1]> (dribble "/Users/ataylor/jerome.lisp")
#<OUTPUT BUFFERED FILE-STREAM CHARACTER #P"/Users/ataylor/jerome.lisp">
[2]> (defun add-two (a b) (+ a b))
ADD-TWO
[3]> (add-two 1 2)
3
[4]> (dribble)
#<CLOSED OUTPUT BUFFERED FILE-STREAM CHARACTER #P"/Users/ataylor/jerome.lisp">
[5]>
Bye.
Viewing the contents of the file is easy, but it can get big quickly.
ataylor:~ $ cat jerome.lisp
;; Dribble of #<IO TERMINAL-STREAM> started on 2011-09-14 18:16:57.
#<OUTPUT BUFFERED FILE-STREAM CHARACTER #P"/Users/ataylor/jerome.lisp">
[2]> (defun add-two (a b) (+ a b))
ADD-TWO
[3]> (add-two 1 2)
3
[4]> (dribble)
;; Dribble of #<IO TERMINAL-STREAM> finished on 2011-09-14 18:17:16.
You could copy (defun add-two (a b) (+ a b)) and paste it into a file for later.
Loading that file (I added it to jerome1.lisp) is very simple.
ataylor:~ $ cat jerome1.lisp
(defun add-two (a b) (+ a b))
ataylor:~ $ clisp
blah blah
[1]> (load "/Users/ataylor/jerome1.lisp")
;; Loading file /Users/ataylor/jerome1.lisp ...
;; Loaded file /Users/ataylor/jerome1.lisp
T
[2]> (add-two 1 2)
3
[3]>
Bye.
Saving a session
The easiest thing you can do is saving your Lisp session to an image. It will save all of the functions you've created or compiled, along with most state. When you load it at your next session, it will be almost as if you hadn't exited clisp. The way to do this is implementation dependent, and differs between clisp, sbcl, etc. I'll show you what you would do for clisp.
The problem with this is that you can't open a file and edit it, post it on github, or whatever. I'll give a brief example.
ataylor:~ $ clisp
blah blah
[1]> (defun add-two (a b) (+ a b))
ADD-TWO
[2]> (add-two 1 2)
3
[3]> (EXT:SAVEINITMEM)
;; Wrote the memory image into lispinit.mem (3,422,616 bytes)
Bytes permanently allocated: 171,840
Bytes currently in use: 3,243,400
Bytes available until next GC: 808,130
3243400 ;
808130 ;
171840 ;
1 ;
65640 ;
7834
[4]>
Bye.
Note that message about where clisp wrote the memory image. You'll give that back to clisp with the -M flag when starting it the next time.
ataylor:~ $ clisp -M lispinit.mem
blah blah
[1]> (add-two 1 2)
3
I wanted a better answer to this same question for the following reasons:
(1) When learning a language, oftentimes you more want to experiment than to actually write a full application.
(2) When experimenting, it can be really nice to look through your history and see what you entered and what results you got.
(3) I come from the world of bash, where you can literally dump your command history into a text file and call it a "script" (though this is only a tiny fraction of the power you can get with actual bash scripting, it still serves the purpose of after-the-fact-automation, with a little cleanup.)
So, from the world of bash, I just went with the simple route—I automated a cleanup of the stdout dump. If you're using a terminal with scrollback history (anything but a virtual terminal—and if you code lisp in a VT you're just strange) to play with clisp interactively, just copy the entire terminal scrollback history to a file, then run:
sed -n -e 's/^\[[0-9]\+\]> //;tstuff' -e 'b;:stuff' -e 'p;:rep' -e 's/([^()]*)//;trep' -e '/^[^(]*$/{s/.*//;h;d;};h;n;p;x;G;brep' myfile.lisphist > myfile.lisp
Magic! You have a working lisp program. (Obviously you should clean it up; the purpose is to have your history, not really to use it as a program. But it will only contain the lisp commands you entered, not the output/result, so it could be used directly as the program file.)
Then you can run clisp -repl myfile.lisp and voila! You're back where you got to in the last session. Of course, to load it interactively, you should take out the final (quit) line. :)
As for that sed command, what it does is look for the clisp prompt [number]>, then print that line (removing the prompt) and then try to balance the parentheses. If it succeeds, it scans for the next prompt; if the parentheses don't balance, it prints lines until they do.
Actually, it can be simplified slightly to:
sed -n -e '/^\[[0-9]\+\]> /{s///;p;:rep' -e 's/([^()]*)//;trep' -e '/^[^(]*$/d;h;n;p;x;G;brep' -e '}' myfile.lisphist > myfile.lisp
(Note: I don't use emacs; I've been using just clisp called directly at the command line. I don't know if there is a scrollback history within SLIME.
So I generally have 3 buffers open in Emacs.
One buffer for the actual code I am writing.
One buffer for the unit test for said code.
A third buffer that displays the results of the unit test. This buffer comes into being
below the two other buffers when I run my unit test C-x SPACE.
How do I disable this third buffer such that when I press C-x o I am only switching between buffer 1 and buffer 2? Currently, I switch between buffer 1, then buffer 2, then buffer 3, then buffer 1, etc. To be specific, I want C-x o to only switch between buffer 1 and 2.
Thank you.
A general solution to this (can look) something like the following:
(defvar ignore-windows-containing-buffers-matching-res '("\\*Help")
"List of regular expressions specifying windows to skip (if window contains buffer that matches, skip)")
(defadvice other-window (before other-window-ignore-windows-containing activate)
"skip over windows containing buffers which match regular expressions in 'ignore-windows-containing-buffers-matching-res"
(if (and (= 1 (ad-get-arg 0)) (interactive-p))
(let* ((win (next-window))
(bname (buffer-name (window-buffer win))))
(when (some 'identity (mapcar '(lambda (re)
(string-match re bname))
ignore-windows-containing-buffers-matching-res))
(ad-set-arg 0 2)))))
Customize the variable to be a regular expression matching the buffer names you want to skip.
Trey's answer will do exactly what you want (at least it looks like it will; I haven't tried it). A more generic solution would be to use swbuff with either swbuff-x or my own swbuff-advice. Info about all three can be found on the Emacs Wiki swbuff page.
Say I have a line in an emacs buffer that looks like this:
foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
I want it to look like this:
foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.
Anybody know of an elisp function to do this?
Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.
(defun tcl-multiline-options ()
"spread option/value pairs across multiple lines with continuation characters"
(interactive)
(save-excursion
(tcl-join-continuations)
(beginning-of-line)
(while (re-search-forward " -[^ ]+ +" (line-end-position) t)
(goto-char (match-beginning 0))
(insert " \\\n")
(goto-char (+(match-end 0) 3))
(indent-according-to-mode)
(forward-sexp))))
(defun tcl-join-continuations ()
"join multiple continuation lines into a single physical line"
(interactive)
(while (progn (end-of-line) (char-equal (char-before) ?\\))
(forward-line 1))
(while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\))
(end-of-line 0)
(delete-char -1)
(delete-char 1)
(fixup-whitespace)))
In this case I would use a macro. You can start recording a macro with C-x (, and stop recording it with C-x ). When you want to replay the macro type C-x e.
In this case, I would type, C-a C-x ( C-s v a l u e C-f C-f \ RET SPC SPC SPC SPC C-x )
That would record a macro that searches for "value", moves forward 2, inserts a slash and newline, and finally spaces the new line over to line up. Then you could repeat this macro a few times.
EDIT: I just realized, your literal text may not be as easy to search as "value1". You could also search for spaces and cycle through the hits. For example, hitting, C-s a few times after the first match to skip over some of the matches.
Note: Since your example is "ad-hoc" this solution will be too. Often you use macros when you need an ad-hoc solution. One way to make the macro apply more consistently is to put the original statement all on one line (can also be done by a macro or manually).
EDIT: Thanks for the comment about ( versus C-(, you were right my mistake!
Personally, I do stuff like this all the time.
But I don't write a function to do it unless I'll be doing it
every day for a year.
You can easily do it with query-replace, like this:
m-x (query-replace " -option" "^Q^J -option")
I say ^Q^J as that is what you'll type to quote a newline and put it in
the string.
Then just press 'y' for the strings to replace, and 'n' to skip the wierd
corner cases you'd find.
Another workhorse function is query-replace-regexp that can do
replacements of regular expressions.
and also grep-query-replace, which will perform query-replace by parsing
the output of a grep command. This is useful because you can search
for "foo" in 100 files, then do the query-replace on each occurrence
skipping from file to file.
Your mode may support this already. In C mode and Makefile mode, at least, M-q (fill-paragraph) will insert line continuations in the fill-column and wrap your lines.
What mode are you editing this in?