Ignore long lines in silversearcher

2.8k Views Asked by At

Right now I am using:

 ag sessions --color|cut -b1-130

But this will cause color artifacts if the search match is cut bu the cut command.

Silversearcher has this in the docs:

   --print-long-lines
          Print matches on very long lines (> 2k characters by default).

Can I change 2k to something else? (120 for me, because honestly never in any of the code I work with the real code is longer than that).

3

There are 3 best solutions below

3
On BEST ANSWER

Very strangely, the documented --print-long-lines actually does nothing at all, yet there is a working switch for this: -W NUM / --width NUM which is not documented at all. See https://github.com/ggreer/the_silver_searcher/pull/720

0
On
ag --width 400 string dir/

# In .bash_aliases (s is for short)
alias ags='ag --width 400'

Ignores lines longer than 400 chars.

1
On

I can think of three options:

  1. Just print the result of your search instead of the whole line, using the -o option: ag --color -o

  2. Use less instead of cut which nicely chops long lines at the screen size's width using the -S option (chop long lines) and the -R option (to deal with the color escape sequences): ag --color <pattern> | less -R -S

  3. Use something like sed or awk instead of cut: ag --color <pattern> |sed -E "s/(.{$COLUMNS}).*$/\1/"

Which will cut the returned line at the limit of your screen size. Of course, if you're determined to chop at 120 columns, you can: ag --color <pattern> |sed -E "s/(.{120}).*$/\1/"

This last option doesn't prevent the possibility of chopping in the middle of a color escape sequence; if you're really hellbent, you can modify the sed search pattern to ignore color escape sequences -- already answered on SO. That said, I don't see the purpose of doing this given the easiness and correctness of option 1 above.