0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

vscode 文字化け判定してみた

Last updated at Posted at 2022-11-01

Shift-jisのファイルをUTF-8で開いてしまってそのまま保存...なんてことがないように。

自動判定する・しないの記事はたくさんあるが、結局のところ

  • 日本語コーディング完全自動判定は無理?
  • 拡張子ごとにコーディングを指定? 多分無理、拡張子で決められない

ちゃんと開くのはあきらめる。文字化けが判定できればいい。

じゃあvscodeのコーディング判定と正しいコーディングを比較したらいい。
ステータスバーに見えているのに、実際のコーディング判定結果は取得しにくい。

じゃあvscodeがコーディング判定して読み込んだ文字列と正しくコーディング判定をした文字列を比較すればいい。違っていたらメッセージ。

副作用で、\r\n と \nが混ざっているファイルも文字化け判定してしまう。vscodeは改行混在が扱えないかもしれない。そんなファイルそんなにないけど。

しばらくはこれで大丈夫。だと思う。

encoding-japanese すごすぎ。

async function handlerOnOpenRefreshModification(
  textDocument: vscode.TextDocument
) {

  // get vscode text on unicode
  const docText = textDocument.getText();

  // get file text on unicode
  const text = fs.readFileSync(textDocument.uri.fsPath);
  let docFile = Encoding.convert(text, {
    to: "UNICODE",
    type: "string",
  });

  // BOM
  if (docFile.charCodeAt(0) === 0xfeff) {
    docFile = docFile.substring(1);
  }

  const result = docText === docFile;
  // show result !!
}

とりあえずサンプル
mojibake-hunter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?