I'm getting started with using VIM to program Python. I've run into some issues, hopefully someone can help me with this one.
The "gd" command is supposed to take you to the first place a variable is defined/used in the current function. From what I understand, it's the same as doing "[[" to go to the top of the function, then performing a search for the variable name.
Problem is, when I try this in Python functions, vim finds the first occurrence of the variable in the entire file.
Any thoughts on why this happens/how I can fix this?
I think the problem is due to the way that Vim treats a function. From the documentation for [[:
*[[*
[[ [count] sections backward or to the previous '{' in
the first column. |exclusive|
Note that |exclusive-linewise| often applies.
Unless a section is somehow defined specifically for python files somewhere (I'm not convinced this is possible as they're supposed to be two-letter nroff sections), this will assume that there should be an open-brace in the first column, which isn't relevant for python files.
I'd suggest asking on the Vim mailing list to see if there are any plugins or work-arounds for this. Alternatively, you could define a mapping like this:
nmap gd :let varname = '\<<C-R><C-W>\>'<CR>?\<def\><CR>/<C-R>=varname<CR><CR>
This could be done more elegantly with a function, but this was just a quick hack that should work. It maps gd to a function that sets the variable 'varname' to hold the word the cursor is on, searches backward for def and then searches forward for the variable:
:let varname = " Variable setting
'\< " String start and word boundary
<C-R><C-W> " Ctrl-R, Ctrl-W: pull in the word under the cursor
\>' " Word boundary and string end
<CR> " Enter - finish this command
? " Search backwards for...
\<def\> " def but not undefined etc (using word boundaries)
<CR> " Enter - Perform search
/ " Now search forward
<C-R>= " Pull in something from an expression
varname<CR> " The expression is 'varname', so pull in the contents of varname
<CR> " Enter - perform search
I didn't redefine varname in my Vim configuration, and it works good, but I have vim compiled with python.
Maybe this is the problem?
Do you have VIM version 7.x installed, compiled with Python support? To check for this, enter :python print “hello, world”
into VIM. If you see an error message like
E319: Sorry, the command is not available in this version,
then it’s time to get a new one.
Related
I'm trying to use docstrings w/ triple-quotes in my Jupyter notebooks using Python 2.7 .
I can disable the autoclose brackets/quotes thing but I'm quite keen on them; major increase in workflow.
Does anyone know how to do triple quotes without over-quoting while keeping the autoclose feature?
If I press the " key 3x I get """""";
If I press it 3x and delete once, I get """" pressing; and
If I press it 3x and delete twice, I get ""
Annoying, right? How can I have the best of both worlds (autoclose | docstrings) ?
This is a pretty low-level question, but I haven't seen an easy fix anywhere so the answer should be useful for the community. If you downvote, can you explain why this is a poor question please?
Nothing is wrong. When you type three " your cursor is at the middle of the resulting six. Thus, anything you type is within the string and has been auto-closed.
Type this exact string of characters: """This is working without clicking or otherwise moving the cursor. The result will be a correcly formatted string, because it will have auto-closed the string. Therefore you have both strings and autoclose.
MyDir = os.getcwd().split(os.sep)[-1]
command = re.search(r"(MyDir)", body).group(1)
etc
hi guys,
am trying to have a python script (on windows)
search my outlook email body for certain words using regex
that works fine, coupled with the rest of the script (not shown)
but the minute i want it to search for a variable, ie MyDir it does nothing when i fire off an email to
myself with the word: documents in the body of the email (documents, being the directory the script is located on this occasion; though should populate the variable with whatever top level directory the script is being run from)
now i have read and seen that re.escape is a method to consider, and have copied lots of different variations, and examples
and adapted it to my scenario, but none have worked, i have built the regex as a string also, still no joy
is there anything in my MyDir "variable" that is throwing the regex search off?
am stumped, its my first python script, so am sure am doing something wrong - or maybe i cant use os.getcwd().split(os.sep)[-1] inside regex and have it not look at the variable but the literal string!
thanks for any help, as i have read through similar regex+variable posts on here but havent worked for me
:)
Try:
command = re.search("(" + re.escape(MyDir) + ")", body).group(1)
You searching for the string MyDir not the variable MyDir. You could use str.format
command = re.search(r"({})".format(MyDir), body).group(1)
If you are a bash/posix sh wizard you will know the $(command substition) feature in bash, which could even be inserted in a string. For example,
$ echo "I can count: $(seq 1 10 | tr -d '\n')"
I can count: 12345678910
You can imagine all wild things to do with this, especially to make a dynamically formed string. No need to do if..else block outside the string; just embed the code inside! I am s spoiled by this feature. So here's the question: in python, can we do something similar? Is there one person already devising a module to accomplish this task?
(Just a side comment: admittedly having this kind of feature is powerful but also opening yourself to a security risk. The program can be vulnerable to code injection. So think thoroughly before doing this especially with a foreign string coming from outside the code.)
You can use eval() and all of it's potential risks...
Some good links here and here
See the built-in eval() function.
Are you looking for an fstring:
Instead of starting the string with '
We start the string with f'
And whenever we want to embed any script we just put inside these: {}
Does anybody know of a method, or perhaps a plugin, that will
automatically fold long docstrings in Python? I have docstrings in my
code that span several pages, so it is troublesome to keep paging
through them. The other tricky part is that there is embedded python
testing code in the docstrings, so that might make parsing them
difficult. Note that I only need to automatically fold the entire
docstring, regardless of what is in it.
This is a bit of a dirty hack, but you can go through the python syntax file (:sp $VIMRUNTIME/syntax/python.vim) and find all the syntax regions for triple-quoted strings (search for ''' and """) and add the fold keyword to the end of those statements. Then just set foldmethod=syntax for python files and the comments should be folded.
I'm not sure about a plugin or automation, but if you type zf/ you can then search for something and it will fold up to the next instance of it. So in a document like the following (where [] is the cursor):
def foo():
"""[]
Some long docstring
that takes up many
lines
"""
pass
Look at edit2 first for the updated search string!
If you use the command zf/"""[ENTER], it should fold everything from the current line (the beginning of the docstring) to the next occurrence of """ which should be the end of the docstring.
I know this isn't automation, but perhaps it will help in the interim, or lead you down the right path to automating it. See edit2 for a better search function, although I still don't know how to automate.
Hope this helps.
Edit: in a corollary, you can search for any docstring with /"""\_.\{-}""", although this will also return the code within the docstring. To search for a function definition followed by a docstring, you can use /def\_.\{-}"""\_.\{-}""", although this breaks on a def inside the docstring.
Edit2: Actually, some more playing with regexs led me to this: /def.\{-}):\_s*"""\_.\{-}""" which should find any function followed by a docstring. It searches for def followed by any characters, then ): followed by a newline and/or whitespace followed by """ followed by any number of lines than the next """, but always ensures the 2nd triple quote is the one immediately following the first.
In your .vimrc add:
" folding
set foldmethod=indent
This will auto-fold at every indentation, which, in python, translates to docstrings. It works VERY VERY nice. Give it a try. The above answer is correct, but requires a bunch of keystrokes (blah!)
I think I've found a slight improvement to the answer of #too_much_php by trying to figure out how to do the same thing without root access. Copying the syntax region definitions from $VIMRUNTIME/syntax/python.vim to ~/.vim/after/syntax/python.vim and editing them solved the problem for me. Here's my code for ~/.vim/after/syntax/python.vim:
syn region docString1
\ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend transparent fold
syn region docString2
\ start=+[uU]\=[rR]\z('''\|"""\)+ end="\z1" keepend transparent fold
Now I can run :set foldmethod=syntax to fold docstrings.
PS: Credits to #too_much_php for the initial idea
You can do this with :set foldmethod=marker foldmarker=""",""", I think. I haven't tested it, but that should do the trick. The arguments to foldmarker are start and end markers.
I wrote a vimscript plugin many years ago to do exactly this, but never got around to publishing it. I've put it up as a gist, but have also pasted the source below. I've also replicated its functionality for Sublime Text here.
"
" Fold multi-line Python comments into one line.
"
" Also maps the "-" key to toggle expansion and <C-f> to toggle all folding.
"
setlocal foldmethod=syntax
setlocal foldtext=FoldText()
setlocal fillchars=
map <buffer> - za
map <buffer> <C-f> :call ToggleFold()<CR>
let b:folded = 1
hi Folded gui=bold cterm=bold guifg=cyan ctermfg=cyan guibg=NONE ctermbg=NONE
function! ToggleFold()
if b:folded == 0
exec "normal! zM"
let b:folded = 1
else
exec "normal! zR"
let b:folded = 0
endif
endfunction
function! s:Strip(string)
return substitute(a:string, '^[[:space:][:return:][:cntrl:]]\+\|[[:space:][:return:][:cntrl:]]\+$', '', '')
endfunction
" Extract the first line of a multi-line comment to use as the fold snippet
function! FoldText()
let l:snippet = getline(v:foldstart)
if len(s:Strip(l:snippet)) == 3
let l:snippet = strpart(l:snippet, 1) . s:Strip(getline(v:foldstart + 1))
endif
return '+' . l:snippet . ' ...'
endfunction
My solution involves using SimpylFold. After installing it using Vundle, I put this in my vimrc file:
autocmd FileType python setlocal foldlevel=2
Which makes all docstrings folded by default when you open a python file, which is super awesome.
How can I reverse a word in Vim? Preferably with a regex or normal-mode commands, but other methods are welcome too:
word => drow
Thanks for your help!
PS: I'm in windows XP
Python is built in supported in my vim, but not Perl.
Here is another (pythonic) solution based on how this works:
:echo join(reverse(split('hello', '.\zs')), '')
olleh
If you want to replace all words in the buffer,
:%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g
This works by first creating a list of characters in the word, which is reversed and joined back to form the word. The substitute command finds each word and then passes the word to the expressions and uses the result as replacement.
This Tip might help: http://vim.wikia.com/wiki/Reverse_letters
It says:
Simply enable visual mode (v), highlight the characters you want inverted, and hit \is. For a single word you can use vw (or viw): viw\is
vnoremap <silent> <Leader>is :<C-U>let old_reg_a=#a<CR>
\:let old_reg=#"<CR>
\gv"ay
\:let #a=substitute(#a, '.\(.*\)\#=',
\ '\=#a[strlen(submatch(1))]', 'g')<CR>
\gvc<C-R>a<Esc>
\:let #a=old_reg_a<CR>
\:let #"=old_reg<CR>
There are more solutions in the comments.
Assuming you've got perl support built in to vim, you can do this:
command! ReverseWord call ReverseWord()
function! ReverseWord()
perl << EOF
$curword = VIM::Eval('expand("<cword>")');
$reversed = reverse($curword);
VIM::Msg("$curword => $reversed");
VIM::DoCommand("norm lbcw$reversed");
EOF
endfun
And potentially bind that to a keystroke like so:
nmap ,r :ReverseWord<CR>
I don't have Python supported on my VIM, but it looks like it would be pretty simple to do it with Python. This article seems like a good explanation of how to use Python in VIM and I'm guessing you'd do something like this:
:python 'word'[::-1]
The article indicates that the result will appear in the status bar, which would be non-optimal if you were trying to replace the string in a document, but if you just want to check that your girlfriend is properly reversing strings in her head, this should be fine.
If you have rev installed (e.g. via MSys or Cygwin) then it's really not this difficult.
Select what you want to reverse and filter (%! <cmd>) it:
:%! rev
This pipes your selection to your shell while passing it a command.
if your version of VIM supports it you can do vw\is or viw\is (put your cursor at the first letter of the word before typing the command)... but I have had a lot of compatibility issues with that. Not sure what has to be compiled in or turned on but this only works sometimes.
EDIT:
\is is:
:<C-U>let old_reg_a=#a<CR>
\ :let old_reg=#"<CR>
\ gv"ay :let #a=substitute(#a, '.\(.*\)\#=', '\=#a[strlen(submatch(1))]', 'g')<CR>
\ gvc<C-R>a<Esc> :let #a=old_reg_a<CR>
\ :let #"=old_reg<CR>
Didn't remember where it came from but a google search come this article on vim.wikia.com. Which shows the same thing so I guess that's it.
Well you could use python itself to reverse the line through the filter command. Say the text you had written was:
Python
You could reverse it by issuing.
:1 ! python -c "print raw_input()[::-1]"
And your text will be replaced to become:
nohtyP
The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input.
There is a tricky way to do this if you have Vim compiled with +rightleft. You set 'allowrevins' which let you hit Ctrl+_ in insert mode to start Reverse Insert mode. It was originally made for inserting bidirectional scripts.
Type your desired word in Insert mode, or move your cursor to the end of an already typed word. Hit Ctrl+_ and then pick a completion (i_Ctrl-x) method which is the most likely not to return any results for your word. Ysing Ctrl+e to cancel in-place completion does not seem to work in this case.
I.e. for an unsyntactic text file you can hit in insert mode Ctrl+x Ctrl+d which is guaranteed to fail to find any macro/function names in the current file (See :h i_CTRL-X_CTRL-D and:h complete for more information).
And voila! Completion lookup in reverse mode makes the looked up word reverse. Notice that the cursor will move to the beginning of that word (it's reversed direction of writing, remember?)
You should then hit Ctrl+_ again to get back to regular insert mode and keyboard layout and go on with editing.
Tip: You can set 'complete' exclusively (for the buffer, at least) to a completion option that is guaranteed to return no result. Just go over the options in :h 'complete'. This will make the easy i_Ctrl-N / i_Ctrl-P bindings available for a handy word reversal session. You can ofcourse further automate this with a macro, a function or a binding
Note: Setting/resetting 'paste' and 'compatible' can set/reset 'allowrevins'. See :h allowrevins.
If you have some time on your hands, you can bubble your way there by iteratively transposing characters (xp)...
I realize I'm a little late to the game, but I thought I'd just add what I think is the simplest method.
It's two things:
Vim's expression register
pyeval (py3eval on recent vim releases) function
So to reverse a word you would do the following:
"ayiw yank word into register a
<C-r>=py3eval('"".join(reversed(str(' . #a ')))') use vim's = (expression) register to call the py3eval function which evaluates python code (duh) and returns the result, which is then fed via the expression register into our document.
For more info on the expression register see https://www.brianstorti.com/vim-registers/#the-expression-and-the-search-registers
you can use revins mode in order to do it:
at the beginning type :set revins. from now on every letter you type will be inserted in a reverse order, until you type :set norevins to turn off. i.e, while revins is set, typing word will output drow.
in order to change an existing word after revins mode is set, and the cursor on beginning of the word, type:
dwi<C-r>"<ESC>
explanation:
dw deleted a word.
i to enter insert mode
<C-r>" to paste the last deleted or yaked text in insert mode, <ESC> to exit insert mode.
remember to :set norevins at the end!