[Tex/LaTex] Pasting vs typing into LyX

lyx

I have this bit of LaTeX code.

f(n)=\begin{cases}n/2&\mbox{if }n\equiv0\\(3n+1)/2&\mbox{if}n\equiv1.\end{cases}\pmod{2}    

I want to see it rendered in my LyX document. If I copy and paste it into the "Insert Math" box given by Ctrl+M, it works and I see the this in my document

I would like to be able to manually type that code (and code in general) into LyX and get the same result. That is, I would like to be able to manually enter code into LyX and have it have the same effect as pasting that code into LyX. I can't find a way to do this. My current workaround is to keep a separate text editor open from which I paste into LyX, which is not ideal.

If I try to type the same code by hand into a math box, I get a mess whose beginning looks like this:

The same happens if try to type it into a "Insert -> TeX code" box nested inside the math box.

If I type or paste it into a code box not nested inside a math box, I get this:

What am I doing wrong? Based on googling, the "instant preview" setting seems to be connected. I've turned it on and off and see no difference. I'm using LyX 2.12 with all default settings (except for the instant preview).

Best Answer

The reason why pasting is different from typing is because when you paste, LyX tries to detect what content you are pasting. It can detect LaTeX, for example, which is what it does in this case and it then runs tex2lyx to import the LaTeX into LyX's format (although for math there is not much conversion that needs to be done I believe). When you type, LyX sees it as character by character, so it does not try to detect the format.

You might be interested in preview boxes. In your TeX Box example, select the red box (the box, not what's inside the box) and then go to Insert > Preview. That will put a black box around the red box. Note that your TeX Code is incomplete as it is. You have to surround it with $ (or similar), just like in LaTeX. After you have the preview box, move click outside so that LyX knows to refresh the box. Then you should see your expression as LaTeX would display it.

Below I show a screen shot with duplicate expressions. That is, both are a TeX box inside of a preview box. The only difference is that in the top one I have my cursor inside it.

enter image description here

I'm not sure why there is no space between "if" and "n". Did you make a mistake in your post or did I make a mistake?

Related Question