开发者

How to get (not display) the section number

Notebook sections can be automatically numbered by inserting the automatically numbering object CounterBox["Section"] using the Insert > Automatic Numbering... menu. However this object only controls the display of the section number and I would like to get its numerical value to use in a program. Any idea how to do that?

Edit

The reason I want to use this is outlined he开发者_开发技巧re.


Wrap the CounterBox with a TagBox and a known tag:

Cell[BoxData[TagBox[CounterBox["Section"], "tag"]], "Text"]

Then use FrontEnd`ObjectContents to convert all DynamicBox/CounterBox/ValueBox to literals and pick out the value of that TagBox:

x = First@Cases[FrontEnd`ObjectContents[nb, True], TagBox[x_, "tag"] :> x, \[Infinity]]

If all you want to know is how many of a certain type of counters there are you can do:

x = FE`Evaluate[CurrentValue[{"MaxCounterValue", "Section"}]]


There's got to be a better way to do this, but here's something that works, if I understand what you want to do.

Create a notebook to play with:

nb = CreateDocument[{
    Cell["My Title", "Title"],
    Cell["My first section", "Section"],
    Cell["My second section", "Section"],
    Cell[TextData[{"Section ",
       CounterBox["Section"]}], "Section"]}];

Select the last cell, which happens to be a Section cell.

SelectionMove[nb, After, Notebook];
SelectionMove[nb, Previous, Cell];

Count backwards.

cnt = sectionCnt = c = 0;
While[True, Print[c];
  c = NotebookRead[nb];
  If[c === {}, Break[]];
  If[c[[2]] == "Section", sectionCnt++];
  cnt++;
  SelectionMove[nb, Previous, Cell]];

Now sectionCnt should hold the value that you want. You can move back to where you were easily enough:

Do[SelectionMove[nb, Next, Cell], {cnt}]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