Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbconvert/filters/pandoc.py: 31%

29 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-01 06:54 +0000

1""" 

2Convert between any two formats using pandoc, 

3and related filters 

4""" 

5import os 

6 

7from pandocfilters import Image, applyJSONFilters # type:ignore 

8 

9from nbconvert.utils.base import NbConvertBase 

10from nbconvert.utils.pandoc import pandoc 

11 

12 

13def convert_pandoc(source, from_format, to_format, extra_args=None): 

14 """Convert between any two formats using pandoc. 

15 

16 This function will raise an error if pandoc is not installed. 

17 Any error messages generated by pandoc are printed to stderr. 

18 

19 Parameters 

20 ---------- 

21 source : string 

22 Input string, assumed to be valid in from_format. 

23 from_format : string 

24 Pandoc format of source. 

25 to_format : string 

26 Pandoc format for output. 

27 

28 Returns 

29 ------- 

30 out : string 

31 Output as returned by pandoc. 

32 """ 

33 return pandoc(source, from_format, to_format, extra_args=extra_args) 

34 

35 

36# When converting to pdf, explicitly relative references 

37# like "./" and "../" doesn't work with TEXINPUTS. 

38# So we need to convert them to absolute paths. 

39# See https://github.com/jupyter/nbconvert/issues/1998 

40class ConvertExplicitlyRelativePaths(NbConvertBase): 

41 """A converter that handles relative path references.""" 

42 

43 def __init__(self, texinputs=None, **kwargs): 

44 """Initialize the converter.""" 

45 # texinputs should be the directory of the notebook file 

46 self.nb_dir = os.path.abspath(texinputs) if texinputs else "" 

47 self.ancestor_dirs = self.nb_dir.split("/") 

48 super().__init__(**kwargs) 

49 

50 def __call__(self, source): 

51 """Invoke the converter.""" 

52 # If this is not set for some reason, we can't do anything, 

53 if self.nb_dir: 

54 return applyJSONFilters([self.action], source) 

55 return source 

56 

57 def action(self, key, value, frmt, meta): 

58 """Perform the action.""" 

59 # Convert explicitly relative paths: 

60 # ./path -> path (This should be visible to the latex engine since TEXINPUTS already has .) 

61 # ../path -> /abs_path 

62 # assuming all relative references are at the start of a given path 

63 if key == "Image": 

64 # Image seems to have this composition, according to https://github.com/jgm/pandoc-types 

65 attr, caption, [filename, typedef] = value 

66 

67 if filename[:2] == "./": 

68 filename = filename[2:] 

69 elif filename[:3] == "../": 

70 n_up = 0 

71 while filename[:3] == "../": 

72 n_up += 1 

73 filename = filename[3:] 

74 ancestors = "/".join(self.ancestor_dirs[:-n_up]) + "/" 

75 filename = ancestors + filename 

76 return Image(attr, caption, [filename, typedef]) 

77 # If not image, return "no change" 

78 return None