;;; convert-to-table --- Convert a selected region to an `org-mode' table.

;;; Commentary:

;;; Code:

(defun leo/remove-excess-line-breaks (input)
  "Remove excess line breaks from INPUT."
  (let ((mylist (split-string input "\n")))
    ;; (setq mylist (remove-duplicates mylist :test 'string=))
    ;; (delete "" mylist)
    (string-join mylist "\n")
    ))

(defun set-nth (list n val)
  "Update LIST at position N with value VAL."
  (if (> n 0)
      (cons (car list)
            (set-nth (cdr list) (1- n) val))
    (cons val (cdr list))))

(defun leo/build-divider (cols)
  "Build an `org-mode' table divider with COLS columns."
  (let ((index 0)
        (output '()))

    (while (> cols index)
      (push "---" output)
      (setq index (+ index 1)))
    (concat "|" (string-join output "|") "|")))

(defun leo/convert-to-table (beg end)
  "Convert <RET> delimited region (BEG and END) into `org-mode' table."
  (interactive (if (use-region-p)
                   (list (region-beginning) (region-end))
                 (list nil nil)))
  (let (
        (input (leo/remove-excess-line-breaks (buffer-substring-no-properties beg end)))
        (cols (read-number "How many columns: "))
        )
    (if (and input cols)
        (let (
              (lines (split-string input "\n"))
              (length (length (split-string input "\n")))
              (times 1)
              (output "")
              )
          (setq output (mapcar (lambda (in) (concat " | " in)) lines))
          ;; (message "%s" output)
          (while (>= length (* times cols))
            (setq output (set-nth output (- (* times cols) 1) (concat (nth (- (* times cols) 1) output) " |\n")))
            (setq times (+ times 1))
            )
          (kill-region beg end)
          (let (
                (rows (split-string (string-join output "") "\n"))
                (first "")
                )
            (setq first (pop rows))
            (push (leo/build-divider cols) rows)
            (push first rows)
            (insert (string-join rows "\n"))
            ))
      (message "Nothing selected!"))))

(provide 'convert-to-table)
;;; convert-to-table.el ends here
