vim highlighting everything in red - python

I added a print line to a python script while the script was executing, and now all the text is highlighted in red when I open the file. Opening and closing the file doesn't get rid of it. Opening a second python file momentarily fixed the problem, but then closing file and reopening brought the problem back. Now it wont go away at all. Any body know what could cause this?

This happens sometimes in vim when it goes to highlight syntax on multi-line comments. Occasionally everything after the multi-line comment also becomes colored the same as the comment.
I am unsure whether this is a legit bug in vim, or in the actual syntax settings for Python (e.g. python.vim), but I definitely experience this from time-to-time.

For a quick fix, you might try typing:
:hi Error NONE
And then hit Enter.

Old thread, but hope this helps.
By mistake I did a "/." on my vim screen, which highlighted all lines in red. If I open any other file, the red highlighting stays.
Try searching for some other keyword, let's say "/word" - doesn't matter word exists or not. It restores the color.

You probably have an unterminated multiline string. They start and end with either three single or three double quotes.
''' <== this is the start of a multiline string
this is still in the string
this is the last line '''

As per this article http://vim.wikia.com/wiki/Fix_syntax_highlighting, I mapped F12 to resync the syntax highlighting from the start of the file. It has worked better in some instances where <ctrl-l> didn't.
noremap <F12> <Esc>:syntax sync fromstart<CR>
inoremap <F12> <C-o>:syntax sync fromstart<CR>

Related

VS Code Python autopep8 does not honor 2 spaces hanging indentation

I'm trying to get autopep8 work to properly indent Python code with 2 spaces instead of 4. I'm using VS Code with Python extension which uses autopep8 for formatting. I found here that autopep8 can be configured to use 2 spaces by
"python.formatting.autopep8Args": ["--indent-size=2"]
But it does not work for me.
My situation is like this. When I press enter, it correctly starts the next line with the same indentation as the previous line. Press enter after an open parenthesis, it correctly starts the new line with 2 more spaces. But when I paste or save (I have "editor.formatOnPaste" and "editor.formatOnSave" set to true), the annoying thing happened: all the 2-space indentation inside the parentheses became 4 (other 2-space indentation are unaffected). Why is it doing this and how can I make it 2 spaces everywhere?
====EDIT====
I found out that the pylint error Wrong hanging indentation (remove 2 spaces). [bad-continuation]. It's because my pylintrc has indent-after-paren=2. I'm wondering if autopep8 or other Python formatter can set this property?
I also had to include this in my array in settings.json, similar to yours.
"--ignore E121"
According to https://pypi.org/project/autopep8/, this setting ensures your indents are a multiple of 4. By not enforcing that, the configured tab size in VSCode is used.
E121 - Fix indentation to be a multiple of four.
That being said, your indentation is still "acceptable" according to pep8, so it actually will not change it to the 4 spaces you are expecting in your parens. I had to outdent mine one level, then when it ran again, it didn't change it.
Unfortunately this is actually just a workaround and it actually negatively affects other indention rules...
You can see in the code for pep8 that they hardcode the default tab size to be the "python way" (4 spaces) in:
https://github.com/hhatto/autopep8/blob/120537a051d7f3cbbb5c4ede19b9e515156bd3d1/autopep8.py#L104
That makes it look like the hanging indent is just not respecting the --indent-size option...
Adding --indent-size=2 --ignore=E121 worked for me.
had the same issue, here is the solution:
Navigate to library directory of your environment
Open autopep8.py
Search for "DEFAULT_INDENT_SIZE" and change it to 2

Indentation error in simple python

