pythonemacslatex

Emacs preview-latex to format python comments and docstrings


One of my favorite features of Emacs is the preview-latex package: it renders LaTeX equations in LaTeX documents as an inline graphic. Like this:

preview-latex screenshot

I'd like similar functionality in Emacs for Python comments and function docstrings. My docstrings have a lot of math in them:

def proj_levenberg(x,y,wsqrt,A):
    """
    Finds a homography between two sets of 2d points.

    Specifically, approximately minimize the weighted image plane
    error

       min_A  sum_{X,y,w}  w  ||(A_12 x_) /  (A_3 x_)  -  y||^2

    where x_=[x;1], A_12 are the first two rows of A and A_3 is the
    third row of A.
    ...

I'd like to write these in LaTex so that I when I browse my code, I can see rendered docstrings and comments.

Is there a way to do this or do I have to do surgergy on preview-latex?


Solution

  • I modified your code sample a bit so that emacs understands what portion of that needs to be replaced with latex fragments:

    def proj_levenberg(x,y,wsqrt,A):
        """
        Finds a homography between two sets of 2d points.
    
        Specifically, approximately minimize the weighted image plane
        error
    
           \(min_A  sum_{X,y,w}  w  ||(A_12 x_) /  (A_3 x_1)  -  y||^2\)
    
        where \(x_1\)=[x;1], \(A_{12}\) are the first two rows of A and \(A_3\) is the
        third row of A.
        """
    

    Note that I have wrapped the latex fragments between \( and \) Source

    You need to have org mode installed. Org is installed by default in emacs but I have the latest org mode installed (version 8.0+) using the emacs package manager.

    I have the following in my emacs setup for previewing latex fragments:

    ;; Previewing latex fragments in org mode
    (setq org-latex-create-formula-image-program 'imagemagick) ;; Recommended to use imagemagick
    
    (load "auctex.el" nil t t)
    (load "preview-latex.el" nil t t)
    (setq LaTeX-command "latex -shell-escape")
    

    My org mode setup for emacs

    My latex setup for emacs

    With this setup when I do M-x org-preview-latex-fragment, I get the below. You can remove the previews using M-x org-ctrl-c-ctrl-c Note that I don't need to have the major mode to be org-mode. This function worked even where the buffer was in Python mode and the file was temp.py.

    The catch is that this function will have to be run every time you re-open that file; emacs does not save the preview state of each file.

    Latex fragment preview