Emacs: Write buffer to new file, but keep this file open - file

I want to do the following in Emacs: Save the current buffer to a new file, but also keep the current file open.
When I do C-x C-w then current buffer gets replaced, but I want to keep open both buffer. Is this possible without reopening the original file?

I don't think there's anything built in, but it's easy enough to write:
(defun my-clone-and-open-file (filename)
"Clone the current buffer writing it into FILENAME and open it"
(interactive "FClone to file: ")
(save-restriction
(widen)
(write-region (point-min) (point-max) filename nil nil nil 'confirm))
(find-file-noselect filename))

Here's a snippet I've had for a while to do just this
;;;======================================================================
;;; provide save-as functionality without renaming the current buffer
(defun save-as (new-filename)
(interactive "FFilename:")
(write-region (point-min) (point-max) new-filename)
(find-file-noselect new-filename))

I found it helpful to combine Scott's and Chris's answers above. The user can call save-as and then answer "y" or "n" when prompted whether to switch to the new file. (Alternatively, the user can select the desired functionality via the function name save-as-and-switch or save-as-but-do-not-switch, but this requires more keystrokes. Those names are still available for being called by other functions in the future, however.)
;; based on scottfrazer's code
(defun save-as-and-switch (filename)
"Clone the current buffer and switch to the clone"
(interactive "FCopy and switch to file: ")
(save-restriction
(widen)
(write-region (point-min) (point-max) filename nil nil nil 'confirm))
(find-file filename))
;; based on Chris McMahan's code
(defun save-as-but-do-not-switch (filename)
"Clone the current buffer but don't switch to the clone"
(interactive "FCopy (without switching) to file:")
(write-region (point-min) (point-max) filename)
(find-file-noselect filename))
;; My own function for combining the two above.
(defun save-as (filename)
"Prompt user whether to switch to the clone."
(interactive "FCopy to file: ")
(if (y-or-n-p "Switch to new file?")
(save-as-and-switch filename)
(save-as-but-do-not-switch filename)))

C-x h
selects all the buffer, then
M-x write-region
writes the region (whole buffer in this example) to another file.
Edit: this function does what you need
(defun write-and-open ( filename )
(interactive "GClone to file:")
(progn
(write-region (point-min) (point-max) filename )
(find-file filename ))
)
It's a bit crude, but modify to your will.
The interactive code 'G' prompts for a filename which goes into the 'filename' argument.
Drop this into your .emacs and call with M-x write-and-open (or define a key sequence).

Related

After a reading a clojure file line-by-line how to fetch a particular string from particular line?

I am new to clojure. I am having trouble as in how to print a particular string after removing special characters and reading a clojure file line-by-line.
I have a file named example.clj which looks like:
(defn patient
"Some string"
(measures
patient/symptom-fever
patient/symptom-cold
.
.
.
.
patient/symptom-bp))
From the above file i have removed all the special characters and reading the file line-by-line with below clojure code.
(defn loadcljfile []
(def newstring(clojure.string/replace (slurp "C:/Users/Desktop/example.clj") #"[\[/.(:)\]-]" " "))
(with-open [rdr (reader newstring)]
(doseq [line (line-seq rdr)]
(println line))))
(loadcljfile)
Now not getting how to print patient i.e my defn name and all the measures.
Can anyone help me?
Thanks
when defining things with names inside a function it's much safer and easier to use let rather than def. def defines it for the whole namespace (usually the whole file) and let gives something a name just until it's closing ).
I'm this case it makes a lot of sense to let Clojure read the expression and turn it into a data structure for you. you can do this with the load-file function if your file is a function you wish to run or use tools.reader if you just want to have it at a data structure.
if you go the load-file approach you can print it with the clojure.repl/source function and if you go the tools.reader path then you can just print it.

Run program with arbitrary filename in emacs

I want to launch an arbitrary program that takes selected filename argument from a buffer that lists files in a directory.
I tried to use F3 key to insert the filename but the following records a new macro instead which is rather confusing.
(define-key minibuffer-local-map [f3] (lambda () (interactive (find-file-at-point))))
You're problem is not completely clear to me, but maybe this helps.
Please see the following screenshot of my Emacs in the scratch buffer. It contains a function and the keybinding, the echo area at the bottom is showing the results from the call to message
For your convenience, here is the function and the keybinding repeated for better copying:
(defun command-on-file-at-point ()
(interactive)
(let ((f (ffap-file-at-point)))
(message "File is %s" f)))
(global-set-key [f3] 'command-on-file-at-point)
Hope, that helps.

Emacs lisp: Concise way to get `directory-files` without "." and ".."?

The function directory-files returns the . and .. entries as well. While in a sense it is true, that only this way the function returns all existing entries, I have yet to see a use for including these. On the other hand, every time a use directory-files I also write something like
(unless (string-match-p "^\\.\\.?$" ...
or for better efficiency
(unless (or (string= "." entry)
(string= ".." entry))
..)
Particularly in interactive use (M-:) the extra code is undesirable.
Is there some predefined function that returns only actual subentries of a directory efficiently?
You can do this as part of the original function call.
(directory-files DIRECTORY &optional FULL MATCH NOSORT)
If MATCH is non-nil, mention only file names that match the regexp MATCH.
so:
(directory-files (expand-file-name "~/") nil "^\\([^.]\\|\\.[^.]\\|\\.\\..\\)")
or:
(defun my-directory-files (directory &optional full nosort)
"Like `directory-files' with MATCH hard-coded to exclude \".\" and \"..\"."
(directory-files directory full "^\\([^.]\\|\\.[^.]\\|\\.\\..\\)" nosort))
although something more akin to your own approach might make for a more efficient wrapper, really.
(defun my-directory-files (directory &optional full match nosort)
"Like `directory-files', but excluding \".\" and \"..\"."
(delete "." (delete ".." (directory-files directory full match nosort))))
although that's processing the list twice, and we know there's only one instance of each of the names we wish to exclude (and there's a fair chance they'll appear first), so something more like this might be a good solution if you're expecting to deal with large directories on a frequent basis:
(defun my-directory-files (directory &optional full match nosort)
"Like `directory-files', but excluding \".\" and \"..\"."
(let* ((files (cons nil (directory-files directory full match nosort)))
(parent files)
(current (cdr files))
(exclude (list "." ".."))
(file nil))
(while (and current exclude)
(setq file (car current))
(if (not (member file exclude))
(setq parent current)
(setcdr parent (cdr current))
(setq exclude (delete file exclude)))
(setq current (cdr current)))
(cdr files)))
If you use f.el, a convenient file and directory manipulation library, you only need function f-entries.
However, if you don't want to use this library for some reason and you are ok for a non-portable *nix solution, you can use ls command.
(defun my-directory-files (d)
(let* ((path (file-name-as-directory (expand-file-name d)))
(command (concat "ls -A1d " path "*")))
(split-string (shell-command-to-string command) "\n" t)))
The code above suffice, but for explanation read further.
Get rid of dots
According to man ls:
-A, --almost-all
do not list implied . and ..
With split-string that splits a string by whitespace, we can parse ls output:
(split-string (shell-command-to-string "ls -A"))
Spaces in filenames
The problem is that some filenames may contain spaces. split-string by default splits by regex in variable split-string-default-separators, which is "[ \f\t\n\r\v]+".
-1 list one file per line
-1 allows to delimit files by newline, to pass "\n" as a sole separator. You can wrap this in a function and use it with arbitrary directory.
(split-string (shell-command-to-string "ls -A1") "\n")
Recursion
But what if you want to recursively dive into subdirectories, returning files for future use? If you just change directory and issue ls, you'll get filenames without paths, so Emacs wouldn't know where this files are located. One solution is to make ls always return absolute paths. According to man ls:
-d, --directory
list directory entries instead of contents, and do not dereference symbolic links
If you pass absolute path to directory with a wildcard and -d option, then you'll get a list of absolute paths of immediate files and subdirectories, according to How can I list files with their absolute path in linux?. For explanation on path construction see In Elisp, how to get path string with slash properly inserted?.
(let ((path (file-name-as-directory (expand-file-name d))))
(split-srting (shell-command-to-string (concat "ls -A1d " path "*")) "\n"))
Omit null string
Unix commands have to add a trailing whitespace to output, so that prompt is on the new line. Otherwise instead of:
user#host$ ls
somefile.txt
user#host$
there would be:
user#host$ ls
somefile.txtuser#host$
When you pass custom separators to split-string, it treats this newline as a line on its own. In general, this allows to correctly parse CSV files, where an empty line may be valid data. But with ls we end up with a null-string, that should be omitted by passing t as a third parameter to split-string.
How about just using remove-if?
(remove-if (lambda (x) (member x '("." "..")))
(directory-files path))

Read a very large text file into a list in clojure

What is the best way to read a very large file (like a text file having 100 000 names one on each line) into a list (lazily - loading it as needed) in clojure?
Basically I need to do all sorts of string searches on these items (I do it with grep and reg ex in shell scripts now).
I tried adding '( at the beginning and ) at the end but apparently this method (loading a static?/constant list, has a size limitation for some reason.
There are various ways of doing this, depending on exactly what you want.
If you have a function that you want to apply to each line in a file, you can use code similar to Abhinav's answer:
(with-open [rdr ...]
(doall (map function (line-seq rdr))))
This has the advantage that the file is opened, processed, and closed as quickly as possible, but forces the entire file to be consumed at once.
If you want to delay processing of the file you might be tempted to return the lines, but this won't work:
(map function ; broken!!!
(with-open [rdr ...]
(line-seq rdr)))
because the file is closed when with-open returns, which is before you lazily process the file.
One way around this is to pull the entire file into memory with slurp:
(map function (slurp filename))
That has an obvious disadvantage - memory use - but guarantees that you don't leave the file open.
An alternative is to leave the file open until you get to the end of the read, while generating a lazy sequence:
(ns ...
(:use clojure.test))
(defn stream-consumer [stream]
(println "read" (count stream) "lines"))
(defn broken-open [file]
(with-open [rdr (clojure.java.io/reader file)]
(line-seq rdr)))
(defn lazy-open [file]
(defn helper [rdr]
(lazy-seq
(if-let [line (.readLine rdr)]
(cons line (helper rdr))
(do (.close rdr) (println "closed") nil))))
(lazy-seq
(do (println "opening")
(helper (clojure.java.io/reader file)))))
(deftest test-open
(try
(stream-consumer (broken-open "/etc/passwd"))
(catch RuntimeException e
(println "caught " e)))
(let [stream (lazy-open "/etc/passwd")]
(println "have stream")
(stream-consumer stream)))
(run-tests)
Which prints:
caught #<RuntimeException java.lang.RuntimeException: java.io.IOException: Stream closed>
have stream
opening
closed
read 29 lines
Showing that the file wasn't even opened until it was needed.
This last approach has the advantage that you can process the stream of data "elsewhere" without keeping everything in memory, but it also has an important disadvantage - the file is not closed until the end of the stream is read. If you are not careful you may open many files in parallel, or even forget to close them (by not reading the stream completely).
The best choice depends on the circumstances - it's a trade-off between lazy evaluation and limited system resources.
PS: Is lazy-open defined somewhere in the libraries? I arrived at this question trying to find such a function and ended up writing my own, as above.
Andrew's solution worked well for me, but nested defns are not so idiomatic, and you don't need to do lazy-seq twice: here is an updated version without the extra prints and using letfn:
(defn lazy-file-lines [file]
(letfn [(helper [rdr]
(lazy-seq
(if-let [line (.readLine rdr)]
(cons line (helper rdr))
(do (.close rdr) nil))))]
(helper (clojure.java.io/reader file))))
(count (lazy-file-lines "/tmp/massive-file.txt"))
;=> <a large integer>
You need to use line-seq. An example from clojuredocs:
;; Count lines of a file (loses head):
user=> (with-open [rdr (clojure.java.io/reader "/etc/passwd")]
(count (line-seq rdr)))
But with a lazy list of strings, you cannot do those operations efficiently which require the whole list to be present, like sorting. If you can implement your operations as filter or map then you can consume the list lazily. Otherwise it'll be better to use an embedded database.
Also note that you should not hold on to the head of the list, otherwise the whole list will be loaded in memory.
Furthermore, if you need to do more than one operation, you'll need to read the file again and again. Be warned, laziness can make things difficult sometimes.
see my answer here
(ns user
(:require [clojure.core.async :as async :refer :all
:exclude [map into reduce merge partition partition-by take]]))
(defn read-dir [dir]
(let [directory (clojure.java.io/file dir)
files (filter #(.isFile %) (file-seq directory))
ch (chan)]
(go
(doseq [file files]
(with-open [rdr (clojure.java.io/reader file)]
(doseq [line (line-seq rdr)]
(>! ch line))))
(close! ch))
ch))
so:
(def aa "D:\\Users\\input")
(let [ch (read-dir aa)]
(loop []
(when-let [line (<!! ch )]
(println line)
(recur))))
You might find the iota library useful for working with very large files in Clojure. I use iota sequences all the time when I am applying reducers to large amounts of input, and iota/vec provides random access to files larger than memory by indexing them.

How do I create an empty file in emacs?

How can I create an empty file from emacs, ideally from within a dired buffer?
For example, I've just opened a Python module in dired mode, created a new directory, opened that in dired, and now need to add an empty __init__.py file in the directory.
If I use C-x C-f __init__.py RET C-x C-s then emacs doesn't create the file because no changes have been made to it. I would have to type in the file, save it, delete my typing and then save it again for that to work.
Thanks
You can use the touch command:
M-! touch __init__.py RET
The following works: C-x b __init__.py RET C-x C-w RET
If you're in a dired buffer the file will be saved in the directory show here.
The trick is to first create an empty buffer by switching to a name that doesn't exist. Then write out the file.
If you want Emacs to treat all new files as modified, you can automate the solution like this:
(add-hook 'find-file-hooks 'assume-new-is-modified)
(defun assume-new-is-modified ()
(when (not (file-exists-p (buffer-file-name)))
(set-buffer-modified-p t)))
Programatically and without any dependency on touch, it's quite easy:
(with-temp-buffer (write-file "path/to/empty/file/"))
After this thread, Emacs has added two new commands:
make-empty-file
dired-create-empty-file
These commands will be available in the emacs 27.1 release.
Here's an adaptation of dired-create-directory. It works the same way, so as well as a plain filename, you can also specify new parent directories (to be created under the current directory) for the file (e.g. foo/bar/filename).
(eval-after-load 'dired
'(progn
(define-key dired-mode-map (kbd "C-c n") 'my-dired-create-file)
(defun my-dired-create-file (file)
"Create a file called FILE.
If FILE already exists, signal an error."
(interactive
(list (read-file-name "Create file: " (dired-current-directory))))
(let* ((expanded (expand-file-name file))
(try expanded)
(dir (directory-file-name (file-name-directory expanded)))
new)
(if (file-exists-p expanded)
(error "Cannot create file %s: file exists" expanded))
;; Find the topmost nonexistent parent dir (variable `new')
(while (and try (not (file-exists-p try)) (not (equal new try)))
(setq new try
try (directory-file-name (file-name-directory try))))
(when (not (file-exists-p dir))
(make-directory dir t))
(write-region "" nil expanded t)
(when new
(dired-add-file new)
(dired-move-to-filename))))))
Emacs won't allow you to save a buffer unless it thinks the contents have changed. The quickest, though possibly not cleanest is to open the file using C-x C-f, then press (say) space and backspace, then you should be able to save a file with no contents.
There are other ways of changing the "buffer has been modified" flag, but I don't think there's any easier.
Use touch command.
M-! touch __init__.py RET
The shortest way
Creates an empty file via a shell operation (but does not open it):
M-! > __init__.py RET
Open the new file:
C-x C-f RET
(Note: we don't have to type in the name again, because the new file is automatically the first choice)
(shell-command (concat "touch " (buffer-file-name))) will do what you want, if you've already opened the empty file.
In addition to other answers on the page, you can use f.el's function f-touch:
M-:(f-touch "__init__.py")RET
You can mark an empty buffer as modified by running set-buffer-modified-p. Then when you save it, Emacs will write the file.
M-; ; Eval
(set-buffer-modified-p t) ; Mark modified
C-x C-s ; Save buffer
I use the following bound to t in dired.
(defun my-dired-touch (filename)
(interactive (list (read-string "Filename: " ".gitkeep")))
(with-temp-buffer
(write-file filename)))
;; optionally bind it in dired
(with-eval-after-load 'dired
(define-key dired-mode-map "t" 'my-dired-touch))
I've modified answer from MrBones and created custom function with keybinding:
; create empty __init__.py at the place
(defun create-empty-init-py()
(interactive)
(shell-command "touch __init__.py")
)
(global-set-key (kbd "C-c p i") 'create-empty-init-py)
This is very useful to not spend time on recurring action of creating init.py everywhere in new Python project folder.
The best option would be:
(with-temp-file "filename"
(insert ""))

Resources