Insert text shortcode at cursor in codemirror #4311
-
Hello, I want to insert shortcodes ([HELLO], [DATUM] ...) into the editor next to the cursor. editor_el = ui.codemirror("A lot of text", line_wrapping=True)
def insert_shortcode():
js: str = textwrap.dedent("""\
const nicegui_editor_id = "{}";
let editor_el = document.querySelector('#' + nicegui_editor_id);
const cursor = editor_el.getCursor();
editor.replaceRange("[HELLO]", cursor);
""")
ui.run_javascript(js.format(f"c{editor_el.id}"))
ui.button(
"Insert shortcode HELLO at cursor",
on_click=lambda: insert_shortcode(),
) In the code above the Maybe this is not the good way, how can I put some text to the editor cursor? I can't figure it out. Thanks: Adam |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @arunaseva, You can use NiceGUI's helper function editor = ui.codemirror("A lot of text")
ui.button("Insert shortcode HELLO at cursor", on_click=lambda: ui.run_javascript(f"""
const view = getElement("{editor.id}").editor;
const cursor = view.state.selection.main.head
view.dispatch(view.state.update({{
changes: {{from: cursor, insert: "[HELLO]"}}
}}));
""")) By the way, JavaScript doesn't care about code indentation. So you don't need to remove the indentation. |
Beta Was this translation helpful? Give feedback.
Hi @arunaseva,
You can use NiceGUI's helper function
getElement
to get a Vue element by ID. But the methodsgetCursor
andreplaceRange
don't seem to work, so I improvised with the help of some AI:By the way, JavaScript doesn't care about code indentation. So you don't need to remove the indentation.