(Sep-06-2019, 10:35 PM)Skaperen Wrote: a tab does not mean a fixed amount of spacing from where it is, instead, it means whatever amount of spacing to get to the fixed position of the next tab stop.
Yes it's more diabolical,and a little more difficult to write.
Why do you not try yourself?
As i started look into this,i did write some code that can do both tab to space or even space.
For in place change of file
in-place,and i did use
Click to make it a command line tool(no decorator question now)
If you want to use some code can take functions out they work stand alone.
# tab.py
import click
import re
import in_place
@click.group()
def cli():
"""
\b
tab-space: Tab to space replace like Linux <expand> command
Usage: tab-space --tabs 4 file_1.txt
---
tab-even: Tab to equal spacing between text content
Usage: tab-even --space 4 file_1.txt
"""
pass
def tab__space(text, tabs=8):
result = ''
for c in text:
if c == '\t':
result += ' '
while len(result) % tabs != 0:
result += ' '
else:
result += c
return result
@cli.command()
@click.option('-t', '--tabs', default=8, help='Number of spaces')
@click.argument('file', type=click.Path(exists=True))
def tab_space(file, tabs=8):
with in_place.InPlace(file) as f_out:
for line in f_out:
line = tab__space(line, tabs)
f_out.write(line)
@cli.command()
@click.option('-s', '--space', default=4, help='Number of spaces')
@click.argument('file', type=click.Path(exists=True))
def tab_even(file, space=4):
with in_place.InPlace(file) as f:
text = f.read()
result = re.sub(r'\s\s+|\t', ' '*space, text)
click.echo(result)
f.write(result)
if __name__ == '__main__':
cli()
Usage:
Output:
λ tab --help
Usage: tab [OPTIONS] COMMAND [ARGS]...
tab-space: Tab to space replace like Linux <expand> command
Usage: tab-space --tabs 4 file_1.txt
---
tab-even: Tab to equal spacing between text content
Usage: tab-even --space 4 file_1.txt
Options:
--help Show this message and exit.
Commands:
tab-even
tab-space
# tab dos not give even space between words
λ tab tab-space --tabs 4 file_1.txt
One Two Three Four Five six seven
One Two Three Four Five six seven
One Two Three Four Five six seven
λ tab tab-even --space 4 file_1.txt
One Two Three Four Five six seven
One Two Three Four Five six seven
One Two Three Four Five six seven