Tabs to Spaces with PyPN

Want to convert your tabs to spaces and annoyed that your editor author hasn’t implemented that feature in a handy menu item yet?

Add a PyPN script to do it:

import pn
import scintilla
from pypn.decorators import script

def SetTarget(e, x, y):
	e.TargetStart = x
	e.TargetEnd = y

@script("Tabs to Spaces", "Text")
def TabsToSpaces():
	editor = scintilla.Scintilla(pn.CurrentDoc())

	tabSpaces = editor.TabWidth
	spaces = ""
	for x in range(tabSpaces):
		spaces = spaces + " "

	end = editor.Length

	SetTarget(editor, 0, end)
	editor.SearchFlags = 0
	editor.BeginUndoAction()

	pos = editor.SearchInTarget(1, "\t")

	while(pos != -1):
		l1 = editor.TargetEnd - editor.TargetStart
		editor.ReplaceTarget(tabSpaces, spaces)

		# adjust doc length
		end = end + tabSpaces - l1
		start = pos + tabSpaces

		if start >= end:
			pos = -1
		else:
			SetTarget(editor, start, end)
			pos = editor.SearchInTarget(1, "\t")

	editor.EndUndoAction()

One Comment

  1. Posted August 2, 2007 at 11:19 am | Permalink

    Only just noticed this post. While tabs to spaces is handy for those that use spaces for indenting, how would you do the reverse (i.e. spaces to tabs)?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*