tags:

views:

47

answers:

1

I have text files with tables like this:

   Investment advisory and                                                    
   related fees receivable           (161,570 )      (71,739 )      (73,135 )
   Net purchases of trading                                                   
   investments                        (93,261 )      (30,701 )      (11,018 )
   Other receivables                   61,216        (10,352 )      (69,313 ) 
   Restricted cash                     20,658        (20,658 )            -   
   Other current assets               (39,643 )       14,752             64   
   Other non-current assets            71,896        (26,639 )      (26,330 ) 

Since these are accounting numbers, parenthesized numbers indicate negative numbers. Dashes represent 0 or no number.

I'd like to be able to mark a rectangular region such as third column above, call a function (format-thousands-column), and automatically have -73.135-11.018-69.313+0.064-26.330 sitting in my kill-ring.

This is what I've come up with:

(defun div_by_1000 (astr)
  (number-to-string
   (/ (string-to-number astr) 1000.0))
  )

(defun format-column-base (format-hook)
  "format accounting numbers in a rectangular column. format-column puts the result
   in the kill-ring"
  (copy-rectangle-to-register 0 (min (mark) (point)) (max (mark) (point)) nil)
  (with-temp-buffer
(insert-register 0)
(replace-regexp "[^0-9.+( \n]" "" nil (point-min) (point-max))
(goto-char (point-min))
(while (search-forward "(" nil t)   
  (replace-match "-" nil t)
  (just-one-space)
  (delete-backward-char 1)
  )
(kill-new 
 (replace-regexp-in-string 
  "+-" "-" (mapconcat format-hook
              (split-string (buffer-substring (point-min) (point-max))) "+")))))

(defun format-column ()
  (interactive)
  (format-column-base 'identity)
)

(defun format-thousands-column ()
  (interactive)
  (format-column-base 'div_by_1000)
)

(global-set-key "\C-c\C-f" 'format-thousands-column)
(global-set-key "\C-c\C-g" 'format-column)

Although it seems to work, I suspect this function is poorly coded.

Do you see a better way to write format-column-base, or barring that, could you make suggestions on how to improve this code?

Edit: I've made some improvements; it can now do simple processing on the numbers, such as dividing each number by 1000. The processing on each number can also be customized with a format-hook.

+3  A: 

I'd check out org-mode's table features; they probably do a lot of what you're trying to do.

offby1
Thank you. I look forward to studying that.
unutbu