indent python file (with pydev) in eclipse - python

I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D in visual studio, which formats and indents all the source code lines automatically?

If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces.

I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
# Valid Code
for i in range(10):
b = i
for j in range(b):
c = j
# Also Valid Code.
for i in range(10):
b = i
for j in range(b):
c = j
There's no possible way that the IDE can know which of those is the correct version, or what your intent is. If you're going to write Python code, you're going to have to learn to manage the indentation. There's no way to avoid it, and expecting the IDE to magically clean it up and still get the desired result out of it is pretty much impossible.
Further example:
# Valid Code.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
# Again, also valid code, wildly different behavior.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
The first will produce a list of strings, then print the joined result to the console 1 time. The second will still produce a list of strings, but prints the cumulative joined result for each iteration of the loop - 100 print statements. The two are both 100% syntactically correct. There's no problem with them. Either of them could be what the developer wanted. An IDE can't "know" which is correct. It could, very easily incorrectly change the first version to the second version. Because the Language uses Indentation as Syntax, there is no way to configure an IDE to perform this kind of formatting for you.

Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all.

It is much easier:
Select multiple lines
Press Tab to indent (move right), Shift + Tab to unindent (move left) all selected
lines.

Indentation is syntactically significant; consider the difference between
for i in range(5):
print i
print "done"
and
for i in range(5):
print i
print "done"
However, it certainly makes sense for the IDE to be able to normalize the existing indentation (e.g. apply a consistent number of spaces/tabs at each level).
Currently PyDev does not support such a feature; Pydev author Fabioz at one point expressed interest in adding it in the future and indicated that for now you can use the supplied reindent.py script to do it.

Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL + ALT + . and CTRL + ALT + ,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View". This effectively indents/dedents all lines that you've selected as much as you'd like

I think that what you're looking for is some kind of shortcut in Eclipse/PyDev so that the selected code can be idented all at once. Just like when you create a new "if" or a "for" loop above a block of code and then need to rearrange the identation. The IDLE Editor has the "Ctrl + ]" shortcut that works exactly that way. It seems that the PyDev in Eclipse doesnt have something like that as far as I know.

One can also select the lines, right click, then shift right / shift left

It seems source formatting is still not available in PyDev.
For one off instances I found this web app does the job nicely.
http://pythoniter.appspot.com/

Like earlier said python requires to indent your code, so for other things like: space between variables passed as arguments to methods, etc., one can use ctrl+shift+f to format the code. This what is used for java, I tried for pydev and does some formatting.

Related

why in the Python interpreter the first indentation level is set to 4 space, while the second to 8?

let's take the really simple case of two nested for loops
after pressing return and tab the first time, I get an indentation level where 1 tab equals 4 spaces
after pressing return and tab the second time, I get an indentation level where 1 tab equals 9 spaces
this is rather annoying when I want to copy a piece of code from a script and run it on the interpreter, as it returns the
TabError: inconsistent use of tabs and spaces in indentation
I did some googling but you can imagine what the keywords "python", "interpreter", "indentation" returns: nothing useful
Is there a way to correct this? Thanks
EDIT
just try yourselves:
open a terminal
run python command
then type for i in range(3):
press Enter
then press Tab once, to get to the right indentation level
then type for j in range(3):
press Enter again
then press Tab twice, to get to the (expected) indentation level
if, like me, you have a Mac, chances are that the second Tab hit in the last step above, will yield 8 spaces, instead of 4
This causes problems when copying lines of code written with an IDE
(I'm using Sublime 3, with the option translate_tabs_to_spaces set to True)
I was hoping someone could identify some flag/options/setting of my interpreter which could solve this issue
Title question :
Because you are at 2nd indentation level since you have a loop inside a loop.
Tabulation/space error :
Python uses only indentation to interpret which block belongs to the code. No "BEGIN...END" , no brackets. So indentation IS information.
The rule is "indentation must be uniform", so either everything is spaces (1,2,4.. as you want) or everything is tabulations.
For more information, refer to the Python style guideline (PEP8) here :
https://www.python.org/dev/peps/pep-0008/
By using an IDE ( such as Spyder, for example) tabs will automatically be replaced by spaces. I recommend you to use one, especially if you are a new to python.

Python indentation in Spacemacs with hard tabs is off

Let me preface by saying that I am a relatively new emacs/spacemacs convert from vim, so my my knowledge is still pretty basic.
I have spacemacs set up with the python layer, with the additional package of dtrt-indent listed in dotspacemacs-additional-packages. And setting
(dtrt-indent-mode t)
in the dotspacemacs/user-config. I need the dtrt-indent as I am working on a few projects (in python and lua) where I am not the one who sets the indentation rules.
This configuration works fine for python files with soft-tabs of varying length. This configuration also works for lua files that have hard tabs.
When I open a python file indented with hard tabs something seems to get messed up, it appears to think that the indentation is two hard tabs. Meaning, if I have code like this (pretend that the 4 spaces are tabs):
def func():| <--- Cursor
print 'line'
and press enter, I get:
def func():
| <--- Cursor
print 'line'
The status line prints dtrt-indent's message saying:
Note: indent-tabs-mode adjusted to t
Note: As stated I'm pretty new at this, and my spacemacs configuration is pretty sparse. There is nothing else in my user-config, I have not custom layers, I don't even have any additional packages other than dtrt-indent.
EDIT:
python-indent-offset is set to 8
indent-tabs-mode is set to t
tab-width is set to 4
Try M-x whitespace-mode and repeat this experiment. What do you see? Did you indent with spaces or with tabs?
I'm guessing you'll see something like this:
def·func():
········
» print·'line'
This would mean you have python-indent-offset set to 8, indent-tabs-mode set to nil (aka indent with spaces), and tab-width set to 4.
If that's not the case, what are the values of those variables (C-h v python-indent-offset, etc.)?
If that is the case, you can fix the problem by running
(setq-default python-indent-offset 4)

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 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.

Indentation in a Python GUI

As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected...
It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or something?
For example:
def somefunction:
x =5
return x
If I want to add a control block
For example:
def somefunction:
if True:
x =5
return x
return 0
this small change of adding a control block took a lot of tab work...
Is there a shortcut or something to do this easily?
I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.
This is true for Visual Studio, Notepad2, e, Textmate, Slickedit, #Develop, etc. etc. etc.
If you're not doing large multi-file projects, I strongly recommend Notepad2. Its a very lightweight, free, easy-to-use notepad replacement with just enough code-centric features (line numbers, indentation guides, code highlighting, etc.)
In the Idle editor, you can just select the lines you want to indent and hit Tab.
I should note that this doesn't actually insert any tabs into your source, just spaces.
In IDLE I just use ctrl+] and ctrl+[ on a block of code.
With emacs there's Python mode. In that mode you highlight and do:
ctrl-c >
ctrl-c <
Use VI and never program the same again. :^)
[Funny ;-)] Dude, I told you that you would need one developer less if you had this new keyboard model
Pythonic keyboard http://img22.imageshack.us/img22/7318/pythonkeyboard.jpg
If you are using vim there is a plugin specifically for this: Python_fn.vim
It provides useful python functions (and menu equivalents):
]t -- Jump to beginning of block
]e -- Jump to end of block
]v -- Select (Visual Line Mode) block
]< -- Shift block to left
]> -- Shift block to right
]# -- Comment selection
]u -- Uncomment selection
]c -- Select current/previous class
]d -- Select current/previous function
]<up> -- Jump to previous line with the same/lower indentation
]<down> -- Jump to next line with the same/lower indentation
Vim: switch to visual mode, select the block, use > to indent (or < to unindent).
See also: Indent multiple lines quickly in vi
In TextMate, just highlight the lines you want to indent and use:
⌘ + [
or
⌘ + ]
To move the text in the appropriate direction.
PyDev, which you can find at http://pydev.sourceforge.net/ has a "Code Formatter". It also has autoindent feature. It is a plugin for Eclipse which is freely available for Mac too.
Another option would be http://code.google.com/p/macvim/ if you are familiar or invest time for Vim, which has lots of autoindent features not just for Python.
But, do not forget that, in Python, indentation changes the meaning of the program unlike C family languages. For example for C or C#, a utility program can beautify the code according to the "{" and "}" symbols. But, in Python that would be ambiguous since a program can not format the following:
#Say we wrote the following and expect it to be formatted.
a = 1
for i in range(5):
print i
a = a + i
print a
Do you expect it to be
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 5
or
a = 1
for i in range(5):
print i
a = a + i
print a #Will print 11
which are two different snippets.
In Komodo the Tab and Shift Tab both work as expected to indent and unindent large blocks of code.
In vim, you can enter:
>>
to indent a line. If you enter:
5>>
you indent the 5 lines at and below the cursor. 5<< does the reverse.

Categories

Resources