让less行号左对齐

Wayne posted @ Tue, 31 Aug 2010 17:54:47 +0000 in Experience , 5485 readers

用vim习惯于显示行号,用less也想要显示行号.没行号找东西太麻烦了.开始连能不能显示行号都不知道.看了man手册,发现可以用 -N ,只是在打开大文件的时候会略微拖慢点速度. 拖慢点就拖慢点了,无所谓. 于是设置了 "alias less=less -N". 然后又发现一个问题.这行号显示得也太别扭了.前面空了老大一块空白,后面跟个行号,然后一个空格之后就是正文了,很容易搞混.我于是想把行号分开点,如果能彩色那更好了.

查遍了man,除了看到个没效果的 -R 之外,没看到什么关于颜色的东西. 上网查了下, -R 是用来支持解析ANSI颜色代码的,而不是less自己能用颜色.至于对齐之类的,我都不知道怎么查......

于是就想着反正开源嘛,改源码吧. 从GNU上下载了最新的less,2008年产的418版.机器上原来用的是394版,略微升级了.解压后,看到好大一堆文件.然后开始找.都不知道关于打印行号的这段在哪个文件的哪个部分.在Linuxsir上也发帖问了,不过还没人给出答案. 好在看了数个文件后,机缘巧合之下,让我翻到了 line.c 这个文件.没翻几行,就找到了关键的地方.它的关键部分是这样写的:

 

if (linenums == OPT_ONPLUS)
        {    
                char buf[INT_STRLEN_BOUND(pos) + 2];
                int n;

                linenumtoa(linenum, buf);
                n = strlen(buf);
                if (n < MIN_LINENUM_WIDTH)
                        n = MIN_LINENUM_WIDTH;
                sprintf(linebuf+curr, "%*s ",n, buf);
                n++;  /* One space after the line number. */
                for (i = 0; i < n; i++) 
                        attr[curr+i] = AT_NORMAL;
                curr += n;
                column += n;
                lmargin += n;
        }  

 

要点在"sprintf(linebuf+curr, "%*s ",n, buf);"这一句.这句打印出了行号,并给不足最小长度MIN_LINENUM_WIDTH的地方填上了空白.如果我要单纯地去除这些空白,只需要把前面的"n = MIN_LINENUM_WIDTH" 这一整个条件判断去掉,然后改成"sprintf(linebuf+curr, "%s " buf);". 只是这样一来,在行号从一位变成两位,从两位变成三位等类似的时候,正文整体都会偏移一个字符,看上去很不美观.所以还是需要保留那些空白,最多把MIN_LINENUM_WIDTH改小一点.然而靠右对齐实在不可忍耐.所以我最后改成了"sprintf(linebuf+curr, "%-*s ",n, buf);" 在前面加一个"-",使之左对齐.

这样修改后,对齐问题算是解决了.就是颜色依然没法搞定.

SEBA 10th Social Mod said:
Thu, 29 Sep 2022 17:07:00 +0000

Every student of Assam Government and Private school class 10th standard student can download SEBA Question Paper for EVS by expert reference to guessing important questions for all chapters of EVS to all mediums of Hindi, English, Assamese, Bengali, Bodo, Manipuri, Garo, Nepali Medium general, SEBA 10th Social Model Paper curriculum and vocational course students to the academic year of 2023.very student of Assam Government and Private school class 10th standard student can download SEBA Question Paper for EVS by expert reference to guessing important questions for all chapters of EVS to all mediums


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter