|
49 | 49 |
|
50 | 50 | import html5lib |
51 | 51 | import nh3 |
52 | | -import pyparsing |
53 | 52 | import six |
54 | 53 | from calc.preview import latex_preview |
| 54 | +import pyparsing |
55 | 55 | from chem import chemcalc |
56 | 56 | from lxml import etree |
57 | 57 |
|
@@ -1300,22 +1300,47 @@ def preview_formcalc(self, get): |
1300 | 1300 |
|
1301 | 1301 | result["request_start"] = int(get.get("request_start", 0)) |
1302 | 1302 |
|
| 1303 | + # TODO add references to valid variables and functions |
| 1304 | + # At some point, we might want to mark invalid variables as red |
| 1305 | + # or something, and this is where we would need to pass those in. |
1303 | 1306 | try: |
1304 | | - # TODO add references to valid variables and functions |
1305 | | - # At some point, we might want to mark invalid variables as red |
1306 | | - # or something, and this is where we would need to pass those in. |
1307 | | - result["preview"] = latex_preview(formula) |
| 1307 | + numeric_result = preview_numeric_input(formula) |
| 1308 | + # Map results into the correct format |
| 1309 | + result["preview"] = numeric_result["preview"] |
| 1310 | + if numeric_result["error"]: |
| 1311 | + result["error"] = numeric_result["error"] |
| 1312 | + # if formula is invalid return formula |
| 1313 | + if not numeric_result["is_valid"]: |
| 1314 | + result["formula"] = formula |
1308 | 1315 | except pyparsing.ParseException: |
1309 | | - result["error"] = _("Sorry, couldn't parse formula") |
1310 | | - result["formula"] = formula |
| 1316 | + result['error'] = _("Sorry, couldn't parse formula") |
| 1317 | + result['formula'] = formula |
1311 | 1318 | except Exception: # lint-amnesty, pylint: disable=broad-except |
1312 | | - # this is unexpected, so log |
1313 | 1319 | log.warning("Error while previewing formula", exc_info=True) |
1314 | 1320 | result["error"] = _("Error while rendering preview") |
| 1321 | + return result |
1315 | 1322 |
|
1316 | 1323 | return result |
1317 | 1324 |
|
1318 | 1325 |
|
| 1326 | +def preview_numeric_input(formula): |
| 1327 | + """ |
| 1328 | + Handles numeric validations, validates that the formula provided is a valid formula. |
| 1329 | + """ |
| 1330 | + result = {'preview': '', 'is_valid': True, 'error': ''} |
| 1331 | + try: |
| 1332 | + result['preview'] = latex_preview(formula) |
| 1333 | + except pyparsing.ParseException: |
| 1334 | + result["error"] = "Sorry, couldn't parse formula" |
| 1335 | + result['is_valid'] = False |
| 1336 | + return result |
| 1337 | + except Exception: # pylint: disable=broad-exception-caught |
| 1338 | + log.warning("Error while previewing formula", exc_info=True) |
| 1339 | + result['error'] = "Error while rendering preview" |
| 1340 | + result['is_valid'] = False |
| 1341 | + return result |
| 1342 | + |
| 1343 | + |
1319 | 1344 | # ----------------------------------------------------------------------------- |
1320 | 1345 |
|
1321 | 1346 |
|
|
0 commit comments