4

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))))
Drew
  • 77,472
  • 10
  • 114
  • 243
wdkrnls
  • 3,707
  • 2
  • 28
  • 46
  • How about using move-to-column? See also vertical-motion if you use wrapped lines. Emacs has stuff built in for transpose lines, etc., if you haven't already checked those out. IF the position is visible, you may also wish to experiment with posn-at-point: https://www.gnu.org/software/emacs/manual/html_node/elisp/Accessing-Mouse.html The other stuff, however, doesn't rely upon point being visible. – lawlist Feb 09 '15 at 03:30
  • This thread appears to be directly on point to your question: http://stackoverflow.com/a/2423919/2112489 It cites another link that specifically deals with transposing regions using move-to-column: https://groups.google.com/forum/#!msg/gnu.emacs.help/dd2R_UV0LVQ/F06ihLb7hKcJ The thread cites another library that handles this issue. – lawlist Feb 09 '15 at 03:38

1 Answers1

8

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

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

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

sds
  • 6,104
  • 22
  • 39