I have many python code examples in my markdown files, which should be prepended with >>>
symbols.
So I write a vim function to do this job:
function AddShellPrompt() range
let lnum = a:firstline
while lnum <= a:lastline
let replaced_line = substitute(getline(lnum), '^\s\+', '&>>>', '')
call setline(lnum, replaced_line)
let lnum += 1
endwhile
endfunction
The problem is, for raw text like:
pow(2, 3)
8
I need only add >>>
before pow(2, 3)
, but not before 8
.
So I need to expand my regex.
It comes to me that if I only add >>>
for a line which contains any character of +-*/%(=
.
I can get a pretty good result(though not perfect).
But the problem is, how to write regex (especially in vim) which expresses Some of the characters in the given set has appeared in the current line?
A specific version of this question is:
How to detect if a line contains any +
, -
, *
, /
, %
, (
, =
, or even a word import
with a vim regex?
After the suggestion of the following answers, I got my improved function as below:
" Massively add python prompt symbol in a markdown file
function AddShellPrompt() range
let lnum = a:firstline
let match_pattern = '^\s\+.*[-\+_*/%=]\|.*import\|.*print\|.*def\|.*class\|.*while\|.*for\|.*if\|.*elif\|.*else\|.*pass\|.*continue\|.*break\|.*return'
while lnum <= a:lastline
let current_line = getline(lnum)
if match(current_line, match_pattern) == 0
let replaced_line = substitute(current_line, '^\s\+', '&>>>', '')
call setline(lnum, replaced_line)
endif
let lnum += 1
endwhile
endfunction
:global
with the pattern and the commandnorm I>>>
. The whole command would be:g/[-+*/%()]\|import/norm I>>>
. – Sakari Cajanus Aug 7 '15 at 12:36:g/[-+*/%()]\|import/s/^/>>>/
. (And yes, you can reuse that command as well, you don't need a complex function.) – Janis Aug 8 '15 at 17:31