# Check if two cells are identifcal

Is it possible to check whether two cells in a Mathematica notebook have exactly the same code? I'm comparing two bits of code that might be the same, but rather than eye-checking, I wonder if there is an inbuilt tool to do that (and ideally, to even highlight the differences).

The solution I found was to simply turn both cells into strings by using " " and simply testing if they're the same with ==, but I know about Cells and SelectedCells so perhaps there's a better way to do this.

Any ideas?

Edit: I've found this post in the meantime, regarding strings, but I wonder if there's a nicer way of doing it rather than resort to strings.

## 1 Answer

You can utilize the command PreviousCell[] along with NotebookRead[], I made an example illustrating how it could compare two cells. PreviousCell grabs the Notebook Input that Wolfram Desktop stores and the first index of the NotebookRead of the cell is the typed input.

in[22]:= f[x] := x + 2

In[23]:= val = NotebookRead[PreviousCell[]][[1]]
Out[23]= BoxData[RowBox[{RowBox[{"f", "[", "x", "]"}], ":=", " ", RowBox[{"x", "+", "2"}]}]]

in[24]:=f[x] := x + 1

In[25]:= val2 = NotebookRead[PreviousCell[]][[1]]
Out[25]= BoxData[RowBox[{RowBox[{"f", "[", "x", "]"}], ":=", RowBox[{"x", "+","1"}]}]]

In[26]:= val === val2
Out[26]= False


Important to note is that the cells you're comparing are not executed, PreviousCell grabs the output cell instead. Using "===" calls the SameQ function that tests if two expressions(code-wise) instead of the more mathematical "==" which will attempt to solve symbolic functions.

https://reference.wolfram.com/language/ref/PreviousCell.html -- This shows explicit outputs of PreviousCell with a nested NotebookRead.

Hope this helps!