Emacs specific region read only - emacs

How does one make a specific region in a text file read only when using emacs. I know ctrl+X+Q
to make the whole file a read only.
I am currently writing a code and I do not want to modify by accident the first 40 lines of my code while working on lines 41 and upwards.

Use text properties:
(defun set-region-read-only (begin end)
(interactive "r")
(add-text-properties begin end '(read-only t)))
Relevant Docs:
Text-Properties
Changing Properties
Special Properties (like read-only)

You can use narrow-to-region (C-x n n) to narrow the buffer just to the part you want to change. Then you won't see or be able to change the region you don't want to change.

You can also apply highlight-changes-mode. That way you can see which text is changed as it is in different color. narrow-to-region is a good solution. You can also use that with 2 buffer, so you can see the read-only text too, if needed.

Related

Overriding buffer-read-only in a region

I want most of a buffer to be read-only, except for one small region (part of a line).
I first tried something like
(setq buffer-read-only t)
(let ((inhibit-read-only t))
(add-text-properties start end '(read-only nil)))
but apparently buffer-read-only takes precedence over the read-only property.
I now have buffer-read-only set to nil, and set the read-only property to t on everything except the editable region. (Or read-only nil is regarded as a no-op.)
Is there a better way?
EDIT:
A more detailed description of my use case is that I want my buffer to display the output of an asynchronous process. The output is mostly for read-only viewing. However, a small part of a line is editable. This part will become input to the process if it is run again.
There's no simple way to do what you need in Emacs 24 and earlier. I agree with your solution to mark everything with the read-only property except the parts that you want to be editable.
Emacs 25 will have the inhibit-read-only property, which does exactly what you want. It was implemented by larsi on 16 November, and is used by eww.

Is there a good emacs mode for displaying and editing huge delimiter separated files?

I've been searching without finding for a while for a mode that makes editing huge tab/comma/colon-separated files easy. I've been wanting a mode that ensures that columns always line up, just like org-mode tables. I know I can easily turn the whole file into an org-mode table and then turn it back when I'm done, but that gets really slow with huge files, and is a hassle for quick edits (there's also the problem of what happens if a field contains a vertical bar). So does anyone know of either a mode or a built-in function/variable I can use so that I can get a file like
col1\tcol2\tcol3
very long column1\tcol2\tcol3
displayed like
col1 col2 col3
very long column1 col2 col3
? (perhaps with some color lining the separator)
Perhaps you could tell us what you've already found and rejected?
If you've been searching, then you must surely have seen http://emacswiki.org/emacs/CsvMode ? You don't mention it, or say why it wasn't any good, though.
SES (Simple Emacs Spreadsheet) might be a useful approach:
C-hig (ses) RET
You can create a ses-mode buffer and yank tab-delimited data into it (that's the import mechanism).
It's probably more hassle than you were after, though, and I'm not sure how well it will perform with "huge" files.
Try csv-mode, which works in at least Emacs 24.
You can set the variable csv-separators to change the separator if you do not use the default one (comma).
See EmacsWiki.
As #choroba mentioned, use csv-mode. To answer your question specifically:
Make sure your separator is in csv-separators, which for example you can set with
(setq csv-separators '("," " "))
Use csv-align-fields (default keybinding C-c C-a) to line up the field values into columns.
#unhammer's comment about aligning only visible lines is great. Their code properly indented:
(add-hook 'csv-mode-hook
(lambda ()
(define-key csv-mode-map (kbd "C-c C-M-a")
(defun csv-align-visible (&optional arg)
"Align visible fields"
(interactive "P")
(csv-align-fields nil (window-start) (window-end))
)
)
)
)
There is pretty-column.el, which I found in Group gnu.emacs.sources years ago (it was added in 1999). That group is now blocked, by Google. I just used pretty-column.el on a ~5000 line tab-separated text file that Org mode choked on (Org mode has a 999 line limit on converting such a file--for that reason).
Added in edit: This seems to now be called delim-col.el (see this Emacs Wiki entry); the author is the same person.

How to make flyspell bypass some words by context?

I use Emacs for writing most of my writings. I write using reStructuredText, and then transform them to LaTeX after some preprocessing since I write my citations รก-la LaTeX. This is an excerpt of one of my texts (in Spanish):
En \cite[pp.~XXVIII--XXIX]{Crnkovic2002} se brindan algunos riesgos
que se pueden asumir con el desarrollo basado en componentes, los
This text is processed by some custom scripts that deals with the \cite part so rst2latex can do its job.
When I activate flyspell-mode it signals most of the citation keys as spelling errors.
How can I tell flyspell not to spellcheck things within \cite commands.
Furthermore, how can I combine rst-mode and flyspell, so that rst-mode would keep flyspell from spellchecking the following?
reST comments
reST code literal
reST directive parameters and arguments
reST raw directive contents
Any ideas?
You can set the variable ispell-parser to the value 'tex so that flyspell will ignore (la)tex sequences. To do so, you can either set it manually in each buffer like so:
M-: (setq 'ispell-parser 'tex)
or you write a little function that will do that for you. Put the following in your .emacs file:
(defun flyspell-ignore-tex ()
(interactive)
(set (make-variable-buffer-local 'ispell-parser) 'tex))
Then you can still invoke it manually, using
M-x flyspell-ignore-tex
or you could add a hook that calls that function automatically whenever you edit a file of a certain type. You would do the latter by adding the newly defined function to your auto-mode-alist. Say your filenames typically end with ".rst", then add this line to your .emacs file:
(add-to-list 'auto-mode-alist '("\\.rst$" . flyspell-ignore-tex))
As for the second part of your question: making flyspell-mode ignore larger regions, such as, e.g., reST comments, is not easily achievable. It becomes clear when you think about the way flyspell works: it checks text on a word-by-word basis. For that, flyspell-word only looks at one word at a time which it sends to an ispell process running in the background. The ispell process does the dictionary lookup and returns whether or not the current word is correct. If flyspell-word had to check every single time whether or not the current word is part of a comment or other region that should not be checked, it would be rather slow, because that would include quite a bit of searching through the buffer.
Now of course, one could approach this a little bit smarter and first find the non-comment regions etc. and then do the word-by-word checking only in those parts that are outside of those regions - but unfortunately, that's not the way flyspell is implemented.
If you can do without the "fly" part, however, ispell-mode has a mechanism to customize which regions of a buffer can be skipped. This is done via the variable ispell-skip-region-alist. But although flyspell-mode works off ispell-mode, for the reasons outlined above that variable is not used by flyspell-mode.
You can also use flyspell-generic-check-word-predicate as I explained in this question at Super User.
(aspell's tex filter may do exactly what you want - but if you want a more general solution)
Although I am using the code below to persuade flyspell to not flag certain words with numbers in them,
you can use this sort of hook to match certain context.
looking-at starts at the position you want - so you may want to search backwards for start/end of whatever context you care about.
(when "another attempt to accept certain words flyspell/ispell/aspell flags as incorrect"
(defun flyspell-ignore-WordNumber99-stuff/ag (beg end info)
(save-excursion
(goto-char beg)
(cond
((or
(looking-at "\\bWord1\\b")
(looking-at "\\bWord99Foo\\b")
)
t)
(t nil)
)
)
)
)
(add-hook 'flyspell-incorrect-hook 'flyspell-ignore-WordNumber99-stuff/ag)

How to replace a region in emacs with yank buffer contents?

When I use VIM or most modeless editors (Eclipse, NetBeans etc.) I frequently do the following. If I have similar text blocks and I need to change them all, I will change one, copy it (or use non-deleting yank), select next block I need and paste the changed version over it. If I do the same thing in emacs (select region and paste with C-y), it doesn't replace the region, it just pastes at the cursor position. What is the way to do this in emacs?
Add this to your .emacs:
(delete-selection-mode 1)
Anything that writes to the buffer while the region is active will overwrite it, including paste, but also simply typing something or hitting backspace
Setting delete-selection-mode, as Michael suggested, seems the most natural way to do it.
However, that's not what I do :) Instead, I put the good stuff into a "register" -- for example, register "a" -- with C-x r x a. Then I kill the other copy, and copy the register into the same spot with C-x r g a.
This is convenient because killing doesn't affect the registers, so C-x r g a always inserts the good stuff.
The default way to do something like this is the not-entirely-elegant following:
Get your desired replacement text into the kill ring somehow (e.g., M-w).
Highlight the region to be replaced.
Delete it (C-w).
Replace it with the prior-copied region (C-y, M-y). This replaces the freshly deleted contents with the exact same text that you just deleted (C-y), and then re-replaces it with the next most-recently saved buffer in the buffer ring (M-y).
This would get to be a real pain if you wanted to do this 10 times with the same text, as the desired replacement would get pushed farther back in the kill ring each time you deleted a region, so you'd have to call M-w an increasing number of times each time you wanted to yank it.
I've also just discovered M-x delete-region, thanks to Emacs: how to delete text without kill ring?. As the question implies, this deletes the offending text without putting it into the kill ring, avoiding the problem of pushing your replacement text further down on the stack. And, as the relevant response mentions, you can bind this to a shortcut key of your choosing.
The way I do this is:
go to where you want the new stuff
paste the good stuff
your cursor is now between the new stuff and the stuff you want to get rid of
select forward until everything you want to get rid of is selected
delete it
It's a slightly different way of thinking about it. Paste what you want, then get rid of what you don't want, rather than replace what you don't want with what you do.
If you enable CUA-mode, this paste over selected region becomes the normal behaviour.
Use delete-selection-mode, so that pasted text replaces the active region.
Use the secondary selection, to paste the same text over and over, even if you alternately select a new region to replace.
See http://www.emacswiki.org/emacs/SecondarySelection.
For anyone landing on this who doesn't want to change the global setting like me, I use this function and key binding:
(defun replace-yank(beg end)
(interactive "r")
(kill-region beg end)
(yank 3))
(global-set-key (kbd "C-S-y") 'replace-yank)
I intentionally add the selected text to the kill ring incase I want it later, and yank what was previously first in the ring.
If you don't care to preserve the highlighted text in the kill ring you could use something similar to the answer above by ekneiling
(defun replace-yank(beg end)
(interactive "r")
(delete-region beg end)
(yank 1))
(global-set-key (kbd "C-S-y") 'replace-yank)
One advantage is the above can be done repeatedly.

How do I run an Emacs hook when a buffer is modified?

Building on Getting Emacs to untabify when saving certain file types (and only those file types) , I'd like to run a hook to untabify my C++ files when I start modifying the buffer. I tried adding hooks to untabify the buffer on load, but then it untabifies all my writable files that are autoloaded when emacs starts.
(For those that wonder why I'm doing this, it's because where I work enforces the use of tabs in files, which I'm happy to comply with. The problem is that I mark up my files to tell me when lines are too long, but the regexp matches the number of characters in the line, not how much space the line takes up. 4 tabs in a line can push it far over my 132 character limit, but the line won't be marked appropriately. Thus, I need a way to tabify and untabify automatically.)
Take a look at the variable "before-change-functions".
Perhaps something along this line (warning: code not tested):
(add-hook 'before-change-functions
(lambda (&rest args)
(if (not (buffer-modified-p))
(untabify (point-min) (point-max)))))
Here is what I added to my emacs file to untabify on load:
(defun untabify-buffer ()
"Untabify current buffer"
(interactive)
(untabify (point-min) (point-max)))
(defun untabify-hook ()
(untabify-buffer))
; Add the untabify hook to any modes you want untabified on load
(add-hook 'nxml-mode-hook 'untabify-hook)
This answer is tangential, but may be of use.
The package wide-column.el link text changes the cursor color when the cursor is past a given column - and actually the cursor colors can vary depending on the settings. This sounds like a less intrusive a solution than your regular expression code, but it may not suit your needs.
And a different, tangential answer.
You mentioned that your regexp wasn't good enough to tell when the 132 character limit was met. Perhaps a better regexp...
This regexp will match a line when it has more than 132 characters, assuming a tabs width is 4. (I think I got the math right)
"^\\(?: \\|[^ \n]\\{4\\}\\)\\{33\\}\\(.+\\)$"
The last parenthesized expression is the set of characters that are over the limit. The first parenthesized expression is shy.