How to copy to clipboard in Emacs Lisp - emacs

I want to copy a string to the clipboard (not a region of any particular buffer, just a plain string). It would be nice if it were also added to the kill-ring. Here's an example:
(copy-to-clipboard "Hello World")
Does this function exist? If so, what is it called and how did you find it? Is there also a paste-from-clipboard function?
I can't seem to find this stuff in the Lisp Reference Manual, so please tell me how you found it.

You're looking for kill-new.
kill-new is a compiled Lisp function in `simple.el'.
(kill-new string &optional replace yank-handler)
Make string the latest kill in the kill ring.
Set `kill-ring-yank-pointer' to point to it.
If `interprogram-cut-function' is non-nil, apply it to string.
Optional second argument replace non-nil means that string will replace
the front of the kill ring, rather than being added to the list.
Optional third arguments yank-handler controls how the string is later
inserted into a buffer; see `insert-for-yank' for details.
When a yank handler is specified, string must be non-empty (the yank
handler, if non-nil, is stored as a `yank-handler' text property on string).
When the yank handler has a non-nil PARAM element, the original string
argument is not used by `insert-for-yank'. However, since Lisp code
may access and use elements from the kill ring directly, the string
argument should still be a "useful" string for such uses.

I do this:
(with-temp-buffer
(insert "Hello World")
(clipboard-kill-region (point-min) (point-max)))
That gets it on the clipboard. If you want it on the kill-ring add a kill-region form also.

The command to put your selection on the window system clipboard is x-select-text. You can give it a block of text to remember. So a (buffer-substring (point) (mark)) or something should give you what you need to pass to it. In Joe's answer, you can see the interprogram-cut-function. Look that up for how to find this.

In my .emacs file, i use this
(global-set-key "\C-V" 'yank)
(global-set-key "\C-cc" 'kill-ring-save)
I could not use Ctrl-C (or System-copy), but this may be enough in case old habits kick in.

Related

Emacs: How to select word under cursor and append to file

I want the following behavior:
Append the word under cursor into a file(~/vocabulary.txt, for example)
Better still to bind a key for it.
Could anyone show me how to do it?
Should I put those code into .emacs ?
Try the following function:
(defun my-write-to-file ()
"Save word at point to file"
(interactive)
(write-region (concat (thing-at-point 'word) "\n") nil "~/vocabulary.txt" 'append))
When called, this function will save the word at point (the word the cursor is on or the word right before the cursor) to ~/vocabulary.txt.
You can bind it to a key (C-c w in this case, but you can change it to whatever you like) like this:
(global-set-key (kbd "C-c w") 'my-write-to-file)
To use, simply put the function and the keybinding assignment in your .emacs.
#Elethan wrote you a command that does just what you ask for, and bound it to a key.
It might also help to mention some general commands that you can use for this kind of thing. M-x append-to-file appends the region contents to a file, and M-x write-region prepends.
The manual is your friend for things like this. See nodes Misc File Ops and Accumulating Text.
Be aware too that for the two commands just mentioned, as the manual says about append-to-file (it should say it about both):
You should use append-to-file only with files that are not being
visited in Emacs. Using it on a file that you are editing in Emacs
would change the file behind Emacs’s back, which can lead to losing some
of your editing.
Accumulating Text also tells you about commands for adding text to a buffer, including the case of adding to a buffer for a file that you are visiting (as opposed to what the above quote warns you about for append-to-file). These include commands append-to-buffer and prepend-to-buffer.

Save value of old function in elisp to call

I have a function:
(defun alternate-narrow-to-region (start end)
(message "Hi!")
(narrow-to-region start end))
I want all uses of narrow-to-region, except for the one in this function body, to call alternate-narrow-to-region (so narrow-to-defun, narrow-to-page, direct calls to narrow-to-region, end up calling alternate-narrow-to-region).
How do I do this?
To save the original definition (which is in your question title but not in the text), use defalias:
(defalias 'ORIGINAL-narrow-to-region (symbol-function 'narrow-to-region)
"My doc string about this.")
Note that in this case you do not want to use this:
(defalias 'FOREVER-narrow-to-region 'narrow-to-region
"My doc string about this.")
What you want to do is copy the function definition at a given point in time. The latter use of defalias instead has the effect of pointing FOREVER-narrow-to-region to whatever the current definition of narrow-to-region is. If you redefine narrow-to-region then it will point to the new definition, which is presumably not what you want in this case.
As for the question implied by your text, the answer is that you cannot. You cannot get Emacs to always use your function instead of narrow-to-region. This is explained at your other question: code that calls narrow-to-region and is compiled will continue to (in effect) call the original narrow-to-region. (It is not really called at all. Its code is effectively inlined.)
If you wanted to get Emacs to use a replacement command only when called interactively, you could of course remap the original command's key bindings to the replacment. But that does not seem to be the case here.

Emacs - noninteractive call to shell-command-on-region always deletes region?

The Emacs Help page for the function shell-command-on-region says (elided for space):
(shell-command-on-region START END COMMAND &optional OUTPUT-BUFFER
REPLACE ERROR-BUFFER DISPLAY-ERROR-BUFFER)
...
The noninteractive arguments are START, END, COMMAND,
OUTPUT-BUFFER, REPLACE, ERROR-BUFFER, and DISPLAY-ERROR-BUFFER.
...
If the optional fourth argument OUTPUT-BUFFER is non-nil,
that says to put the output in some other buffer.
If OUTPUT-BUFFER is a buffer or buffer name, put the output there.
If OUTPUT-BUFFER is not a buffer and not nil,
insert output in the current buffer.
In either case, the output is inserted after point (leaving mark after it).
If REPLACE, the optional fifth argument, is non-nil, that means insert
the output in place of text from START to END, putting point and mark
around it.
This isn't the clearest, but the last few sentences just quoted seem to say that if I want the output of the shell command to be inserted in the current buffer at point, leaving the other contents of the buffer intact, I should pass a non-nil argument for OUTPUT-BUFFER and nil for REPLACE.
However, if I execute this code in the *scratch* buffer (not the real code I'm working on, but the minimal case that demonstrates the issue):
(shell-command-on-region
(point-min) (point-max) "wc" t nil)
the entire contents of the buffer are deleted and replaced with the output of wc!
Is shell-command-on-region broken when used non-interactively, or am I misreading the documentation? If the latter, how could I change the code above to insert the output of wc at point rather than replacing the contents of the buffer? Ideally I'd like a general solution that works not only to run a command on the entire buffer as in the minimal example (i.e., (point-min) through (point-max)), but also for the case of running a command with the region as input and then inserting the results at point without deleting the region.
You are wrong
It is not a good idea to use an interactive command like shell-command-on-region in emacs lisp code. Use call-process-region instead.
Emacs is wrong
There is a bug in shell-command-on-region: it does not pass the replace argument down to call-process-region; here is the fix:
=== modified file 'lisp/simple.el'
--- lisp/simple.el 2013-05-16 03:41:52 +0000
+++ lisp/simple.el 2013-05-23 18:44:16 +0000
## -2923,7 +2923,7 ## interactively, this is t."
(goto-char start)
(and replace (push-mark (point) 'nomsg))
(setq exit-status
- (call-process-region start end shell-file-name t
+ (call-process-region start end shell-file-name replace
(if error-file
(list t error-file)
t)
I will commit it shortly.
If you follow the link to the functions' source code, you'll quickly see that it does:
(if (or replace
(and output-buffer
(not (or (bufferp output-buffer) (stringp output-buffer)))))
I don't know why it does that, tho. In any case, this is mostly meant as a command rather than a function; from Elisp I recomend you use call-process-region instead.
In my case (emacs 24.3, don't know what version you're using), the documentation is slightly different in the optional argument:
Optional fourth arg OUTPUT-BUFFER specifies where to put the
command's output. If the value is a buffer or buffer name, put
the output there. Any other value, including nil, means to
insert the output in the current buffer. In either case, the
output is inserted after point (leaving mark after it).
The code that checks whether to delete the output (current) buffer contents is the following:
(if (or replace
(and output-buffer
(not (or (bufferp output-buffer) (stringp output-buffer)))))
So clearly putting t as in your case, it is not a string or a buffer, and it is not nil, so it will replace current buffer contents with the output. However, if I try:
(shell-command-on-region
(point-min) (point-max) "wc" nil nil)
then the buffer is not deleted, and the output put into the "Shell Command Output" buffer. At first sight, I'd say the function is not correctly implemented. Even the two versions of the documentation seem not to correspond with the code.

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.

Emacs Org-Mode: how to fold block without going to block header?

I know I can go to a block header and fold/unfold by hitting the TAB key.
However suppose I'm inside a block that has hundreds of lines, and I just want to fold the current block, without having to go to the block header -- is there a keyboard short-cut that can do that? Or is there an elisp function that does that, so that I can bind some shortcut to that function?
Create a keybinding that performs the following function:
(defun zin/org-cycle-current-headline ()
(interactive)
(outline-previous-heading)
(org-cycle))
This will jump back to the previous headline and then cycle. Since the headline is already open, it will close it. It also places the point at the start of the headline.
If you wrap the two commands in (save-excursion ) it will retain the point, however that could lead to entering information inside the ellipsis without realizing it. Alternately you can change the command to call a non-interactive form:
(defun zin/org-cycle-current-headline ()
(interactive)
(org-cycle-internal-local))
This is equivalent to the above with (save-excursion ).
C-c C-p will get you to the heading, TAB will fold. You can create a keyboard macro for this, or the equivalent ELISP:
(defun up-n-fold ()
(interactive)
(progn
(outline-previous-visible-heading 1)
(org-cycle)))
Edit: corrected C-c p for C-c C-p as noted by many below. Thanks!
I am not sure whether such a function exists, but it is not hard to create one. Just replace the following keystrokes with functions: C-M-r^*Entertab.