4

I have a piece of legacy code in Python that uses inconsistent tabs - 2 spaces in some instances and 4 in others. I have my defaults set in my .emacs file to use 4 spaces, but in this case emacs finds the inconsistent spacing and uses a tab width of 2.

I'm working to update the file in other ways, and I'd like to set the tab width, in this specific file, to 4. How can I do this?

Thanks!

3

One method of setting variables on a per-file basis is to write a local variable specification in the first line of the file. The details for doing this are in §48.2.4.1 ‘Specifying File Variables’ of the Emacs manual.

A local variable specification takes the following form:

-*- mode: MODENAME; VAR: VALUE; ... -*-

You can repeat VAR: VALUE; for as many variables as you want to set.

Assuming you are using python-mode, you need to set the variable python-indent-offset to 4. Don’t forget to comment out the specification so that the Python interpreter doesn’t attempt to parse it:

# -*- mode: python-mode; python-indent-offset: 4 -*-

You can do this by hand, or use M-x add-file-local-variable-prop-line and Emacs will prompt you for a variable and its value. It will also take care of commenting out the specification.

  • Great! Note that you must restart emacs for this to take effect (or reload the file somehow). – J Jones May 23 '16 at 21:12
  • That’s a consideration I perhaps should have mentioned. You can use M-x revert-buffer to reload the file. – amdt May 24 '16 at 9:54
  • I had to specify mode: Python instead of mode: python-mode. – Marc Belmont Aug 14 '18 at 12:47
2

Unfortunately, you can't.

Consider this piece of code.

x = 0
if True:
    x += 1
  x += 2

You can't programmatically decide if that block should become this

x = 0
if True:
    x += 1
    x += 2

or this

x = 0
if True:
    x += 1
x += 2

It's almost impossible to fix inconsistent spaces with a program.

However you can write a simple function to change indentation level of file, say all 2 spaces can be converted to 4 spaces.

I faced the exact problem a year back. I just indented entire file to 4 spaces using M-x indent-region. After that I have manually fixed lines which are incorrectly indented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.