1

I am trying to write a :sort wrapper that sorts from current column.

command! -bang -range=% -nargs=* Sortc exe '<line1>,<line2>sort<bang> <args> /\%' .. virtcol('.') .. 'v/'

E.g.

hello world
foo   bar
apple google

When the cursor is on [w]orld, :Sortc will sort into

foo   bar
apple google
hello world

It works in all cases except when in visual mode. E.g. From original text, I select all lines in virtual line mode and type :'<,'>Sortc, it ignores the column and sorts from beginning. i.e. virtcol('.'), returns 0.

Is there anyway to fix this such that it works in visual mode too?

Workaround: After it incorrectly sorts, run the same command again placing in the correct column, without the visual mode (i.e. @:), then it works.

Using visual block selection works.

1
  • Passing an argument to sort is easier: :command! -range=% -nargs=1 Sortc :<line1>,<line2> !sort -k<q-args>,<q-args>
    – r_31415
    Commented Sep 30, 2022 at 23:53

1 Answer 1

1

Before running any Ex command over a line range the cursor is always positioned to the column no. 1. So you've got your logic broken.

There can be different ways to fix it. I would probably choose taking column no. from "less-than" bookmark, and not from the cursor position (which is never a good idea anyway, as cursor can be moved to any of four(!) corners of the visual selection).

2
  • >taking column no. from "less-than" bookmark | How do you do that? What is "less-than" bookmark?
    – balki
    Commented Sep 29, 2022 at 18:09
  • @balki See Reference Manual, Basic Editing, motion.txt
    – Matt
    Commented Sep 29, 2022 at 20:44

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.