# Automatic indentation of text and equations depending on Style

I have a rule when writing text and equations. Starting from the Section environment, each text/equation that sits inside Section will get indexed by one Tab. Anything that lives inside a Subsection gets a further Tab (i.e. 2 Tabs) and so on. Now, as I expand my notebook, sometimes Sections become Subsections or vice-versa, meaning that I need to go back and correct all the indentations manually. Is there a way to automate this?

CellMargins -> Dynamic[ AbsoluteCurrentValue[ PreviousCell[CellStyle->{"Section","Subsection"}], CellMargins]]

works. However, Mathematica becomes rather laggy. I am assuming it is because Mathematica keeps checking each line of text all the time. Ideally, it would only do that once (e.g. when the Stylesheet is selected as it does so with the above code) and anytime a grouping occurs or when a Style environment (e.g. via Alt+ (1-6)) is created. This sounds a bit complicated, so alternatively, it is fine if a button is created that sorts the selected grouping as desired.

• Does this answer help? – Carl Woll May 15 '19 at 19:09
• Thank you. I tried implementing both suggestions, but I get many error messages, all saying: "The specified setting for the option CellMargins cannot be used." – Patrick.B May 15 '19 at 20:07
• What's your Mathematica version and OS? – Carl Woll May 15 '19 at 20:08
• I am working on Linux x86 (64-bit Ubuntu) with Mathematica 11.3.0.0 – Patrick.B May 15 '19 at 20:10
• Looks like it only works on M12, and it still issues messages there too. – Carl Woll May 15 '19 at 20:16

Here's a button that can do this for you. I put it in a docked cell:

With[{styles = {"Section", "Subsection", "Subsubsection"}},
SetOptions[EvaluationNotebook[],
DockedCells -> Cell @ BoxData @ ToBoxes @ Button[
"align",
Map[
Set[
CurrentValue[#, {CellMargins,1,1}],
CurrentValue[PreviousCell[#, CellStyle->styles], {CellMargins,1,1}]
]&,
Cells[CellStyle->"Text"]
]
]
]
]


You could also put the button in a palette. A short animation:

• Very nice. If I want to slightly tweak the placement of the text with respect to the environment, what part of this code needs to be altered? For example, if I wanted the text to be aligned with the title as it does here + a few spaces, how can I do that? Also, does this also work with Code? (by replacing the "Text" with "Code" I guess) – Patrick.B May 20 '19 at 9:30
• @Patrick.B To adjust the alignment, modify the RHS of the Set (e.g., 5 + CurrentValue[..]). To make it work with "Code" cells as well, use CellStyle->{"Text", "Code"}. – Carl Woll May 20 '19 at 16:29