;;; -*- emacs-lisp -*-
;;;
;;; case-convert.el: performs semi-automatic conversion of words from
;;; camel-case to underscore-separated, and (maybe in the future)
;;; vice-versa
;;;
;;; Copyright Carlos Eduardo Scheidegger, 2007
;;;
;;; This is GPL v2 or later, your choice.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(require 'thingatpt)
(provide 'case-convert)

(defun iter-pos (fun start-pos end-pos)
  (cond
   ((> start-pos end-pos)
    (error "start-pos must be <= end-pos"))
   ((= start-pos end-pos) nil)
   (t (cons (funcall fun (char-after start-pos))
	    (iter-pos fun (1+ start-pos) end-pos)))))

(defun convert-char-to-underscore-case (char)
  (if (and (>= char (string-to-char "A"))
	   (<= char (string-to-char "Z")))
      ; char + 32 is the lowercase equivalent`
      (list (string-to-char "_") (+ char 32))
    (list char)))

(defun convert-to-underscore-case ()
  (interactive)
  (save-excursion
    (let* ((bounds (bounds-of-thing-at-point 'word))
	   (start (car bounds))
	   (end (cdr bounds)))
      (let ((word-before (word-at-point))
	    (word-after
	     (apply 'concat
		    (iter-pos 'convert-char-to-underscore-case start end))))
	(query-replace word-before word-after)))))
  
