telesoho / vscode-markdown-paste-image

Smartly paste for Markdown.
MIT License
135 stars 41 forks source link

Fix encoding problem in non-english language in Windows os #7

Closed huhk-sysu closed 7 years ago

huhk-sysu commented 7 years ago

I'm using your extension, which has saved me much time.

Everything is fine before I tried to use it when the Markdown file was in a folder with Chinese letter in its name, which means the imagePath below may contain Chinese letter.

private static saveClipboardImageToFileAndGetPath(imagePath, cb: (imagePath: string) => void)

I traced the execution of your extension and found the Chinese part of imagePath became a mess in the callback function of saveClipboardImageToFileAndGetPath:

image

According to your code, when plplatform === 'win32', it will run the /res/pc.ps1 file with PowerShell. And in the file pc.ps1, the output is exactly the input, without any modification.

param($imagePath)

......

$imagePath

After some search I found this article, which says

When we pipe output data from PowerShell cmdlets into native applications, the output encoding from PowerShell cmdlets is controlled by the $OutputEncoding variable, which is by default set to ASCII

And that's the problem, Chinese letters(and also letters in many other languages) can't be represented in ASCII encoding, so the data.toString() in following code can't get the correct imagePath.

powershell.stdout.on('data', function (data: Buffer) {
    cb(data.toString().trim());
});

AFAIK there's two way to fix the problem:

powershell.on('exit', function (code, signal) {
    cb(imagePath)
 });
powershell.stdout.on('data', function (data: Buffer) {
    // do nothing
});
param($imagePath)

......

[System.Console]::OutputEncoding=[System.Text.Encoding]::GetEncoding(65001)
$imagePath

Thanks for your work!

telesoho commented 7 years ago

Thank you very much for your help. I had try your second way to fix this bug, but not work. Because using $imagePath directly always get ASCII output. I found this answer, so I use the following code to fix this bug.

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::WriteLine($imagePath)