Переключение скрытого атрибута для подсветки синтаксиса в VIM - PullRequest
3 голосов
/ 04 октября 2010

В настоящее время у меня есть файл синтаксиса, который анализирует файл журнала, очень похожий на следующий [это для системного журнала]:

syn match   syslogText  /.*$/
syn match   syslogFacility  /.\{-1,}:/  nextgroup=syslogText skipwhite
syn match   syslogHost  /\S\+/  nextgroup=syslogFacility,syslogText skipwhite
syn match   syslogDate  /^.\{-}\d\d:\d\d:\d\d/  nextgroup=syslogHost skipwhite

Я хотел бы, используя карту, переключать ли данныйгруппа (скажем, syslogHost) скрыта или нет.Есть ли способ сделать что-то вроде следующего псевдокода:

map <leader>ch :syn match syslogHost conceal!

и тем самым переключить определение syslogHost между:

syn match   syslogHost  /\S\+/  nextgroup=syslogFacility,syslogText skipwhite

и

syn match   syslogHost  /\S\+/  nextgroup=syslogFacility,syslogText skipwhite conceal

Спасибо.

Ответы [ 3 ]

4 голосов
/ 04 октября 2010

I думаю единственный способ сделать это с помощью функции:

map <leader>ch :call ToggleGroupConceal('sysLogHost')<CR>

function! ToggleGroupConceal(group)
    " Get the existing syntax definition
    redir => syntax_def
    exe 'silent syn list' a:group
    redir END
    " Split into multiple lines
    let lines = split(syntax_def, "\n")
    " Clear the existing syntax definitions
    exe 'syn clear' a:group
    for line in lines
            " Only parse the lines that mention the desired group
            " (so don't try to parse the "--- Syntax items ---" line)
        if line =~ a:group
                    " Get the required bits (the syntax type and the full definition)
            let matcher = a:group . '\s\+xxx\s\+\(\k\+\)\s\+\(.*\)'
            let type = substitute(line, matcher, '\1', '')
            let definition = substitute(line, matcher, '\2', '')
                    " Either add or remove 'conceal' from the definition
            if definition =~ 'conceal'
                let definition = substitute(definition, ' conceal\>', '', '')
                exe 'syn' type a:group definition
            else
                exe 'syn' type a:group definition 'conceal'
            endif
        endif
    endfor
endfunction
1 голос
/ 03 января 2018

Вот модификация оригинальной @ DrAl, которая работает как с синтаксическими группами, так и с регионами.

" function to toggle conceal attribute for a syntax group
function! ToggleGroupConceal(group)
    " Get the existing syntax definition for specified group
    redir => syntax_def
    exe 'silent syn list' a:group
    redir END
    " Split into multiple lines
    let lines = split(syntax_def, "\n")
    " Clear the existing syntax definitions
    exe 'syn clear' a:group
    for line in lines
        " Only parse lines that contain the desired group's definition
        " (skip "--- Syntax items ---" line and 'links to' lines)
        if line =~ a:group
            "echo 'line = ' . line
            " need to handle match and region types separately since type
            " isn't specified for regions in the syn list output like it is
            " for matches.
            let type = substitute(line, '\v' . a:group . '\s+xxx\s+(\k+)\s+(.*)', '\1', '')
            if type == 'match'
                " get args as everything after 'xxx match'
                let args = substitute(line, '\v' . a:group . '\s+xxx\s+(\k+)\s+(.*)', '\2', '')
            else
                " get args as everything after 'xxx'
                let args = substitute(line, '\v' . a:group . '\s+xxx\s+(.*)', '\1', '')
                if args =~ 'start' && args =~ 'end'
                    let type = 'region'
                endif
            endif
            "echo '    type = ' . type
            "echo '    args = ' . args
            " Either add or remove 'conceal' from the definition
            if args =~ 'conceal'
                exe 'syn' type a:group substitute(args, ' conceal', '', '')
            else
                exe 'syn' type a:group args 'conceal'
            endif
        endif
    endfor
endfunction
0 голосов
/ 21 января 2014

Вы также можете изменить синтаксис файла. У меня есть несколько правил скрытия для моих файлов json, которые не применяются для моих файлов javascript (например, я скрываю кавычки и конечные запятые, чтобы облегчить чтение файлов), поэтому, когда я хочу просмотреть все файл, который я просто использую set syntax=javascript. Возможно, вы могли бы пойти еще дальше и просто определить два набора правил для типов файлов (например, syslog.vim и syslog2.vim), где 1 наследует все из 2, а затем применяет скрытые правила, затем вы можете связать ключ для переключения между ними.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...