Vim and python - jump to definition key binding - python

The following youtube video shows that it is possible to jump to definition using vim for python.
However when I try the same shortcut (Ctrl-G) it doesnt work...
How is it possible to perform the same "jump to definition"?
I installed the plugin Ctrl-P but not rope.

This does not directly answer your question but provides a better alternative. I use JEDI with VIM, as a static code analyser, it offers far better options than ctags. I use the spacemacs key-binding in vim so with localleader set to ','
" jedi
let g:jedi#use_tabs_not_buffers = 0 " use buffers instead of tabs
let g:jedi#show_call_signatures = "1"
let g:jedi#goto_command = "<localleader>gt"
let g:jedi#goto_assignments_command = "<localleader>ga"
let g:jedi#goto_definitions_command = "<localleader>gg"
let g:jedi#documentation_command = "K"
let g:jedi#usages_command = "<localleader>u"
let g:jedi#completions_command = "<C-Space>"
let g:jedi#rename_command = "<leader>r"

Vim's code navigation is based on a universal database called tags file. It needs to be generated (and updated) manually. :help ctags lists some applications that can do that. Exuberant ctags is a common one that supports many programming languages, but there are also specialized ones, like ptags.py (found in your Python source directory at Tools/scripts/ptags.py).
Plugins like easytags.vim provide more convenience by e.g. automatically updating the tags file on each save.
The default command for jumping to the definition is CTRL-] (not CTRL-G; that prints the current filename; see :help CTRL-G), or the Ex command :tag {identifier}; see all at :help tag-commands.

Some suggestions for people reading other answers to this question in the future:
tags file has one limitation. If in your code multiple objects has the same name you will have problem using ctrl-] as it will jump to first one and not necessary correct one. In this situation you can use g ctrl-] (or :tjump command or :tselect command) to get selection list. Potentially you want to map ctrl-] to "g ctrl-]"
It is possible that you want to have possibility to jump to correct object. In that case you might want to use jedi vim and if you are used to c-] you might want to use this mapping for jedi goto let g:jedi#goto_command = ""
Lastly you want to use universal ctags instead of excuberant ctags because of better new files support (not necessary python).

If you're using YouCompleteMe there is a command for that
:YcmCompleter GoToDefinition
if you want to add a shortcut for doing that in a new tab
nnoremap <leader>d :tab split \| YcmCompleter GoToDefinition<CR>

Related

Using error names rather than error codes in pydocstyle's ignore file

My team's repo using pydocstyle to manage doc string standardization. I've been tasked with reformatting the relevant configuration file. Currently it looks something like this:
[pydocstyle]
ignore = D100,D203,D405
match = *.py
but we want something more like:
[pydocstyle]
ignore = "error-name1", "error-name2", "error-name3"
match = *.py
so that it's more obvious to readers what rules are being ignored. However from what I can see this is not mentioned in the documentation (here).
Instead I thought I'd do something like this:
[pydocstyle]
ignore =
D100, # corresponds to "error-name1"
D203, # corresponds to "error-name2"
D405 # corresponds to "error-name3"
match = *.py
But I don't know if this is valid syntax in this file, or how to check.
So my questions are:
Is there a way to the original task I was given (ignore="error-name1" etc)?
If not, would my pseudo-solution work?
Really appreciate any help!
The pseudo-solution is fine. You can test it by just running
pydocstyle --config=name_of_config_file
in console. Note name_of_config_file must conform to one of the standards listed here.

Python - How to fix CWE-117: Improper Output Neutralization for Logs

I have tried using clean = message.replace('\n', '').replace('\r', '').
But it still fails the veracode scan.
Is there any better way to do it?
Also I read about ESAPI Python but not getting any good documentation to fix this issue.
ESAPI Python unfortunately is an extremely long dead project. I don't have any Python alternatives, but the library hasn't had a commit since August 9, 2010.
I'm not familiar with Python web frameworks, but I do teach regularly about secure programming.
Every time you make a function call, you need to ask yourself the question:
"Am I passing this off of to an interpreter?"
If the answer is "yes," then you need to encode to ensure that THAT function is going to treat the input purely as data and not executable code.
In this particular case, if your logging has the potential to be interpreted by a browser (which is common) you'd also want to encode for HTML. However if your environment never uses html-based logging and is always raw text, this could be considered "mitigated" or a "false positive" depending on how your company has agreed to those terms.
Also, I like the practice of wrapping any user input with a unique delimiter. You can use square brackets, but I like strong visual cues in my logs.
Picture: [USERACTION] + userId + ' ►' + encode(userInput) + '◀'
Or even:
[USERACTION] + userId + ' ( ͡ʘ ͜ʖ ͡ʘ)' + encode(userInput) + '<:::::[]=¤ (▀̿̿Ĺ̯̿̿▀̿ ̿)'
Anything that helps make it obvious that someone has tampered with your logs is good. The louder the better!

