@@ -16,6 +16,28 @@ def __init__(self, qmd_path: str):
16
16
self .qmd_path = Path (qmd_path )
17
17
self .cells : List [Dict [str , Any ]] = []
18
18
self .kernel_name = "julia" # Default kernel
19
+ self .packages : set = set () # Track packages found in using statements
20
+
21
+ def _extract_packages_from_line (self , line : str ) -> None :
22
+ """Extract package names from a 'using' statement and add to self.packages."""
23
+ line = line .strip ()
24
+ if not line .startswith ('using ' ):
25
+ return
26
+
27
+ # Remove 'using ' prefix and any trailing semicolon/whitespace
28
+ remainder = line [6 :].rstrip (';' ).strip ()
29
+
30
+ # Handle 'using Package: item1, item2' format - extract just the package name
31
+ if ':' in remainder :
32
+ package = remainder .split (':' )[0 ].strip ()
33
+ if package and package != 'Pkg' :
34
+ self .packages .add (package )
35
+ else :
36
+ # Handle 'using Package1, Package2, ...' format
37
+ packages = [pkg .strip () for pkg in remainder .split (',' )]
38
+ for pkg in packages :
39
+ if pkg and pkg != 'Pkg' :
40
+ self .packages .add (pkg )
19
41
20
42
def parse (self ) -> None :
21
43
"""Parse the .qmd file and extract cells."""
@@ -113,6 +135,11 @@ def _add_markdown_cell(self, lines: List[str]) -> None:
113
135
114
136
def _add_code_cell (self , lines : List [str ], lang : str ) -> None :
115
137
"""Add a code cell."""
138
+ # Extract packages from Julia code cells
139
+ if lang == 'julia' :
140
+ for line in lines :
141
+ self ._extract_packages_from_line (line )
142
+
116
143
content = '\n ' .join (lines )
117
144
118
145
# For non-Julia code blocks (like dot/graphviz), add as markdown with code formatting
@@ -141,12 +168,19 @@ def to_notebook(self) -> Dict[str, Any]:
141
168
# Add package activation cell at the top for Julia notebooks
142
169
cells = self .cells
143
170
if self .kernel_name .startswith ("julia" ):
171
+ # Build the source code for the setup cell
172
+ pkg_source_lines = ["using Pkg; Pkg.activate(; temp=true)" ]
173
+
174
+ # Add Pkg.add() calls for each package found in the document
175
+ for package in sorted (self .packages ):
176
+ pkg_source_lines .append (f'Pkg.add("{ package } ")' )
177
+
144
178
pkg_cell = {
145
179
"cell_type" : "code" ,
146
180
"execution_count" : None ,
147
181
"metadata" : {},
148
182
"outputs" : [],
149
- "source" : "using Pkg; Pkg.activate(; temp=true)"
183
+ "source" : "\n " . join ( pkg_source_lines )
150
184
}
151
185
cells = [pkg_cell ] + self .cells
152
186
0 commit comments