How can I "Save As..." in Emacs without visiting the new file? - file-io

If I use C-xC-w (write-file) to write the current buffer's content to a new location, then afterwards my buffer will be visiting the new file instead of the original one. Sometimes I would like to save off a copy of the buffer to a new location, but then keep editing at the original location.
I know I can kill the existing filename from the (write-file) minibuffer history, and then yank that back at the C-xC-f (find-file) prompt immediately afterwards to re-visit the original file, and this is the work-around I use at the moment. However, this feels inelegant.
I had wondered if (write-file) might take a prefix argument of some kind to not visit the buffer, but this only appears to affect overwrite confirmation.
So: Is there any simpler way to save my buffer content to a file without altering which file I'm visiting?

Select the entire buffer with C-xh, then use M-xwrite-region.

This is based on Inaimathi's answer and my comment to that, plus some additional tweaks:
Offer the current filename for editing by default, as personally I often want a variation on that, and it's slightly annoying not having it there to begin with.
Don't overwrite an existing file without asking the user, and never overwrite the current buffer's file.
If the region is active, write the region; otherwise write the entire (widened) buffer.
(defun my-write-copy-to-file ()
"Write a copy of the current buffer or region to a file."
(interactive)
(let* ((curr (buffer-file-name))
(new (read-file-name
"Copy to file: " nil nil nil
(and curr (file-name-nondirectory curr))))
(mustbenew (if (and curr (file-equal-p new curr)) 'excl t)))
(if (use-region-p)
(write-region (region-beginning) (region-end) new nil nil nil mustbenew)
(save-restriction
(widen)
(write-region (point-min) (point-max) new nil nil nil mustbenew)))))
(global-set-key (kbd "C-c w") 'my-write-copy-to-file)

If you do this regularly enough that it's getting annoying for you, you could define this function
(defun write-file-copy (filename)
(interactive "F")
(write-region (point-min) (point-max) filename))
and bind it to something that makes sense to you.

If you require dired-x by default, or otherwise make the dired-jump function available1, then the following is pretty simple:
C-xC-jC (type new name) RETq
Which is:
Jump to dired, with point at the file you came from
Copy that file
Exit dired, returning to the file buffer
1 C-hig (dired-x) Optional Installation Dired Jump RET

After reading phils' (dired-jump) answer, the following approach occurred to me for people who are less familiar with Dired:
M - !cp FILE NEWNAMERET
As a bonus, you have tab completion available and you're already in FILE's directory, so typing the first filename is nice and fast.

This is based on #phil's response, adapted to be called programmatically from Lisp. See docstring for details.
(defun my-backup-buffer-or-region (&optional buffer-or-name file beg end)
"Write copy of BUFFER-OR-NAME between BEG and END to FILE.
BUFFER-OR-NAME is either a buffer object or name. Uses current
buffer when none is passed. Uses entire buffer for region when
BEG and END are nil. Prompts for filename when called
interactively. Will always ask before overwriting. Returns the
name of the file written to.
See URL `https://stackoverflow.com/a/18780453/5065796'."
(interactive)
(let* ((buffer-or-name (or buffer-or-name (current-buffer)))
(buffo (or (get-buffer buffer-or-name) (error "Buffer does not exist"))) ; buffer object
(buffn (or (buffer-file-name buffo) (buffer-name buffo))) ; buffer name
(beg (or beg (if (use-region-p) (region-beginning) beg)))
(end (or end (if (use-region-p) (region-end) end)))
(prompt (if (and beg end) "region" "buffer"))
(new (if (called-interactively-p 'interactive)
(read-file-name
(concat "Write " prompt " to file: ")
nil nil nil
(and buffn (file-name-nondirectory buffn)))
(or file (error "Filename cannot be nil"))))
;; See `write-region' for meaning of 'excl
(mustbenew (if (and buffn (file-equal-p new buffn)) 'excl t)))
(with-current-buffer buffo
(if (and beg end)
(write-region beg end new nil nil nil mustbenew)
(save-restriction
(widen)
(write-region (point-min) (point-max) new nil nil nil mustbenew))))
new))

Related

Turbo C++ : while(fin) vs while(!fin.eof())

I was told that I should be using while(fin) instead of while(!fin.eof()) when reading a file.
What exactly is the difference?
Edit: I do know that while(fin) actually checks the stream object and that when it becomes NULL, the loop breaks and it covers eof and fail flags.
But my course teacher says that fin.eof() is better so I need to understand the fundamental operation that's going on here.
Which one is the right practice?
Note: This is not a duplicate, I need assistance in Turbo C++ and with binary files.
I'm basically trying to read a file using a class object.
First of all I am assuming fin is your fstream object. In which case your teacher would not have told you to use while(fin.eof()) for reading from file. She would have told to use while(!fin.eof()).
Let me explain. eof() is a member of the fstream class which returns a true or false value depending on whether the End Of File (eof) of the file you are reading has been reached. Thus while eof() function returns 0 it means the end of file has not been reached and loop continues to execute, but when eof() returns 1 the end of the file has been reached and the loop exits.
while(fin) loop is entered because fin actually returns the value of an error flag variable inside the class object fin whose value is set to 0 when any function like read or write or open fails. Thus the loop works as long as the read function inside the loop works.
Personally I would not suggest either of them.
I would suggest
//assume a class abc.
abc ob;
While(fin.read((char*)&ob, sizeof(ob)))
{}
Or
While(fin.getline(parameters))
{}
This loop reads the file record inside the loop condition and if nothing was read due to the end of file being reached, the loop is exited.
The problem with while(!fin.eof()) is that it returns 1 if the end of file has been reached. End of file is actually a character that is put at the end of the file. So when the read function inside the loop reads this character and sets a variable eof to 1. All the function actually does is return this value.
Thus works fine when you are reading lines in words but when you are reading successive records of a class from a file, this method will fail.
Consider
clas abc
{}a;
Fstream fin("file");
While(!fin.eof())
{
fin.read((char*)&a,sizeof(a));
a.display(); // display is a member function which displays the info }
Thus displays the last record twice. This is because the end of file character is the character after the last byte of the last record. When the last is read the file pointer is at the eof byte but hasn't read it yet. So it will enter the loop again but this time the eof char is read but the read function fails. The values already in the variable a, that is the previous records will be displayed again.
One good method is to do something like this:
while ( instream.read(...) && !instream.eof() ) { //Reading a binary file
Statement1;
Statement2;
}
or in case of a text file:
while ( (ch = instream.get()) && !instream.eof() ) { //To read a single character
Statement1;
Statement2;
}
Here, the object is being read within the while loop's condition statement and then the value of eof flag is being tested.
This wouldn't result in undesired outputs.
Here we are checking the status of the actual I/O operation and the eof together. You may also check for the fail flag.
I would like to point out that according to #RetiredNinja, we may only check for the I/O operation.
That is:
while ( instream.read(...) ) { //Reading a binary file
Statement1;
Statement2;
}
A quick and easy workaround that worked for me to avoid any problems when using eof is to check for it after the first reading and not as a condition of the while loop itself. Something like this:
while (true) // no conditions
{
filein >> string; // an example reading, could be any kind of file reading instruction
if (filein.eof()) break; // break the while loop if eof was reached
// the rest of the code
}

Emacs function returns Symbol's value as variable is void:

I am fairly new to Emacs but I know enough to be dangerous. I've built my .emacs file from scratch and now have it in an org file. I am now trying to take it to the next level and make my configuration more user friendly for myself.
I mostly use Emacs for writing. Books, blogs, screenwriting, etc. I am trying to create a function that will turn on multiple modes and add the settings on the fly.
For example, I use olivetti-mode when writing. It centers the text. Each time I have to adjust the olivetti-set-width. I thought I would get fancy and enable the spell checker and turn off linum-mode as well.
However, every time I try it I get the error:
Symbol's value as variable is void: my-writing
Can anyone explain what I am doing wrong? I've google-fu'd quite a bit but I clearly have a gap in my understanding of what I am doing.
#+BEGIN_SRC emacs-lisp
(defun my-writing ()
"Start olivetti mode, set the width to 120, turn on spell-check."
((interactive)
(olivetti-mode)
(setq olivetti-set-width . 120)
(flyspell-mode)
(global-linum-mode 0)))
(add-hook 'olivetti-mode-hook
(lambda () olivetti-mode my-writing t))
#+END_SRC
To disable global-linum-mode for specific major-modes, see automatically disable a global minor mode for a specific major mode
[Inasmuch as olivetti-mode is a minor-mode that is enabled subsequent to whatever major-mode is already present in the buffer, the original poster may wish to turn off linum-mode locally in the current buffer by adding (linum-mode -1) to the tail end of the function my-writing (see below). That idea, however, assumes that the original poster wanted to have linum-mode active in the current buffer just prior to calling my-writing.]
The function my-writing in the initial question contains an extra set of parenthesis that should be omitted, and the hook setting is not in proper form.
olivetti-set-width is a function that takes one argument, so you cannot use setq -- see function beginning at line 197: https://github.com/rnkn/olivetti/blob/master/olivetti.el setq is used when setting a variable, not a function.
Although flyspell-mode is generally buffer-local, it is a good idea to get in the habit of using an argument of 1 to turn on a minor-mode or a -1 or 0 to turn it off. When an argument is omitted, calling the minor-mode works as an on/off toggle.
Unless there are other items already attached to the olivetti-mode-hook that require prioritization or special reasons for using a hook with buffer-local settings, you do not need the optional arguments for add-hook -- i.e., APPEND and LOCAL.
There is no apparent reason to call (olivetti-mode) as part of the olivetti-mode-hook that gets called automatically at the tail end of initializing the minor-mode, so there is now a check to see whether that mode has already been enabled. The olivetti-mode-hook is being included in this example to demonstrate how to format its usage. However, the original poster should consider eliminating (add-hook 'olivetti-mode-hook 'my-writing) as it appears to serve no purpose if the user will be calling M-x my-writing instead of M-x olivetti-mode. The hook would be useful in the latter circumstance -- i.e., when typing M-x olivetti-mode -- in which case, there is really no need to have (unless olivetti-mode (olivetti-mode 1)) as part of my-writing.
#+BEGIN_SRC emacs-lisp
(defun my-writing ()
"Start olivetti mode, set the width to 120, turn on spell-check."
(interactive)
(unless olivetti-mode (olivetti-mode 1))
(linum-mode -1) ;; see comments above
(olivetti-set-width 120)
(flyspell-mode 1))
;; original poster to consider eliminating this hook
(add-hook 'olivetti-mode-hook 'my-writing)
#+END_SRC
lawlist's answer describes how you can go about doing what you're actually trying to accomplish, but the particular error you're getting is because Emacs Lisp (like Common Lisp, but not Scheme) is a Lisp-2. When you associate a symbol with a function using defun, it doesn't make the value of that symbol (as a variable) that function, it makes the function value of that symbol the function. You'll get the same error in a much simplified situation:
(defun foo ()
42)
(list foo)
The symbol foo has no value here as a variable. To get something that you could later pass to funcall or apply, you need to either use the symbol foo, e.g.:
(funcall 'foo)
;=> 42
or the form (function foo):
(funcall (function foo))
;=> 42
which can be abbreviated with the shorthand #':
(funcall #'foo)
;=> 42
You're getting the error because of:
(add-hook 'olivetti-mode-hook
(lambda () olivetti-mode my-writing t))
which tries to use my-writing as a variable, but it has no variable value at that point.

How do EMACS Lisp programmers read text files for non-editing purposes?

What do EMACS Lisp programmers do, when they want to write something roughly the equivalent of...
for line in open("foo.txt", "r", encoding="utf-8").readlines():
...(split on ws and call a fn, or whatever)...
..?
When I look in the EMACS lisp help, I see functions about opening files into text editing buffers -- not exactly what I was intending. I suppose I could write functions to visit the lines of the file, but if I did that, I wouldn't want the user to see it, and besides, it doesn't seem very efficient from a text-processing standpoint.
I think a more direct translation of the original Python code is as follows:
(with-temp-buffer
(insert-file-contents "foo.txt")
(while (search-forward-regexp "\\(.*\\)\n?" nil t)
; do something with this line in (match-string 1)
))
I think with-temp-buffer/insert-file-contents is generally preferable to with-current-buffer/find-file-noselect, because the former guarantees that you're working with a fresh copy of the entire file contents. With the latter construction, if you happen to already have a buffer visiting the target file, then that buffer is returned by find-file-noselect, so if that buffer has been narrowed, you'll only see that part of the file when you process it.
Keep in mind that it may very well be more convenient not to process the file line-by-line. For example, this is an expression that returns a list of all sequences of consecutive digits in the file:
(with-temp-buffer
(insert-file-contents "foo.txt")
(loop while (search-forward-regexp "[0-9]+" nil t)
collect (match-string 0)))
(require 'cl) first to bring in the loop macro.
Yes, that is what you want to do: visit the file in a buffer, and operate on the text in that buffer.
You do not have to display the buffer, i.e., the user need not see it.
And as for efficiency: manipulating text in a buffer is typically the most efficient way to manipulate text.
You can visit a file in a buffer in several ways. You might want to use an existing file buffer for this, depending on the use case. That is, if the file is already "open" in Emacs then you might want to use its buffer.
Or you might want to disregard any existing file buffer for an already "open" file, and read the file anew into a new buffer. For that, as #Sean mentions, you can use insert-file-contents with a buffer that you create. You can create the buffer using with-temp-buffer or generate-new-buffer, depending, again, on what you want/need to do with it.
If you do want to reuse a buffer that is already visiting the file, you can test whether it has been modified in memory, whether it is narrowed, etc., and do whatever is appropriate for your use case. You can check whether there is already a buffer visiting the file (using any path/file name) using function find-buffer-visiting.
To visit the file, taking advantage of any existing buffer that is visiting it, you can use find-file-noselect. That function returns the buffer that visits the file, so you can pass that buffer as the first argument to with-current-buffer. Here is a simple example.
(with-current-buffer (let ((enable-local-variables ())) (find-file-noselect file))
;; Do some stuff with the text in the buffer.
;; Optionally save the buffer back to the file.
)
(The binding of enable-local-variables to nil is a minor optimization, for the common case where you don't need to bother with buffer-local variables.)

Can't declare constant variable locally Error installing Artificial Intelligence a Modern Approach Code on Ubuntu Trusty Tahr - Common Lisp

Im installing the code for the book Artificial Intelligence a Modern Approach i got here http://aima.cs.berkeley.edu/lisp/doc/install.html its the lisp version im installing btw
I'm on Ubuntu Trusty using Emacs SBCL slime, I placed the code in ~/.emacs.d
so per the instructions at above link i run (load "/home/w/.emacs.d/aima/code/aima.lisp")
which loads fine i get "T" as output
i run (aima-load 'all) that works I get "T" as output
but when i run (aima-compile) I get the error
Can't declare constant variable locally special: +NO-BINDINGS+
[Condition of type SIMPLE-ERROR]
I'm not sure I understand the error I read the Hyperspec on Declare and Special but that didn't help. I'm not opposed to a hack to make this work so if someone can help me reword the code or figure out if its a emacs setting or sbcl setting i could change to get the aforementioned variable declared that would be great. The error message is referring to this file /home/w/.emacs.d/aima/code/logic/algorithms/tell-ask.lisp
this section
(defmethod ask-each ((kb literal-kb) query fn)
"For each proof of query, call fn on the substitution that
the proof ends up with."
(declare (special +no-bindings+))
(for each s in (literal-kb-sentences kb) do
(when (equal s query) (funcall fn +no-bindings+))))
I verified all the permisions of all the files in my aima folder are set to read write for my username with my username as owner as a step to correct....but as far as understanding the error I could use help figuring out the next step one would take to debug this...The code is downloadable here http://aima.cs.berkeley.edu/lisp/code.tar.gz and its an easy install for a veteran emacs/lisp user....any help is appreciated.
Using SBCL:
I tried loading the AIMA code as well, with the same problem in SBCL. Just comment out line in ./logic/algorithms/tell-ask.lisp:
(declare (special +no-bindings+))
like so
;;(declare (special +no-bindings+))
, or delete the whole line altogether. Nevertheless, this is what I did:
(defmethod ask-each ((kb literal-kb) query fn)
"For each proof of query, call fn on the substitution that
the proof ends up with."
;;(declare (special +no-bindings+))
(for each s in (literal-kb-sentences kb) do
(when (equal s query) (funcall fn +no-bindings+))))
You will still have an issue running (aims-compile) with SBCL. It will complain about some constants being redefined. Just look at the possible restarts and select every time:
0: [CONTINUE] GO ahead and change the value.
Do this as many times (about 6 times that is) as it needs to, and it will load eventually. This is probably happening because of AIMA's code non-standard build/compile system. This can be annoying, but an alternative is to trace the code and see why/where some files are being reloaded.
USING Clozure (CCL):
CCL has a different problem with ./utilities/utilities.lisp. CCL has both true and false functions predefined, therefore you have to make sure that both lines:
#-(or MCL Lispworks)
that directly precede both (defun true ...) and (defun false ...) are changed to:
#-(or MCL Lispworks CCL)
also, in the same source, modify error inside for-each macro to look like so:
(error "~a is an illegal variable in (for each ~a in ~a ...)"
var var list)
With these modifications, CCL seems load AIMA code just fine.
In general:
It's a bad idea to redefine constants or to somehow bypass debugger restarts. Best solution is to have (defconstant ...)s evaluated once only, perhaps by placing them in a separate source file and making sure that the build system picks it up only once.
Another solution found here, which entails wrapping calls to defconstantin a macro like so (borrowed from here):
(defmacro define-constant (name value &optional doc)
(if (boundp name)
(format t
"~&already defined ~A~%old value ~s~%attempted value ~s~%"
name (symbol-value name) value))
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,#(when doc (list doc))))
And then replacing all occurrences of defconstant like so:
(defconstant +no-bindings+ '((nil))
"Indicates unification success, with no variables.")
with:
(define-constant +no-bindings+ '((nil))
"Indicates unification success, with no variables.")
If you opt for define-constant "solution", make sure that define-constant is evaluated first.

Common lisp restart to condition binding

I'm learning common lisp in my free time and have a questions about the condition system.
When we handle an error in common lisp we specify error-type in a handler to determine which error to handle. Between raising and handling an error I can place some restarts (for example with restart-case) but I cannot specify in restart an error type.
For example, assume I have a function that takes a string and a stream, sends string to stream and read the response from stream and returns it. Assume that if my message is wrong I read from stream an error response. And I want to raise an error and bind a restart that asks for new message like this:
(defun process-message (stream raw-message)
(let ((response (get-response stream raw-message)))
(restart-case
(when (response-error-p response)
(error 'message-error :text response))
(change-raw-message (msg)
(process-message stream msg)))))
Now assume that the message is complicated and I got another function send-command at higher level that can create a message from some arguments and calls the process-message. I want to bind another restart recreate-command-message that will allow user to send new command from arguments if 'message-error acquires. This restart could be places in restart-case at process-message, but it is not fully correct because process-message should not know about such high-level function like send-command and the return values can differ.
But now the stream errors (such as EOF etc.) will be thrown throw recreate-command-message and if socket will fail the recreate-command-message restart will be available in some super-high-level socket-error handler and this restart will be useless and idiomatically wrong.
Is this a program design problem and a program should be designed to avoid such problems, or I just cannot find how to bind restart to error type or I do not understand the condition system correctly?
Thanks.
Maybe this helps:
(define-condition low-level-error (simple-error)
()
(:report (lambda (c s)
(format s "low level error."))))
(define-condition high-level-error (simple-error)
()
(:report (lambda (c s)
(format s "high level error."))))
(defun low-level (errorp)
(restart-case
(when errorp (error 'low-level-error))
(go-on ()
:report "go on from low-level"
t)))
(defun high-level (high-level-error-p low-level-error-p)
(restart-case
(progn
(when high-level-error-p (error 'high-level-error))
(low-level low-level-error-p))
(go-on ()
:report "go on from high level"
:test (lambda (c) (typep c 'high-level-error))
t)))
Try invoking high-level with different values (t or nil) for its arguments and check in the debugger if the respective available restarts fit your needs. The high level restart will only be seen if a high level error is signalled, and since the restart for the higher level is kept up the stack, the lower level function won't have to know about high level means to recover.
For your particular use-case, if I understand you correctly, this would mean: Establish your recreate-command-message restart to re-invoke process-message in send-command, and make it only available for high level errors.
As you probably know after reading the PCL chapter Vsevolod linked above, actually handling those errors, i.e. deciding which restarts to invoke, is done with handler-bind and handler-case.