5

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!

J Jones
  • 153
  • 1
  • 4

3 Answers3

5

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.

amdt
  • 96
  • 3
3

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.

Chillar Anand
  • 4,042
  • 1
  • 23
  • 52
0

For switching to tab character for indents, put the following at the top of your file:

# -*- mode: python-mode; indent-tabs-mode: t -*-
CPBL
  • 101
  • 1