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$ Commented May 1, 2022 at 7:50
  • $\begingroup$ It would be good or better if it is possible using menu also! $\endgroup$ Commented May 1, 2022 at 7:59
  • 1
    $\begingroup$ It is possible to use the menus: Format -> Style. $\endgroup$ Commented 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$ Commented 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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.