Friday, April 9, 2021

Syntax highlighting of multiple languages in a single program

Check out this URL:

https://vim.fandom.com/wiki/Different_syntax_highlighting_within_regions_of_a_file

My overarching goal is to be able to write a shell script (bash) with embedded code in other languages (Perl, AWK, sed, Python, Expect, whatever) and have the main script syntax highlighted as shell (of course), but have the regions containing code in other languages highlighted in those other languages.

Specifically, right now, I am working on a shell script with embedded Expect. Something like

expect -c '
# Expect script here
'

At the above link, there is a solution that sort of works. It's really quite frustrating, because it will work one minute then not the next and so on. I can't find any rhyme or reason to it.

So, if anyone wants to check it out and see what's wrong with it (note, BTW, that the comments section there indicate the same sort of frustration as I'm seeing - people complaining that it works, then it doesn't and so on), that'd be great. Also, please suggest alternatives. Thanks.

Here is the function they provide at the URL:

" Found at:
" https://vim.fandom.com/wiki/Different_syntax_highlighting_within_regions_of_a_file
function! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
let ft=toupper(a:filetype)
let group='textGroup'.ft
if exists('b:current_syntax')
let s:current_syntax=b:current_syntax
" Remove current syntax definition, as some syntax files (e.g. cpp.vim)
" do nothing if b:current_syntax is defined.
unlet b:current_syntax
endif
execute 'syntax include @'.group.' syntax/'.a:filetype.'.vim'
try
execute 'syntax include @'.group.' after/syntax/'.a:filetype.'.vim'
catch
endtry
if exists('s:current_syntax')
let b:current_syntax=s:current_syntax
else
unlet b:current_syntax
endif
execute 'syntax region textSnip'.ft.'
\ matchgroup='.a:textSnipHl.'
\ keepend
\ start="'.a:start.'" end="'.a:end.'"
\ contains=@'.group
endfunction

After sourcing the above file, I do:

call TextEnableCodeSnip('expect','@begin=expect@','@end=expect@','SpecialComment')

Then I start typing (starting with the @begin...@ thing) and sometimes it works, sometimes it doesn't.

Also, the original instructions at the URL, have a line in there about :hi link
which I can't tell what it is there for or if it is needed. Sometimes, it works without it, sometimes not.

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/1689131849.206325.1617998848033%40mail.yahoo.com.

No comments:

Post a Comment