-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExport-OneNoteMarkdown.ps1
More file actions
1959 lines (1699 loc) · 75.5 KB
/
Copy pathExport-OneNoteMarkdown.ps1
File metadata and controls
1959 lines (1699 loc) · 75.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Exports Microsoft OneNote notebooks to Markdown by reading the raw OneNote XML
over the OneNote COM API.
.DESCRIPTION
Drives the local OneNote 2016 desktop client via its COM interface:
GetHierarchy() -> notebook / section group / section / page tree
GetPageContent() -> per-page OneNote XML (piBasic, current schema)
GetBinaryPageContent() -> image bytes, fetched on demand per image
The XML is converted to GitHub-Flavored Markdown in-process. Word and Pandoc are
NOT used, so nothing is written to disk except the output tree, and collapsed
(folded) paragraphs are included -- unlike the Publish()->.docx->Pandoc route.
MUST run under Windows PowerShell 5.1. The OneNote COM interop fails under
PowerShell 7.x with "Unexpected HRESULT has been returned from a call to a COM
component"; support for the required Win32 GAC assembly was dropped after 7.0.
Exports one notebook per run. Just run the script with no arguments and it lists
the notebooks you have open in OneNote and asks which one to export.
.PARAMETER Notebook
Name of the single notebook to export. Omit to be shown a numbered list to pick from.
.PARAMETER OutputRoot
Destination folder. Defaults to an "out" folder next to this script.
.PARAMETER Force
Re-export every page, even ones already up to date.
.PARAMETER RetryFailed
Re-export only the pages the previous run reported a problem with.
.PARAMETER HighlightAs
How highlighter-pen text is written: 'equals' (==text==, Obsidian/Orbit
syntax, the default), 'html' (<mark>, for GitHub-bound output) or 'none'.
.EXAMPLE
Right-click this file in File Explorer and choose "Run with PowerShell".
.EXAMPLE
powershell.exe -NoProfile -File .\Export-OneNoteMarkdown.ps1 -Notebook "Sales Notebook"
#>
[CmdletBinding()]
param(
[string] $Notebook,
[string] $OutputRoot,
[switch] $Force,
[switch] $RetryFailed,
[switch] $IncludeFrontMatter,
[switch] $FlattenPageGroups,
[ValidateSet('html', 'plus', 'bold', 'italic', 'none')]
[string] $UnderlineAs = 'html',
[ValidateSet('html', 'equals', 'none')]
[string] $HighlightAs = 'equals',
[switch] $NoHydrateImages,
[int] $HydrateWaitMs = 1200,
[int] $HydrateMaxMs = 30000
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# OneNote COM constants
$script:HS_PAGES = 4 # HierarchyScope.hsPages
$script:PI_BASIC = 0 # PageInfo.piBasic - no inline binary data
$script:XS_CURRENT = 1 # XMLSchema, current
# Open/close pair used for underlined runs; overridden from -UnderlineAs at startup.
# Markdown has no underline syntax, so <u> is the default: it is the most portable
# option, working on GitHub, Jupyter and Obsidian without plugins.
$script:UnderlineMarkers = @('<u>', '</u>')
# Same idea for highlighted runs; overridden from -HighlightAs at startup.
# '==' is the Obsidian/Orbit syntax and the default; Orbit escapes raw HTML,
# so <mark> (the 'html' option) is only useful for GitHub-bound output.
$script:HighlightMarkers = @('==', '==')
# Tag 'symbol' values whose glyph is a checkbox. Tags using these become Markdown
# task-list items instead of an emoji prefix, taking their ticked state from the
# Tag element's 'completed' attribute.
#
# Note that 'completed' cannot be used to detect a checkbox: OneNote writes it on
# EVERY tag, including Important (a star) and Definition (a book), so keying off it
# would turn all of them into checkboxes. The glyph is the only reliable signal.
# Observed in these notebooks: 3 = To Do, 94 = Attendance and In Attendance.
$script:CheckboxTagSymbols = @{ '3' = $true; '94' = $true }
# Note tag name (lowercased) -> emoji prefix. Keyed by name because the numeric
# 'symbol' attribute is a glyph index that does not track tag meaning (the
# Important star, for instance, reports symbol 13). Checkbox glyphs are handled
# separately above: they become task-list items, not a prefix.
# Emoji are built from codepoints so this file stays ASCII-safe under PS 5.1.
$script:TagEmoji = @{
'important' = [char]::ConvertFromUtf32(0x2B50) # star
'question' = [char]::ConvertFromUtf32(0x2753) # red question mark
'idea' = [char]::ConvertFromUtf32(0x1F4A1) # light bulb
'critical' = [char]::ConvertFromUtf32(0x2757) # red exclamation
'phone number' = [char]::ConvertFromUtf32(0x1F4DE) # telephone receiver
'contact' = [char]::ConvertFromUtf32(0x1F464) # person silhouette
'address' = [char]::ConvertFromUtf32(0x1F3E0) # house
'web site to visit' = [char]::ConvertFromUtf32(0x1F310) # globe
'remember for later' = [char]::ConvertFromUtf32(0x1F516) # bookmark
'definition' = [char]::ConvertFromUtf32(0x1F4D6) # open book
'book to read' = [char]::ConvertFromUtf32(0x1F4DA) # books
}
#region Environment
function Assert-Environment {
if ($PSVersionTable.PSVersion.Major -ne 5) {
throw @"
This script must run under Windows PowerShell 5.1, not PowerShell $($PSVersionTable.PSVersion).
The OneNote COM interop fails on 7.x with 'Unexpected HRESULT'.
Re-run with:
powershell.exe -NoProfile -File "$PSCommandPath" $($MyInvocation.UnboundArguments -join ' ')
"@
}
# OneNote runs at medium integrity as the logged-on user. COM activation and the
# Running Object Table are partitioned by integrity level, and Office refuses to
# launch elevated, so an elevated host cannot attach -- it just gets
# 0x80080005 CO_E_SERVER_EXEC_FAILURE.
$principal = New-Object Security.Principal.WindowsPrincipal(
[Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw @"
This PowerShell window is running as Administrator. OneNote COM cannot be reached from an
elevated process -- it fails with 0x80080005 CO_E_SERVER_EXEC_FAILURE.
Close this window and open a NORMAL (non-Administrator) Windows PowerShell, then re-run.
This script does not need administrator rights.
"@
}
}
function Get-OneNoteApp {
# The COM server can report an unexpected HRESULT while cold. Retry briefly.
for ($attempt = 1; $attempt -le 4; $attempt++) {
try {
return New-Object -ComObject OneNote.Application
}
catch {
if ($attempt -eq 4) {
throw "Could not attach to OneNote after $attempt attempts: $($_.Exception.Message)"
}
Write-Verbose "OneNote COM attach failed (attempt $attempt); retrying..."
Start-Sleep -Seconds ($attempt * 2)
}
}
}
#endregion
#region Timestamps
function ConvertTo-UtcOrNull {
# OneNote hands back ISO-8601 UTC, e.g. 2022-10-06T06:21:40.000Z
param([string] $Value)
if ([string]::IsNullOrWhiteSpace($Value)) { return $null }
$parsed = [datetime]::MinValue
$styles = [System.Globalization.DateTimeStyles]::AdjustToUniversal -bor
[System.Globalization.DateTimeStyles]::AssumeUniversal
if ([datetime]::TryParse($Value, [System.Globalization.CultureInfo]::InvariantCulture,
$styles, [ref]$parsed)) {
# Windows cannot represent anything before 1601 on NTFS.
if ($parsed.Year -ge 1601) { return $parsed }
}
return $null
}
function Set-ItemTimestamps {
<#
Stamps a file or folder with OneNote's own created/modified times so Explorer,
SharePoint and Orbit show when the note was really written rather than when
this export ran.
#>
param([string] $Path, $CreatedUtc, $ModifiedUtc)
if ([string]::IsNullOrWhiteSpace($Path)) { return }
if (-not $CreatedUtc -and -not $ModifiedUtc) { return }
$wasReadOnly = $false
$item = $null
try {
$item = Get-Item -LiteralPath $Path -Force -ErrorAction Stop
# Copy-Item inherits the source's read-only flag, and under .NET Framework
# (Windows PowerShell 5.1) setting a timestamp on a read-only file throws
# Access Denied. Lift the flag for the write, then put it back.
if ($item -is [System.IO.FileInfo] -and $item.IsReadOnly) {
$item.IsReadOnly = $false
$wasReadOnly = $true
}
if ($CreatedUtc) { $item.CreationTimeUtc = $CreatedUtc }
if ($ModifiedUtc) { $item.LastWriteTimeUtc = $ModifiedUtc }
}
catch {
Write-Warning "Could not set the date on '$Path': $($_.Exception.Message)"
}
finally {
if ($wasReadOnly -and $item) {
try { $item.IsReadOnly = $true } catch { }
}
}
}
#endregion
#region Naming helpers
function Get-SafeName {
param(
[string] $Name,
[hashtable] $Used,
[int] $MaxLength = 120
)
if ([string]::IsNullOrWhiteSpace($Name)) { $Name = 'Untitled' }
$safe = $Name
foreach ($c in [System.IO.Path]::GetInvalidFileNameChars()) {
$safe = $safe.Replace($c, '-')
}
# Collapse runs of whitespace/dashes and trim characters Windows dislikes at the ends.
$safe = ($safe -replace '\s+', ' ').Trim().Trim('.', ' ', '-')
if ($safe.Length -gt $MaxLength) { $safe = $safe.Substring(0, $MaxLength).Trim() }
if ([string]::IsNullOrWhiteSpace($safe)) { $safe = 'Untitled' }
# Reserved DOS device names.
if ($safe -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$') { $safe = "_$safe" }
if ($null -eq $Used) { return $safe }
$candidate = $safe
$n = 2
while ($Used.ContainsKey($candidate.ToLowerInvariant())) {
$candidate = "$safe-$n"
$n++
}
$Used[$candidate.ToLowerInvariant()] = $true
return $candidate
}
function Get-Slug {
param([string] $Text)
$s = ($Text -replace '[^A-Za-z0-9]+', '-').Trim('-').ToLowerInvariant()
if ([string]::IsNullOrWhiteSpace($s)) { $s = 'page' }
if ($s.Length -gt 40) { $s = $s.Substring(0, 40).Trim('-') }
return $s
}
#endregion
#region Inline text conversion
function ConvertFrom-HtmlEntities {
# OneNote sometimes double-encodes, storing "&#128222;" so a single decode
# leaves a visible "📞". Decode until it stops changing.
param([string] $Text)
for ($i = 0; $i -lt 3; $i++) {
$next = [System.Net.WebUtility]::HtmlDecode($Text)
if ($next -eq $Text) { break }
$Text = $next
}
# .NET Framework's HtmlDecode only handles code points that fit in a char, so
# numeric references above U+FFFF (emoji, almost always) come back untouched.
# Convert those by hand via surrogate pairs.
if ($Text.Contains('&#')) {
$Text = [regex]::Replace($Text, '&#([xX][0-9A-Fa-f]+|[0-9]+);', {
param($m)
$raw = $m.Groups[1].Value
try {
if ($raw[0] -eq 'x' -or $raw[0] -eq 'X') {
$cp = [Convert]::ToInt32($raw.Substring(1), 16)
} else {
$cp = [int]$raw
}
if ($cp -gt 0 -and $cp -le 0x10FFFF) { return [char]::ConvertFromUtf32($cp) }
}
catch { }
return $m.Value
})
}
return $Text
}
function ConvertTo-EscapedText {
param([string] $Text)
if ([string]::IsNullOrEmpty($Text)) { return '' }
# Conservative: only characters that would otherwise be read as Markdown syntax.
# Underscore is deliberately left alone -- GFM has no intra-word emphasis, and
# escaping it mangles identifiers like My_Project.
$t = $Text -replace '\\', '\\'
$t = $t -replace '([`\*\[\]])', '\$1'
$t = $t -replace '<', '\<'
return $t
}
function Get-HighlightBucket {
<#
Maps a CSS colour (name or #hex) to the nearest Orbit highlight bucket:
yellow, green, blue, red, purple or orange. Anything unparseable or
washed-out (greys) falls back to yellow, the default highlighter.
#>
param([string] $Color)
$named = @{
'yellow' = '#ffff00'; 'gold' = '#ffd700'; 'lime' = '#00ff00'
'green' = '#008000'; 'olive' = '#808000'; 'teal' = '#008080'
'aqua' = '#00ffff'; 'cyan' = '#00ffff'; 'blue' = '#0000ff'
'navy' = '#000080'; 'darkblue' = '#00008b'; 'skyblue' = '#87ceeb'
'red' = '#ff0000'; 'darkred' = '#8b0000'; 'maroon' = '#800000'
'pink' = '#ffc0cb'; 'fuchsia' = '#ff00ff'; 'magenta' = '#ff00ff'
'purple' = '#800080'; 'violet' = '#ee82ee'; 'orange' = '#ffa500'
'darkorange' = '#ff8c00'
}
$c = $Color.Trim().ToLowerInvariant()
if ($named.ContainsKey($c)) { $c = $named[$c] }
if ($c -match '^#([0-9a-f])([0-9a-f])([0-9a-f])$') {
$c = '#' + $Matches[1] + $Matches[1] + $Matches[2] + $Matches[2] + $Matches[3] + $Matches[3]
}
if ($c -notmatch '^#[0-9a-f]{6}$') { return 'yellow' }
$r = [Convert]::ToInt32($c.Substring(1, 2), 16)
$g = [Convert]::ToInt32($c.Substring(3, 2), 16)
$b = [Convert]::ToInt32($c.Substring(5, 2), 16)
$max = [Math]::Max($r, [Math]::Max($g, $b))
$min = [Math]::Min($r, [Math]::Min($g, $b))
if (($max - $min) -lt 30) { return 'yellow' } # grey-ish: no real hue
$hue = 0.0
$d = [double]($max - $min)
if ($max -eq $r) { $hue = 60.0 * ((($g - $b) / $d) % 6) }
elseif ($max -eq $g) { $hue = 60.0 * ((($b - $r) / $d) + 2) }
else { $hue = 60.0 * ((($r - $g) / $d) + 4) }
if ($hue -lt 0) { $hue += 360 }
if ($hue -lt 15 -or $hue -ge 330) { return 'red' }
if ($hue -lt 45) { return 'orange' }
if ($hue -lt 75) { return 'yellow' }
if ($hue -lt 165) { return 'green' }
if ($hue -lt 255) { return 'blue' }
return 'purple'
}
function Get-SpanMarkers {
<#
Maps a CSS style attribute to Markdown open/close marker pairs.
Returns an array of two-element arrays: @(open, close).
#>
param([string] $Style)
$markers = @()
if ([string]::IsNullOrEmpty($Style)) { return ,$markers }
$s = $Style.ToLowerInvariant()
$have = @{}
if ($s -match 'font-weight\s*:\s*bold' -and -not $have['**']) {
$markers += ,@('**', '**'); $have['**'] = $true
}
if ($s -match 'font-style\s*:\s*italic' -and -not $have['*']) {
$markers += ,@('*', '*'); $have['*'] = $true
}
if ($s -match 'text-decoration\s*:[^;]*line-through' -and -not $have['~~']) {
$markers += ,@('~~', '~~'); $have['~~'] = $true
}
# Markdown has no underline. Whatever we map it to must not be emitted twice when
# the run is also bold/italic, or the doubled markers render literally.
if ($s -match 'text-decoration\s*:[^;]*underline') {
$u = $script:UnderlineMarkers
if ($u -and -not $have[$u[0]]) { $markers += ,$u; $have[$u[0]] = $true }
}
# Highlighter pen arrives as 'background:lime;mso-highlight:lime' (any colour).
# The property-start anchor keeps 'mso-highlight' itself from matching, but it
# is used as a fallback when no background property is present.
$bg = $null
if ($s -match '(?:^|;)\s*background(?:-color)?\s*:\s*([^;]+)') { $bg = $Matches[1].Trim() }
elseif ($s -match '(?:^|;)\s*mso-highlight\s*:\s*([^;]+)') { $bg = $Matches[1].Trim() }
if ($bg -and $bg -notmatch '^(transparent|none|white|window|auto|automatic|#fff|#ffffff)$') {
$h = $script:HighlightMarkers
if ($h -and -not $have[$h[1]]) {
if ($h[0] -eq '==') {
# Orbit colour-codes highlights: =g= green, =b= blue, =r= red,
# =p= purple, =o= orange; plain == is yellow.
$open = switch (Get-HighlightBucket $bg) {
'green' { '=g=' }
'blue' { '=b=' }
'red' { '=r=' }
'purple' { '=p=' }
'orange' { '=o=' }
default { '==' }
}
$markers += ,@($open, '==')
}
else {
$markers += ,$h
}
$have[$h[1]] = $true
}
}
# Unary comma: stop PowerShell unrolling a single marker pair into two strings.
return ,$markers
}
function Format-LinkTarget {
# onenote: URLs routinely contain unescaped parentheses and spaces, which would
# terminate a Markdown link early. Angle brackets make them safe.
param([string] $Href)
if ($Href -match '[()\s]') { return "<$Href>" }
return $Href
}
function Convert-TextRun {
<#
Converts the CDATA payload of a <one:T> element to Markdown.
The complete inline surface OneNote emits is three tags: span, a, br.
#>
param([string] $Raw)
if ([string]::IsNullOrEmpty($Raw)) { return '' }
$sb = New-Object System.Text.StringBuilder
$stack = New-Object System.Collections.ArrayList
$tokens = [regex]::Split($Raw, '(<[^>]*>)')
foreach ($token in $tokens) {
if ([string]::IsNullOrEmpty($token)) { continue }
if ($token[0] -ne '<') {
# Literal text.
$decoded = ConvertFrom-HtmlEntities $token
$decoded = $decoded -replace " ", ' ' # nbsp
# GFM emphasis is ignored when the marker touches whitespace ('** text**'),
# and OneNote spans routinely include their surrounding spaces. So span
# markers are deferred: written here, just before the first non-blank text
# inside the span, with any leading whitespace emitted ahead of them.
if ($decoded.Trim().Length -gt 0) {
if ($decoded -match '^(\s+)') {
[void]$sb.Append($Matches[1])
$decoded = $decoded.Substring($Matches[1].Length)
}
foreach ($frame in $stack) {
if ($frame.Kind -eq 'span' -and -not $frame.Opened) {
foreach ($m in $frame.Markers) { [void]$sb.Append($m[0]) }
$frame.Opened = $true
}
}
}
[void]$sb.Append((ConvertTo-EscapedText $decoded))
continue
}
if ($token -match '^<\s*br\s*/?\s*>$') {
[void]$sb.Append("`n")
continue
}
if ($token -match '^<\s*span\b') {
$style = ''
if ($token -match 'style\s*=\s*"([^"]*)"') { $style = $Matches[1] }
elseif ($token -match "style\s*=\s*'([^']*)'") { $style = $Matches[1] }
$markers = Get-SpanMarkers $style
# Opened stays false until the span produces visible text (see above);
# a marker-less span is born 'opened' so closing it is a no-op.
[void]$stack.Add(@{ Kind = 'span'; Markers = $markers; Opened = ($markers.Count -eq 0) })
continue
}
if ($token -match '^<\s*/\s*span\s*>$') {
$frame = $null
for ($i = $stack.Count - 1; $i -ge 0; $i--) {
if ($stack[$i].Kind -eq 'span') { $frame = $stack[$i]; $stack.RemoveAt($i); break }
}
if ($frame -and $frame.Opened -and $frame.Markers.Count -gt 0) {
# Shuffle trailing whitespace outside the close marker ('**foo **' -> '**foo** ').
$tail = ''
while ($sb.Length -gt 0 -and [char]::IsWhiteSpace($sb[$sb.Length - 1])) {
$tail = [string]$sb[$sb.Length - 1] + $tail
$sb.Length--
}
for ($i = $frame.Markers.Count - 1; $i -ge 0; $i--) {
[void]$sb.Append($frame.Markers[$i][1])
}
[void]$sb.Append($tail)
}
continue
}
if ($token -match '^<\s*a\b') {
$href = ''
if ($token -match 'href\s*=\s*"([^"]*)"') { $href = $Matches[1] }
elseif ($token -match "href\s*=\s*'([^']*)'") { $href = $Matches[1] }
$href = ConvertFrom-HtmlEntities $href
[void]$sb.Append('[')
[void]$stack.Add(@{ Kind = 'a'; Href = $href })
continue
}
if ($token -match '^<\s*/\s*a\s*>$') {
$frame = $null
for ($i = $stack.Count - 1; $i -ge 0; $i--) {
if ($stack[$i].Kind -eq 'a') { $frame = $stack[$i]; $stack.RemoveAt($i); break }
}
if ($frame) {
[void]$sb.Append('](' + (Format-LinkTarget $frame.Href) + ')')
} else {
[void]$sb.Append(']')
}
continue
}
# Any other tag: drop it, keep the text.
}
# Close anything OneNote left dangling.
for ($i = $stack.Count - 1; $i -ge 0; $i--) {
$frame = $stack[$i]
if ($frame.Kind -eq 'a') {
[void]$sb.Append("]($($frame.Href))")
} elseif ($frame.Opened) {
for ($j = $frame.Markers.Count - 1; $j -ge 0; $j--) {
[void]$sb.Append($frame.Markers[$j][1])
}
}
}
$out = $sb.ToString()
# Safety net: drop emphasis that ended up wrapping only whitespace, which would
# render literally. The italic rule needs \s+ (not \s*) or it would eat the two
# stars of every legitimate '**' bold marker.
$out = $out -replace '\*\*(\s+)\*\*', '$1'
$out = $out -replace '~~(\s+)~~', '$1'
$out = $out -replace '\+\+(\s+)\+\+', '$1'
$out = $out -replace '<u>(\s*)</u>', '$1'
$out = $out -replace '<mark>(\s*)</mark>', '$1'
$out = $out -replace '(?<!\*)\*(\s+)\*(?!\*)', '$1'
return $out
}
#endregion
#region Block conversion
function Get-ChildElements {
param($Node)
$result = @()
if ($null -eq $Node) { return $result }
foreach ($c in $Node.ChildNodes) {
if ($c.NodeType -eq [System.Xml.XmlNodeType]::Element) { $result += $c }
}
return ,$result
}
function Get-Attr {
param($Node, [string] $Name, [string] $Default = '')
if ($null -eq $Node) { return $Default }
$a = $Node.Attributes.GetNamedItem($Name)
if ($null -eq $a) { return $Default }
return $a.Value
}
function Convert-Table {
param($Table, $Ctx, [int] $Depth)
# First pass keeps each cell as block content (an array of lines), because
# the table might turn out to be a layout wrapper that we unwrap instead.
$rows = @()
foreach ($child in (Get-ChildElements $Table)) {
if ($child.LocalName -ne 'Row') { continue }
$cells = @()
foreach ($cell in (Get-ChildElements $child)) {
if ($cell.LocalName -ne 'Cell') { continue }
$inner = @()
foreach ($cc in (Get-ChildElements $cell)) {
if ($cc.LocalName -eq 'OEChildren') {
$inner += Convert-OeChildren -OeChildren $cc -Ctx $Ctx -Depth 0
}
}
$cells += ,@($inner)
}
if ($cells.Count -gt 0) { $rows += ,$cells }
}
if ($rows.Count -eq 0) { return @() }
$width = 0
foreach ($r in $rows) { if ($r.Count -gt $width) { $width = $r.Count } }
# A one-column table is a layout container, not data -- pasted emails wrap
# their entire body in one. GFM cannot nest block content (headings, lists,
# other tables) inside a cell anyway, so unwrap: emit each row's content as
# ordinary blocks. Nested real tables inside then render as proper tables.
if ($width -eq 1) {
$out = @()
foreach ($r in $rows) {
$lines = @($r[0])
if ((($lines -join '').Trim()).Length -eq 0) { continue }
if ($out.Count -gt 0) { $out += '' }
$out += $lines
}
return $out
}
# A real (multi-column) table: flatten each cell to a single line, since GFM
# cells cannot contain newlines, and escape any pipes from nested content.
$flatRows = @()
foreach ($r in $rows) {
$cells = @()
foreach ($c in $r) {
$text = (($c -join "`n") -replace '\r', '').Trim()
$text = ($text -split "`n" | Where-Object { $_.Trim().Length -gt 0 }) -join '<br>'
$text = $text -replace '\|', '\|'
$cells += $text
}
$flatRows += ,$cells
}
$rows = $flatRows
function Format-Row {
param([string[]] $Cells, [int] $Width)
$padded = @($Cells) + @('') * ($Width - $Cells.Count)
return '| ' + (($padded | ForEach-Object { $_ }) -join ' | ') + ' |'
}
$hasHeader = (Get-Attr $Table 'hasHeaderRow' 'false') -eq 'true'
$lines = @()
if ($hasHeader) {
$lines += Format-Row -Cells $rows[0] -Width $width
$lines += '|' + (' --- |' * $width)
for ($i = 1; $i -lt $rows.Count; $i++) {
$lines += Format-Row -Cells $rows[$i] -Width $width
}
}
else {
# GFM requires a header row, so emit an empty one.
$lines += '|' + (' |' * $width)
$lines += '|' + (' --- |' * $width)
foreach ($r in $rows) { $lines += Format-Row -Cells $r -Width $width }
}
$indent = ' ' * (2 * $Depth)
return ($lines | ForEach-Object { "$indent$_" })
}
function Copy-EmbeddedFile {
<#
Copies an embedded file (InsertedFile / MediaFile) into the page's media
folder. The original path (pathSource) is tried first, then OneNote's local
cache copy (pathCache) -- the file's bytes stored under a .bin name, and
usually the only copy present for notebooks authored on another machine.
#>
param($Node, $Ctx)
$name = Get-Attr $Node 'preferredName' 'attachment'
$safe = Get-SafeName -Name $name -Used $null
foreach ($src in @((Get-Attr $Node 'pathSource'), (Get-Attr $Node 'pathCache'))) {
if ([string]::IsNullOrWhiteSpace($src)) { continue }
if (-not (Test-Path -LiteralPath $src)) { continue }
try {
$mediaDir = Join-Path $Ctx.PageDir 'media'
if (-not (Test-Path -LiteralPath $mediaDir)) {
New-Item -ItemType Directory -Path $mediaDir -Force | Out-Null
}
$attachTarget = Join-Path $mediaDir $safe
Copy-Item -LiteralPath $src -Destination $attachTarget -Force
Set-ItemTimestamps -Path $attachTarget -CreatedUtc $Ctx.CreatedUtc -ModifiedUtc $Ctx.ModifiedUtc
$Ctx.FilesSaved++
return [pscustomobject]@{ Name = $name; Link = "[$name](media/$($safe -replace ' ', '%20'))"; Copied = $true }
}
catch {
$Ctx.Warnings.Add("attachment-copy-failed:$safe") | Out-Null
}
}
return [pscustomobject]@{ Name = $name; Link = ''; Copied = $false }
}
function Save-PageImage {
param($Image, $Ctx)
$callback = $null
foreach ($c in (Get-ChildElements $Image)) {
if ($c.LocalName -eq 'CallbackID') { $callback = $c; break }
}
$format = Get-Attr $Image 'format' 'png'
if ([string]::IsNullOrWhiteSpace($format)) { $format = 'png' }
$alt = Get-Attr $Image 'alt' ''
if ($null -eq $callback) {
$Ctx.Warnings.Add('image-without-callback') | Out-Null
return "> [!NOTE] An image on this page could not be extracted (no callback ID)."
}
$Ctx.ImageIndex++
$fileName = '{0}-{1:d2}.{2}' -f $Ctx.PageSlug, $Ctx.ImageIndex, $format
$mediaDir = Join-Path $Ctx.PageDir 'media'
$fullPath = Join-Path $mediaDir $fileName
try {
if (-not (Test-Path -LiteralPath $mediaDir)) {
New-Item -ItemType Directory -Path $mediaDir -Force | Out-Null
}
[ref]$b64 = ''
$Ctx.App.GetBinaryPageContent($Ctx.PageId, (Get-Attr $callback 'callbackID'), $b64)
$bytes = [Convert]::FromBase64String($b64.Value)
[System.IO.File]::WriteAllBytes($fullPath, $bytes)
Set-ItemTimestamps -Path $fullPath -CreatedUtc $Ctx.CreatedUtc -ModifiedUtc $Ctx.ModifiedUtc
$Ctx.ImagesSaved++
}
catch {
$Ctx.Warnings.Add("image-failed:$fileName") | Out-Null
Write-Verbose "Image extraction failed for $fileName : $($_.Exception.Message)"
return "> [!NOTE] An image on this page could not be extracted."
}
# OneNote stuffs its OCR output into @alt as "Machine generated alternative text:"
# followed by the entire scraped page. Useless as alt text, so fall back to the title.
$altText = $alt
if ($altText -match '^\s*Machine generated alternative text\s*:') { $altText = '' }
if ([string]::IsNullOrWhiteSpace($altText)) { $altText = $Ctx.PageTitle }
$altText = (($altText -replace '[\[\]]', '') -replace '\s+', ' ').Trim()
if ($altText.Length -gt 120) { $altText = $altText.Substring(0, 117).TrimEnd() + '...' }
return ""
}
function Convert-Oe {
param($Oe, $Ctx, [int] $Depth)
$out = @()
$parts = @()
$blocks = @()
$styleName = ''
$quickIndex = Get-Attr $Oe 'quickStyleIndex' ''
if ($quickIndex -ne '' -and $Ctx.QuickStyles.ContainsKey($quickIndex)) {
$styleName = $Ctx.QuickStyles[$quickIndex]
}
$listMarker = ''
$checkbox = ''
$tagPrefix = ''
$sawText = $false
# User-enlarged text is a heading in all but name: quickStyleIndex stays 'p' and
# the size lands in a font-size on the OE or its T children. Track the largest.
$fontSize = 0.0
if ((Get-Attr $Oe 'style') -match 'font-size\s*:\s*([\d.]+)\s*pt') {
$fontSize = [double]$Matches[1]
}
foreach ($child in (Get-ChildElements $Oe)) {
switch ($child.LocalName) {
'T' {
$sawText = $true
if ((Get-Attr $child 'style') -match 'font-size\s*:\s*([\d.]+)\s*pt') {
$ts = [double]$Matches[1]
if ($ts -gt $fontSize) { $fontSize = $ts }
}
$parts += Convert-TextRun $child.InnerText
}
'List' {
foreach ($l in (Get-ChildElements $child)) {
if ($l.LocalName -eq 'Bullet') { $listMarker = '-' }
elseif ($l.LocalName -eq 'Number') { $listMarker = '1.' }
}
}
'Tag' {
$idx = Get-Attr $child 'index' ''
if ($Ctx.TagDefs.ContainsKey($idx)) {
$def = $Ctx.TagDefs[$idx]
if ($script:CheckboxTagSymbols[$def.Symbol]) {
$done = (Get-Attr $child 'completed' 'false') -eq 'true'
if ($done) { $checkbox = '- [x]' } else { $checkbox = '- [ ]' }
}
else {
$emoji = $null
if ($def.Name) { $emoji = $script:TagEmoji[$def.Name.ToLowerInvariant()] }
if ($emoji) {
$tagPrefix = "$emoji "
}
elseif ($def.Name) {
# Custom tags with no emoji mapping keep a readable label.
$tagPrefix = "``$($def.Name.ToUpperInvariant())`` "
}
}
if ($def.Name) { $Ctx.PageTags[$def.Name] = $true }
}
}
'Image' {
# Indent to the enclosing list depth, otherwise a column-0 image
# terminates the surrounding list and the items after it get
# reinterpreted as an indented code block.
$blocks += ''
$blocks += (' ' * (2 * $Depth)) + (Save-PageImage -Image $child -Ctx $Ctx)
}
'Table' {
$blocks += ''
$blocks += (Convert-Table -Table $child -Ctx $Ctx -Depth $Depth)
}
'OEChildren' {
# Indentation only means 'nested list' in Markdown when the parent is
# itself a list item. Under a heading, plain paragraph or empty wrapper
# OE, 4+ leading spaces turn the children into an indented code block,
# so those children stay at the current depth instead.
$childDepth = $Depth
if ($listMarker -or $checkbox) { $childDepth = $Depth + 1 }
$blocks += Convert-OeChildren -OeChildren $child -Ctx $Ctx -Depth $childDepth
}
'InkDrawing' {
$Ctx.Warnings.Add('ink-not-exported') | Out-Null
$blocks += ''
$blocks += '> [!WARNING] Handwritten ink on this page was not exported.'
}
'InkWord' {
$Ctx.Warnings.Add('ink-not-exported') | Out-Null
}
'InsertedFile' {
$f = Copy-EmbeddedFile -Node $child -Ctx $Ctx
if ($f.Copied) {
$parts += $f.Link
} else {
$Ctx.Warnings.Add("attachment-missing:$($f.Name)") | Out-Null
$parts += "``[attachment: $($f.Name)]``"
}
}
'MediaFile' {
$f = Copy-EmbeddedFile -Node $child -Ctx $Ctx
if ($f.Copied) {
$parts += $f.Link
} else {
$Ctx.Warnings.Add("mediafile-not-exported:$($f.Name)") | Out-Null
$parts += "``[embedded media: $($f.Name)]``"
}
}
}
}
$text = ($parts -join '').Trim()
$indent = ' ' * (2 * $Depth)
if ($text.Length -gt 0) {
if ($styleName -match '^h([1-6])$') {
# The page title owns '#', so shift OneNote headings down one level.
$level = [int]$Matches[1] + 1
if ($level -gt 6) { $level = 6 }
$out += ('#' * $level) + ' ' + $tagPrefix + ($text -replace "`n", ' ')
}
elseif ($fontSize -ge 14 -and -not $listMarker -and -not $checkbox) {
# Enlarged plain text becomes a heading. OneNote's own scale: h1 = 16pt,
# h2 = 14pt, body = 11-12pt, so 14pt is the smallest safe cutoff.
$level = if ($fontSize -ge 16) { 2 } else { 3 }
$t = $text -replace "`n", ' '
# A heading is already emphasised by its size; drop redundant full-wrap bold.
if ($t -match '^\*\*([^*]+)\*\*$') { $t = $Matches[1] }
$out += ('#' * $level) + ' ' + $tagPrefix + $t
}
elseif ($checkbox) {
$out += "$indent$checkbox $tagPrefix$text"
}
elseif ($listMarker) {
$out += "$indent$listMarker $tagPrefix$text"
}
elseif ($styleName -eq 'cite' -or $styleName -eq 'blockquote') {
foreach ($line in ($text -split "`n")) { $out += "$indent> $line" }
}
elseif ($styleName -eq 'code') {
$out += "$indent``````"
foreach ($line in ($text -split "`n")) { $out += "$indent$line" }
$out += "$indent``````"
}
else {
# A soft break inside a paragraph becomes a hard Markdown line break.
# A tag prefix belongs on the first line only.
$lines = $text -split "`n"
for ($i = 0; $i -lt $lines.Count; $i++) {
$suffix = ''
if ($i -lt $lines.Count - 1) { $suffix = ' ' }
$prefix = ''
if ($i -eq 0) { $prefix = $tagPrefix }
$out += "$indent$prefix$($lines[$i])$suffix"
}
}
}
elseif ($checkbox) {
$out += "$indent$checkbox"
}
elseif ($sawText -and $blocks.Count -eq 0) {
# An OE whose text is empty is a blank line the author left on purpose.
# Markdown collapses blank lines, so make the gap explicit: a paragraph
# holding a single non-breaking space. Renderers that escape raw HTML
# (Orbit does) would show a literal '<br>', so a bare U+00A0 it is.
$out += "$indent" + [char]0xA0
}
$out += $blocks
return $out
}
function Convert-OeChildren {
param($OeChildren, $Ctx, [int] $Depth)
$out = @()
$prevList = $false
foreach ($oe in (Get-ChildElements $OeChildren)) {
if ($oe.LocalName -ne 'OE') { continue }
$lines = @(Convert-Oe -Oe $oe -Ctx $Ctx -Depth $Depth)
if ($lines.Count -eq 0) { continue }
$isList = $lines[0] -match '^\s*(-|\d+\.)\s'
# Blank line between blocks, but not between consecutive list items --
# that would break the list into separate loose lists. Trim space/tab
# only: a deliberate-gap line holds a U+00A0 and must count as content.
if ($out.Count -gt 0 -and -not ($isList -and $prevList)) {
if ($out[-1].Trim(' ', "`t").Length -gt 0) { $out += '' }
}
$out += $lines
$prevList = $isList
}
return $out
}
#endregion
#region Page export
function Format-MarkdownBody {
<#
Safety net over the emitted lines:
* re-baselines each contiguous run of non-blank lines so its shallowest
line sits at column 0 -- a run that starts at 4+ spaces with no parent
list would otherwise be parsed as an indented code block
* collapses runs of blank lines down to one
Fenced code blocks are passed through untouched.
#>
param([string[]] $Lines)
# Collapse runs of deliberate-gap lines (a lone U+00A0 from empty paragraphs):
# pasted emails stack many empty rows, and one gap reads the same as six.
# Full Trim() removes U+00A0; Trim(' ',tab) does not -- that difference is
# exactly what identifies a gap line.
$filtered = New-Object System.Collections.ArrayList
$gapPending = $false
foreach ($line in $Lines) {
$isGap = ($line.Trim(' ', "`t").Length -gt 0) -and ($line.Trim().Length -eq 0)
if ($isGap) {
if ($gapPending) { continue }
$gapPending = $true
}
elseif ($line.Trim().Length -gt 0) { $gapPending = $false }
[void]$filtered.Add($line)
}
$Lines = @($filtered)
$out = New-Object System.Collections.ArrayList
$inFence = $false
$run = New-Object System.Collections.ArrayList
$flushRun = {
if ($run.Count -eq 0) { return }
$min = [int]::MaxValue
foreach ($l in $run) {
$indent = $l.Length - $l.TrimStart(' ').Length
if ($indent -lt $min) { $min = $indent }
}
if ($min -eq [int]::MaxValue) { $min = 0 }
# A run whose FIRST line is 4+ spaces deep opens an indented code block, even
# when a later line in the same run sits at column 0 (so re-baselining on the
# run minimum alone is not enough). Shift the whole run left until the opening
# line clears the 4-space threshold, clamping at column 0.