From 79259a1c3526673225f54e4f2777d1816bd50b1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20K=C5=82osko?= Date: Tue, 1 Apr 2025 11:10:43 +0200 Subject: [PATCH] Add shortcut to toggle line wrapping in code cells (#2974) --- assets/js/hooks/cell_editor/live_editor.js | 2 ++ .../live_editor/codemirror/toggle_with.js | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 assets/js/hooks/cell_editor/live_editor/codemirror/toggle_with.js diff --git a/assets/js/hooks/cell_editor/live_editor.js b/assets/js/hooks/cell_editor/live_editor.js index 40df9aa4d..8b767723d 100644 --- a/assets/js/hooks/cell_editor/live_editor.js +++ b/assets/js/hooks/cell_editor/live_editor.js @@ -57,6 +57,7 @@ import { ancestorNode, closestNode } from "./live_editor/codemirror/tree_utils"; import { selectingClass } from "./live_editor/codemirror/selecting_class"; import { globalPubsub } from "../../lib/pubsub"; import { hoverDetails } from "./live_editor/codemirror/hover_details"; +import { toggleWith } from "./live_editor/codemirror/toggle_with"; /** * Mounts cell source editor with real-time collaboration mechanism. @@ -385,6 +386,7 @@ export default class LiveEditor { settings.editor_mode === "vim" ? [vim()] : [], settings.editor_mode === "emacs" ? [emacs()] : [], this.languageCompartment.of(this.languageExtensions()), + toggleWith("Alt-z", EditorView.lineWrapping), EditorView.domEventHandlers({ click: this.handleEditorClick.bind(this), keydown: this.handleEditorKeydown.bind(this), diff --git a/assets/js/hooks/cell_editor/live_editor/codemirror/toggle_with.js b/assets/js/hooks/cell_editor/live_editor/codemirror/toggle_with.js new file mode 100644 index 000000000..50268af2e --- /dev/null +++ b/assets/js/hooks/cell_editor/live_editor/codemirror/toggle_with.js @@ -0,0 +1,22 @@ +import { EditorView, keymap } from "@codemirror/view"; +import { Compartment } from "@codemirror/state"; + +/** + * Returns an extension that toggles the given extension with the given + * keyboard shortcut. + */ +export function toggleWith(key, extension) { + const compartment = new Compartment(); + + function toggle(view) { + const isEnabled = compartment.get(view.state) === extension; + + view.dispatch({ + effects: compartment.reconfigure(isEnabled ? [] : extension), + }); + + return true; + } + + return [compartment.of([]), keymap.of({ key, run: toggle })]; +}