Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Helpers to call pandoc and convert documents 

4""" 

5import os 

6from .conf_path_tools import find_pandoc_path 

7from ..loghelper import noLOG, run_cmd 

8 

9 

10def call_pandoc(params, fLOG=noLOG): 

11 """ 

12 Call :epkg:`pandoc`. 

13 

14 @param params parameters 

15 @param fLOG logging function 

16 @return out, err 

17 """ 

18 pandoc = os.path.join(find_pandoc_path(), "pandoc") 

19 cmd = '"{0}" {1}'.format(pandoc, params) 

20 out, err = run_cmd(cmd, wait=True, fLOG=fLOG) 

21 if err is not None and "Cannot decode byte" in err: 

22 raise RuntimeError( # pragma: no cover 

23 "Issue with pandoc:\n{0}\n" 

24 "--OUT--\n{1}\n--ERR--\n{2}".format( 

25 cmd, out, err)) 

26 return out, err 

27 

28 

29def latex2rst(input, output, encoding="utf-8", fLOG=noLOG, temp_file=None): 

30 """ 

31 convert a latex document into a rst document using pandoc 

32 

33 @param input input file 

34 @param output output file 

35 @param encoding encoding 

36 @param temp_file temporary file 

37 @param fLOG logging function 

38 @return see @see fn call_pandoc 

39 

40 If the encoding is not utf-8, the function uses *temp_file* to store 

41 the temporary conversion into utf-8. 

42 """ 

43 if encoding not in ("utf-8", "utf8"): 

44 with open(input, "r", encoding=encoding) as f: 

45 content = f.read() 

46 if temp_file is None: 

47 raise ValueError("temp_file cannot be None, encoding is not utf-8 and a temporary " + 

48 "file will be used to do the conversion.") 

49 with open(temp_file, "w", encoding="utf-8") as f: 

50 f.write(content) 

51 input = temp_file 

52 else: 

53 temp_file = None 

54 cmd = '-s -t rst --toc "{0}" -o "{1}"'.format(input, output) 

55 out, err = call_pandoc(cmd, fLOG=fLOG) 

56 if temp_file is not None: 

57 os.remove(temp_file) 

58 return out, err