【问题标题】:Templating language, determine current scope模板语言,确定当前范围
【发布时间】:2011-12-08 13:53:03
【问题描述】:

我正在使用一种支持使用特殊分隔符更改范围的诱人语言,如下所示:

%% scope Foo %%
Stuff
%% end %%

块可以像这样无限嵌套:

%% scope Foo %%
Stuff in the Foo namespace
  %% scope Bar %%
     Stuff in the bar namespace
  %% end %%
%% end %%

在文本区域中编辑其中一个模板时,我希望运行一个 Javascript 函数来报告当前范围。当前行号和光标位置是已知的,可以传递给函数。

换句话说,使用上面的例子,如果我的光标在第二行的任何地方,函数应该记录'Foo'。同样,如果我在第 4 行,它应该记录 'Bar'。如果我在第三行的最开头(在 %% 之前),它应该记录“Foo”。

【问题讨论】:

  • 我们如何获取光标位置?

标签: javascript regex scope templating


【解决方案1】:

这可能对你有用:

value = "%% scope Foo %% \nStuff in the Foo namespace\n  %% scope Bar %% \n     Stuff in the bar namespace \n  %% end %% \n%% end %%" // the value of the text area
cursor= Math.round(Math.random() * value.length) //just to get a random cursor position for testing

console.log(logTag(cursor,value), cursor); // should be foo or bar

function logTag (pos,string) {
    string = string.slice(0,pos);
    string = string.match(/%%\s*scope\s*(\w*)\s*%%/g);
    string = string[string.length - 1].match(/%%\s*scope\s*(\w*)\s*%%/)[1];
    return string;
}

这个函数简单地获取所有%% scope <something> %% 并返回最新的,这将是用户输入的范围。空格可以忽略。并且只能包含字母数字和下划线。

【讨论】:

  • 您也可以使用+ 代替*+ 用于字符重复一次或多次,* 用于重复 0 次或多次。让我知道它是否有效。