0

File sample:

abc xyz aca sdasda 2.4 rn 3.4
abc xyz acs sd3sa 2.4 rn 3.1
abc xyz acs s12 2.1 rn 3.2

What Im trying to achieve here is if diff of values (ex: 3.4 and 2.4) is equal to or greater than 1.0 ,then both value should highlight. Above output should happen by default when I open a specific file (ex: file_output12 ).

vim version: 7.4
system:Centos 6.8
2
  • 1
    Are you sure you have Vim version 1.7.629? On one of Vim's FTPs I found Vim version 3.0 from 1996, and Centos 6.8 isn't so old.
    – grodzik
    Aug 24 '17 at 6:11
  • @ grodzik my bad ,version is 7.4
    – Rakesh.N
    Aug 24 '17 at 6:16
2

You can try something like this:

    function! HighlightDiff(match1, match2)
        let a=str2float(a:match1)
        let b=str2float(a:match2)
        if abs(a-b) >= 1.0
            call add(w:matchid, matchaddpos('WarningMsg', [[line('.'), col('.'), strlen(a:match1)]]))
            call add(w:matchid, matchaddpos('WarningMsg', [[line('.'), col('.')+strlen(a:match1) + 4, strlen(a:match2)]]))
        endif
    endfunction

    function! HighlightMatches()
        " ignore non-existing highlighting ids
        sil! call map(get(w:, 'matchid', []), 'matchdelete(v:val)')
        let w:matchid = []
        :%s/\(\d\+\%(\.\d\+\)\?\) rn \(\d\+\%(\.\d\+\)\?\)/\=HighlightDiff(submatch(1), submatch(2))/gn
    endfunction

    com! HighlightDiff :call HighlightMatches()

It uses a regular expression to find numbers optionally followed by . and more numbers, followed by rn followed again by numbers with an optional dot. It remembers the position of the two matches and uses matchaddpos() to highlight those positions if both numbers are greater than 1.0 apart. However, since we do not know exactly know, the position of the second match, we have do to some calculation from the first number to the second number (therefore I assume, that rn must always be 1 space followed by rn followed by 1 space).

It uses a :%s/../\=function/gn to perform the highlight. It means, that it actually runs a search/replace command, however because of the n flag, it won't replace anything, just call the function with the match.

All of this depends on the following version: Vim 7.4 compiled with float support, support for evaluating the expression even when using the n flag (patch 7.3.627), and matchaddpos

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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