"Touch" current file in emacs - emacs

Im emacs, I want to run "touch" on the file referenced by the current buffer (specifically want to change the modification time). I use guard to run some tests after files are changed, but sometimes I want to invoke it manually. I don't care about running the actual shell utility touch so long as mtime is set.

Of course, this assumes that you have a command named touch on your path.
(defun touch ()
"updates mtime on the file for the current buffer"
(interactive)
(shell-command (concat "touch " (shell-quote-argument (buffer-file-name))))
(clear-visited-file-modtime))
In dired-mode there is a touch command bound by default to T. That command isn't so easy to use though because it prompts the user for a timestamp. I suppose that's very general, but it isn't a very convenient way to do what is typically intended by "touch."

Maybe more keystrokes than a custom function, but you can do this out the box with C-u M-~ then C-x C-s.
M-~ is bound by default to not-modified, which clears the buffer's modification flag, unless you call it with an argument (C-u prefix), in which case it does the opposite. Then just save the buffer.

Here is a pure emacs way to do it:
(defun touch-file ()
"Force modification of current file, unless already modified."
(interactive)
(if (and (verify-visited-file-modtime (current-buffer))
(not (buffer-modified-p)))
(progn
(set-buffer-modified-p t)
(save-buffer 0))))

I do it like this: insert a space, end then I delete the space again and save. This changes the mtime.

8 years later, the useful "f" library in melpa provides f-touch.
See: https://github.com/rejeep/f.el

Related

How to create a new, unnamed file in emacs?

This is a very simple request: I want to create a new, blank file without giving it a name (yet). I can use the scratch buffer but there's only one. I can C-x C-f and open a new file, but then I have to give it a name and path. If I'm just writing notes to myself or sketching out ideas, I don't want to have to give it a name. How do I create a new, empty, unnamed file?
You can create a new buffer with: C-xb and type in the buffer name and it will create a new buffer with a name that you choose.
If you want to save that buffer, just hit C-x w to create the file with its contents to a desired location.
My recommendation is that you give org-mode a try. It will do what want among a million other things.
Give it a name. Just don't save it.
Not what you wanted to hear, but this is the Emacs way.
Use C-x C-f, giving the (to-be-file-visiting) buffer a name. Edit the text. Do not use C-x C-s to save the buffer to the file (i.e., to disk).
Note that you can first put yourself in a directory whose contents you don't care about, so that if you accidentally do save the buffer there then you can easily find, recognize and toss the file. To change directories, you can use M-x cd. Or just do it by editing the directory part when you first use C-x C-f. Or use C-x d to put yourself in a Dired buffer for the directory.
If you don't want to take the chance of accidentally hitting C-x C-s and thus saving your edits, then use C-x b instead of C-x C-f. You are (even here) prompted for the buffer name. Giving it a new name (not the name of an existing buffer) creates a new buffer. In this case, if you use C-x C-s then Emacs prompts you for the file location to save the buffer in.
Why would you want to use C-x C-f instead of C-x b, if you might not want to save the buffer? Providing a file extension in the file name you give automatically puts the buffer in the proper major mode (typically). Otherwise (for C-x b) you need to put the buffer in the mode you want.
Buffer *scratch* is by default in Lisp-Interaction mode, which is similar to Emacs-Lisp mode (but not the same).
In every other text editor or word processor the intuition is to create a “new file” or a “new buffer”, not to switch to idiosyncratic *scratch* buffer. For example, you write quick notes or thoughts in several different buffers to keep trace of them—later you decide if you throw them away or save them. Or you manipulate a snippet of text or code, but you don't want to change the original buffer, so you just copypaste it to a new temporary buffer.
*scratch* is set to Lisp Interaction mode, but if I want to quickly evaluate some Elisp code, I could eval it running eval-expression (Alt+:) or in Elisp interpreter IELM (Alt+x Enter ielm). Also, if you close *scratch* buffer, it doesn't ask you to save it, so you can accidentally lose all your work. Drew's traditional solution seems too sub-optimal. And I don't buy the argument that “this is how you do it in Emacs”. Emacs is a customizable editor, so you can and should create whatever workflow is comfortable for you.
That's how ErgoEmacs solves it, buy creating a new-empty-buffer command. You can implemented like this:
(defun new-empty-buffer ()
"Opens a new empty buffer."
(interactive)
(switch-to-buffer (generate-new-buffer "untitled"))
(funcall initial-major-mode)
(put 'buffer-offer-save 'permanent-local t)
(setq buffer-offer-save t))
The variable buffer-offer-save resets every time you change a major mode, therefore you need to annotate it with permanent-local. It also prompts only when you exit Emacs. I think it is intuitive for it to also ask, when you close a modified untitled buffer, therefore see my solution on how to upgrade kill-buffer to prompt before closing a modified buffer.
ErgoEmacs revamps the default keybindings completely and has new-empty-buffer bound to Ctrl+N, like in almost all software. Change variable initial-major-mode if you want the new buffer to have another mode on start.
See also:
Emacs: Problems of the Scratch Buffer # Xah Lee
Emacs: New Empty Buffer # Xah Lee
You can try the following snippet, just add it to your .emacs
(defun new-file-tmp()
"Create a new empty file."
(interactive)
(let ((buf (generate-new-buffer "untitled")))
(switch-to-buffer buf)
(put 'buffer-offer-save 'permanent-local t)
(setq buffer-offer-save t)))
(defun tool-bar-local-item-pre (icon def key map after_item &rest props)
"Add an item to the tool bar in map MAP.
ICON names the image, DEF is the key definition and KEY is a symbol
for the fake function key in the menu keymap. Remaining arguments
PROPS are additional items to add to the menu item specification. See
Info node ‘(elisp)Tool Bar’. The item is added after AFTER_ITEM.
ICON is the base name of a file containing the image to use. The
function will first try to use low-color/ICON.xpm if ‘display-color-cells’
is less or equal to 256, then ICON.xpm, then ICON.pbm, and finally
ICON.xbm, using ‘find-image’."
(let* ((image-exp (tool-bar--image-expression icon)))
(define-key-after map (vector key)
`(menu-item ,(symbol-name key) ,def :image ,image-exp ,#props) after_item)
(force-mode-line-update)))
(when (boundp 'tool-bar-map)
(tool-bar-local-item-pre "new" 'new-file-tmp 'new-file-tmp tool-bar-map
'new-file :label "" :help "New untitled File")
(define-key tool-bar-map (vector 'new-file) nil)
;; comment the above line if you want to keep the button for the default behavior
)
(global-set-key (kbd "C-n") 'new-file-tmp)
It defines a new command which creates new empty buffers
Then the code binds it to the top left button of the toolbar, if you are in gui mode, and to the Control-n shortcut.
You can check the post on my site about it.
disclaimer: it's my site
A buffer and a file are not the same thing.
terminology
Regarding buffers,
The text you are editing in Emacs resides in an object called a
buffer. Each time you visit a file, a buffer is used to hold the file's text.
Regarding files,
The operating system stores data permanently in named files, so most
of the text you edit with Emacs comes from a file and is ultimately
stored in a file.
Buffers and files are related through visiting,
Visiting a file means reading its contents into an Emacs buffer so you
can edit them. Emacs makes a new buffer for each file that you visit.
answering the question
Unless I'm mistaken, technically speaking, your question, as written, can't be answered. Pedantically speaking, there's no such thing as (or little practical use for) an unnamed file. A file is a handle for something stored on disk. If you have no handle, then why make a file?
The question can then be interpreted as having two possible meanings1.
1. Making a new buffer (without regard to name)
A new buffer must have a name. An unsaved buffer can be saved to file with a given name using write-file (C-x C-w). You will be prompted for a path/name. Once written, the buffer update to be visiting the file you just wrote.
Since the name of the buffer doesn't matter (until you write it to file), here's a function which creates buffers named *scratch1*, *scratch2*, ... .
(defun create-scratch-buffer ()
"Create a new numbered scratch buffer.
Taken from URL `https://stackoverflow.com/a/21058075/5065796' "
(interactive)
(let ((n 0)
bufname)
(while (progn
(setq bufname (concat "*scratch"
(if (= n 0) "" (int-to-string n))
"*"))
(setq n (1+ n))
(get-buffer bufname)))
(switch-to-buffer (get-buffer-create bufname))
(org-mode)
(if (= n 1) initial-major-mode)))
2. Making a new file (without regard to name)
As hinted at in the new buffer solution, new files can be created with write-file.
When called interactively (M-x make-random-file), this function prompts for a directory. It then writes an empty file named something random like tmp-17388716387615.txt.
(defun make-random-file (dir)
"Make a random file in DIR."
(interactive "DDir: ")
(let* ((filename (concat "tmp-" (int-to-string (random t)) ".txt"))
(filepath (concat dir filename)))
(write-region "" nil filepath nil 'silent nil 'excl)))
As always, if the code above doesn't make sense, look at the documentation for functions and variables with C-h f and C-h v, respectively. And/or read the Introduction to Programming in Emacs Lisp.
1 It was the second meaning which I was searching for solutions to when I found this as the top search engine hit. Apologies if this was a bit obtuse. Figured it was better to share my solutions with y'all than not. :)

How to make emacs switch to *scheme* by default when eval / load from the file?

The problem:
I'm in scheme-mode (simple quack)
scheme is already running
eval expression
it sends the expression to scheme buffer
but! doesn't bring that buffer up in 2nd window = no immediate feedback
and I have to manually switch second buffer to scheme which is annoying
Some (more recent) modes like fsharp-mode or tuareg do that automatically. Tried to read quack.el, but didn't find convenient separate function like "pop scheme". It's tangled within run-scheme which also changes focus. Settings also don't help.
I want to stay in my rkt/scm file and see repl buffer pop up if not already popped. Like this simple build logic in sublime-text but with persistent repl.
Maybe I should try geiser, but quack is ok for now. Just missing few obvious conveniences.
Just rungeiser. It's in MELPA now, so it's a quick install.
You can also try lispy (which uses geiser) for in-place scheme eval.
e will eval current expression and display the result in the minibuffer.
E will eval current expression and insert the result in current buffer.
u is bound to undo, so you can either e or Eu if you prefer.
I ended up writing this:
(setq scheme-program-name "guile")
(defun run-scheme-2.0 ()
"Loads your chosen Scheme implementation for interactive development,
and displays that buffer below your main editing buffer, and makes sure that
your cursor will be on your code."
(interactive)
(if (not (get-buffer "*scheme*"))
(progn
(setq starting-buffer (buffer-name))
(run-scheme scheme-program-name)
(split-window-below)
(other-window 1)
(shrink-window-if-larger-than-buffer)
(other-window 1)
(switch-to-buffer starting-buffer))))
(add-hook 'scheme-mode-hook 'run-scheme-2.0)

Emacs/AUCTeX prefix arguments

In LaTeX mode C-c C-c is bound to:
(TeX-command-master &optional OVERRIDE-CONFIRM)
Normally this interactive function runs a command, perhaps a LaTeX compilation, asking for confirmation.
In tex-buf.el it reads:
If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
depend on it being positive instead of the entry in `TeX-command-list'.
This is a bit cryptic for me and reading C-h v TeX-command-list didn't help.
How can I pass the prefix argument to "TeX-command-master" so that I avoid all the confirmation requests?
Take a look at Emacs' documentation to find out about prefix arguments. In general, you can pass a command a prefix argument with C-u followed by a number. For one-digit numbers, you can also just type Meta followed by the digit. Thus to pass a positive prefix argument to TeX-command-master you could type:
M-1 C-c C-c
However, this will actually add another minibuffer confirmation, namely about the shell command to be used to compile the LaTeX source. Without the prefix argument, a command-dependent default is used for that.
If you want to avoid the question about the command to use, you can bind the undocumented variable TeX-command-force to "LaTeX" via:
(setq TeX-command-force "LaTeX")
However, this will have the downside that you're basically binding C-c C-c to the "latex" command, you cannot use any of the other commands such as "bibtex" or "view".
Other than that, LaTeX-mode does not allow for any customization of C-c C-c. Your best options are to either advise the function TeX-command-query or to bind C-c C-c to a wrapper function to set TeX-command-force dynamically. The latter would probably be the preferred option if you also want to auto-save the buffer.
It seems that the mystery of the OVERRIDE-CONFIRM continues. In the meantime a fellow suggests that, if we are unable to manage TeX-command-master, we can simply rewrite it.
In my version, based on his, if the buffer is not modified, the external viewer is launched; if the buffer is modified the compiler is run.
Everything with no confirmation for saving or running the given command.
(defun my-run-latex ()
(interactive)
(if (buffer-modified-p)
(progn
(setq TeX-save-query nil)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
(TeX-view)))
Of course one can bind my-run-latex to whatever keybinding.
On the user's point of view this is a solution to my own question.
Do I click the close tag? Well, on the curious guy point of view I am still interested in understanding the mysterious TeX-command-master technicalities.
If someone should happen to know...
P.S.
Yes, TeX-save-query overrides the save-file request, also with TeX-command-master, that is C-c C-c. But you will still be asked to confirm the command action.
Build & view
Again, this solution, instead of modifying the behaviour of the TeX-command-master, rewrites it. The rewritten version of the command, named build-view, follows a rather straightforward logic.
If the LaTeX file buffer is not-modified, it runs the default viewer;
If the buffer is dirty, it runs the default LaTeX compiler and, after the build, opens the output in the default viewer.
Here's the code:
(defun build-view ()
(interactive)
(if (buffer-modified-p)
(progn
(let ((TeX-save-query nil))
(TeX-save-document (TeX-master-file)))
(setq build-proc (TeX-command "LaTeX" 'TeX-master-file -1))
(set-process-sentinel build-proc 'build-sentinel))
(TeX-view)))
(defun build-sentinel (process event)
(if (string= event "finished\n")
(TeX-view)
(message "Errors! Check with C-`")))
You can now type M-x build-view and start the told build-view process or associate it with a new keybinding such as “F2”:
(add-hook 'LaTeX-mode-hook '(lambda () (local-set-key (kbd "<f2>") 'build-view)))
Note: As suggested by Tyler, TeX-save-query variable is changed locally, therefore the old C-c C-c/ TeX-command-master is unaffected and will keep asking confirmations.
Do edit this code to make it better or easier to read!
I puzzled over the OVERRIDE-CONFIRM bit for a while, and couldn't figure out how it was supposed to work. If you want to automatically run Latex on your file, without being bothered about saving it first, or confirming that you want latex (rather than view, bibtex etc), you could use a function like this:
(defun my-run-latex ()
(interactive)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
Bind this to something handy, and you'll still have C-c C-c for when you want to use the default processing commands. You may want to modify the TeX-command line if "Latex" isn't the processor you want to call.
If you are just looking to compile the latex source without a confirmation dialog, just add the following to your .emacs:
(setq TeX-command-force "")
You can then compile the source with C-c C-c and it won't ask to confirm. The only problem with this solution is that you can no longer change the command, but with most documents you won't want to. I might suggest that at the same time you can add this to your .emacs for even more flexibility, giving you a C-c C-c equivalent to the former behavior:
(define-key LaTeX-mode-map "\C-c\C-a"
;;; 'a' for ask, change to anything you want
(lambda (arg) (interactive "P")
(let ((TeX-command-force nil))
(TeX-command-master arg))))
You can then just work away at your document, do a C-x C-s, C-c C-c and then C-c C-v to see it. Like others have suggested you can also do the same for the save command and have it compile automatically on save, but some of my documents are in CVS and so I avoid putting hooks on that.
Credit to Ivan for some help on this one - don't know if he is on StackOverflow
I think the gist of this question is "how do I quickly compile my TeX document from AUCTeX without all the key presses and confirmations?"
My answer to that is to use the latexmk command rather than trying to coerce AUCTeX to do it.
latexmk -pdf -pvc myfile.tex
latexmk will monitor the file in question and rebuilt it as soon as you save it. If you use a good pdf viewer, it will notice the change in PDF and re-display it immediately. On OS X, skim works well for this.

How to force Emacs to save even if it thinks (no changes need to be saved)

This happens to me all the time:
I have a file open in emacs,
I save it ('save-buffer),
the file changes on disk (or get's deleted, moved, etc.)
but I want it back, so I try to save again in emacs ('save-buffer) and instead of saving it says "(no changes need to be saved)" and does nothing.
Is there a different function, or a setting, that I can use to force emacs to save?
Wrap a function around save-buffer that marks the buffer modified first:
(defun save-buffer-always ()
"Save the buffer even if it is not modified."
(interactive)
(set-buffer-modified-p t)
(save-buffer))
You can save as, with C-x C-w. That should save unconditionally. You can also just type a space then backspace over it. Emacs is smart enough to realize that if you undo everything you've done so far the buffer has no changes, but if you make changes and then manually reverse them it will consider the buffer to have been changed.
You can mark the current buffer as modified using the Emacs-Lisp function not-modified with a prefix arg, bound to:
C-u M-~
The answer above won't work if you don't call the new function directly.
If you want to seamlessly change emacs saving behavior. The best solution is to create an advice:
(defadvice save-buffer (before save-buffer-always activate)
"always save buffer"
(set-buffer-modified-p t))
As a slight alternative to scottfrazer's answer:
(defun my-save-buffer-always-sometimes (prefix)
"Save the buffer even if it is not modified."
(interactive "P")
(when prefix
(set-buffer-modified-p t))
(save-buffer))
This was you can force it when you want to with a prefix (C-u C-x C-s) but not unnecessarily change a file otherwise. The last modified timestamp is very useful (e.g. source code control) that it seems a shame to change it arbitrarily. YMMV, of course.
A similar problem brought me online to look for a solution. Then it hits me that all I have to do is type a space (or any character) and delete it, which marks the buffer as changed. Then I can type C-x C-s as normal. Maybe not sophisticated or advanced, but it works.
Like Tagore Smith said, you can force Emacs to save the buffer with C-x C-w.
If you're using Evil mode, you can also achieve this behavior by typing :w! in normal state. Unlike C-x C-w, :w! will not prompt you for the filename to save to.

How to make emacs stay in the current directory

When I start working on a project in emacs, I use M-x cd to get into the project root directory. But every time I use C-x C-f to open a file in one of the subdirectories (like app/model/Store.rb) emacs changes current directory to that of the file. Is there a way to make emacs stay at the root?
How about this? It replaces the regular find-file command with your own which always starts in some "root" directory (customize the find-file-root-dir variable):
(defvar find-file-root-dir "~/"
"Directory from which to start all find-file's")
(defun find-file-in-root ()
"Make find-file always start at some root directory."
(interactive)
(let ((default-directory find-file-root-dir))
(call-interactively 'find-file)))
(global-set-key (kbd "C-x C-f") 'find-file-in-root)
Assuming that you want the working directory of a file to be set to whatever the working directory was before you executed find-file, you could try the following:
(defmacro disallow-cd-in-function (fun)
"Prevent FUN (or any function that FUN calls) from changing directory."
`(defadvice ,fun (around dissallow-cd activate)
(let ((old-dir default-directory) ; Save old directory
(new-buf ad-do-it)) ; Capture new buffer
;; If FUN returns a buffer, operate in that buffer in addition
;; to current one.
(when (bufferp new-buf)
(set-buffer new-buf)
(setq default-directory old-dir))
;; Set default-directory in the current buffer
(setq default-directory old-dir))))
Armed with this macro, go search for operations that set the variable default-directory: M-x find-library files; M-x occur (setq default-directory. After some investigation, you discover that the desired function is called find-file-noselect-1. Also, it looks like set-visited-file-name is also a candidate. So:
(disallow-cd-in-function find-file-noselect-1)
(disallow-cd-in-function set-visited-file-name)
Note
Note that (disallow-cd-in-function find-file) would work just fine, but then if you switched to ido-mode, you'd be opening files with ido-find-file instead of find-file. Both of these functions ultimately use find-file-noselect-1, so hitting that with the macro is a more univeral solution.
Is there a way to make emacs stay at the root?
No, there isn't. C-x C-f always visits starting from the default directory of the buffer you are already vising. The default directory, by default, is the same directory as the file. You can change these (separately for every buffer) using M-x cd.
But that is not what you want. What you should do is C-x b to *scratch* (whose default directory is the same as where you launched Emacs from -- in your words "root"), and then visit a new file. And if you need to do this frequently, just open up a dired in there and work your way thru.
I appreciate I'm not answering your question directly, but I noticed you were more specific in your requirements in one of your comments: "I don't use compile or recompile, I just tend to close files I am not working on, since it takes fewer keystrokes to open a file again".
Have you got ido turned on for buffer switching? If you exclude the directory thing for a moment, switching files or buffers with ido is an identical number of keystrokes (C-x C-f vs C-x b, followed by a few characters in the file name). If you include the directory thing, switching files is more tricky for the precisely the reasons you mention. Sticking with buffers is much easier.
Going a step further, with the help of 'anything.el' it's quite easy to abstract away whether a given file is in a buffer or in a file using the file cache. For example, if you do the following:
(file-cache-add-directory-recursively "/my/ruby/project") ".*\\.rb$")
and run 'anything-for-files' (I have it bound to C-x f) all your open buffers are listed, along with all of the files you've just added to the file cache; isolating a given file usually only takes one or two more characters.
Any file in your project is thus 4 or 5 key presses away, and the directory they are in or whether or not they are in a buffer becomes irrelevant.
Hope that's helpful...
Sorry I haven't worked out the details, but you might be able to add a function to find-file-hook that resets the default directory to whatever you want.