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.
Related
How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
You can use triple-quoted strings. When they're not a docstring (the first thing in a class/function/module), they are ignored.
'''
This is a multiline
comment.
'''
(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)
Guido van Rossum (creator of Python) tweeted this as a "pro tip".
However, Python's style guide, PEP8, favors using consecutive single-line comments, like this:
# This is a multiline
# comment.
...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
To protect against link decay, here is the content of Guido van Rossum's tweet:
#BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
From the accepted answer...
You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.
This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.
If you try to run this code...
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
You'll get either...
ValueError: invalid \x escape
...on Python 2.x or...
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...on Python 3.x.
The only way to do multi-line comments which are ignored by the parser is...
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()
In Python 2.7 the multiline comment is:
"""
This is a
multilline comment
"""
In case you are inside a class you should tab it properly.
For example:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.
If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.
There is no such feature as a multi-line comment. # is the only way to comment a single line of code.
Many of you answered ''' a comment ''' this as their solution.
It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.
Check the official documentation here
I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.
If you put a comment in
"""
long comment here
"""
in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use
# Long comment
# here.
If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.
If you don’t want to use plugins like the above you can use search and replace like
:.,.+1s/^/# /g
This will replace the first character on the current and next line with #.
Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.
macOS: Select code-block and then ⌘+/
Windows: Select code-block and then Ctrl+/
Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.
Here is an example:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
I would advise against using """ for multi line comments!
Here is a simple example to highlight what might be considered an unexpected behavior:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
Now have a look at the output:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.
If you want to comment multiple lines do so according to PEP 8 guidelines:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
Output:
I am a string
clearly I am also a string
Well, you can try this (when running the quoted, the input to the first question should quoted with '):
"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")
"""
a = input()
print(a)
print(a*5)
Whatever enclosed between """ will be commented.
If you are looking for single-line comments then it's #.
Multiline comment in Python:
For me, both ''' and """ worked.
Example:
a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)
Example:
a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign
print("Hello World") # printing
If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign
# single line comment
To write comments longer than 1 line, you use 3 quotes
"""
This is a comment
written in
more than just one line
"""
On Python 2.7.13:
Single:
"A sample single line comment "
Multiline:
"""
A sample
multiline comment
on PyCharm
"""
The inline comments in Python starts with a hash character.
hello = "Hello!" # This is an inline comment
print(hello)
Hello!
Note that a hash character within a string literal is just a hash character.
dial = "Dial #100 to make an emergency call."
print(dial)
Dial #100 to make an emergency call.
A hash character can also be used for single or multiple lines comments.
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
Hello
World
Enclose the text with triple double quotes to support docstring.
def say_hello(name):
"""
This is docstring comment and
it's support multi line.
:param name it's your name
:type name str
"""
return "Hello " + name + '!'
print(say_hello("John"))
Hello John!
Enclose the text with triple single quotes for block comments.
'''
I don't care the parameters and
docstrings here.
'''
Using PyCharm IDE.
You can comment and uncomment lines of code using Ctrl+/.
Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts).
Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print("Loop ended.")
Select all lines then press Ctrl + /
# n = 5
# while n > 0:
# n -= 1
# if n == 2:
# break
# print(n)
# print("Loop ended.")
Yes, it is fine to use both:
'''
Comments
'''
and
"""
Comments
"""
But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.
Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.
I am using Anaconda Spyder and it has:
Ctrl + 1 - Comment/uncomment
Ctrl + 4 - Comment a block of code
Ctrl + 5 - Uncomment a block of code
It would comment/uncomment a single/multi line/s of code with #.
I find it the easiest.
For example, a block comment:
# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
Yes, you can simply use
'''
Multiline!
(?)
'''
or
"""
Hello
World!
"""
BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:
# This is also
# a multiline comment.
For this one, you can select the text you want to comment and press Ctrl / (or ⌘ /), in PyCharm and VS Code.
But you can edit them. For example, you can change the shortcut from Ctrl /
to Ctrl Shift C.
WARNING!
Be careful, don't overwrite other shortcuts!
Comments have to be correctly indented!
Hope this answer helped. Good luck next time when you'll write other answers!
This can be done in Vim text editor.
Go to the beginning of the first line in the comment area.
Press Ctrl+V to enter the visual mode.
Use arrow keys to select all the lines to be commented.
Press Shift+I.
Press # (or Shift+3).
Press Esc.
For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:
# This is comment 1
# This is comment 2
# This is comment 3
For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax
Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.
'''
This is
multiline
comment
'''
Also, mention that you can access docstring by a class object like this
myobj.__doc__
A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.
A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.
def foo():
"This is a doc string."
# A single line comment
"""
This
is a multiline
comment/String
"""
"""
print "This is a sample foo function"
print "This function has no arguments"
"""
return True
Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.
Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.
For single line you can use Shift + #.
You can use the following. This is called DockString.
def my_function(arg1):
"""
Summary line.
Extended description of function.
Parameters:
arg1 (int): Description of arg1
Returns:
int: Description of return value
"""
return arg1
print my_function.__doc__
in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments.
in mac: it should be comment + /
I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
It is obvious to any other programmer this is a comment. It's self-descriptive.
It compiles
It doesn't show up as a doc comment in help()
It can be at the top of the module if desired
It can be automated with a macro.
[The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.
Cons
It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.
Here's an attempt at the VS Code macro, although I haven't tested it yet:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}
In python to comment-out multiple lines we use triple quotes
def x():
"""This code will
add 1 and 1 """
a=1+1
but what if I have to comment out a block of code which already contains lot of other comment out blocks (triple quote comments). For example if I want to comment out this function fully..
"""
def x():
"""This code will
add 1 and 1 """
a=1+1
"""
This doesn't work. How can I comment out such blocks of code.
In python to comment-out multiple lines we use triple commas
That’s just one way of doing it, and you’re technically using a string literal, not a comment. And, although it has become fairly established, this way of writing comments has the drawback you observed: you cannot comment out nested blocks.1
Python doesn’t have nesting multiline comments, it’s as simple as that. If you want to comment out multiple lines allowing for nested comments, the only safe choice is to comment out each line.
Most editors have some command that makes commenting out or in multiple lines easy.
1 For a single level of nesting you can in fact use '''"""nested """''', or the other way round. But I wouldn’t recommend it.
What I often do in brief hack&slay situations is something like this below. It is not really a comment, and it does not cover all cases (because you need to have a block), but maybe it is helpful:
if 0: # disabled because *some convincing reason*
def x():
"""This code will
add 1 and 1 """
a=1+1
Or, if you cannot or don't like to introduce indenting levels between the typical ones:
# disabled because *some convincing reason*
if 0: # def x():
"""This code will
add 1 and 1 """
a=1+1
You should use # for commenting, and at the beginning of each line. This is very easy if you're using eclipse + pydev.
Simply select the block of code to comment, and press Ctrl + \. The same goes for uncommentng as well.
I'm sure there are such easy ways in other editors as well.
I'm taking a Udacity python programming course building a search engine. They use the triple quotes to enclose a webpage's source code as a string in the variable 'page' to be searched for all the links.
page = '''web page source code''' that is searched with a page.find()
In TextMate 1.5.10 r1623, you get little arrows that allow you to fold method blocks:
Unfortunately, if you have a multi-lined Python comment, it doesn't recognize it, so you can't fold it:
def foo():
"""
How do
I fold
these comments?
"""
print "bar"
TextMate has this on their site on how to customize folding: http://manual.macromates.com/en/navigation_overview#customizing_foldings
...but I'm not skilled in regex enough to do anything about it. TextMate uses the Oniguruma regex API, and I'm using the default Python.tmbundle updated to the newest version via GetBundles.
Does anyone have an idea of how to do this? Thanks in advance for your help! :)
Adding the default foldingStartMarker and foldingStopMarker regex values for Python.tmbundle under the Python Language in Bundle Editor:
foldingStartMarker = '^\s*(def|class)\s+([.a-zA-Z0-9_ <]+)\s*(\((.*)\))?\s*:|\{\s*$|\(\s*$|\[\s*$|^\s*"""(?=.)(?!.*""")';
foldingStopMarker = '^\s*$|^\s*\}|^\s*\]|^\s*\)|^\s*"""\s*$';
It appears that multi-line comment folding does work in TextMate, but your must line up your quotes exactly like so:
""" Some sort of multi
line comment, which needs quotes
in just the right places to work. """
That seems to do it:
According to this Textmate Mailing list thread, if you follow it to the end, proper code folding for Python is not supported. Basically, regular expressions as implemented in the foldingStartMarker and foldingStopMarker do not allow for captures, thus the amount of spacing at the beginning of the "end fold" cannot be matched to the "begin fold".
The issue is not finally and officially addressed by Textmate's creator, Allan Odgaard; however since the thread is from 2005, I assume it is a dead issue, and not one that will be supported.
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!
This question already has answers here:
Why doesn't Python have multiline comments?
(18 answers)
Closed 9 years ago.
Is there a mechanism to comment out large blocks of Python code?
Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """.
The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation.
After reading all comments, the answer seems to be "No".
Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-hash-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.
Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.
Hide the triple quotes in a context that won't be mistaken for a docstring, eg:
'''
...statements...
''' and None
or:
if False: '''
...statements...
'''
The only cure I know for this is a good editor. Sorry.
The only way you can do this without triple quotes is to add an:
if False:
And then indent all your code. Note that the code will still need to have proper syntax.
Many Python IDEs can add # for you on each selected line, and remove them when un-commenting too. Likewise, if you use vi or Emacs you can create a macro to do this for you for a block of code.
In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.
M-x comment-region, in Emacs' Python mode.
At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:
I#<esc>
In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.
In vi:
Go to top of block and mark it with letter a.
Go to bottom of block and mark it with letter b
Then do
:'a,'b s!^!#!
comm='''
Junk, or working code
that I need to comment.
'''
You can replace comm by a variable of your choice that is perhaps shorter, easy to touch-type, and you know does not (and will not) occur in your programs. Examples: xxx, oo, null, nil.
In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.
I use Notepad++ on a Windows machine, select your code, type CTRL-K. To uncomment you select code and press Ctrl + Shift + K.
Incidentally, Notepad++ works nicely as a Python editor. With auto-completion, code folding, syntax highlighting, and much more. And it's free as in speech and as in beer!
In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.
Yes, there is (depending on your editor). In PyDev (and in Aptana Studio with PyDev):
Ctrl + 4 - comment selected block
Ctrl + 5 - uncomment selected block
The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.
As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.
In Eclipse using PyDev, you can select a code block and press Ctrl + #.
Triple quotes are OK to me.
You can use ''' foo ''' for docstrings and """ bar """ for comments or vice-versa to make the code more readable.
Another editor-based solution: text "rectangles" in Emacs.
Highlight the code you want to comment out, then C-x-r-t #
To un-comment the code: highlight, then C-x-r-k
I use this all-day, every day. (Assigned to hot-keys, of course.)
This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".
On Eric4 there is an easy way: select a block, type Ctrl+M to comment the whole block or Ctrl+alt+M to uncomment.
Use a nice editor like SciTe, select your code, press Ctrl + Q and done.
If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.