3

I use siunitx to typeset units in LaTeX. This is quite painless when typesetting it directly because of Emacs's siunitx.el (see below).

However, sometimes I copy exercises or solutions containing units from the Web or other sources which are not formatted.

So I paste something like 50 m, 50m/s, 1.2 m or 1,2 m (german comma) into a file in Emacs. Now I want to be able to mark this, type C-c C-m \SI and make Emacs automatically recognize units and transform them to \SI{50}{m}, \SI{50}{m\per s}, \SI{1,2}{m} and so on.

Any ideas how to modify siunitx.el to achieve this?

;;; siunitx.el --- AUCTeX style file for Siunitx
(TeX-add-style-hook "siunitx"
              (function
               (lambda ()
             (TeX-add-symbols
              '("SI"       "Value" "Unit")
                      '("ang"      "Angle")
              ))))
4

Something, perhaps a tad more automatic (but in general it's hard to get the representation right, you'd probably need to adjust that for your specific use-cases).

(defun try-replace-units (begin end)
  (interactive "r")
  (save-excursion
    (goto-char begin)
    (while
        (re-search-forward
         "\\<\\([-+]?\\([0-9]+\\|[0-9]*[.,][0-9]+\\)\\(e[0-9]+\\)?\\)\\s-*\\([a-zA-Z/]+\\)" end)
      (replace-match
       (let ((num (replace-regexp-in-string
                   "\\." "," (match-string 1)))
             (unit (match-string 4)))
         (setf end (+ end 8))
         (format "\\SI{%s}{%s}"
                 num
                 (replace-regexp-in-string
                  "/" "\\per " (or unit "") nil t)))
       nil t))))
3

Instead of changing the existing LaTeX-arg-siunitx-unit function, which is designed for interactive use, I would define a new function to do this, to be inserted in your init file. Here is a start of a solution

(defun mg-LaTeX-siunitx-SI-region (beg end)
  (interactive "r")
  (goto-char end)
  (insert TeX-grcl)
  (goto-char beg)
  (insert (concat TeX-esc "SI{"))
  (skip-chars-forward "[0-9\.,]")
  (insert (concat TeX-grcl TeX-grop)))

It can be improved to automatically remove space between value and unit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.