[Top][All Lists]

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

Re: [AUCTeX] Insert counter in Emacs tex file

From: Joost Kremers
Subject: Re: [AUCTeX] Insert counter in Emacs tex file
Date: Sat, 25 Aug 2018 20:30:06 +0200
User-agent: mu4e 1.1.0; emacs 26.1.50

On Fri, Aug 24 2018, Rodolfo Medina wrote:
Hi all...

In a MusiXTeX document, you insert several \bar(s) TeX commands, that I
manually count typing a number next to each occurence of `\bar':

 \bar %1
 \bar %2
 \bar %3

and so on. Of course, it gets very uncomfortable when editing the document and adding, in the middle of it, new \bar-s: then I have to re-write all the numbers, that may be dozens or hundreds...! So I was wondering if was possible
to have an automatic \bar numbering within my Emacs tex file...

I have a bunch of functions to help me with something similar. The following function allows me to renumber counters used as labels in a TeX document:

| (defun jk-renumber-counters (start regexp)
|   "Renumber counters.
| Renumbering starts at START. REGEXP describes the counters to be
| renumbered.  The actual number must be enclosed in a group."
|   (save-excursion
|     (goto-char (point-min))
| ;; because we incf the counter before using it, we need to adjust:
|     (let ((counter (1- start))
|           (counters (make-hash-table :test 'equal))
|           fn)
|       (while (re-search-forward regexp nil t)
|         (setq fn (match-string 1))
|         (replace-match (or (gethash fn counters)
| (puthash fn (format "%s" (cl-incf counter)) counters))
|                        nil nil nil 1)))))

This assumes that the counters are also used for referencing, so both need to be renumbered correctly, hence the hash table. If you don't reference your examples, the function could be simplified. The REGEXP argument is used to identify the counters. In my case, I use labels of the form `ex:01`, `ex:02`, etc. When run, this function renumbers all counters from the start of the document. I've added a START argument because sometimes I don't want the numbers to start at 1.

The function is rather dumb, because it doesn't distinguish between a label definition and a reference, so if the reference occurs before the definition, the numbering might be unintuitive. (In my case, that rarely happens, so it's good enough for me. ;-)

I also have a Yasnippet template that inserts a new label and automatically increases the counter. On first use, it goes through the document to look for the highest existing counter, so as not to create labels with the same number.

I can post all of the code if you're interested.

Joost Kremers
Life has its moments

reply via email to

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