Skip to content

Commit

Permalink
Fix some bugs (Mainly string parsing) (#79)
Browse files Browse the repository at this point in the history
* fix: latex punctuation convert error
* test: add latex convert test
* fix: send to dirname deck can not work normally at opensuse
  • Loading branch information
duguosheng committed Aug 20, 2022
1 parent c0114a2 commit 876cac3
Show file tree
Hide file tree
Showing 8 changed files with 82 additions and 11 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to the "anki" extension will be documented in this file.

Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.

## [1.2.7]

- Fix bug that LaTeX curly brackets do not convert correctly [#63](https://github.com/jasonwilliams/anki/issues/63)
- Fix bug when user sets the `saveStrategy` to `useDirStructure`, the actual deck does not match the displayed deck when executing the `Send To Deck` command

## [1.2.6]

- Add a new feature: Use the current directory structure as deck name [#71](https://github.com/jasonwilliams/anki/issues/71)
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ echo "Hello, World!"
- `Anki: Sync Anki`: This will run Sync on your Anki Instance
- `Anki: Anki: Send To Deck`: This will attempt to send your (markdown) card into Anki - More info above
- `Anki: Anki: Send To Own Deck`: Sends to a new deck using the Markdown's title (# example) as a deck name
- `Anki: Anki: Send To DirName Deck`: Sends to a new deck using the directory structure as a deck name
- `Anki: Force Re-install`: This will attempt to re-setup the extension on Anki (Anki needs to be running). You shouldn't need this unless there's an issue.

## Extension Settings
Expand All @@ -153,6 +154,7 @@ echo "Hello, World!"
- `anki.api.hostname`: API Hostname. | _127.0.0.1_
- `anki.api.port`: API Port. | _8765_
- `anki.api.schema`: Schema. | _http_
- `anki.saveStrategy`: the behavior of the command `Anki: Send To Deck` | _default_

I don't recommend messing with the following settings

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "anki",
"displayName": "Anki for VSCode",
"description": "Sync notes with your locally running Anki",
"version": "1.2.6",
"version": "1.2.7",
"publisher": "jasew",
"engines": {
"vscode": "^1.66.0"
Expand Down
11 changes: 5 additions & 6 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,19 @@ export const registerCommands = (ctx: IContext) => {
"anki.sendToDeck",
async () => {
// The code you place here will be executed every time your command is executed
let strategyStr = workspace.getConfiguration("anki").get("saveStrategy") as string;
let processInfo = strategyStr === "default" ? `Sending to Deck: ${ctx.config.defaultDeck}...` : `Sending to dirname deck...`;
let strategy = strategyStr === "default" ? DeckNameStrategy.UseDefault : DeckNameStrategy.ParseDirStru;
window.withProgress(
{
location: ProgressLocation.Notification,
title: `Sending to Deck: ${ctx.config.defaultDeck}...`,
title: processInfo,
cancellable: false,
},
async () => {
try {
getLogger().info("active Editor..");
if (workspace.getConfiguration("anki").get("saveStrategy") as string === "default") {
await new Transformer(MarkdownFile.fromActiveTextEditor(), ctx.ankiService, DeckNameStrategy.UseDefault).transform();
} else {
await new Transformer(MarkdownFile.fromActiveTextEditor(), ctx.ankiService, DeckNameStrategy.ParseDirStru).transform();
}
await new Transformer(MarkdownFile.fromActiveTextEditor(), ctx.ankiService, strategy).transform();
} catch (e) {
window.showErrorMessage(e.toString());
}
Expand Down
55 changes: 55 additions & 0 deletions src/markdown/__tests__/Latex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { CardParser } from "../parsers/cardParser";

describe("Latex", () => {
it("Should keep the content of 'Latex inline' unchanged.", async () => {
// linesToHtml always return a newline at the end of string
const latexs = ["a=\\%1", "b=\\#1"];
const input = [
`extra stuff before the latex`,
`extra stuff before the latex $${latexs[0]}$ extra stuff after the latex`,
`$${latexs[1]}$`,
`extra stuff after the latex`
];
const cardParser = new CardParser();
// Act
const result = await cardParser.linesToHtml(input);
// Assert
for (let latex of latexs) {
expect(result).toMatch(latex);
}
});
it("Should keep the content of 'Latex block' unchanged.", async () => {
// linesToHtml always return a newline at the end of string
const latexs = ["a=\\%1", "b=\\#1",
"\\before{align}", "c=\\{1,2\\} \\\\", "d=\\$2", "\\end{align}"];
const input = [
`extra stuff before the latex`,
`$$${latexs[0]} ${latexs[1]}$$`, // one line latex block
`extra stuff`,
`$$`, // multiline latex block
`${latexs[2]}`,
`${latexs[3]}`,
`${latexs[4]}`,
`${latexs[5]}`,
`$$`
];
const cardParser = new CardParser();
// Act
const result = await cardParser.linesToHtml(input);
// Assert
for (let latex of latexs) {
expect(result).toMatch(latex);
}
});
it("Should not affect the conversion outside of latex", async () => {
const htmlStr = "<p>%</p>\n";
const input = [
"\\%"
];
const cardParser = new CardParser();
// Act
const result = (await cardParser.linesToHtml(input));
// Assert
expect(result).toEqual(htmlStr);
});
});
11 changes: 10 additions & 1 deletion src/markdown/parsers/cardParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,16 @@ export class CardParser extends BaseParser {
* @private
*/
async linesToHtml(lines: string[]) {
const string = lines.join("\n");
const fixLatex = (match: string) => (
/\n\n/.test(match) ?
match : // If there is an empty line, return directly
match.replace(/\\[{}%#&$_\\]/g, str => str === "\\\\" ? "\\\\\\\\" : ("\\" + str))
);
const string = lines.join("\n")
// $$\{1,2\} \%100$$ => $$\\{1,2\\} \\%100$$
.replace(/(?<!\\)\$\$.+?(?<!\\)\$\$/gs, fixLatex)
// $\{1,2\} \%100$ => $\\{1,2\\} \\%100$
.replace(/(?<![\\$])\$(?!\$).+?(?<!\\)\$/gs, fixLatex);

const mdString = await new MdParser({}).parse(string);
if (!this.options.convertMath) {
Expand Down
5 changes: 3 additions & 2 deletions src/markdown/parsers/mathParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { BaseParser } from "./baseParser";

export class MathParser extends BaseParser {
async parse(string = ""): Promise<string> {
// (?<!\\): $100\$$->\(100\$\)
return string
.replace(/\$\$(.+?)\$\$/g, "\\[$1\\]") // $equation$ -> \(equation\)
.replace(/\$(.+?)\$/g, "\\($1\\)"); // $$equation$$ -> \[equation\]
.replace(/(?<!\\)\$\$(.+?)(?<!\\)\$\$/g, "\\[$1\\]") // $$equation$$ -> \[equation\]
.replace(/(?<!\\)\$(.+?)(?<!\\)\$/g, "\\($1\\)"); // $equation$ -> \(equation\)
}
}
2 changes: 1 addition & 1 deletion src/markdown/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export class Transformer {
const filePath = fileUri.path;
let deckName: string = "";
if (rootPath && filePath) {
deckName = relative(rootPath, dirname(filePath)).replace(/\\/g, '::');
deckName = relative(rootPath, dirname(filePath)).replace(/[\/\\]/g, '::');
}
return deckName || this.defaultDeck;
}
Expand Down

0 comments on commit 876cac3

Please sign in to comment.