Welcome to Cadabra Q&A, where you can ask questions and receive answers from other members of the community.
+1 vote

How do I copy Cadabra output as a LaTeX string?

There are a couple of different use cases:

  1. If I want to set a big expression to zero in a further manipulation, I need to rearrange one of the terms of the output expression to the left hand side to create a substitution rule.
  2. For example, if I want to copy one output expression into a TeX file elsewhere, I wouldn't want to have to compile my entire notebook for just one expression.

So, is there a way to copy the output of a Cadabra evaluation as a LaTeX string? Or an alternative that allows me to achieve this?

in General questions by (740 points)

1 Answer

+1 vote

Cadabra's philosophy is that notebooks should be viewed as code, which you should be able to run from start to end in one shot if needed. This clashes rather strongly with the idea of cutting and pasting (parts of) expressions which are then manipulated in following cells: the information about what you cut and how that should change when any of the earlier cells change is not contained in the notebook. This is very, very bad for reproducibility; try to avoid working like this.

To enforce a better working style, there are various tools in Cadabra to select sub-expressions programmatically and then act with algorithms on only those sub-expressions; I refer to the section on zoom/unzoom in the manual: selecting expressions

Re-arranging expressions by moving terms to the left/right of an equals sign should be done using to_lhs and to_rhs of the cdb.core.manip module. In this way, if you expression changes, you are still sure to do the right thing, and you can run your notebook without doing the cut-n-paste again.

Now having said that (which addresses part 1), I am sympathetic to part 2 of your question: sometimes you simply want to copy a result into a LaTeX file somewhere else. There is no cut-n-paste way to do that, but you can use the pyperclip python module to put the LaTeX form of an expression into the clipboard (and then paste that elsewhere):

import pyperclip as pc
ex:= A_{m} + B_{n} D_{n m};
pc.copy(ex._latex_())

You can then paste the LaTeX form of ex to another program.

Of course you can abuse the above to cut an expression, edit it elsewhere and paste it back into a new input cell, but I would advise you not to do that, and learn instead about zoom/unzoom/to_lhs/to_rhs and various other tools.

Hope this helps.

by (83.1k points)

Thanks Kasper. I've managed to implement most of what you were suggesting to programmatically implementing things.

However, whenever I need to copy individual LaTeX expressions elsewhere, the pyperclip import throws a NoModuleFound error. Whereas I manually did a pip install pyperclip and checked that it is indeed installed. Do you know what this might be due to?

...