Skip to content

Commit 377c174

Browse files
authored
fix: Better handling of source map for importing files (#336)
1 parent dfffe53 commit 377c174

File tree

8 files changed

+100
-92
lines changed

8 files changed

+100
-92
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ Please visit https://github.com/shd101wyy/vscode-markdown-preview-enhanced/relea
44

55
## [Unreleased]
66

7+
## [0.9.3] - 2023-10-15
8+
9+
### Bug fixes
10+
11+
- Better handling of source map for importing files.
12+
713
## [0.9.2] - 2023-10-15
814

915
### New features

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "crossnote",
3-
"version": "0.9.2",
3+
"version": "0.9.3",
44
"description": "A powerful markdown notebook tool",
55
"keywords": [
66
"markdown"

src/markdown-engine/transformer.ts

+39-86
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ export interface TransformMarkdownOptions {
5858
headingIdGenerator?: HeadingIdGenerator;
5959
notebook: Notebook;
6060
forJest?: boolean;
61+
timestamp?: number;
6162
}
6263

6364
const fileExtensionToLanguageMap = {
@@ -245,6 +246,7 @@ export async function transformMarkdown(
245246
notebook,
246247
forJest = false,
247248
fileHash,
249+
timestamp,
248250
}: TransformMarkdownOptions,
249251
): Promise<TransformMarkdownOutput> {
250252
// Replace CRLF with LF
@@ -593,7 +595,7 @@ export async function transformMarkdown(
593595
// =========== Start: File import ============
594596
const importMatch = line.match(/^(\s*)@import(\s+)"([^"]+)";?/);
595597
const imageImportMatch = line.match(
596-
/^(\s*)!\[([^\]]*)\]\(([^)]+)\)(?:{([^}]*)})?\s*$/,
598+
/^(\s*)!\[([^\]]*)\]\(([^)]+)\)(?:{([^}]*)})?(\s*)$/,
597599
);
598600
const wikilinkImportMatch = line.match(
599601
/^(\s*)!\[\[(.+?)\]\](?:{([^}]*)})?\s*$/,
@@ -626,6 +628,9 @@ export async function transformMarkdown(
626628
}
627629
}
628630
}
631+
if (canCreateAnchor()) {
632+
config['data-source-line'] = lineNo + 1;
633+
}
629634

