Skip to content

Commit

Permalink
added string input variant and updated readme
Browse files Browse the repository at this point in the history
  • Loading branch information
s9w committed Nov 23, 2014
1 parent f4a4f78 commit 6245b9f
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 50 deletions.
43 changes: 21 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ Most of the transformations do things that would be expected of a modern LaTeX a
preTeX is currently automatically tested on 8 randomly selected [arXiv](http://arxiv.org/) papers (323KB raw LaTeX) and makes sure they're untouched with default settings. Transformations are considered safe when they pass that test (among normal unit tests of course).

## Usage
To use, either install with `(sudo) pip install pretex` or simply put the `pretex.py` wherever you need it. The only mandatory argument is an input filename. You can also supply an output filename (default is `{original}_t.tex`) and change settings. Usage:
Install with `(sudo) pip install pretex`. The only mandatory argument is an input filename or string. You can also supply an output filename (default is `{original}_t.tex`) and change settings. Usage:

```
pretex thesis.tex # for installed version
python pretex.py thesis.tex # for copied file
```
python pretex.py thesis.tex
python pretex.py thesis.tex -o thesis_output.tex
python pretex.py thesis.tex --set braket=disabled --set sub_superscript=aggressive
python pretex.py "a ... b" #prints a \dots b
```

There are no dependencies on other packages and is fully tested with Python 2.7 to 3.4. Works in any math mode I know of. That is: `$x$`, `$$x$$`, `\(x\)`, `\[x\]` for inline modes and in all of these math environments (starred and unstarred): `equation`, `align`, `math`, `displaymath`, `eqnarray`, `gather`, `flalign`, `multiline`, `alignat`.
Expand All @@ -41,22 +40,22 @@ This is experimental and mostly used for debbuging right now. Enable with `prete

name | input | output | default | notes
------------- | -----|--------|---|---
arrow | `a -> b` | `a \to b` | enabled :white_check_mark: | [below](#arrow)
approx | `a~=b` | `a\approx b` | enabled :white_check_mark:
leq | `a<=b` | `a\leq b` | enabled :white_check_mark:
geq | `a>=b` | `a\geq b` | enabled :white_check_mark:
ll | `a<<b` | `a\ll b` | enabled :white_check_mark:
gg | `a>>b` | `a\gg b` | enabled :white_check_mark:
neq | `a != b` | `a \neq b` | enabled :white_check_mark:
cdot | `a*b` | `a\cdot b` | enabled :white_check_mark: | [below](#cdot)
dots | `1, 2, ...` | `1, 2, \dots` | enabled :white_check_mark:
braket | `<a|b|c>` | `\braket{a|b|c}` | enabled :white_check_mark: | [below](#braket)
frac | `\frac a+b 2` | `\frac{a+b}{2}` | enabled :white_check_mark: | [below](#frac)
auto_align | | | enabled :white_check_mark: | [below](#auto_align)
substack | | | enabled :white_check_mark: | [below](#substack)
dot | `x..` | `\ddot{x}` | disabled :x: | [below](#dot)
sub_superscript | `e^a+b` | `e^{a+b}` | enabled :white_check_mark: | [below](#sub_superscript)
brackets | `(\frac 1 2)` | `\left(\frac 1 2\right)` | disabled :x: | [below](#brackets)
arrow | `a -> b` | `a \to b` | on :white_check_mark: | [below](#arrow)
approx | `a~=b` | `a\approx b` | on :white_check_mark:
leq | `a<=b` | `a\leq b` | on :white_check_mark:
geq | `a>=b` | `a\geq b` | on :white_check_mark:
ll | `a<<b` | `a\ll b` | on :white_check_mark:
gg | `a>>b` | `a\gg b` | on :white_check_mark:
neq | `a != b` | `a \neq b` | on :white_check_mark:
cdot | `a*b` | `a\cdot b` | on :white_check_mark: | [below](#cdot)
dots | `1, 2, ...` | `1, 2, \dots` | on :white_check_mark:
braket | `<a|b|c>` | `\braket{a|b|c}` | on :white_check_mark: | [below](#braket)
frac | `\frac a+b 2` | `\frac{a+b}{2}` | on :white_check_mark: | [below](#frac)
auto_align | | | on :white_check_mark: | [below](#auto_align)
substack | ` \sum_{i<m \\ j<n}` | `\sum_{\substack{i<m \\ j<n}}` | on :white_check_mark: | [below](#substack)
dot | `x..` | `\ddot{x}` | off :x: | [below](#dot)
sub_superscript | `e^a+b` | `e^{a+b}` | on :white_check_mark: | [below](#sub_superscript)
brackets | `(\frac 1 2)` | `\left(\frac 1 2\right)` | off :x: | [below](#brackets)

### arrow
Simple arrow expressions like `a -> b` get replaced by their LaTeX counterpart `a \to b`. Note the necessary whitespace around it.
Expand Down Expand Up @@ -142,7 +141,7 @@ When typesetting a sum with two subscripted rows like:
LaTeX doesn't allow this with normal newlines and you need to invoke the `\substack` command from amsmath this way: `\sum_{\substack{i<m \\ j<n}}`. preTeX does this for you, so you can just write `\sum_{i<m \\ j<n}`. Enabled by default, needs `amsmath` package.

### brackets
Automatically changes ()'s to their `\left(` and `\right)` versions when they're not already like that. This can be typigraphically unwanted, so it's disabled by default. Activate with `pretex -set brackets=enabled ...`
Automatically changes ()'s to their `\left(` and `\right)` versions when they're not already like that. This can be typographically unwanted, so it's disabled by default. Activate with `pretex -set brackets=enabled ...`

## Roadmap / Ideas
- braket-size would be neat to be able to set. Right now they default to the small versions (`\ket` etc). There are big versions (`\Ket`) but I have no clue what's a clever way to indicate their use in the code. Right now that's a config var, but that's global or too much effort for a per-use-case
Expand Down
9 changes: 9 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
0.5.3
- Improved comment handling in tricky auto_align situations
- Added substack and paren trafos
- Extended arrow trafo with xrightarrow syntax
- added string input mode

0.5.1 + 0.5.2
- just fixing pypi package imports

0.5.0
- Improved sub_superscript: Can have + and - inside
- Added optional aggressive sub_superscript mode with mandatory trailing whitespace
Expand Down
52 changes: 32 additions & 20 deletions pretex/pretex.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,45 +22,57 @@ def setting_sanitizer(setting):
return setting

parser = argparse.ArgumentParser()
parser.add_argument("input_filename", type=filename_sanitizer, help="pyth to file input")
parser.add_argument("input_filename", type=str, help="pyth to file input")
parser.add_argument("-o", "--output", dest="output_filename", type=filename_sanitizer, help="output file")
parser.add_argument('--html', action='store_const', const="enabled")
parser.add_argument("-s", "--set", dest="changed_settings", action='append', type=setting_sanitizer,
help="comma seperated list of changed settings, eg --set ggg")
args = parser.parse_args(parameters)

# parse output filename
if args.output_filename:
output_filename = args.output_filename
else:
dot_position = args.input_filename.rfind(".")
output_filename = args.input_filename[:dot_position] + "_t" + args.input_filename[dot_position:]

# make sure output and input filename are not
if args.input_filename == output_filename:
raise ValueError("Output and input file are same. You're a crazy person! Abort!!!")

# parse skip parameter into config
# parse config
config_new = copy.deepcopy(config)
if args.changed_settings:
for param in args.changed_settings:
setting, value = param.split("=")
if setting not in config_new:
raise argparse.ArgumentTypeError("Unknown setting '{setting}'".format(setting=setting))
config_new[setting] = value

config_new["html"] = args.html or "disabled"
return args.input_filename, output_filename, config_new

# file mode
if args.input_filename.endswith(".tex"):
input_filename = args.input_filename
input_string = ""
if args.output_filename:
output_filename = args.output_filename
else:
dot_position = args.input_filename.rfind(".")
output_filename = args.input_filename[:dot_position] + "_t" + args.input_filename[dot_position:]

# make sure output and input filename are not
if args.input_filename == output_filename:
raise ValueError("Output and input file are same. You're a crazy person! Abort!!!")

# string iput mode
else:
input_string = args.input_filename
input_filename = output_filename = ""

return input_filename, output_filename, config_new, input_string


def main():
optimus_prime = Transformer()
filename_in, filename_out, optimus_prime.config = parse_cmd_arguments(optimus_prime.config, parameters=sys.argv[1:])
filename_in, filename_out, optimus_prime.config, input_string = parse_cmd_arguments(optimus_prime.config, parameters=sys.argv[1:])

with io.open(filename_in, 'r', encoding='utf-8') as file_in, \
io.open(filename_out, 'w', encoding='utf-8') as file_out:
file_content_transformed = optimus_prime.get_transformed_str(file_in.read(), filename=filename_in)
file_out.write(file_content_transformed)
if input_string:
print(optimus_prime.get_transformed_math(input_string, "inline")[0])

else:
with io.open(filename_in, 'r', encoding='utf-8') as file_in, \
io.open(filename_out, 'w', encoding='utf-8') as file_out:
file_content_transformed = optimus_prime.get_transformed_str(file_in.read(), filename=filename_in)
file_out.write(file_content_transformed)


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from setuptools import setup

setup(name='preTeX',
version="0.5.2",
version="0.5.3",
packages=['pretex'],
package_data={
'pretex': ['viz\script.js', 'viz/style.css']
Expand Down
24 changes: 17 additions & 7 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,6 @@ def test_parse_filenames(self, trans):
default_config = trans.get_default_config()
with pytest.raises(SystemExit):
pretex.parse_cmd_arguments(default_config, [])
with pytest.raises(SystemExit):
pretex.parse_cmd_arguments(default_config, ["test_no_extension"])
with pytest.raises(ValueError):
pretex.parse_cmd_arguments(default_config, "same_filename.tex -o same_filename.tex".split())
with pytest.raises(argparse.ArgumentTypeError):
Expand All @@ -118,24 +116,36 @@ def test_parse_filenames(self, trans):
pretex.parse_cmd_arguments(default_config, "test.tex -s wrong_format".split())

assert pretex.parse_cmd_arguments(default_config, "in.tex -o out.tex".split()) == (
"in.tex", "out.tex", default_config)
assert pretex.parse_cmd_arguments(default_config, ["in.tex"]) == ("in.tex", "in_t.tex", default_config)
"in.tex", "out.tex", default_config, "")
assert pretex.parse_cmd_arguments(default_config, ["in.tex"]) == ("in.tex", "in_t.tex", default_config, "")

config_expected = copy.deepcopy(default_config)
config_expected["cdot"] = "disabled"
assert pretex.parse_cmd_arguments(default_config, "test.tex -s cdot=disabled".split()) == (
"test.tex", "test_t.tex", config_expected)
"test.tex", "test_t.tex", config_expected, "")

config_expected = copy.deepcopy(default_config)
config_expected["cdot"] = "disabled"
config_expected["geq"] = "disabled"
assert pretex.parse_cmd_arguments(default_config, "in.tex --set cdot=disabled --set geq=disabled".split()) == (
"in.tex", "in_t.tex", config_expected)
"in.tex", "in_t.tex", config_expected, "")

config_expected = copy.deepcopy(default_config)
config_expected["html"] = "enabled"
assert pretex.parse_cmd_arguments(default_config, "in.tex --html".split()) == (
"in.tex", "in_t.tex", config_expected)
"in.tex", "in_t.tex", config_expected, "")


def test_interactive(self, monkeypatch, trans, capsys):
monkeypatch.setattr(sys, 'argv', ["xx", "a ... b"])
pretex.main()
out, err = capsys.readouterr()
assert out == "a \\dots b\n"

monkeypatch.setattr(sys, 'argv', ["xx", "a ... b", "--set", "dots=disabled"])
pretex.main()
out, err = capsys.readouterr()
assert out == "a ... b\n"


def test_re_sub_superscript(self, trans):
Expand Down

0 comments on commit 6245b9f

Please sign in to comment.