I need a function which strips the leading and trailing whitespaces from a string.
func! RemoveWhitespaces(String)
...
return formattedString
endfunc
I was only able to find ways to substitute lines in buffer with their whitespaces stripped but this is not what I'm looking for.
How should I complete this function?
My attempt:
func! RemoveWhitespaces(string)
let string = a:string
let result = substitute(string, '\s\+$', '', '')
let result = substitute(string, '^\s\+', '', '')
silent return result
endfunc
Now to get your result you can:
:let var=RemoveWhitespaces(' my string with spaces ')
:echo var
update:
As romainl commentted, there is a easier way:
:let var=trim(' some text ')
Related
I am using the following function to get the Selected test
let s:drawscript = "somerandom.py"
func! GetSelectedText()
normal gv"xy
let result = getreg("x")
normal gv
return result
endfunc
vnoremap <tab><tab> :<c-u>call Box(GetSelectedText())<CR>
func! Box(text)
let s:b = '"' . a:text . '"'
echom s:b
" exec boxcmd
"echom 'hi'
let c = ["python3", s:drawscript, s:b]
execute ":.!".join(c, " ")
endfunc
I am trying to pass in the text selected to my python file, it works when I only select 1 line, but when I select multiple lines, there are "^#" symbols in the selected text which caused automatic execution which leads to an error. I just wanna pass in the text I have selected into the .py file.
It's a matter of escaping special characters for the shell. While you correctly thought of quoting the text, you missed to escape the line separator. There's the function shellescape() which takes care of this and more, so you can replace
let s:b = '"' . a:text . '"'
by
let s:b = shellescape(a:text, 1)
I am trying to create a vimrc function which will clean up a line by doing simple substitutions. The function is called upon CARRIAGE RETURN. The function is being called and is cleaning up the line contents. My question is how do I overwrite the previous content with the cleaned up content from inside the function?
function! CleanLine()
let s = getline( '.' )
let s = substitute( s, '( )', '()', 'g' )
let s = substitute( s, ';', '; ', 'g' )
let s = substitute( s, '(', ' (', 'g' )
"HOW DO I SET THE CURRENT LINE CONTENT AS s
endfunction
inoremap <CR> <C-R>=CleanLine()<CR>
thanks.
There is a function called setline()
Type :help setline() for help.
I'm getting a trailing characters error for the 'for loop' in the following lines of code and I've no clue why.
function! s:HashID(str) "{{{
let l:hash_id = 0
for i in split(a:str, '\zs')
l:hash_id += float2nr(pow(2, stridx('abcdefg', i)))
endfor
return l:hash_id
endfunction
What am I goofing up here?
You need let command to assign value to variable.
Suppose that I have a document like this, and I want to search for all occurences of the URL:
Vim resources: [http://example.com/search?q=vim][q]
...
[q]: http://example.com/search?q=vim
I don't want to type it out in full, so I'll place my cursor on the first URL, and run "uyi[ to yank it into the 'u' register. Now to search for it, I'd like to just paste the contents of that register into the search field by running:
/\V<c-r>u<CR>
This results in Vim searching for the string 'http:' - because the '/' character terminates the search field.
I can get around the problem by running this instead:
/\V<c-r>=escape(#u, '\/')<CR><CR>
But it's a lot of typing!
How can I create a mapping for Vim's commandline that simplifies this workflow?
My ideal workflow would go something like this:
press /\V to bring up the search prompt, and use very nomagic mode
hit ctrl-x to trigger the custom mapping (ctrl-x is available)
Vim listens for the next key press... (pressing <Esc> would cancel)
pressing 'u' would escape the contents of the 'u' register, and insert on the command line
Try this:
cnoremap <c-x> <c-r>=<SID>PasteEscaped()<cr>
function! s:PasteEscaped()
" show some kind of feedback
echo ":".getcmdline()."..."
" get a character from the user
let char = getchar()
if char == "\<esc>"
return ''
else
let register_content = getreg(nr2char(char))
return escape(register_content, '\/')
endif
endfunction
By the way, something that might be useful to know (if you don't already) is that you can use ? as the delimiter for :s. Which means that you could write a search-and-replace for an url like so:
:s?http://foo.com?http://bar.com?g
I've accepted Andrew Radev's solution, which solved the hard parts. But here's the version that I've added to my vimrc file, which adds a couple of enhancements:
cnoremap <c-x> <c-r>=<SID>PasteEscaped()<cr>
function! s:PasteEscaped()
echo "\\".getcmdline()."\""
let char = getchar()
if char == "\<esc>"
return ''
else
let register_content = getreg(nr2char(char))
let escaped_register = escape(register_content, '\'.getcmdtype())
return substitute(escaped_register, '\n', '\\n', 'g')
endif
endfunction
This should work:
whether you use / or ? (to search forwards, or backwards)
and when the pasted register includes multiple lines
Also, I changed the prompt. While waiting for a register, the prompt switches to \ - which seems like a suitable cue for 'PasteEscaped'. Also, I've appended a ", which mimics Vim's behavior after pressing <c-r> at the command line.
If you've any further suggestions for improvements, please leave a comment.
How about different workflow? For example, creating your own operator to search target text as is:
" https://gist.github.com/1213642
" Requiement: https://github.com/kana/vim-operator-user
map YourFavoriteKeySequence <Plug>(operator-search-target-text)
call operator#user#define('search-target-text', 'OperatorSerachTargetText')
function! OperatorSerachTargetText(motion_wise)
execute 'normal!' '`['.operator#user#visual_command_from_wise_name(a:motion_wise).'`]"xy'
let #/ = '\V' . escape(substitute(#x, '[\r\n]$', '', ''), '\')
normal! n
endfunction
I like #nelstrom's solution and made a small change to support escaping [ and ].
cnoremap <c-x> <c-r>=<SID>PasteEscaped()<cr>
function! s:PasteEscaped()
echo "\\".getcmdline()."\""
let char = getchar()
if char == "\<esc>"
return ''
else
let register_content = getreg(nr2char(char))
let escaped_register = escape(register_content, '\'.getcmdtype())
let escaped_register2 = substitute(escaped_register,'[','\\[','g')
let escaped_register3 = substitute(escaped_register2,']','\\]','g')
return substitute(escaped_register3, '\n', '\\n', 'g')
endif
endfunction
I'm trying to write a beautify.vim script that makes C-like code adhere to a standard that I can easily read.
My file contains only substitution commands that all begin with %s/...
However, when I try to run the script with my file open, in the manner :source beautify.vim, or :runtime beautify.vim, it runs but all the substitute commands state that their pattern wasn't found (patterns were tested by entering them manually and should work).
Is there some way to make vim run the commands in the context of the current buffer?
beautify.vim:
" add spaces before open braces
sil! :%s/\%>1c\s\#<!{/ {/g
" beautify for
sil! :%s/for *( *\([^;]*\) *; *\([^;]*\) *; *\([^;]*\) *)/for (\1; \2; \3)/
" add spaces after commas
sil! :%s/,\s\#!/, /g
In my tests the first :s command should match (it matches when applied manually).
I just recently wrote a similar beautifier script but I implemented it in what I think is a more flexible way; plus, I tried to come up with a mechanism to avoid substituting stuff within strings.
" {{{ regex silly beautifier (avoids strings, works with ranges)
function! Foo_SillyRegexBeautifier(start, end)
let i = a:start
while i <= a:end
let line = getline(i)
" ignore preprocessor directives
if match(line, '^\s*#') == 0
let i += 1
continue
endif
" ignore content of strings, splitting at double quotes characters not
" preceded by escape characters
let chunks = split(line, '\(\([^\\]\|^\)\\\(\\\\\)*\)\#<!"', 1)
let c = 0
for c in range(0, len(chunks), 2)
let chunk = chunks[c]
" add whitespace in couples
let chunk = substitute(chunk, '[?({\[,]', '\0 ', 'g')
let chunk = substitute(chunk, '[?)}\]]', ' \0', 'g')
" continue like this by calling substitute() on chunk and
" reassigning it
" ...
let chunks[c] = chunk
endfor
let line = join(chunks, '"')
" remove spaces at the end of the line
let line = substitute(line, '\s\+$', '', '')
call setline(i, line)
let i += 1
endw
endfunction
" }}}
Then I define a mapping that affects the whole file in normal mode, and only the selected lines in visual mode. This is good when you have some carefully formatted parts of the file that you don't want to touch.
nnoremap ,bf :call Foo_SillyRegexBeautifier(0, line('$'))<CR>
vnoremap ,bf :call Foo_SillyRegexBeautifier(line("'<"), line("'>"))<CR>