Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/dncl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ DNCL 風の形の読み方(切りかえる前の変換に合わせたもの)
- Ruby はこれらをどれも名前に使えて、Ruby → 日本語は名前をそのまま書く(`@佐々木` → `佐々木`)。日本語 → Ruby が同じ範囲を名前として読むので、書いた名前は読み戻せる。
- 全角英字・全角数字は、文字列(`"…"` `'…'` `「…」`)とコメントの外では、読む前にすべて半角にする(`x1` は `x1`、`and` は `and`)。見た目だけの揺れで(`policy.md`)、Ruby モードの自動置換も半角にするのと同じ考え。
ただし日本語タブの自動置換は `%` を半角にしない(書き出しが全角の `%` なので、半角にすると書き出すたびに戻って行ったり来たりする)。
文字列とコメントの中は書いたとおりに残す(`表示する("ABC")` は `"ABC"` のまま)。全角と半角は 1 字ずつ同じ長さなので、誤りの列は変わらない。
文字列とコメントの中は書いたとおりに残す(`表示する("ABC")` は `"ABC"` のまま)。日本語タブ・ルビータブの自動置換も、文字列とコメントの中を変えない(`表示する("こんにちは!")` の `!` は全角のまま。全角の `"` `'` や `“` `”` も文字列の囲みとして読み、囲みだけを半角にする)。全角と半角は 1 字ずつ同じ長さなので、誤りの列は変わらない。
Ruby → 日本語は Ruby の名前をそのまま書く(`@x` → `x`)ので、日本語から Ruby に戻すと `@x` になる。
- `☆` `①` `😀` のような記号は名前に使えず、「「☆」が読めません」の誤りになる(BMP の外の文字も 1 文字として示す)。

Expand Down
2 changes: 1 addition & 1 deletion docs/ruby-editor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ ruby-toolbar 上部のセグメントで切替:
| 元に戻す/やり直す | Monaco の undo/redo |
| 検索 | Monaco の find |
| キーボード (`ruby-toolbar-keyboard`) | ソフトウェアキーボードの表示/非表示(タッチデバイスのみ表示)。Monaco 組み込みの iPad キーボードウィジェットは zoom ボタンと重なるため CSS で非表示にしており、その代替 |
| 自動置換 (`ruby-toolbar-auto-correct`) | 自動置換のオン/オフを切りかえるスイッチ(`role="switch"`・`aria-checked`。つまみとラベル「自動置換」。形はデザインシステムの「スイッチ」)。全角の数字・英字・記号・空白を半角にする。コメント(`#` の後ろ。日本語タブでは設定で `//` をコメントにしたときの `//` の後ろも)の中は変えない(`#` は `#` になる) |
| 自動置換 (`ruby-toolbar-auto-correct`) | 自動置換のオン/オフを切りかえるスイッチ(`role="switch"`・`aria-checked`。つまみとラベル「自動置換」。形はデザインシステムの「スイッチ」)。全角の数字・英字・記号・空白を半角にする。文字列(`"…"` `'…'`。日本語タブでは `「…」` も)とコメント(`#` の後ろ。日本語タブでは設定で `//` をコメントにしたときの `//` の後ろも)の中は変えない(`puts("こんにちは!")` の `!` は全角のまま。囲みの `"` `“` と `#` は半角になる)。ただし `"…"` の中の `#{…}` は式なので半角にする(`"#{x + 1}"` は `"#{x + 1}"`)。文字列はその行の終わりまでと読む(打っている途中の閉じていない引用符で、下の行の文字列が変わらないように)。設定で変えられるのは、半角にする文字の種類だけ |
| その他メニュー (`ruby-toolbar-more-menu`) | Ruby スクリプト保存、クラス挿入、プレビュー、自動置換設定 |
| スプライト切替 | エディタ対象スプライトの prev/next |

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,9 @@ const messages = defineMessages({
description: 'Setting for fullwidth space conversion',
id: 'gui.autoCorrectModal.fullwidthSpace',
},
replaceInStrings: {
defaultMessage: 'Also replace inside strings',
description: 'Setting for replacing inside string literals',
id: 'gui.autoCorrectModal.replaceInStrings',
},
});

