[education/rkward/snippets] rkward: Fix lineCommand() in snippets

Thomas Friedrichsmeier null at kde.org
Sat Jun 18 21:13:52 BST 2022


Git commit 0cc10db4902294a0d1d5d338e0d7b314b885dded by Thomas Friedrichsmeier.
Committed on 18/06/2022 at 20:13.
Pushed by tfry into branch 'snippets'.

Fix lineCommand() in snippets

M  +13   -15   rkward/RKWardRMd.xml

https://invent.kde.org/education/rkward/commit/0cc10db4902294a0d1d5d338e0d7b314b885dded

diff --git a/rkward/RKWardRMd.xml b/rkward/RKWardRMd.xml
index ee8d68c4..fb65f8de 100644
--- a/rkward/RKWardRMd.xml
+++ b/rkward/RKWardRMd.xml
@@ -1,5 +1,5 @@
 <snippets name="R Markdown (RKWard)" filetypes="R Markdown" authors="RKWard Team" namespace="SnippetsRmd" license="BSD">
- <script>require("range.js")
+  <script>require("range.js")
 require("cursor.js")
 require("document.js")
 require("view.js")
@@ -9,17 +9,15 @@ function encoding() { return document.encoding(); }
 function year() { return new Date().getFullYear(); }
 function upper(x) { return x.toUpperCase(); }
 function lower(x) { return x.toLowerCase(); }
-function braces(text) { return "{" + text + "}"}
-function lineCommand(command) {
-    if (view.selectedText().length > 0) {
-        let prefix = view.selection().start.column > 0 ? "\n" : "";
-        let postfix = document.line(view.selection().end.line).length > view.selection().end.column ? "\n" : "";
-        return (prefix + command + " " + view.selectedText() + postfix);
-    }
-
-    let l = view.cursorPosition().line;
-    document.insertText(l, 0, command + " ");
-    return "";
+function braces(text) { return "{" + text + "}"; }
+function lineCommand(command, replaces="", label_if_empty="Heading") {
+    let c = view.cursorPosition();
+    // NOTE: snippet scripts work by 1. inserting the raw snippet as a raw "template" 2. evaluating any commands inside the template 3. replacing the template with the evaluated template. As a result, when this function gets called, it contains the call to itself...
+    let line = document.line(c.line).replace(/\$\{lineCommand\s*\([^\}]*\}/g, "");
+    line = line.replace(new RegExp(replaces), "");
+    if (line == "") line = label_if_empty;
+    else document.removeLine(c.line);
+    return command + " " + line + "\n";
 }
 
 function rangeCommand(command, def) {
@@ -32,15 +30,15 @@ function rangeCommand(command, def) {
 </script>
  <item>
   <match>Heading1</match>
-  <fillin>${rangeCommand("# ")}</fillin>
+  <fillin>${lineCommand("#", "^#+ ", "Heading")}</fillin>
  </item>
  <item>
   <match>Heading2</match>
-  <fillin>${rangeCommand("## ")}</fillin>
+  <fillin>${lineCommand("##", "^#+ ", "Heading")}</fillin>
  </item>
  <item>
   <match>Heading3</match>
-  <fillin>${rangeCommand("### ")}</fillin>
+  <fillin>${lineCommand("###", "^#+ ", "Heading")}</fillin>
  </item>
  <item>
   <match>List (Unordered)</match>


More information about the rkward-tracker mailing list