[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Function to replace some strings from region and save result in kill
From: |
Marcin Borkowski |
Subject: |
Re: Function to replace some strings from region and save result in kill-ring |
Date: |
Sun, 08 Oct 2023 08:26:44 +0200 |
User-agent: |
mu4e 1.1.0; emacs 30.0.50 |
On 2023-10-07, at 19:38, PierGianLuca <luca@magnaspesmeretrix.org> wrote:
> Hi everyone!
>
> For some time I've wished to write a function that does the following:
>
> 1. Takes a string from (a) a region, if one is selected, or (b) user prompt,
> if a region is not selected.
>
> 2. Internally replaces a couple of regexp in the string with other strings.
> Specifically, the regexp "[ _]+" with "_", and "[.,;:?!'"`]" with ""
> (nothing).
>
> 3. Saves the new string obtained from the replacement into the kill-ring
>
>
> Note that the original region is *not* changed.
>
>
> I have basically no knowledge of elisp, so I tried to reverse-engineer and
> combine some functions with similar features that I have in my init file
> (origins forgotten in the depths of time). There is also an old post in this
> mailing list
> <https://lists.gnu.org/archive/html/help-gnu-emacs/2013-09/msg00219.html>
> with a partially similar request, yet with important differences.
>
>
> My starting point is this, which should take care of 1.:
>
>
> (defun changestring (&optional arg)
> "Replace some character in string and save to kill-ring."
> (interactive "p")
> (if (use-region-p)
> (let ((region (buffer-substring-no-properties (region-beginning)
> (region-end))))
> *** the replacing part should go here ***
> )
> (let ((region (read-string "String to be converted: ")))
> *** the replacing part should go here, again ***
> )
> )
> )
>
>
> I thought I should use something like "(kill-region ...)" somewhere; but not
> quite, because the actual region should be untouched. I'm also having
> difficulties using several query-replace-regexp within a lisp function.
>
> I'd appreciate any help!
First of all, you seem to want to repeat the replacing code, which is
not the best idea - better to first assign the text to be manipulated to
a variable (using `let'), then manipulate it.
While at that, if you want more than one expression in the "then" branch
if an `if', use `progn' or some similar construct.
Then, don't use `query-replace-regexp' in Elisp - use a `while' loop
with a `replace-regexp-in-string', for example.
Then, you're right that `kill-region' is not what you want. But if you
skim the source of `kill-region' (you don't even have to analyze or
fully understand it!), you'll find `kill-new', whose docstring says:
--8<---------------cut here---------------start------------->8---
Make STRING the latest kill in the kill ring.
--8<---------------cut here---------------end--------------->8---
Have you read the excellent "Intro to Emacs Lisp" by Robert Chassel?
Hth,
--
Marcin Borkowski
http://mbork.pl