Editor (Sublime, Notepad++, etc.) Paste 'around' existing text

Motivation: I was going around assigning parameters read in from a config file to variables in a function like so:
john = my_quest
terry = my_fav_color
eric = airspeed
ni = swallow_type
...
when I realized this was going to be a lot of parameters to pass. I thus decided I'd put these parameters in a nice dictionary, grail, e.g. grail['my_quest'] so that the only thing I needed to pass to the function was grail.
Question: Is there a simple way in Sublime (or Notepad++, Spyder, Pycharm, etc.) to paste grails['variable'] around those variables in one step, instead of needing to paste the front and back seperately? (I know about multiple cursors in Sublime, that does help, but I'd love to find a "highlight-variable-and-hit-ctrl-meta-shift-\" and it's done.)
Based on examples you provided, this is a simple task solvable using standard regex find/replace.
So in Notepad++, record this macro (for recording control examine Macro menu):
Press Ctrl+H to open Find/Replace dialog
Find what: = (.*)$
Replace with: = grail['\1']
Choose Regular Expression and press Replace All
If you finish recording the macro and you choose to save it, shortcut key is requested. Assign your favorite ctrl-meta-shift-\ and you are done.

Vim syntax highlighting of doxygen style docstrings in Python

I started working with doxygen to generate the documentation of my Python code.
I use doxypy filter to preprocess the Python docstrings.
My goal is to have a nice syntax highlighting of doxygen comments in Python.
When writing my mainpage in a dedicated .dox file, I found that the doxygen comments can be highlighted in vim with the following command:
set syntax=c.doxygen
I tried the same command for Python but I got nothing:
set syntax=python.doxygen
I also made some googling and couldn't find anything interesting
Here is a typical piece of code I'd like to highlight:
class CompilationTab:
"""
The compilation tab of the verif GUI. It contains the layout description
and the functions required to deal with specific behaviors of the tab
"""
def __init__(self, notebook, tab_name):
"""
The class constructor.
#param notebook Notebook: The parent #c Notebook widget
#param tab_name String: The display name of the tab
"""
Does anybody already fixed this issue?
Thank you for help!
If you look into syntax/doxygen.vim you can read in the preamble of the file that currently only
cpp, c, idl, doxygen and php
files are supported.
Since doxygen.vim works a lot with the syn region command i searched for the line that defines the multiline string in syntax/python.vim.
The interesting part of the command that defines this region is
syn region pythonString start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend
Derived from that what is in doxygen.vim and the above line you can add the following lines
"delete the following line if you don't want to have enhanced colors
let g:doxygen_enhanced_color=1
runtime! syntax/doxygen.vim
syn region doxygenComment matchgroup=pythonString start=+[uU]\=\z('''\|"""\)+ end="\z1" contains=doxygenSyncStart,doxygenStart,doxygenTODO keepend fold containedin=pythonString
to ~/.vim/after/syntax/python.vim or execute them by hand.
In addition you may have to customize the colors of the added doxygen highlighting groups by hand. At least i would do so since the resulting look doesn't conform with my taste.
Perhaps the fold argument of the syn command is of special interest for you. If you set foldmethod to syntax you can fold and unfold the multiline comments. That seems to be useful if you could no longer stand the view of those colors and are to lazy to adjust them :)
without doxygen highlighting:
with doxygen highlighting and g:doxygen_enhanced_color == 1:

Using imaplib, how can I create a mailbox without the \\NoSelect attribute

I'm attempting to create directory trees in an gmail IMAP account. I've used the "create()" command in imaplib, but it seems to add the \\Noselect attribute to the created folder. This breaks gmail's nested labels feature - is there a way to remove the \\Noselect attribute, or avoid it being created in the first place?
Example:
>> imap.create("foo/bar")
('OK', [b'Success'])
>> imap.list()
[b'(\\Noselect \\HasChildren) "/" "foo"', b'(\\HasNoChildren) "/" "foo/bar"',...
I figured out a solution - Not sure if it's the 'best' way though. When creating a nested mailbox in one command, the top level mailboxes automatically are flagged \\Noselect. While it may be hacky, you can remove this flag by creating each level explicitly.
Example:
folder = "abc/def/ghi/jkl"
target = ""
for level in folder.split('/'):
target += "{}/".format(level)
imap.create(target)
I'll leave the question open to see if anyone has a better solution.
bjeanes: Sam's solution works for me as long as I leave off the trailing hierarchy delimiter.
So, if I want to create the nested folder a/b/c, I first create just plain "a". If I do an xlist, it has the hasNoChildren flag set. Now I create "a/b", and an xlist will now show "a" with the "hasChildren" flag set, and "a/b" with the "hasNoChildren" flag set. Finally, I create "a/b/c", and now "b" has the "hasChildren" flag set as well. A look at the gmail web interface confirms this as well.
Sam: thanks for figuring this out and posting the solution. "Hacky" beats "not working." :^)

Categories

Resources