Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Toggle Indent between Tabs and Spaces on Front Document of CotEditor
#!/usr/bin/env python
"""Toggle Indent between Tabs and Spaces on Front Document of CotEditor.
This is a CotEditor script.
%%%{CotEditorXInput=Selection}%%%
%%%{CotEditorXOutput=ReplaceSelection}%%%
"""
__version__ = '1.0'
__date__ = '2013-04-16'
__author__ = '1024jp <http://wolfrosch.com/>'
__license__ = "Creative Commons Attribution-NonCommercial 3.0 Unported License"
import re
import sys
# settings ----------------------------------------------------------
NUMBER_OF_SPACES = 4
# main --------------------------------------------------------------
SPACES = ' ' * NUMBER_OF_SPACES
def toggle_indent(text):
"""Toggle indent style of inputed text."""
lines = text.splitlines(True)
# detect indent type
tab_count = 0
space_count = 0
for line in lines:
if line.startswith('\t'):
tab_count += 1
elif line.startswith(SPACES):
space_count += 1
# set indent strings
if tab_count > space_count:
indent = '\t'
new_indent = SPACES
else:
indent = SPACES
new_indent = '\t'
# replace
toggled_text = ''
for line in lines:
matched = re.match(indent[0] + '*', line).group()
indent_level, remainder = divmod(len(matched), len(indent))
if remainder == 0:
line = new_indent * indent_level + line.lstrip(indent)
toggled_text += line
return toggled_text
if __name__ == "__main__":
text = sys.stdin.read()
toggled_text = toggle_indent(text)
sys.stdout.write(toggled_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment