I'm trying to swap the contents of a region with the text of the same width region below it. I think I should be able to atleast correctly capture the region on the next line using the code below, assuming I can get the positions for them. Any suggestions on how I should implement pos-at-line-col or is there already a function to do this?

(defun region-selected ()
  "Return a list of the currently selected region if active."
  (if (use-region-p)
      (list (region-beginning) (region-end))
    (list nil nil)))

(defun column-number-at-pos (pos)
  "Analog to line-number-at-pos."
  (save-excursion (goto-char pos) (current-column)))

(defun tabular-swap-region-down (beg end)
  "Swap the highlighted text with the same region on the next row."
  (interactive (region-selected))
  (let* ((selection (buffer-substring-no-properties beg end))
         (line      (line-number-at-pos beg))
         (bcol      (column-number-at-pos beg))
         (ecol      (column-number-at-pos end))
         (next-line (1+ line))
         (next-beg  (pos-at-line-col next-line bcol))
         (next-end  (pos-at-line-col next-line ecol))
         (next-sel  (buffer-substring-no-properties next-beg next-end)))
    (message "Region: %s Beginning column: %s Ending column: %s"
             next-sel (int-to-string bcol) (int-to-string ecol))))

1 Answer 1


Here is a version using forward-line and move-to-column:

(defun pos-at-line-col (l c)
    (goto-char (point-min))
    (forward-line l)
    (move-to-column c)

Note that next-error has to be able to do that, so you might want to start with functions parsing compilation output...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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