630635
let absoluteFilePath: string;
631636
if (
@@ -648,14 +653,12 @@ export async function transformMarkdown(
648653
const extname = path.extname(absoluteFilePath).toLocaleLowerCase();
649654
let output = '';
650655
if (filePath === '[TOC]') {
651-
if (!config) {
652-
config = {
653-
// same case as in normalized attributes
654-
['depth_from']: 1,
655-
['depth_to']: 6,
656-
['ordered_list']: true,
657-
};
658-
}
656+
/*
657+
// NOTE: No need to set this
658+
config['depth_from'] = config['depth_from'] ?? 1;
659+
config['depth_to'] = config['depth_to'] ?? 6;
660+
config['ordered_list'] = config['ordered_list'] ?? true;
661+
*/
659662
config['cmd'] = 'toc';
660663
config['hide'] = true;
661664
config['run_on_save'] = true;
@@ -693,51 +696,42 @@ export async function transformMarkdown(
693696
imageSrc =
694697
path.relative(fileDirectoryPath, absoluteFilePath) +
695698
'?' +
696-
Math.random();
699+
(timestamp ?? Math.random());
697700
} else {
698701
imageSrc =
699702
'/' +
700703
path.relative(projectDirectoryPath, absoluteFilePath) +
701704
'?' +
702-
Math.random();
705+
(timestamp ?? Math.random());
703706
}
704707
// enchodeURI(imageSrc) is wrong. It will cause issue on Windows
705708
// #414: https://github.com/shd101wyy/markdown-preview-enhanced/issues/414
706709
imageSrc = imageSrc.replace(/ /g, '%20').replace(/\\/g, '/');
707710
filesCache[filePath] = imageSrc;
708711
}
709712

710-
if (config) {
711-
if (
712-
config['width'] ||
713-
config['height'] ||
714-
config['class'] ||
715-
config['id']
716-
) {
717-
output = `<img src="${imageSrc}" `;
718-
for (const key in config) {
719-
// eslint-disable-next-line no-prototype-builtins
720-
if (config.hasOwnProperty(key)) {
721-
output += ` ${key}="${config[key]}" `;
722-
}
723-
}
724-
output += '>';
725-
} else {
726-
output = '![';
727-
if (config['alt']) {
728-
output += config['alt'];
729-
}
730-
output += `](${imageSrc}`;
731-
if (config['title']) {
732-
output += ` "${config['title']}"`;
733-
}
734-
output += ') ';
735-
}
713+
output = '![';
714+
if (config['alt']) {
715+
output += config['alt'];
716+
delete config['alt'];
717+
}
718+
output += `](${imageSrc}`;
719+
if (config['title']) {
720+
output += ` "${config['title']}"`;
721+
delete config['title'];
722+
}
723+
output += ')';
724+
const configStr = stringifyBlockAttributes(config);
725+
if (configStr) {
726+
output += `{${configStr}} `;
736727
} else {
737-
output = `![](${imageSrc}) `;
728+
output += ' ';
738729
}
739730
} else if (imageImportMatch) {
740-
output = imageImportMatch[0]; // NOTE: Don't change anything here
731+
const configStr = stringifyBlockAttributes(config);
732+
output = `![${imageImportMatch[2] ?? ''}](${
733+
imageImportMatch[3] ?? ''
734+
})${configStr ? `{${configStr}}` : ''}${imageImportMatch[5]}`;
741735
}
742736
i = end + 1;
743737
lineNo = lineNo + 1;
@@ -756,7 +750,7 @@ export async function transformMarkdown(
756750
);
757751
filesCache[absoluteFilePath] = fileContent;
758752

759-
if (config && (config['line_begin'] || config['line_end'])) {
753+
if (config['line_begin'] || config['line_end']) {
760754
const lines = fileContent.split(/\n/);
761755
fileContent = lines
762756
.slice(
@@ -766,7 +760,7 @@ export async function transformMarkdown(
766760
.join('\n');
767761
}
768762

769-
if (config && config['code_block']) {
763+
if (config['code_block']) {
770764
const fileExtension = extname.slice(1, extname.length);
771765
output = `\`\`\`${
772766
config['as'] ||
@@ -775,7 +769,7 @@ export async function transformMarkdown(
775769
} ${stringifyBlockAttributes(
776770
config,
777771
)} \n${fileContent}\n\`\`\` `;
778-
} else if (config && config['cmd']) {
772+
} else if (config['cmd']) {
779773
if (!config['id']) {
780774
// create `id` for code chunk
781775
config['id'] = computeChecksum(absoluteFilePath);
@@ -880,7 +874,7 @@ export async function transformMarkdown(
880874
// css or less file
881875
output = `<style>${fileContent}</style>`;
882876
} else if (extname === '.pdf') {
883-
if (config && config['page_no']) {
877+
if (config['page_no']) {
884878
// only disply the nth page. 1-indexed
885879
const pages = fileContent.split('\n');
886880
let pageNo = parseInt(config['page_no'], 10) - 1;
@@ -943,11 +937,8 @@ export async function transformMarkdown(
943937
output = "<script>${fileContent}</script>"
944938
*/
945939
// # codeblock
946-
let aS = null;
947-
if (config) {
948-
aS = config['as'];
949-
}
950-
if (config && config['code_block'] === false) {
940+
const aS = config['as'] ?? null;
941+
if (config['code_block'] === false) {
951942
// https://github.com/shd101wyy/markdown-preview-enhanced/issues/916
952943
output = fileContent;
953944
} else {
@@ -1001,44 +992,6 @@ export async function transformMarkdown(
1001992
// =========== End: File import ============
1002993
// =========== Start: Normal line ============
1003994
else {
1004-
// =========== Start: Add attributes to links and images ========
1005-
if (canCreateAnchor()) {
1006-
let newLine = '';
1007-
let restLine = line;
1008-
const regexp = /!?\[([^\]]*)\]\(([^)]*)\)/;
1009-
// Add and data-source-line to links and images {...} attributes
1010-
// eslint-disable-next-line no-constant-condition
1011-
while (true) {
1012-
const match = restLine.match(regexp);
1013-
if (!match || typeof match.index !== 'number') {
1014-
newLine = newLine + restLine;
1015-
break;
1016-
} else {
1017-
newLine =
1018-
newLine + restLine.substring(0, match.index + match[0].length);
1019-
restLine = restLine.substring(match.index + match[0].length);
1020-
1021-
if (restLine[0] === '{') {
1022-
// Might find attribute
1023-
// TODO: Write a generic parser for this
1024-
const end = restLine.indexOf('}');
1025-
if (end > 0) {
1026-
const attributeString = restLine.substring(1, end);
1027-
newLine += `{data-source-line="${
1028-
lineNo + 1
1029-
}" ${attributeString}}`;
1030-
restLine = restLine.substring(end + 1);
1031-
}
1032-
} else {
1033-
newLine += `{data-source-line="${lineNo + 1}"}`;
1034-
}
1035-
}
1036-
}
1037-
line = newLine;
1038-
}
1039-
1040-
// =========== End: Add attributes to links and images ========
1041-
1042995
i = end + 1;
1043996
lineNo = lineNo + 1;
1044997
outputString = outputString + line + '\n';

test/markdown/test-files/test2.expect.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
```text cmd="toc" depthFrom=1 depthTo=6 orderedList=false hide=true run_on_save=true modify_source=true code_chunk_offset=0
1+
```text cmd="toc" depthFrom=1 depthTo=6 orderedList=false data-source-line=1 hide=true run_on_save=true modify_source=true code_chunk_offset=0
22
```
33

44

5-
- [Heading 1](#heading-1){data-source-line="5"}
6-
- [Heading 2](#heading-2){data-source-line="6"}
5+
- [Heading 1](#heading-1)
6+
- [Heading 2](#heading-2)
77

88

99

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
# This is test3.md {#this-is-test3md data-source-line="1"}
22

3-
![@embedding](test2.md){x=1 y=2 embedding="JTBBJTYwJTYwJTYwdGV4dCUyMGNtZCUzRCUyMnRvYyUyMiUyMGRlcHRoRnJvbSUzRDElMjBkZXB0aFRvJTNENiUyMG9yZGVyZWRMaXN0JTNEZmFsc2UlMjBoaWRlJTNEdHJ1ZSUyMHJ1bl9vbl9zYXZlJTNEdHJ1ZSUyMG1vZGlmeV9zb3VyY2UlM0R0cnVlJTIwJTIwJTBBJTYwJTYwJTYwJTIwJTIwJTBBJTBBJTBBLSUyMCU1QkhlYWRpbmclMjAxJTVEKCUyM2hlYWRpbmctMSklMEElMjAlMjAtJTIwJTVCSGVhZGluZyUyMDIlNUQoJTIzaGVhZGluZy0yKSUwQSUwQSUwQSUwQSUyMyUyMEhlYWRpbmclMjAxJTIwJTdCJTIzaGVhZGluZy0xJTIwJTdEJTBBJTBBcGFyYWdyYXBoJTBBJTBBJTIzJTIzJTIwSGVhZGluZyUyMDIlMjAlN0IlMjNoZWFkaW5nLTIlMjAlN0QlMEElMEFwYXJhZ3JhcGglMEElMjAlMjA="}
3+
![@embedding](test2.md){x=1 y=2 data-source-line=3 embedding="JTBBJTYwJTYwJTYwdGV4dCUyMGNtZCUzRCUyMnRvYyUyMiUyMGRlcHRoRnJvbSUzRDElMjBkZXB0aFRvJTNENiUyMG9yZGVyZWRMaXN0JTNEZmFsc2UlMjBoaWRlJTNEdHJ1ZSUyMHJ1bl9vbl9zYXZlJTNEdHJ1ZSUyMG1vZGlmeV9zb3VyY2UlM0R0cnVlJTIwJTIwJTBBJTYwJTYwJTYwJTIwJTIwJTBBJTBBJTBBLSUyMCU1QkhlYWRpbmclMjAxJTVEKCUyM2hlYWRpbmctMSklMEElMjAlMjAtJTIwJTVCSGVhZGluZyUyMDIlNUQoJTIzaGVhZGluZy0yKSUwQSUwQSUwQSUwQSUyMyUyMEhlYWRpbmclMjAxJTIwJTdCJTIzaGVhZGluZy0xJTIwJTdEJTBBJTBBcGFyYWdyYXBoJTBBJTBBJTIzJTIzJTIwSGVhZGluZyUyMDIlMjAlN0IlMjNoZWFkaW5nLTIlMjAlN0QlMEElMEFwYXJhZ3JhcGglMEElMjAlMjA="}
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
`[test](test.md)`
2+
**[test](test.md)**
3+
4+
`![test](test.png)`
5+
**![test](test.md)**
6+
7+
![test](test.png){data-source-line=7}
8+
![test](https://test.png){data-source-line=8}
9+
![test](test.png#hash){data-source-line=9}
10+
![This is alt](test.png "This is title"){data-source-line=10}
11+
![test](test.png){title="This is title" alt="This is alt" data-source-line=11}
12+
![test](test.png){x=1 y=2 data-source-line=12}
13+
14+
![](/test.png?12345){data-source-line=14}
15+
![](https:/test.png){data-source-line=15}
16+
![](/test.png?12345){data-source-line=16}
17+
![This is alt](/test.png?12345 "This is title"){data-source-line=17}
18+
![](/test.png?12345){x=1 y=2 data-source-line=18}
19+
20+
![](/test.png?12345){data-source-line=20}
21+
![](https://test.png){data-source-line=21}
22+
![](/test.png?12345){data-source-line=22}
23+
![This is alt](/test.png?12345 "This is title"){data-source-line=23}
24+
![](/test.png?12345){x=1 y=2 data-source-line=24}

test/markdown/test-files/test4.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
`[test](test.md)`
2+
**[test](test.md)**
3+
4+
`![test](test.png)`
5+
**![test](test.md)**
6+
7+
![test](test.png)
8+
![test](https://test.png)
9+
![test](test.png#hash)
10+
![This is alt](test.png "This is title")
11+
![test](test.png){title="This is title" alt="This is alt"}
12+
![test](test.png){x=1 y=2}
13+
14+
![[test.png]]
15+
![[https://test.png]]
16+
![[test.png#hash]]
17+
![[test.png]]{title="This is title" alt="This is alt"}
18+
![[test.png]]{x=1 y=2}
19+
20+
@import "test.png"
21+
@import "https://test.png"
22+
@import "test.png#hash"
23+
@import "test.png" {title="This is title" alt="This is alt"}
24+
@import "test.png" {x=1 y=2}

test/markdown/transformer.test.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ describe('test markdown transformer', () => {
3232
projectDirectoryPath: path.join(__dirname, './test-files'),
3333
filesCache: {},
3434
useRelativeFilePath: false,
35-
protocolsWhiteListRegExp: null,
35+
protocolsWhiteListRegExp: /^(https?)/,
3636
forJest: true,
37+
timestamp: 12345,
3738
});
3839
};
3940

0 commit comments

Comments
 (0)