Is there a Vim equivalent to the Linux/Unix "fold" command? - python

I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80.
Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice if it could insert the comment marker at the beginning of the line when it wraps too. Also I'd prefer the solution to not autowrap the entire file since I have a particular convention that I use when it comes to keeping my structured code under the 80 character line-length.
This is mostly for Python code, but I'm also interested in learning the general solution to the problem in case I have to apply it to other types of text.

gq
It's controlled by the textwidth option, see ":help gq" for more info.
gq will work on the current line by default, but you can highlight a visual block with Ctrl+V and format multiple lines / paragraphs like that.
gqap does the current "paragraph" of text.

Take a look at ":help =" and ":help 'equalprg"
:set equalprg=fold
and in normal mode == filters the current line through the external fold program. Or visual-select something and hit =

Related

Is there something similar to __END__ of perl in python? [duplicate]

Am I correct in thinking that that Python doesn't have a direct equivalent for Perl's __END__?
print "Perl...\n";
__END__
End of code. I can put anything I want here.
One thought that occurred to me was to use a triple-quoted string. Is there a better way to achieve this in Python?
print "Python..."
"""
End of code. I can put anything I want here.
"""
The __END__ block in perl dates from a time when programmers had to work with data from the outside world and liked to keep examples of it in the program itself.
Hard to imagine I know.
It was useful for example if you had a moving target like a hardware log file with mutating messages due to firmware updates where you wanted to compare old and new versions of the line or keep notes not strictly related to the programs operations ("Code seems slow on day x of month every month") or as mentioned above a reference set of data to run the program against. Telcos are an example of an industry where this was a frequent requirement.
Lastly Python's cult like restrictiveness seems to have a real and tiresome effect on the mindset of its advocates, if your only response to a question is "Why would you want to that when you could do X?" when X is not as useful please keep quiet++.
The triple-quote form you suggested will still create a python string, whereas Perl's parser simply ignores anything after __END__. You can't write:
"""
I can put anything in here...
Anything!
"""
import os
os.system("rm -rf /")
Comments are more suitable in my opinion.
#__END__
#Whatever I write here will be ignored
#Woohoo !
What you're asking for does not exist.
Proof: http://www.mail-archive.com/python-list#python.org/msg156396.html
A simple solution is to escape any " as \" and do a normal multi line string -- see official docs: http://docs.python.org/tutorial/introduction.html#strings
( Also, atexit doesn't work: http://www.mail-archive.com/python-list#python.org/msg156364.html )
Hm, what about sys.exit(0) ? (assuming you do import sys above it, of course)
As to why it would useful, sometimes I sit down to do a substantial rewrite of something and want to mark my "good up to this point" place.
By using sys.exit(0) in a temporary manner, I know nothing below that point will get executed, therefore if there's a problem (e.g., server error) I know it had to be above that point.
I like it slightly better than commenting out the rest of the file, just because there are more chances to make a mistake and uncomment something (stray key press at beginning of line), and also because it seems better to insert 1 line (which will later be removed), than to modify X-many lines which will then have to be un-modified later.
But yeah, this is splitting hairs; commenting works great too... assuming your editor supports easily commenting out a region, of course; if not, sys.exit(0) all the way!
I use __END__ all the time for multiples of the reasons given. I've been doing it for so long now that I put it (usually preceded by an exit('0');), along with BEGIN {} / END{} routines, in by force-of-habit. It is a shame that Python doesn't have an equivalent, but I just comment-out the lines at the bottom: extraneous, but that's about what you get with one way to rule them all languages.
Python does not have a direct equivalent to this.
Why do you want it? It doesn't sound like a really great thing to have when there are more consistent ways like putting the text at the end as comments (that's how we include arbitrary text in Python source files. Triple quoted strings are for making multi-line strings, not for non-code-related text.)
Your editor should be able to make using many lines of comments easy for you.

Is it possible to let PyCharm auto break line when writing long docstrings and comments?

Writing long docstrings and long comments is annoying because of the 80-characters width limit.
For example, I write something like:
def fun(self):
"""Return some thing
This function do some complex work and return something that need a
long sentence to describe
"""
And then I found I need to insert something in the third line of docstring. After inserting, the width is much longer than 80 characters, so I manually break it. However, after breaking, the length of forth line is much less than 80, and I have to merge the forth and fifth line, and break it at some proper place so that every line is not too short and too long. If there are more lines, this job gets more annoying.
Similar problem occurs when I found I have to delete something in the third line. Is there any trick, or plugin of PyCharm that deals with this problem? Since I'm using vim plugin in PyCharm, tricks for vim are also great.
Edit -> Fill Paragraph
Merges a paragraph, i.e. a text region without a blank line between.
If you want it to leave text alone you need a blank line between it and the text where the focus is

Python indentation borked

I saw that there are similar titles to this. But my case seems a little weirder. I somehow used a mixture of PyCharm and Vim (and within Vim I have tabstop=4 and shiftwidth=2), and my Python code seems un-fixabl-y borked, indentation-wise. I first saw that in Vim everything was mis-aligned, so I re-aligned everything; but then when I run it I get an error that there's an unexpected indentation, even though in Vim everything seems perfectly aligned. Here's an example (this is how it looks like in Vim):
for f in files:
for line in f:
items = line.strip().split()
items = items[2:]
items = ' '.join(items).split(', ')
When I run it, I get:
File "getEsSynonymLSAVectors.py", line 136
items = items[2:]
^
IndentationError: unexpected indent
I used PythonTidy, I used reindent, I tried :retab, I tried manual re-aligning - nothing seems to fix this. Any experiences/ advice will be appreciated.
Python treated a tab as 8 spaces by default, if you get indentation borked, you'll generally want to switch the tabs to spaces (or vice versa, but I generally find that spaces are easier to deal with). So make sure to set vim to show tab as 8 spaces wide (:set ts=8), to see what python sees.
To fix tab errors in vim, I usually do the following, first I need to be able to see the tabs, so I enabled highlight search (:set hlsearch) and search for tabs (/\t). Then I eyeball the areas that needs to be retabbed. Next, I try to find the right vim tab width setting for the file (:set ts=n and vary n until everything looks good), enable expand tab (:set et), then run the automatic tab fixing (:retab). When all else fail, retab manually.
If you're using version control, make sure to diff with the files before the changes and manually check that you didn't introduce a bug because of unintentional changes in the indentation level. If you don't use version control, keep a backup and run diff on the files.
Try something like this.
First set appropriate settings.
Always use 4 spaces. So change it to tabs = 4 spaces.
First convert all spaces to tabs.
And then convert all tabs to spaces.
(I use Geany)
It has worked for me before many times.

## in python using notepad++ syntax coloring

In my editor (notepad++) in Python script edit mode, a line
## is this a special comment or what?
Turns a different color (yellow) than a normal #comment.
What's special about a ##comment vs a #comment?
From the Python point of view, there's no difference. However, Notepad++'s highlighter considers the ## sequence as a STRINGEOL, which is why it colours it this way. See this thread.
I thought the difference had something to do with usage:
#this is a code block header
vs.
##this is a comment
I know Python doesn't care one way or the other, but I thought it was just convention to do it that way.
Also, in a different situations:
Comment whose first line is a double hash:
This is used by doxygen and Fredrik Lundh's PythonDoc. In doxygen,
if there's text on the line with the double hash, it is treated as
a summary string. I dislike this convention because it seems too
likely to result in false positives. E.g., if you comment-out a
region with a comment in it, you get a double-hash.

How to comment out a block of code in Python [duplicate]

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.

Categories