Move current line to the header of current buffer in Emacs - emacs

I'm trying to find a way to automate/simplify the following use case:
I'm somewhere in the middle of a long file and I paste something.
Then I would like to send/move the current line (to the top header of the currently opened file). Most often this is some import/require function.
All of these ideally should happen without losing the relative position in a file (without setting markers manually).
How can I do this?
If it is important, I use Emacs primarily in evil-mode.

Here is the code:
(defun move-region-to-beginning-of-buffer (beg end)
"Move the region to the beginning of the buffer, then go back."
(interactive "r")
(let ((text (buffer-substring beg end)))
(save-excursion
(delete-region beg end)
(goto-char (point-min))
(insert text))))
Use it by selecting the text (actually, right after paste it is already marked) to be sent to the beginning of the buffer, then M-x move-region-to-beginning-of-buffer RET.
You can also bind this command to a key the usual way.

Related

Open selection in different major mode.

Is it possible to select some parts of a text and open it in a different buffer with a different mode?
Fore example, if I often work in ESS mode (syntax highlighting for R),
astring <- '<form>
<input type="checkbox" id="foo", value="bar">
</form>'
if the text within the single quotes is selected, I would like to edit it in a new buffer HTML mode (similar to org-src-lang-modes in orgmode).
What you're describing is called an 'indirect buffer'. You create one by calling M-x clone-indirect-buffer. This creates a second copy of the buffer you're editing. Any changes made in one buffer are mirrored in the other. However, both buffers can have different major modes active, so one can be in ESS mode, and the other in HTML (or whatever you like).
See the manual for details.
Here is one method of handling the issue using narrow-to-region -- the example contemplates that the point (cursor) will be somewhere between the single quotes when typing M-x narrow-to-single-quotes. A simple two-line function can be used to exit -- (widen) (ess-mode); or, you can get fancy with recursive-edit. Of course, this is not the same as opening the text in a new buffer. A similar functionality can also be used to copy the region to a new buffer, but I am assuming that the original poster may want to incorporate the edited text back into the primary buffer.
(defun narrow-to-single-quotes ()
"When cursor (aka point) is between single quotes, this function will narrow
the region to whatever is between the single quotes, and then change the
major mode to `html-mode`. To exit, just type `M-x widen` and then
`M-x [whatever-previous-major-mode-was-used]`."
(interactive)
(let* (
(init-pos (point))
beg
end)
(re-search-backward "'" nil t)
(forward-char 1)
(setq beg (point))
(re-search-forward "'" nil t)
(backward-char 1)
(setq end (point))
(narrow-to-region beg end)
(html-mode)
(goto-char init-pos)))

Delete from current position to the beginning of line in emacs?

Ctrlk would delete everything from the current position of the cursor to the end of line. Is there some equivalence to delete everything from the current position to the beginning of line?
For me Ctrl-0Ctrl-k does what you want. I think this is the default configuration, it's certainly not something I've modified.
If this doesn't work try Ctrl-u0Ctrl-k. Again, that seems to be Emacs' default behaviour on my installation (Emacs 24.x, Mac OS X).
If you prefer to have lesser keybinding (rather than having separate key to delete line, or having to invoke prefix-argument). You can use crux-smart-kill-line
which will "kill to the end of the line and kill whole line on the next
call". But if you prefer delete instead of kill, you can use the
code below.
For point-to-string operation (kill/delete) I recommend to use zop-to-char
(defun aza-delete-line ()
"Delete from current position to end of line without pushing to `kill-ring'."
(interactive)
(delete-region (point) (line-end-position)))
(defun aza-delete-whole-line ()
"Delete whole line without pushing to kill-ring."
(interactive)
(delete-region (line-beginning-position) (line-end-position)))
(defun crux-smart-delete-line ()
"Kill to the end of the line and kill whole line on the next call."
(interactive)
(let ((orig-point (point)))
(move-end-of-line 1)
(if (= orig-point (point))
(aza-delete-whole-line)
(goto-char orig-point)
(aza-delete-line))))
source
Emacs has steep learning curve. When a new user encounters this problem, she should record a macro of 2 keystrokes: Shift+Ctrl+a and Ctrl-w (cut), name it, save it, and set up a key binding so that the macro is available in the subsequent Emacs sessions.

How to use (interactive "r") function in this situation?

