Skip to content

Setup Latex + Emacs + AucTex on Mac (pdf viewer = Skim , Latex compiler = TexLive)

—-It took me 2 hours to finally setup a working Emacs that can create and view pdf on my Mac, with lots of help from internet experts. Here is a summary:

Solved the issue: “LaTeX: problems after [0] pages.”


  • Option 1 (only works on Mac): Just use Aquamacs, a variation of Emacs for Mac. It can be downloaded from here. It comes with everything you need to compile Latex using Emacs. The reason why I stopped using it is because since it is not a standard Emacs, I found it hard to customize (for example, change color theme, etc.)
  • Option 2 (works on Mac, may give you a hint on other systems):
    • Idea: Need 3 things (on Mac)-
      1. Emacs 24: Use as Latex editor (also need the AucTex package installed, see below).
      2. TexLive: Latex compiler, which create the pdf file from your Latex code. Download here.
      3. Skim: Pdf viewer. Download here.
    • Details:
      1. Install the AucTex package in Emacs. Do the following:  Open Emacs; Hit M - x ; Type package-list-packages;  Hit Enter ;  In the list find and left click auctex (alternatively, move your curser to that line [remember you can “search” by typing C-s auctex], type then type x.
      2. (AucTex webpage)
      3. Install TexLive.
      4. Install Skim.
      5. Now the fun part. On my machine, Emacs doesn’t know where to find the compiler, neither does it know where to find the pdf viewer. Adding The following codes to the .emacs file should solve the problem. (if you have no idea what an “.emacs” is, take a look at this site. In short, it is an initial file that modifies the behavior of Emacs. It should be at ~/.emacs, where ~ is your home directory.)
  • Codes to be added to .emacs:


;; This line tells emacs where to find the latex compiler
(setenv "PATH" (concat "/usr/texbin:" (getenv "PATH")))
;; This line tells emacs to create pdf files instead of dvi files.
(setq-default TeX-PDF-mode t)
(setq TeX-view-program-selection '((output-pdf "PDF Viewer")))
(setq TeX-view-program-list
'(("PDF Viewer" "/Applications/Skim.app/Contents/SharedSupport/displayline -b -g %n %o %b")))

;; start emacs in server mode so that skim can talk to it
(server-start)
'(LaTeX-command "latex -synctex=1")
(add-hook 'TeX-mode-hook
(lambda ()
(add-to-list 'TeX-output-view-style
'("^pdf$" "."
"/Applications/Skim.app/Contents/SharedSupport/displayline -b %n %o %b")))
)

  • Final words. Now C-c C-v  in Emacs should compile a .tex file, create a pdf file and view it in Skim.
Advertisements

Protected: A Word Every Day.

This content is password protected. To view it please enter your password below:

Customizing Emacs Tutorial BY Dummy – Change Color Theme

Change Color Theme in Emacs 24

– for dummies like me. I just want to use emacs to edit some files. I don’t plan to run my entire life with it.

– If any emacs expert sees my post,  please correct my mistakes


Part I: Default Themes.

1. In Emacs 24, it is easy to change basic theme. Do the following: Open Emacs, type: M-x load-theme. That is: Hit Meta X, then type load-theme, then hit Enter. You should see “Load custom theme:”. If you know the name of the theme you want to use, type it, if not, hit Tab. Possible themes are listed. Click one.

2. If hitting TAB doesn’t bring up a list of themes…(searching for an answer online, please let me know if you have a solution).  Default themes on my machine include: adwaita, deeper-blue, dichromacy, light-blue, manoj-dark, tango, tango-dark, tsdh-dark, tsdh-light, wheatgrass, whiteboard, wombat. (So to change to tango, type : M-x load-theme, hit Enter, type tango, hit Enter.)


Part II: Use Other Good Looking Themes.

Main Idea:  Download the theme file (a .el file) —> Put it in a folder —> Let Emacs know to look for interesting things in that folder (by editing the .emacs file) —> Ask Emacs to use the theme

1. Download a theme. My friends recommended two themes: zenburn and monokai.  They can be downloaded from

http://marmalade-repo.org/packages/monokai-theme

https://github.com/bbatsov/zenburn-emacs

  • Download the .el file. (For example monokai-theme.el). Note: For some reason if I right click on the download theme, and choose save file, my computer downloads a .el file with html codes in it (not what we want). So make sure you have the correct .el file (for example, download the zip file and extract .el from it). The first few lines of my monokai-theme.el file looks like this

;;; monokai-theme.el — REQUIRES EMACS 24: Monokai Color Theme for Emacs.

;; Copyright (C) 2012 Lorenzo Villani.

  • Put the .el files in your emacs folder (see below)
  • Where is the folder: Actually you can choose any folder, but since you need to type the path to this folder later, put it somewhere close to your home directory, usually ~/emacs.d/themes/ .
  • Windows 7: Internet told me I should put it in /emacs.d/themes. If that folder doesn’t exists, create one. On my Windows 7 machine I put in C:\emacs\emacs.d\themes.
  • Linux or Macs: look for this folder: ~/.emacs.d/themes. The folder may be hidden (because of the “.” in front of the name). So type ls -a from the terminal to see all folders and files (that’s what -a is for). If it is not there, or you just don’t want to look for it, create one.
  • Note: Remember the path of this folder. You need to let Emacs know to look into this folder! (see 2,3 below)

2. The magical .emacs file. (You can skip this part.)

  • .emacs is a Very Important file … which may not exist.  Every time Emacs starts it will run .emacs. By changing contents of this file, you customize the behavior of emacs.
  • How does Emacs know where to find the .emacs file? Most of the time you don’t need to worry about it. I guess in Macs or Linux, Emacs looks for it in the home directory (in the system PATH). With Windows 7, look at my other post “how to install Emacs on Windows”, which I stole from http://www.claremontmckenna.edu/pages/faculty/alee/emacs/emacs.html.
  • The file is written in the “emacs lisp” language (no idea). I don’t plan on learning it in the near future. If you want to, look at this Emacs lisp introduction: http://www.gnu.org/software/emacs/emacs-lisp-intro/

3. Locate your .emacs file.

  • Note: If this is the first time you customize your Emacs, the .emacs file may not exist! So you need to create one (see the last bullet point in this paragraph).
  • Linux:  Should be in the home directory ~/. Note this is a hidden file, you can see it by typing “ls -a” in the terminal. Alternatively or just run “emacs .emacs”, at home directory, which will open (create if it doesn’t exist) the file “.emacs” using Emacs.
  • Mac: Click terminal, then follow the steps above.
  • Windows 7: Too complicated. Mine was put in “C:/emacs/”. See http://www.claremontmckenna.edu/pages/faculty/alee/emacs/emacs.html.
  • Alternative way of finding .emacs: Open (create) it directly in emacs: Open emacs, type C-x C-f, (the command for finding or creating file), then type  .emacs , hit Enter.

4. Edit the .emacs file.

  • Open your .emacs file. Either use Emacs, or use any other text editor. It doesn’t matter. Add the following line to the end of the file:
  • (add-to-list 'custom-theme-load-path "~/.emacs.d/themes/")
  • Remember to change “~/.emacs.d/themes/” to which ever folder you put the .el theme file. On my Windows 7 the line looks like:
  • (add-to-list ‘custom-theme-load-path “C:/emacs/.emacs.d/themes/”)
  • On my Mac the line looks like
  • (add-to-list ‘custom-theme-load-path “~/.emacs.d/color-theme/”)

5. Save the .emacs file. Restart Emacs.

6. Do Part I: Hit M-x, type load-theme, hit TAB, the new themes should be in the list. If hitting TAB doesn’t bring up a list of themes, just type the name of the theme and hit Enter.

7. Last step. If you want emacs to automatically load the theme, add another line:

  • (load-theme 'zenburn t)

Install Emacs on Windows!

This entire article is copied from:

http://www.claremontmckenna.edu/pages/faculty/alee/emacs/emacs.html

which helped me to install emacs on my Windows 7. I copied it here just in case above site is taken down.

Note: Linux and mac come with emacs.

Installing Emacs on Windows 95/98/2K/NT/ME/XP/Vista/Windows 7

July 3, 2012

Many people have successfully installed emacs on Windows 95, 98, 2K, NT, ME, XP, Vista, and Windows 7 using the instructions below.

Disclaimer: This page is being maintained mainly for my students. Use these instructions at your own risk if you are not a student taking one of my classes. There is no warranty in any form or shape whatsoever! There is no guarantee that these instructions are up-to-date although I will try to update them for my students on an on-going basis. With that understood you may continue with the rest of this page if you choose to accept these terms.

Emacs version 24.1: This was the latest version available at the time of this writing (July 3, 2012).

Follow these steps to download and install Emacs on your windows machine. There is no room for creativity here; you must follow the directions exactly – every single word.!.

    1. Pick the drive and a folder in which you want to install Emacs. I’ll assume that it is C:\emacs, but you can choose a different one. If you choose a different drive or a different folder, you’ll need to adapt the directions below accordingly.
    1. Create an empty folder C:\emacs.
    1. Go here and download the following (or the latest version if you find a newer one) at the bottom of that page into the folder that you created above:
      emacs-24.1-bin-i386.zip    30-Jul-2009 01:10   46M

      At this point, you should have one file named emacs-24.1-bin-i386.zip of about 46 megabytes in the C:\emacs folder. Check to be sure.

    1. Click on that file using Windows Explorer to extract files from that archived file. Your extracted files should go into C:\emacs folder. Once extraction is done, you will see a folder named emacs-24.1 under C:\emacs. Under emacs-24.1, you will see other folders including binetcinfo, etc. At this point, you have downloaded and placed the files in the right places.
    1. Depending on the operating system that you use, choose one of the following paths:
        • 95 or 98: edit your autoexec.bat file and add this line:
          set HOME=C:\emacs\

          You will probably find autoexec.bat on your C: drive. Edit it with Notepad. You can’t edit it by clicking on it. Start Notepad and then open it with the File menu in Notepad.

        • 2KMEXPVista: add HOME as an environment variable. Follow Start > Settings > Control Panel > System. Then select Advanced followed by Environment Variables. Then, add HOME as a user variable with its value C:\emacs\.
      • Windows 7: add HOME as an environment variable. Follow Start > Control Panel > System and Security > System > Advanced system settings. Then selectAdvanced followed by Environment Variables. Then, add HOME as a user variable with its value C:\emacs\. (Note that this may be somewhat site dependent.)
    1. Restart your machine.
    1. Let’s run emacs now. At this point, you might want to create an icon on your desktop for the Emacs that you just installed. Go to the C:\emacs\emacs-24.1\bin folder using Windows Explorer. There you will find a file named runemacs.exe. Create a shortcut, then you will see a file named runemacs.exe - Shortcut. Before you take it to the desktop or to the dock, you might want to change the default ‘Start in’ folder. Change it to whatever you like through the Properties menu of the shortcut file. In my case, I changed it from C:\emacs\emacs-24.1\bin to C:\alee, which is my home folder. Your emacs will use that folder as the base folder when it looks for a file to edit. Now, you are ready to take it to the desktop or the dock so that you can use it to run Emacs from there. Now, you should be in business – run it! If it doesn’t work, you’ve made a mistake in one of the steps above. Double and triple check.
    1. Now you are ready to customize your emacs a little so that it will recognize the syntax of the source file that you will edit, e.g., Java files with the .java extension. Downloadinit.txt to C:\emacs\.emacs.d\init.txt by right-clicking on the link. Yes, there should be a folder named .emacs.d by now since you have run emacs at least once by now. Download init.txt into that folder. Now, rename init.txt to be init.el. (Sorry about this extra step – it is due to the local peculiarity that I don’t want to explain.)
    1. If you want to clean up a little, you may delete emacs-24.1-bin-i386.zip at this point. You still need .emacs.d and emacs-24.1 in the C:\emacs folder though.
    1. To learn how to use Emacs, try Emacs Tutorial that you can find under the Help menu in the Emacs window. Or, if you want a simpler version, try this tutorial that I wrote.
  1. [Only optionally because I want this to be a simple page that shows just enough to get started.] To learn how to customize Emacs or simply to see more help on it, tryEmacs Help Guide by Hemant Kumar. (That site will talk about .emacs file, which is the unix/linux version of init.el.) I am sure there are many other sources of information on emacs out there, e.g., GNU Emacs FAQ For MS Windows, but Paul Fiorillo found this site.

Lattice Notes

My Personal Lattice Notes


Add curves to each panel & Mixed keys

def.col = trellis.par.get()$superpose.symbol$col  # Get default colors.

mykey = list(space = “top”, text = list(c(“Observations:”,”Fixed effect fit:”, “Mixed effect fit:”)), columns = 3,

    lines = list(col = c(def.col[1],”grey60″,”red”), type = c(“p”,”l”,”l”),lty = c(1,2,1), pch = c(1,1,1))) #Point & line in key

xyplot(surface ~ days | patient, data = wd.cur, layout = c(13,1),
main = “Pressure Ulcer Wound Surface Area: Mixed Effect Model vs Fixed Effect Model”,
sub = “surface ~ exp(init + days + (days | patient))”,
xlab = “Time post initial treatment (days)”, ylab = “Surface Area”,
panel = function(x,y,…){
        panel.xyplot(x,y,…) # Prints the real observations
# Define x2, and y2. Omitted here
        panel.grid()
        panel.lines(x2,exp(y2),col = “red”) # These two lines will be added to the graph
        panel.lines(x2,exp(y2.fix),col = “grey60”, lty = 2)
    },
key = mykey,
)


Easy way to change plotting preferences of plots and keys together.

with(wd.cur,
stripplot(surface ~ patient, subset(wd.cur, days %in% c(0,1)), group = obs[,drop = TRUE],
par.settings = simpleTheme(col=c(rep(“red”,3),rep(“blue”,5)),
        pch=c(1:3,1:5), cex=1.2, lwd=1),
auto.key = list(space = “right”),
main = “Initial measurements: Surface”,
xlab = “patients”
)
)

Get Lattice default parameters.

ptcol = trellis.par.get(“superpose.symbol”)$col


Multiple Plots on one page
Method 1

library(lattice)
m <- matrix(c(0.1,0.2,0.3,0.4), 2, 2)
col.l <- colorRampPalette(c(‘blue’, ‘green’))(30)

plot.new()
par(mfrow=c(2,2), oma=c(2,0,2,0))
print(levelplot(m, col.regions=col.l, main=”L1″), split=c(1, 1, 2, 2)) # Check ?print.trellis for “split” argument.
print(levelplot(m, col.regions=col.l, main=”L2″), split=c(1, 2, 2, 2), newpage=FALSE)
print(levelplot(m, col.regions=col.l, main=”L3″), split=c(2, 1, 2, 2), newpage=FALSE)
print(levelplot(m, col.regions=col.l, main=”L4″), split=c(2, 2, 2, 2), newpage=FALSE)
title(“Centered Overall Title”, outer=TRUE)
mtext(side=1, “Centered Subtitle”, outer=TRUE)


Multiple Plots on one page
Method 2

–source: http://stackoverflow.com/questions/13327326/r-image-function-in-r

The Lattice Package often (but not always) ignores the par command, so i just avoid using it when plotting w/ Lattice.

To place multiple lattice plots on a single page:

  • create (but don’t plot) the lattice/trellis plot objects, then
  • call print once for each plot
  • for each print call, pass in arguments for (i) the plot; (ii) more, set to TRUE, and which is only passed in for the initial call to print, and (iii) pos, which gives the position of each plot on the page specified as x-y coordinate pairs for the plot’s lower left-hand corner and upper right-hand corner, respectively–ie, a vector with four numbers.

much easier to show than to tell:

data(AirPassengers)     # a dataset supplied with base R
AP = AirPassengers      # re-bind to save some typing

# split the AP data set into two pieces 
# so that we have unique data for each of the two plots
w1 = window(AP, start=c(1949, 1), end=c(1952, 1))
w2 = window(AP, start=c(1952, 1), end=c(1960, 12))

px1 = xyplot(w1)
px2 = xyplot(w2)

# arrange the two plots vertically
print(px1, position=c(0, .6, 1, 1), more=TRUE)
print(px2, position=c(0, 0, 1, .4))

R notes

My Personal R Cheat Sheet

If someone sees this post. I welcome any suggestions or questions.

Progress Bar:

  • matrix(1:6, nrow  = 2)[c(1,1,2,2,2),] # Repeat first rows twice, second row 3 times.

Progress Bar:

  • total <- 20
    # create progress bar
    pb <- txtProgressBar(min = 0, max = total, style = 3)
    for(i in 1:total){
       Sys.sleep(0.1)
       # update progress bar
       setTxtProgressBar(pb, i)
    }
    close(pb)

Some Random Functions:

  • rm(list=ls())  #Remove everything (function, variables, etc.).
  • example(function) #Run the examples given in the help file of the function.
  • str() #Check complete data type and information, more detailed than is().
  • sapply()# Apply a function over a list or vector.
  • hist2d()#Histogram on 2 variables.
  • scatterplot3d() #3d plots

String:

  • strsplit(): split a string.
  • substr(string,1,1): substring.

Data Type: list

  • names(): Get a string of the names of the list elements
  • vector("list", length = 7): Create a list of length 7

Data Type: dataframe

  • colnames(): Returns strings of column names.
  • myframe[1:3]: Returns the first three columns of data frame “my frame”. Still a data frame. (consider “subset()”)
  • nrow(): Returns number of rows.
  • ncol(): Number of columns.
  • subset(): very useful in selecting certain rows and/or columns of the data frame.

Logic:

  • &: point to point logic and
  • &&: entire vector logic and
  • a %in% b: a is a vector, b is a set. Check EACH entry of a to see if it is in b, yes->TRUE, no->FALSE. Returns a logic vector with the same length of a.

Graphics(basic, see post “lattice” for more):

R opens “devices” for graphs. Default device is on screen. Multiple devices can exist at the same time. Several pages, or several graphs on a same page in one device can be created. A device to create pdf file can be called by:

  • pdf("filename.pdf")

Some graphic functions are “high level” functions, which starts a graph in the current device. “low level” functions modify existing graphs. Graphs can also be modified by arguments in the call of high level functions. A high level function:

  • plot(y,type = "p")

If “y” is a data frame, then scatter plot of all pairs of variables will be plotted. plot treats different variable types differently.

  • curve(function name): plots the graph of the function. For example curve(log).
  • matplot(dataframe): plots individual scatter plots on one graph.

boxplot(colname1 ~ colname2, data = dataframe, col = “light grey”, boxwex = 0.5): plots multiple boxplots of colnames1, according to different values of colnames2. boxwex controls the width of boxes.

Adjusting margins:

#mar is the margin around each individual plot, oma is the
outer margin area around all the plots.
  • par(mfrow=c(2,3), mar=c(5,5,5,3), oma=c(3,3,5,3)) #Bottom,Left, Top, Right.

Add Title to page:
#the “line” value tells how far away from the figures the title should be placed.

  • mtext("All my plots",outer=TRUE,line=1)

Graphic Arguments:

Arguments such as lty = “dashed”  can be set as device parameter using par(), which is persistent in all plots drawn in the current device, or as function argument, which temporarily affects the current plot only (and overwrites the device argument temporarily).

      • colors(): List of all colors

Categorical Data:

      • ftable(3 way table):  prints 3 way contingency table in a better way.
      • structable(3 way table): Same as above

Data Frame:

      • a = data.frame(matrix(NA,nrow = n, ncol = m)): Create empty data frame
      • names(a) = c("dd",...): Change dataframe names
      • Sort data.frame by different columns: 
      • mydata = data.frame(x = 1:10, y = rep(5,10), z = rnorm(10))
      • mydata = mydata[order(data$y,data$x),]#sort the data by y first, then by x.

Visual Progress Bar (so you know when your for LOOP will end…):

total <- 20
# create progress bar
pb <- txtProgressBar(min = 0, max = total, style = 3)
for(i in 1:total){
   # update progress bar
   setTxtProgressBar(pb, i)
   #Add whatever expressions you want to evaluate.
}
close(pb)

Formulas:

as.formula(paste(“y~”,paste(listoffactors,collapse=”+”))) # create dynamic formulas.

An example of  functions: with and par.setting:

wd.cur  is a data frame that have columns surface, patient, days,obs.

with(wd.cur,

stripplot(surface ~ patient,

    subset(wd.cur, days %in% c(0,1)),

    group = obs[,drop = TRUE],

    par.settings = simpleTheme(col=c(rep("red",3),rep("blue",5)),

     pch=c(1:3,1:5), cex=1.2, lwd=1),

    auto.key = list(space = "right"),

    main = "Initial measurements: Surface",

    xlab = "patients"

 )

)

Install Packages from CRAN:

install.packages('RMySQL', repos='http://cran.us.r-project.org')

Time Series

- Date-Time: http://www.stat.berkeley.edu/classes/s133/dates.html
- as.Date set dates