const SETTING_KEYS = ['fullwidthNumbers', 'fullwidthAlpha', 'fullwidthSymbols', 'fullwidthSpace', 'replaceInStrings'];
const SETTING_KEYS = ['fullwidthNumbers', 'fullwidthAlpha', 'fullwidthSymbols', 'fullwidthSpace'];

const AutoCorrectModal = ({ intl, settings, onSettingChange, onRequestClose }) => {
const handleChange = useCallback(
Expand Down Expand Up @@ -87,7 +82,6 @@ AutoCorrectModal.propTypes = {
fullwidthAlpha: PropTypes.bool.isRequired,
fullwidthSymbols: PropTypes.bool.isRequired,
fullwidthSpace: PropTypes.bool.isRequired,
replaceInStrings: PropTypes.bool.isRequired,
}).isRequired,
onSettingChange: PropTypes.func.isRequired,
onRequestClose: PropTypes.func.isRequired,
Expand Down
113 changes: 71 additions & 42 deletions packages/scratch-gui/src/lib/auto-correct.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const defaultSettings = {
fullwidthAlpha: true,
fullwidthSymbols: true,
fullwidthSpace: true,
replaceInStrings: true,
};

// Fullwidth ASCII symbols mapped to halfwidth equivalents.
Expand Down Expand Up @@ -117,13 +116,49 @@ const replaceChar = (ch, settings) => {
return ch;
};

// The quotes that open and close a string, half-width, full-width and smart
// ones alike: an IME writes `"` or `“`, and they become `"` only after the
// string is found, so the full-width ones have to be read as quotes too.
const DOUBLE_QUOTES = '"\uFF02\u201C\u201D';
const SINGLE_QUOTES = "'\uFF07\u2018\u2019";

/**
* Whether `ch` is a `/`, half-width or full-width.
* @param {string} ch - A character.
* @returns {boolean} True for `/` and `/`.
*/
const isSlash = (ch) => ch === '/' || ch === '\uFF0F';

/**
* Whether a Ruby `#{` (half-width or full-width) starts at `index`.
* @param {string} code - The source code.
* @param {number} index - The character index.
* @returns {boolean} True for `#{`, `#\uFF5B`, `\uFF03{` and `\uFF03\uFF5B`.
*/
const isInterpolationStart = (code, index) =>
(code[index] === '#' || code[index] === '\uFF03') && (code[index + 1] === '{' || code[index + 1] === '\uFF5B');

/**
* The index of the `}` that closes a `#{`, counting the braces in between
* (`#{h[{a: 1}]}`), or of the end of the line if it is not closed on its line.
* @param {string} code - The source code.
* @param {number} index - The index just after the `{` of `#{`.
* @returns {number} The index of the closing `}` (or `\uFF5D`), or of the `\n` (or the length of the code).
*/
const findInterpolationEnd = (code, index) => {
let depth = 0;
for (let i = index; i < code.length; i++) {
if (code[i] === '\n') return i;
if (code[i] === '{' || code[i] === '\uFF5B') {
depth++;
} else if (code[i] === '}' || code[i] === '\uFF5D') {
if (depth === 0) return i;
depth--;
}
}
return code.length;
};

/**
* Find the string literals and the comments of the source with a simple state
* machine. A string region is `[start, end]` (the indexes of its quotes); a
Expand All @@ -134,8 +169,13 @@ const isSlash = (ch) => ch === '/' || ch === '\uFF0F';
*
* A comment starts with `#` (or `#`). With `slashComments`, `//` (or `//`)
* starts one too (the Japanese tab, when its settings say so). With
* `japanese`, `「…」` is a string as well and a string ends at the end of its
* line, as the Japanese tab reads it.
* `japanese`, `「…」` is a string as well. Without `japanese`, a `#{…}` in
* a double-quoted string is code: the string is split into two regions there.
*
* A string ends at the end of its line, in both tabs. While a quote is being
* typed, the rest of the program has one quote too many: if a string went on
* to the next lines, the strings below would be read as code and be changed.
* The Japanese tab reads a string so too.
* @param {string} code - The source code.
* @param {object} [options] - How the source is read.
* @param {boolean} [options.japanese] - Whether it is the Japanese tab's code.
Expand All @@ -145,30 +185,44 @@ const isSlash = (ch) => ch === '/' || ch === '\uFF0F';
const findRegions = (code, options = {}) => {
const strings = [];
const comments = [];
const closeOf = (ch) => {
if (ch === '"' || ch === "'") return ch;
if (ch === '\u201C') return '\u201D';
if (ch === '\u2018') return '\u2019';
// The quotes that close a string opened by `ch`, or null if `ch` opens none.
const closersOf = (ch) => {
if (DOUBLE_QUOTES.includes(ch)) return DOUBLE_QUOTES;
if (SINGLE_QUOTES.includes(ch)) return SINGLE_QUOTES;
if (options.japanese && ch === '\u300C') return '\u300D';
return null;
};
let i = 0;
while (i < code.length) {
const ch = code[i];
const closeQuote = closeOf(ch);
if (closeQuote) {
const start = i;
const closers = closersOf(ch);
if (closers) {
// A `#{…}` in a Ruby double-quoted string is code, not text.
const interpolates = !options.japanese && closers === DOUBLE_QUOTES;
let start = i;
i++; // skip opening quote
while (i < code.length) {
// A `\` in a 「…」 is text (the Japanese tab takes it as it is).
if (code[i] === '\\' && closeQuote !== '\u300D') {
// A `\` at the end of a line does not carry the string on to the next line.
if (code[i] === '\\' && closers !== '\u300D' && code[i + 1] !== '\n') {
i += 2; // skip escaped character
continue;
}
if (code[i] === closeQuote) {
if (interpolates && isInterpolationStart(code, i)) {
// The string stops before `#` and starts again at the `}`,
// so `#`, `{`, `}` and the code between can be made half-width.
strings.push([start, i]);
start = findInterpolationEnd(code, i + 2);
i = start;
// Not closed on its line: the string ends with the line.
if (code[i] !== '}' && code[i] !== '\uFF5D') break;
i++;
continue;
}
if (closers.includes(code[i])) {
break;
}
if (options.japanese && code[i] === '\n') {
if (code[i] === '\n') {
break;
}
i++;
Expand Down Expand Up @@ -214,26 +268,11 @@ const isInString = (index, regions) => {
return false;
};

/**
* Check if a character at the given index is escaped (preceded by an odd number of backslashes).
* @param {string} code - The source code.
* @param {number} index - The character index.
* @returns {boolean} True if the character is escaped.
*/
const isEscaped = (code, index) => {
let backslashes = 0;
let j = index - 1;
while (j >= 0 && code[j] === '\\') {
backslashes++;
j--;
}
return backslashes % 2 === 1;
};

/**
* Apply fullwidth-to-halfwidth auto-correction to Ruby source code (or the
* Japanese tab's code). What is written in a comment stays as it is, and so
* does the `%` of the Japanese tab.
* Japanese tab's code). What is written in a string or a comment stays as it
* is: it is what is shown or meant, as `"こんにちは!"` (Issue #2621). So does
* the `%` of the Japanese tab.
* @param {string} code - The Ruby source code.
* @param {object} settings - The auto-correct settings.
* @param {object} [options] - How the source is read (see `findRegions`).
Expand All @@ -248,7 +287,7 @@ const autoCorrect = (code, settings, options = {}) => {
const regions = findRegions(code, options);

const result = code.replace(pattern, (match, offset) => {
if (isInComment(offset, regions.comments)) {
if (isInComment(offset, regions.comments) || isInString(offset, regions.strings)) {
return match;
}

Expand All @@ -258,16 +297,6 @@ const autoCorrect = (code, settings, options = {}) => {
return match;
}

// If replaceInStrings is off, skip characters inside string literals
if (!settings.replaceInStrings && isInString(offset, regions.strings)) {
return match;
}

// If replaceInStrings is on but char is escaped inside a string, keep it
if (settings.replaceInStrings && isEscaped(code, offset)) {
return match;
}

return replaceChar(match, settings);
});

Expand Down
1 change: 0 additions & 1 deletion packages/scratch-gui/src/locales/ja-Hira.js
Original file line number Diff line number Diff line change
Expand Up @@ -1966,7 +1966,6 @@ export default {
'gui.autoCorrectModal.fullwidthAlpha': 'ぜんかくアルファベット → はんかくアルファベット',
'gui.autoCorrectModal.fullwidthSymbols': 'ぜんかくきごう → はんかくきごう',
'gui.autoCorrectModal.fullwidthSpace': 'ぜんかくスペース → はんかくスペース',
'gui.autoCorrectModal.replaceInStrings': 'もじれつもおきかえる',

...lessonsMessages,
...activityDiagramMessages,
Expand Down
1 change: 0 additions & 1 deletion packages/scratch-gui/src/locales/ja.js
Original file line number Diff line number Diff line change
Expand Up @@ -1911,7 +1911,6 @@ export default {
'gui.autoCorrectModal.fullwidthAlpha': '全角アルファベット → 半角アルファベット',
'gui.autoCorrectModal.fullwidthSymbols': '全角記号 → 半角記号',
'gui.autoCorrectModal.fullwidthSpace': '全角スペース → 半角スペース',
'gui.autoCorrectModal.replaceInStrings': '文字列も置き換える',

...lessonsMessages,
...activityDiagramMessages,
Expand Down
26 changes: 11 additions & 15 deletions packages/scratch-gui/test/integration/auto-correct.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,30 +70,28 @@ describe('auto-correct integration', () => {
});
});

describe('string content preservation with replaceInStrings off', () => {
const settingsNoStrings = { ...defaultSettings, replaceInStrings: false };

describe('string content preservation', () => {
test('should not modify string content but fix surrounding code', () => {
const input = 'puts "ABC123"';
const result = autoCorrect(input, settingsNoStrings);
const result = autoCorrect(input, defaultSettings);
expect(result).toBe('puts "ABC123"');
});

test('should handle multiple strings on same line', () => {
const input = "puts 'A' + 'B'";
const result = autoCorrect(input, settingsNoStrings);
const result = autoCorrect(input, defaultSettings);
expect(result).toBe("puts 'A' + 'B'");
});

test('should handle code between strings', () => {
const input = 'x = "A" + y + "B"';
const result = autoCorrect(input, settingsNoStrings);
const result = autoCorrect(input, defaultSettings);
expect(result).toBe('x = "A" + y + "B"');
});

test('should preserve content inside smart-quoted strings', () => {
const input = 'puts \u201CABC\u201D';
const result = autoCorrect(input, settingsNoStrings);
const result = autoCorrect(input, defaultSettings);
// Smart quotes become halfwidth, but content inside is preserved
expect(result).toBe('puts "ABC"');
});
Expand Down Expand Up @@ -126,18 +124,16 @@ describe('auto-correct integration', () => {
});

describe('escape handling in strings', () => {
test('should preserve escaped fullwidth chars', () => {
const input = '"\\1 + 2"';
test('should keep everything in a string with an escaped full-width char', () => {
const input = '"\\1 + 2" + 1';
const result = autoCorrect(input, defaultSettings);
// \1 stays as-is, but + and 2 are converted
expect(result).toBe('"\\1 + 2"');
expect(result).toBe('"\\1 + 2" + 1');
});

test('should handle double escaped backslash', () => {
const input = '"\\\\1"';
test('should end a string after a double escaped backslash', () => {
const input = '"\\\\1" + 1';
const result = autoCorrect(input, defaultSettings);
// \\\\ is escaped backslash, so 1 should be converted
expect(result).toBe('"\\\\1"');
expect(result).toBe('"\\\\1" + 1');
});
});

Expand Down
Loading
Loading