I defined a function and wanted to ues the
region as optional parameters.
(defun my-grep-select(&optional beg end)
(interactive "r")
(if mark-active
(....)
(....))
I wanted to grep the select chars in the buffer if the mark is active,
or grep the word under the cursor in the buffer if the mark is not active.
But In the situation: I opened the file and haven't select anything, Then run the command my-grep-select, emacs complains:
The mark is not set now, so there is no region
How can I eliminate this complains? Thanks.
The right way to do it might be:
(defun my-grep-select(&optional beg end)
(interactive
(if (use-region-p) (list (region-beginning) (region-end))
(list <wordbegin> <wordend>)))
...)
You don't need to use (interactive "r"). Instead, you could just check if region is active using (region-active-p) or similar then use (region-beginning) and (region-end) else do whatever else.
Perhaps there is choice to be made when region is active and a different set of parameters are passed...
You can also just use M-n or <down> in mini-buffer (after issuing M-x grep command) to insert selected text.

How to hide extra information in Emacs

I want to open an XML file and process it in a special way in Emacs. (Let's say a major mode which is customized to open XML files and process it and present it in a special way)
What I want to do is to hide the extra markup tags in XML and show just the content to the user. Can anyone advice me how I should do this?
`<name id=22> Luke </name>`
=> I just want "Luke" to be shown.
One way to do this would be to use a regular expression to extract the element information from your XML, and then open a temporary buffer for viewing into which you paste that element information. i'm not sure that narrowing is granular enough to hide the markup and display only the element information.
Having said that, an alternative to the temporary buffer approach would be to extract the element information, paste it into the bottom of the file, and then narrow to just that portion of the file so that the source markup is invisible.
The function below does approximately what I have in mind:
(defun show-xml-entities ()
(interactive)
(save-excursion
(let ((old-max (point-max))) ;; save current end of buffer
(goto-char (point-min)) ;; go to beginning of buffer
(while (re-search-forward ">\\([^<>]+\\)<" nil t) ;; search for elements until not found
(when (> (length (match-string-no-properties 1)) 0) ;; if match is non-zero length
(setq temp (point-marker)) ;; save end of match
(goto-char (point-max)) ;; go to end of buffer
;; paste current match to end of buffer
(insert (concat (buffer-substring-no-properties (match-beginning 1) (match-end 1))))
(goto-char (marker-position temp)) ;; return to end of current match
)
)
(narrow-to-region old-max (point-max))) ;; narrow to newly pasted element text
)
)
Logical steps would be
- calculate starting buffer end position (point-max) and sav in a var
- loop through your XML, collecting your entity information and pasting it after the saved position
- when done call (narrow-to-region original-point-max (point-max)). This will hide all the XML so that only your entity text is visible.
M-x sgml-hide-tags RET
see in menu SGML section VIEW some more related commands

How do I change read/write mode for a file using Emacs?

If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?
M-x read-only-mode
in very old versions of Emacs, the command was:
M-x toggle-read-only
On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "read-only-mode" to call the correct elisp function.
If you are using the default keyboard bindings,
C-x C-q
(which you read aloud as "Control-X Control-Q") will have the same effect. Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary.
Following up from the commentary: you should note that the writeable status of the buffer does not change the writeable permission of the file. If you try to write out to a read only file, you'll see a confirmation message. However, if you own the file, you can write out your changes without changing the permissions on the file.
This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission. I tend to forget that last step, leaving potentially critical files open for accidental changes later on.
Be sure you're not confusing 'file' with 'buffer'. You can set buffers to read-only and back again with C-x C-q (toggle-read-only). If you have permission to read, but not write, a file, the buffer you get when you visit the file (C-x C-f or find-file) will be put in read-only mode automatically. If you want to change the permissions on a file in the file system, perhaps start with dired on the directory that contains the file. Documentation for dired can be found in info; C-h i (emacs)dired RET.
What I found is M-x set-file-modes filename mode
It worked at my Windows Vista box.
For example: M-x set-file-modes <RET> ReadOnlyFile.txt <RET> 0666
As mentioned up there by somebody else: M-x toggle-read-only would work.
However, this is now deprecated and M-x read-only-mode is the current way to do it, that it is set to C-x C-q keybinding.
CTRL + X + CTRL + Q
If only the buffer (and not the file) is read-only, you can use toggle-read-only, which is usually bound to C-x C-q.
If the file itself is read-only, however, you may find the following function useful:
(defun set-buffer-file-writable ()
"Make the file shown in the current buffer writable.
Make the buffer writable as well."
(interactive)
(unix-output "chmod" "+w" (buffer-file-name))
(toggle-read-only nil)
(message (trim-right '(?\n) (unix-output "ls" "-l" (buffer-file-name)))))
The function depends on unix-output and trim-right:
(defun unix-output (command &rest args)
"Run a unix command and, if it returns 0, return the output as a string.
Otherwise, signal an error. The error message is the first line of the output."
(let ((output-buffer (generate-new-buffer "*stdout*")))
(unwind-protect
(let ((return-value (apply 'call-process command nil
output-buffer nil args)))
(set-buffer output-buffer)
(save-excursion
(unless (= return-value 0)
(goto-char (point-min))
(end-of-line)
(if (= (point-min) (point))
(error "Command failed: %s%s" command
(with-output-to-string
(dolist (arg args)
(princ " ")
(princ arg))))
(error "%s" (buffer-substring-no-properties (point-min)
(point)))))
(buffer-substring-no-properties (point-min) (point-max))))
(kill-buffer output-buffer))))
(defun trim-right (bag string &optional start end)
(setq bag (if (eq bag t) '(?\ ?\n ?\t ?\v ?\r ?\f) bag)
start (or start 0)
end (or end (length string)))
(while (and (> end 0)
(member (aref string (1- end)) bag))
(decf end))
(substring string start end))
Place the functions in your ~/.emacs.el, evaluate them (or restart emacs). You can then make the file in the current buffer writable with M-x set-buffer-file-writable.
If you are looking at a directory of files (dired), then you can use Shift + M on a filename and enter the modespec, the same attributes used in the chmod command.
M modespec <RET>
See the other useful commands on files in a directory listing at
http://www.gnu.org/s/libtool/manual/emacs/Operating-on-Files.html
I tried out Vebjorn Ljosa's solution, and it turned out that at least in my Emacs (22.3.1) there isn't such function as 'trim-right', which is used for removing an useless newline at the end of chmod output.
Removing the call to 'trim-right' helped, but made the status row "bounce" because of the extra newline.
C-x C-q is useless. Because your also need the permission to save a file.
I use Spacemacs. It gives me a convenient function to solve this question. The code is following.
(defun spacemacs/sudo-edit (&optional arg)
(interactive "p")
(if (or arg (not buffer-file-name))
(find-file (concat "/sudo:root#localhost:" (ido-read-file-name "File: ")))
(find-alternate-file (concat "/sudo:root#localhost:" buffer-file-name))))
I call spacemacs/sudo-edit to open a file in emacs and input my password, I can change the file without read-only mode.
You can write a new function like spacemacs/sudo-edit.