1
$\begingroup$

How can I change the style of a given cell,
by writing some code on the cell directly below the cell and executing it?

I want to change this cell (*the cell that I want to change cell-style*)

SelectionMove[EvaluationCell[], Previous, Cell];
...

I know that the code probably start like this, but I can't go further.

If it is possible using
menu(mouse right click on the target cell..?) or
shortcuts(when cursor is on the target cell..?),
I also want to know it.

$\endgroup$
3
  • 1
    $\begingroup$ You don’t want to just use the menus? $\endgroup$
    – lericr
    May 1, 2022 at 7:50
  • $\begingroup$ It would be good or better if it is possible using menu also! $\endgroup$
    – imida k
    May 1, 2022 at 7:59
  • 1
    $\begingroup$ It is possible to use the menus: Format -> Style. $\endgroup$
    – lericr
    May 1, 2022 at 8:19

2 Answers 2

3
$\begingroup$

First we move the selection to the previous cell:

SelectionMove[EvaluationCell[], Previous, Cell];

We now read the selected cell, change its style e.g. to "Section" and rewrite the changed cell:

NotebookWrite[cell = SelectedCells[][[1]], 
 ReplacePart[NotebookRead[cell], 2 -> "Section"]]

Finally we move the selection back to the original cell:

SelectionMove[cell, Next, Cell];

For convenience, here is everything together:

SelectionMove[EvaluationCell[], Previous, Cell];
NotebookWrite[cell = SelectedCells[][[1]], 
 ReplacePart[NotebookRead[cell], 2 -> "Section"]]
SelectionMove[cell, Next, Cell]

;

$\endgroup$
1
  • $\begingroup$ Thank you, learned SelectedCells and NotebookWrite $\endgroup$
    – imida k
    May 1, 2022 at 8:38
4
$\begingroup$

You can do it this way :

Cell to be transformed :

I want to change this cell (*the cell that I want to change cell-style*)  

Cell to transform the previous cell :

CurrentValue[PreviousCell[], StyleNames] = "Section" 

After evaluation it gives :
enter image description here

PreviousCell is documented.
CurrentValue[..., StyleNames]=... is not, so far I know. The idea to use this syntax comes from the documentation of Cells, paragraph "Application", where there is this code :

     Scan[(CurrentValue[#, StyleNames] = "Subsection") &, 
 Cells[nb, CellStyle -> "Section"]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.