Here's one way that seems to work.
parentcell[] := Module[{cellstyle, nb},
nb = EvaluationNotebook[];
SelectionMove[nb, All, EvaluationCell];
firstcell[nb];
cellstyle = NotebookRead[nb][[2]];
(* input cell may be grouped with output cell, ignore as parent *)
If[cellstyle == "Input",
SelectionMove[nb, All, CellGroup];
firstcell[nb]
]
]
where firstcell goes to the first cell of the cellgroup
firstcell[nb_] := (SelectionMove[nb, All, CellGroup];
SelectionMove[nb, Before, CellGroup];
SelectionMove[nb, Next, Cell])
Since parentcell simply sets the notebook selection to the desired cell, one can access it's options using CurrentValue, e.g.:
parentcell[];
CurrentValue[NotebookSelection[EvaluationNotebook[]], CellTags]
This function can also be modified to go up until it hits a specified level in the cell grouping hierarchy (e.g., "Section"). This version currently does not terminate unless it finds a cell with the specified style.
parentcell[style_String] := Module[{nb},
nb = EvaluationNotebook[];
SelectionMove[nb, All, EvaluationCell];
firstcell[nb];
While[NotebookRead[nb][[2]] =!= style,
SelectionMove[nb, All, CellGroup];
firstcell[nb]
]
]
Finally, these functions have slightly strange behavior when used in cells with no hierarchy (except in/out grouping). The selection will end up either at the input cell or the first cell in the notebook.
NotebookGet[EvaluationNotebook[]]shows the structureCell[CellGroupData[{Cell[...], Cell[CellGroupData[...]]..},Open]]where the firstCellis the parent, and the subsequent ones are the child groups. The cells containingCellGroupDatado not appear to have any options set, they just provide structure and probably formatting. – rcollyer Jun 7 '12 at 18:42NotebookPut@ Notebook@List@Cell[CellGroupData[{Cell["a"], Cell["b"]}], FontWeight->"Bold"]– Rojo Jun 7 '12 at 18:45Cell, and why I think theCellaroundCellGroupDatais just there for structure. – rcollyer Jun 7 '12 at 18:50CellContext->CellGroupat a higher level of cell group? If so, then perhaps you might find it easier to change theCellGroupingRuleson the relevant styles to confine the context the way you want. TheCellGroupsetting stops at cells with grouping higher than "InputGrouping". So, for example, I tried setting the Subsubsection style toCellGroupingRules->{-10, "InputGrouping"}in a private stylesheet, and$Contextnow spans Subsubsection cells in that notebook. – John Fultz Jun 10 '12 at 7:28