3

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 here.

Community
  • 1
  • 1
Sjoerd C. de Vries
  • 16,122
  • 3
  • 42
  • 94

2 Answers2

5

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"}]]
ragfield
  • 2,486
  • 13
  • 15
  • Thanks! I feel this is getting me closer to what I'd like to do, but I'm not there yet. The goal is to have all the input cells in the same section the same CellContext (see http://stackoverflow.com/q/5898498/615464). To do this I thought to use the section number as part of the context identifier. I'm not sure how to do this with the above code. – Sjoerd C. de Vries May 06 '11 at 19:36
1

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}]
Mark McClure
  • 4,862
  • 21
  • 34
  • Appreciate your effort, but I don't think this can be used for the application I had in my mind. My fault for not being clear. I added a link to my question to clarify matters a bit. – Sjoerd C. de Vries May 06 '11 at 19:39