help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: avoid narrow-to-region (was: Re: replace-regexp)


From: Yuri Khan
Subject: Re: avoid narrow-to-region (was: Re: replace-regexp)
Date: Sun, 9 May 2021 19:27:30 +0700

On Sun, 9 May 2021 at 17:54, Emanuel Berg via Users list for the GNU
Emacs text editor <help-gnu-emacs@gnu.org> wrote:

> Proposal: Instead of quoting computer science theory, why
> don't _you_ write some Elisp and show us how you think it
> should be done?

Mostly because I don’t usually write code to solve tasks I never
encounter in my own workflow. (Unless specifically employed to write
such code, or doing an interview with a prospective employer.)

> It isn't because it is easier and more comfortable to broadly
> criticize someone or something else, than to be active and
> creative oneself - is it?

I’m not criticizing you, I’m advising you about a possible issue with
your code. At the same time, I’m taking an opportunity to raise
general awareness of sorting predicate requirements.

Now, because you asked nicely, here’s my take on implementing the
random shuffle algorithm.

(defun yk-shuffle-lines (begin end)
  "Reorder lines between BEGIN and END randomly.
If BEGIN or END is in the middle of a line, that line is included.
Any markers inside the region may move
to the beginning or end of their respective lines,
and won’t follow the text they were associated with."
  (interactive "*r")
  (save-excursion
    (let ((nlines (count-lines begin end)))
      (goto-char begin)
      (while (> nlines 1)
        (let* ((begin1 (line-beginning-position))
               (line1 (let ((end1 (line-end-position)))
                        (prog1 (buffer-substring begin1 end1)
                          (delete-region begin1 end1))))
               (_ (forward-line (random nlines)))
               (line2 (let* ((begin2 (line-beginning-position))
                             (end2 (line-end-position)))
                        (prog1 (buffer-substring begin2 end2)
                          (delete-region begin2 end2)))))
          (insert line1)
          (goto-char begin1)
          (insert line2))
        (forward-line)
        (setq nlines (1- nlines))))))

(The structure of let*/let/let* bindings may seem excessively complex,
but I’m taking care here to not expose bindings beyond their validity.
E.g. as soon as (delete-region begin1 end1) is executed, end1 no
longer refers to anything meaningful, so I drop that binding asap.)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]