2022-09-18

Resolving Spacing Issues Between Alphabets and Japanese Characters When Formatting Markdown with Prettier

Introduction

When formatting Markdown with Prettier, a half-width space is inserted between alphabets and Japanese characters by default. For example, when formatting AIエンジニア (AI engineer), it becomes AI エンジニア.

This article introduces a method to prevent the insertion of a half-width space between alphabets and Japanese characters when formatting with Prettier.

Solution

Prettier is located in the following directory:

~/.vscode/extensions/esbenp.prettier-vscode-<Your Version>/node_modules/prettier

Open the index.js file in that directory with an editor and locate the section of code shown below.

~/.vscode/extensions/esbenp.prettier-vscode-<Your Version>/node_modules/prettier/index.js
if (lastNode && lastNode.type === "word") {
      if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
        nodes.push({
          type: "whitespace",
          value: " "
        });
      } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
      ![lastNode.value, node.value].some(function (value) {
        return /\u3000/.test(value);
      })) {
        nodes.push({
          type: "whitespace",
          value: ""
        });
      }
    }

Make the following modification:

~/.vscode/extensions/esbenp.prettier-vscode-<Your Version>/node_modules/prettier/index.js
 if (lastNode && lastNode.type === "word") {
       if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
         nodes.push({
           type: "whitespace",
-           value: " "
+           value: ""
         });
       } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
       ![lastNode.value, node.value].some(function (value) {
         return /\u3000/.test(value);
       })) {
         nodes.push({
           type: "whitespace",
           value: ""
         });
       }
     }

The modification changes value: " " to value: "". Once you save the changes, Prettier will no longer insert a half-width space between alphabets and Japanese characters during formatting.

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!