shigma / vscode-wl

Wolfram Language support for Visual Studio Code.
MIT License
49 stars 4 forks source link

Get description of the function from usage #1

Closed oovm closed 5 years ago

oovm commented 5 years ago
oovm commented 5 years ago
getBox[str_String] := StringReplace[str, Shortest["\!\(\*" ~~ expr__ ~~ "\)"] :> Hold[expr]]
format = {
    <|"type" -> "code", "content" -> getFuction[# // First]|>,
    <|"type" -> "text", "content" -> getUsage[# // Rest]|>
}&;

$PlainRule = {
    RowBox[s_] :> s,
    StyleBox[s_, any_] :> s,
    SubscriptBox[a_, b_] :> {a, b}
};
getFuction[getBox_] := StringRiffle[Flatten[ReleaseHold[getBox /. Hold :> MakeExpression] //. $PlainRule], ""];

(*TR=Times Regular*)
(*TI=Times Italic*)
$MDRule = {
    StyleBox[f_, "TI"] :> {"*", f, "*"},
    StyleBox[f_, ___] :> {f},
    RowBox[l_] :> {l},
    SubscriptBox[a_, b_] :> {a, "_", b},
    SuperscriptBox[a_, b_] :> {a, "^", b},
    FractionBox[a_, b_] :> {"(", a, ")/(", b, ")"},
    OverscriptBox[a_, b_] :> {a}
};
BoxParser[str_String] := StringRiffle[Flatten@ReleaseHold[MakeExpression[str, StandardForm] //. $MDRule], ""];
getUsage[expr_] := StringDrop[expr /. Hold :> BoxParser, 1];(*Drop first space*)

然后使用

Flatten[format@*getBox /@ StringSplit[MessageName[Plot, "usage"], "\n"]]
Export["test.json",%, "RawJSON"]

产生的这个是不是合法的表达式

[
    {
        "type":"code",
        "content":"Plot[f,{x,xmin,xmax}]"
    },
    {
        "type":"text",
        "content":"generates a plot of *f* as a function of *x* from *x*_*min* to *x*_*max*. "
    },
    {
        "type":"code",
        "content":"Plot[{f1,f2,…},{x,xmin,xmax}]"
    },
    {
        "type":"text",
        "content":"plots several functions *f*_*i*. "
    },
    {
        "type":"code",
        "content":"Plot[{…,w[fi],…},…]"
    },
    {
        "type":"text",
        "content":"plots *f*_*i* with features defined by the symbolic wrapper *w*."
    },
    {
        "type":"code",
        "content":"Plot[…,{x}∈reg]"
    },
    {
        "type":"text",
        "content":"takes the variable *x* to be in the geometric region *reg*."
    }
]
shigma commented 5 years ago

非常感谢您的提议!基本上没有问题,不过有一些地方我还有一些疑问。

  1. $PlainRule 只给出了 3 条规则,那么对于其他的 Box 也能妥善处理吗?对于 $MDRule 也有类似的问题。
  2. 生成的代码中包含适当的空格会使看起来更好一些。具体规则可以暂定为在逗号后面以及运算符两侧添加空格。
  3. 从代码和说明文本的统一性考虑,是不是应该重新考虑一下生成诸如 a_n, x^y 这种代码是否合理?
shigma commented 5 years ago

问题已经基本解决了。