Update: The original question was posted using C-RET to run the lines, which produces the error. I get no such error using The menu Python > Eval region, which successfully evaluates the script.
However, using the menu for every execution is really annoying, and moreover I can't run the present line alone with that method. So my problem remains.
Forgive me if I'm missing something obvious, but I can't figure this out.
This code is giving me an IndentationError. I can't imagine what's going on.
for x in range(0, 3):
print "We're on time %d" % (x)
Here's everything related to python in my emacs.el
;; elpy
(add-to-list 'package-archives
'("elpy" . "http://jorgenschaefer.github.io/packages/"))
(package-initialize)
(elpy-enable)
You've mixed tabs and spaces. This can lead to some confusing errors.
I'd suggest using only tabs or only spaces for indentation.
Using only spaces is generally the easier choice. Most editors have an option for automatically converting tabs to spaces. If your editor has this option, turn it on.
You can paste your code in notepad to see.
All commands from menu have a command-name callable via M-x COMMAND RET.
In this case M-x python-send-region RET

How to fix this invalid syntax?

I'm trying to make a game in python, and stack trace keeps coming up with 'invalid syntax'(those are the EXACT words of the stack trace, not me summing it up) at this line:
print('Look(1) | Bust down door with weapon(2)')
The cursor is always between the 'p' and the 'o' whenever I check it with ALT+X, regardless of where it
was before I checked it.
There are no syntax errors in that line that I can recognize. I was wondering if someone more experienced could help me?
These are the lines above and below that in case you think it's not that line itself that's causing the
problem:
print('You are in a dark and grimy dungeon. You see no windows, and a door. What\
would you like to do?')
print('Look(1) | Bust down door with weapon(2)')
act_umpteenth = input('>>> ')
while act_umpteenth:
[rest of code continues on here that I'm not bothered to copy and paste]
Edit: Solution found. The culprit was a close bracket behind a string that I was assigning to a variable a few lines up. I think I thought it was a print statement or something. :P I deleted it, and now the code works 100%. Thanks for suggesting that I look over the code for indentation/tab/spaces problems, even if it wasn't the problem, because otherwise I wouldn't have spotted the actual problem.
I would just go and redo all your tabs. You can highlight all the code, and press Shift + Tab (you might have to do this multiple times) to back everything up to the left edge. Then you'll want to re-tab everything over in the proper way.
try running it with
python -tt myscript.py
you are probably mixing tabs and spaces when you run it with the -tt command it will tell you about inconsistent indentation
fixing your indentation should resolve your issue
I figured I would put this as an answer even though it is really a comment

Vim in insert mode jumps to start of line when entering # [duplicate]

When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.
For example, when writing this in vim
for i in range(10):
#
the # does not stay there where I entered it.
It is moved like so, by vim.
for i in range(10):
#
Does anyone know of a configuration item in vim that would change this?
If it helps, I am using Ubuntu 8.10.
I found an answer here http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash
It seems that the vim smartindent option is the cause of the problem.
The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of smartindent.
I replaced
set smartindent
with
set cindent
in my .vimrc file
and so far it is working perfectly.
This changed also fixed the behavior of '<<' and '>>' for indenting visual blocks that include python comments.
There are more configuration options for and information on indentation in the vim help for smartindent and cindent (:help smartindent and :help cindent).
#PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.
I would strongly recommend filetype indent on, and remove the set smartindent and set autoindent (or set cindent) lines from your vimrc. Someone else (appparently David Bustos) was kind enough to write a full indentation parser for us; it's located at $VIMDIRECTORY/indent/python.vim.
(Paul's cindent solution probably works for python, but filetype indent on is much more generally useful.)
I have the following lines in my .vimrc, seems to be installed by default with my Ubuntu 8.10
set smartindent
inoremap # X^H#
set autoindent
And I don't observe the problem. Maybe you can try this. (Note that ^H should be entered by Ctrl-V Ctrl-H)
My solution to the unindenting of #:
If you use cindent, recognize that it is designed for C and C++ coding. Here, a # means you are creating a #DEFINE or #MACRO(), so the behavior is correct. But for other languages where # is a comment, it is irritating.
The following worked for me:
" cindent enable specific indenting for C code
" set cin nocin
set cin
" cinkeys The default cinkeys causes leading # to unindent to column 0.
" To prevent this, remove the 0# from the definition.
" set cinkeys=0{,0},0),:,0#,!^F,o,O,e - default
set cinkeys=0{,0},0),:,!^F,o,O,e
It's caused by the 'smartindent' feature. If you have :set smartindent in your .vimrc you need to remove it.
Some of the other answers were useful, but none were enough to prevent Vim from reindenting a line when '#' is the first character. PolyThinker's answer didn't work for me, but it gave a clue that '#' could be remapped to "insert a character, then #, then delete the extra character and put the cursor where it should be". This is the mapping that does that:
inoremap # X#<left><backspace><right>
This is needed because vim's syntax packages seem to treat '#' as a special character, no matter how the options are set. I want a line started with '#' to be the same as a line begun with any other character. The most reliable solution I've found is the above mapping, which actually does change the line's first character.
Note: I've found this mapping causes problems after running I#<esc> then pressing "." to redo the previous insertion. I haven't found a solution yet.
My Vim configuration doesn't do that. You might try the python.vim script available from this link: http://www.vim.org/scripts/script.php?script_id=790
I removed set smartindent from ~/.vimrc but it still didn't disable smartindent. When I opened a .py file and ran :set smartindent? it displayed smartindent.
Turns out that further down in the ~/.vimrc was this line:
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
^^^^^^^^^^^
Once I deleted "smartindent" from that line, then smartindent was finally disabled and my comments were indented properly again.

How to find and replace all tabs with spaces in idle

I have an invisible expected an indented block error, which is likely caused by me using tabs instead of spaces.
When I open the "find/replace" window and try to enter TAB in the find field IDLE unsurprisingly just skips to the replace field.
How do I do this?
Final update:
Thank you for all answers, much appreciated. My problem was that python wants the function comments to be indented too, that is
def imdheladumb():
"""
I'm dum as hel
"""
does not work, it needs to be
def imdheladumb():
"""
I'm dum as hel
"""
IDLE doesn't let you search to literal tab characters. You can paste one into the search box (as suggested by will), but it will never match anything.
However, it does let you do regular expression searches, and the regular expression \t will match a literal tab. So, turn on the Regular expression checkbox, and put '\t in the Find: box, and 4 or 8 spaces (as appropriate) in the Replace: box.
But, as will suggested, it's better to use IDLE's features instead of trying to do things manually: Select the block of code with tabbed (or inconsistent) indentation, go to the Format menu, and select Untabify Region. (Or just hit control-6.) If the tabs were inserted with an editor that uses 4-space tabs, you may need to first use New Indent Width and change it to 4, then Untabify Region.
IDLE doesn't have any code to guess what your tab size was when you wrote the inconsistent code. The only editor I know of that does is emacs. If you just open the file in emacs, it will try to guess your settings, and then you can select the whole buffer and untabify-region. If it guessed right, you're golden; if it guessed wrong, don't save the buffer, because now it'll be even harder to fix. (If you're one of the 3 people in the world who knows how to read emacs lisp but doesn't like emacs, you could look through the python-mode.el source and see how it does its magic.)
A generic way to do this is to just copy a tab character from the document (or just do one in any random text editor and copy it) and then put that into the field.
You could try putting \t in there, but that only works in some editors.
Most IDEs have a function to automatically replace tabs with a predefined number of spaces. I suggest turning that on...
EDIT: doing a standard find and replace could be dangerous if you're using tabs somewhere else for any reason.
If you look here, there's an option called "tabify region". That might be more interesting for you.
There should be an app for that. ;)
If you enjoy overkill, what about running your code through a regular expression like:
re.sub('\t', '\s\s\s\s', yourCode)
For those people having the problem, the new version of VSCode can solve this easily.
Click on Tab Sizes at the bottom of the page.
Select Convert Indentation to Spaces from the "Select Action" menu that pops up.

Categories

Resources