Como enviar correos electronicos desde la linea de comando con ‘sendemail’ en Ubuntu

Hola amigos, estaba buscando una forma de enviar correos electronicos desde la terminal (consola) en Linux (gracias Pipo por la correccion). La razon es que con frecuencia debo enviar el codigo de programas o archivos y es mas conveniente enviarlos directamente desde el terminal.

Este tip tambien serviria para aquellos que tienen un servidor y quieren tener un script que les envie algunos archivos a su correo. En Ubuntu tenemos varias utilidades que nos brindan esta funcion, pero la que es mas ligera se llama sendemail.

La podemos instalar con:

$ sudo apt-get install sendemail

Ahora para utilizarl este comando el formato es:

sendemail -f FROM -t TO -s SERVER -u SUBJECT -m MESSAGE

Por ejemplo para enviar un email con archivo adjunto usando el servidor de Gmail podemos usar:

$ sendemail -f TUUSUARIO@gmail.com -t TUUSUARIO@gmail.com -m “Enviandome un archivo de configuracion de emacs” -s smtp.gmail.com:587 -o tls=yes -xu TUUSUARIO  -u “Una prueba con sendemail…” -a ARCHIVOAENVIAR_CON_RUTA_COMPLETA

Donde dice ‘TUUSUARIO’ pones tu nombre de usuario de Gmail (sin el @gmail.com) Te pedira la contrasenha de Gmail. Si no deseas ponerla puedes anhadir el argumento -xp password, pero no lo aconsejaria por motivos de seguridad.

Espero que les sea util. Saludos.

Habilitar chat de Facebook (XMPP) en Empathy (Ubuntu)

Facebook ha empezado a soportar el protocolo XMPP para chat. XMPP es tambien conocido como Jabber y es el protocolo usado por Google Talk. En Ubuntu podemos tener soporte para chatear en Facebook instalando el paquete “pidgin-facebookchat”.

Sin embargo, la version de este paquete DEB en los repositorios de Karmic ha dejado de trabajar con los servidores de Facebook. Necesitamos descargar el archivo deb más reciente del sitio de Google de Eion Robb (autor de este plugin). El link es: aqui.

Luego de descargarlo lo instalamos con:

$ sudo dpkg -i pidgin-facebookchat-1.65.deb

A continuación, tendrá que eliminar el siguiente archivo:

$ sudo rm /usr/share/telepathy/managers/haze.manager

Ahora vamos a activar el plugin. Vamos a Empathy y agregamos una nueva cuenta. Elegimos tipo de cuenta “Jabber”, luego ponemos como username: username@chat.facebook.com y como password, nuestra contrasena de Facebook. Pulsamos Aceptar. Por alguna razon, Empathy fallara la primera vez. Sin cerrar Empathy borra la cuenta de Facebook que acabas de crear y vuelve a crearla. La segunda vez se conectara sin problemas.

Creo que eso es todo. Algunas personas dicen que es necesario reiniciar Empathy pero esta forma me ha funcionado a mi.

Colocar un fondo de escritorio animado en Ubuntu Karmic y Lucid con Xwinwrap

Quería probar fondo de pantalla de vídeo (como DreamScene en Windows 7). Yo había intentado xwinwrap con Hardy pero en aquel entonces, tuve problemas al ejecutar Compiz en un viejo PC y no se veía bien en todos.Ahora, estoy tratando de que con un ordenador nuevo y Compiz funciona bien en mi Intel GMA 3000 a bordo de un Ubuntu 10.4 Lucid Lynx Alpha.

Si quieres probar esto, debes tener Compiz activado. Tambien necesitas instalar mplayer y los codecs para los vídeos que desea utilizar como fondo de escritorio.

En primer lugar, he descargado Shantz xwinwrap de aqui. Descargalo e instalalo ($sudo dpkg -i paquete.deb). Debes utilizar los archivos deb para su arquitectura correspondiente. Elegí i386 debido a que uso la versión de 32 bits de Lucid (cuestiones de compatibilidad con algunos programas raros que tengo).

Una vez instalado, puedes abrir la terminal e intentar ejecutar el siguiente comando para ver cómo funciona:

xwinwrap -ni -argb -fs -s -st -sp -nf -b -- /usr/lib/xscreensaver/glmatrix -window-id WID

Salir pulsando Ctrl + C en la terminal.

Luego, he intentado con MPlayer. En primer lugar, es posible que desee configurar mplayer para reproducir en bucle por defecto, de lo contrario MPlayer saldra cuando termine la reproducción del vídeo y junto con mplayer, xwinwrap terminara su ejecucion. Para habilitar el modo de repetición en el mplayer por defecto, edita /home/tuusuario/.mplayer/config (archivo de configuración de MPlayer):

Para ello, pulse Alt + F2 y luego escriba
gedit .mplayer/config

Añadir al final:

loop = 0
Grabas y sales.

Después de ello puedes probar lo siguiente en terminal:

xwinwrap -ni -o 0.9 -fs -s -st -sp -b -nf -- mplayer -wid WID -nosound /full/path/to/video.mpg

Observe la opción “-o 0.9″, esta es la opacidad de los fondos de escritorio de video. Si no utilizas la opción de opacidad (es decir, si usar  -o 1,0 o simplemente omites la opción-o), no serás capaz de ver los iconos en el escritorio. Si ha establecido que sea transparente, es posible que desee en blanco del escritorio con un color sólido. De fondo negro funciona bien para la mayoría de los videos, pero te recomiendo que ajustar el color y los valores de opacidad para que se parezca lo suficientemente bueno.

Puedes encontrar videos de wallpaper en Dreamscene.org

Si desea que el escritorio de vídeo que se mantenga al iniciar la sesión siguiente, será necesario a fin de que en el inicio. Puede hacerlo añadiendo el comando que usó en Sistema> Preferencias> Aplicaciones de inicio.

Traducido de: http://www.khattam.info/2010/02/15/howto-video-wallpaper-on-ubuntu-10-04-lucid-lynx/

Que son las variables ‘volatile’ y para que sirven?

Volatile es una palabra clave del C que se puede aplicar solo a algunos tipos de variable (tipicamente enteras y sus derivados) y básicamente es una indicación al compilador para que no guarde el valor de la variable en un registro del micro, sino que fuerza la actualización en memoria. Esto se hace cuando existe la posibilidad de que el valor de la variable sea modificado por otro proceso que se ejecuta concurrentemente con el actual, por ejemplo cuando usas hilos o admitís interrupciones.

Un ejemplo típico es algo como esto:
// Esta suele ser parte de una declaración global

volatile int flag = 0;

// Esto es parte de un proceso

...
while( !flag ) {
// hacer algo mientras el flag sea falso
}
...

// Y esto es parte de una rutina de interrupción y está en una función o metodo diferente del proceso.

...
if( pasa_algo ) {
flag = 1;
}
...

Como veran, la declaración de flag es global para que sea accesible al proceso y a la ISR. Acá tenes que declarar flag como volatile, por que si no, el compilador puede suponer que los accesos y modificaciones a la variableflag son atómicos y por ello, puede guardar el valor de flag en un registro del micro para acelerar la evaluación de la condición del while, perdiendo las modificaciones introducidas por la ISR, si es que ocurrió una mientras estaba en el while. Poniéndola como volatile, forzás al compilador a generar código para recargar siempre de memoria el valor de la variable antes de verificar si es verdadero o falso. Algo parecido sucede para la ISR (Interrupt Service Routine).

Saludos!

Mantener una coleccion ordenada de articulos tecnicos: usando Mendeley en Ubuntu

Mendeley Desktop es una aplicación de escritorio gratuita (y un servicio web?) Destinadas a ayudar a organizar y gestionar su colección de documentos y trabajos de investigación, principalmente dirigidas a investigadores o personas que manejan muchos articulos tecnicos o cientificos.  Mendeley le permite a uno crear una base de datos de bibliografía de los trabajos de investigación y documents. Mendeley está fuertemente integrada con la web ya través de un servicio denominado Mendeley Web le permite subir 500 MB (para una cuenta gratis) de documentos en línea a su cuenta, que le permite acceder libremente desde cualquier lugar.

Mendeley fue fundada en Londres y su equipo de trabajo incluye, ex presidente de “Last.fm”, los ingenieros fundadores de Skype y de las personas de algunas de las mejores universidades del mundo. Mendeley no, aunque es de código abierto, pero está disponible para Windows, Mac OS X y los sistemas operativos Linux.

Si has utilizado Last.fm, que hasta cierto punto ha revolucionado la música de redes sociales (si ese término aún es que existe), lo que le permite encontrar pistas que te pueden gustar basado en sus listas de reproducción, playcount y conectarse con personas con intereses musicales similares . Mendeley se afirma que es “Last.fm” para los investigadores, permitiendo a los investigadores a colaborar con otros investigadores con intereses de investigación similares a la suya. El algoritmo Mendeley sobre la base de su colección de trabajos de extracción de metadatos de los documentos, te permite encontrar personas con intereses similares de investigación y encontrar documentos que usted podría estar interesado pulg (Para la gente puede encontrar este interesante gusta mirar arXiv)proyecto

Para instalar Mendeley escritorio hay que seguir estos pasos:

1. Abrir la ventana de terminal y ejecutar el comando siguiente para agregar los repositorios de Mendeley.

echo “deb http://www.mendeley.com/repositories/xUbuntu_9.04 /” | sudo tee-a / etc / apt / sources.list

y, estamos actualizando la información del repositorio en el sistema local, al expedir el siguiente comando:

sudo apt-get update

Si está ejecutando una versión anterior en caso de Ubuntu, te recomendaría buscar en esta página y encontrar el repositorio de la derecha.

2. Una vez que haya añadido el repositorio, ejecute el comando siguiente para instalar el escritorio mendeley:

sudo apt-get install mendeleydesktop

Una vez que haya terminado la instalación de escritorio Mendeley, puede iniciarse Mendeley (Aplicaciones -> Educación -> Mendeley Desktop).

Mendeley de escritorio incluye un lector de PDF incorporado :D que es excelente, permite resaltar el texto y añadir notas en el documento. Mendeley lee el documento y encuentra todas las referencias, las citas y construye la base de datos bibliográfica de estos en el sistema local. , si lo deseas, puedes añadir notas, y marque sus documentos sobre la base de qué categoría pertenece el documento.

Mendeley Desktop en Ubuntu

Referencia: http://linuxondesktop.blogspot.com/2009/10/organizing-you-documents-and-research.html

Tutorial: Configurar EMACS como editor completo para C/C++, Python y VHDL (incluye configuracion del navegador con ‘w3m’, blogging con ‘weblogger’ y correo con ‘wanderlust’)

Hola amigos, desde hace ya algun tiempo he estado  utilizando EMACS como editor de texto. Las razones que me han motivado es la capacidad de EMACS para reconocer y trabajar con multiples diferentes lenguajes com C/C++, Ruby, CSS, Python, Perl, VHDL, etc. :)

NOTA: Todos los archivos de configuracion (.emacs, el directorio .emacs.d y .Xresources) los estoy adjuntando comprimidos aqui. Sin embargo aun necesitan instalar los paquetes en Ubuntu y ademas necesitan seguir las instrucciones para Rope y Ropemacs. En caso tengas algun problemas con Wanderlust, por favor seguir las instrucciones acerca de Wanderlust (casi al final de este post). Wanderlust se usa si es que deseas poder redactar emails en EMACS.

http://rapidshare.com/files/365454653/emacs.tar.gz.html

1. Instalandolo en Ubuntu

Para instalarlo en Ubuntu Karmic se puede utilizar este comando en terminal:

$ sudo apt-get install emacs23 emacs-goodies-el emacs-goodies-extra-el python-ropemacs python-rope yasnippet cogre cedet-common cedet-contrib doxymacs python-mode w3m w3m-el-snapshot wl-beta pyflakes

2. Los archivos de configuracion de EMACS

EMACS requiere de un archivo de configuracion llamado ‘.emacs’ el cual tiene que ser colocado en el directorio $HOME (en mi caso seria /home/abelardo, pero este directorio sera diferente dependiendo del usuario).

El archivo de .emacs que estoy utilizando es ($gedit ~/.emacs  y luego copias y pegas el contenido de abajo)

;; -*-mode: Emacs-Lisp; outline-minor-mode:t-*-
;; Copyright (C) 1996-2010 Abelardo Jara-Berrocal
;; URL: http://pintucoperu.wordpress.com
;; This file is free software licensed under the terms of the
;; GNU General Public License, version 3 or later.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(add-to-list 'load-path "~/.emacs.d")

;; Server start
;; (server-start) ;; No need if emacs is called as daemon from command line

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Put a nice title to the window, including filename
(add-hook 'window-configuration-change-hook
(lambda ()
(setq frame-title-format
(concat
invocation-name "@" system-name ": "
(replace-regexp-in-string
(concat "/home/" user-login-name) "~"
(or buffer-file-name "%b"))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Emacs print appearance
;; Set paper size
(setq ps-paper-type 'a4)
(defun set-printer-preferences () ; ps-print settings
"Setup print preferences."
(set 'ps-font-size '(10 . 10)) ; body font size
(set 'ps-header-font-size '(6 . 6)) ; don't need big fonts here
(set 'ps-header-title-font-size '(7 . 7)) ; don't need big fonts here
(set 'ps-line-number nil) ; might turn 'em on sometimes
(set 'ps-bottom-margin 55)
(set 'ps-inter-column 35)
(set 'ps-landscape-mode nil)
(set 'ps-left-margin 55)
(set 'ps-line-number t)
(set 'ps-number-of-columns 1)
(set 'ps-print-color-p t)
(set 'ps-right-margin 55)
(set 'ps-top-margin 110)
(set 'ps-bottom-margin 100)
(set 'ps-zebra-stripe-height 5)
(set 'ps-zebra-stripes t)
(set 'ps-print-header t)
(set 'ps-print-header-frame t)
(set 'ps-header-lines 3)
(set 'ps-show-n-of-n t)
(set 'ps-spool-duplex nil) ; only "works" if queue is set to duplex by default
(set 'ps-font-family 'Courier)
(set 'ps-header-font-family 'Helvetica )
(message "Printing preferences are set."))
(set-printer-preferences)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set up Artist-mode
(setq artist-figlet-program "/usr/bin/figlet")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Change form/shape of emacs cursor
;; Change cursor color according to mode; inspired by
;; http://www.emacswiki.org/emacs/ChangingCursorDynamically

(setq djcb-read-only-color "gray")
;; valid values are t, nil, box, hollow, bar, (bar . WIDTH), hbar,
;; (hbar. HEIGHT); see the docs for set-cursor-type

(setq djcb-read-only-cursor-type 'hbar)
(setq djcb-overwrite-color "red")
(setq djcb-overwrite-cursor-type 'box)
(setq djcb-normal-color "yellow")
(setq djcb-normal-cursor-type 'bar)
(defun djcb-set-cursor-according-to-mode ()
"change cursor color and type according to some minor modes."

(cond
(buffer-read-only
(set-cursor-color djcb-read-only-color)
(setq cursor-type djcb-read-only-cursor-type))
(overwrite-mode
(set-cursor-color djcb-overwrite-color)
(setq cursor-type djcb-overwrite-cursor-type))
(t
(set-cursor-color djcb-normal-color)
(setq cursor-type djcb-normal-cursor-type))))

(add-hook 'post-command-hook 'djcb-set-cursor-according-to-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Garantee utf8 as input-method
(setq locale-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-selection-coding-system 'utf-8)
(prefer-coding-system 'utf-8)
(set-language-environment "UTF-8") ; prefer utf-8 for language settings
(set-input-method nil) ; no funky input for normal editing;
(setq read-quoted-char-radix 10) ; use decimal, not octal
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Maximize function
(defun x11-maximize-frame ()
"Maximize the current frame (to full screen)"
(interactive)
(x-send-client-message nil 0 nil "_NET_WM_STATE" 32 '(2 "_NET_WM_STATE_MAXIMIZED_HORZ" 0))
(x-send-client-message nil 0 nil "_NET_WM_STATE" 32 '(2 "_NET_WM_STATE_MAXIMIZED_VERT" 0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Speedbar on same frame
(require 'sr-speedbar)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Zoom in/out like feature, with mouse wheel
(global-set-key '[C-kp-add] 'text-scale-increase)
(global-set-key '[C-kp-subtract] 'text-scale-decrease)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Integrate with Devhelp
(defun devhelp-word-at-point ()
"runs devhelp"
(interactive)
(setq w (current-word))
(start-process-shell-command "devhelp" nil "devhelp" "-s" w))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; uniquify!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'uniquify)
(setq uniquify-buffer-name-style 'reverse)
(setq uniquify-separator "|")
(setq uniquify-after-kill-buffer-p t)
(setq uniquify-ignore-buffers-re "^\\*")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Some general configuration
;; Make it work with globalmenu
(defun menuupdate () (menu-bar-mode -1) (menu-bar-mode 1))
(add-hook 'window-configuration-change-hook 'menuupdate)

;; Assure window is splitted horizontally (for compilation buffer)
(setq split-width-threshold nil)

;; Keep session
(desktop-save-mode 1)

;; Make ?, ? and such work
(set-language-environment 'spanish)
(set-terminal-coding-system 'iso-latin-1)

;; Inhibit startup window, very annoying
(setq inhibit-startup-message t)

;; Take out the toolbar
;; remove toolbar
(tool-bar-mode -1)

;; Makes final line always be a return
(setq require-final-newline t)

;; Avoid to make a separate frame
(setq display-buffer nil)
(setq display-buffer-reuse-frames t)
(setq pop-up-frames nil)

;; Line numbers, vim style
(require 'linum)
(global-linum-mode 1)

;; Put scrollbar on the right
(set-scroll-bar-mode 'right)

;; Disable tooltips
(tooltip-mode nil)

;; deleting files goes to OS's trash folder
(setq delete-by-moving-to-trash t) ; "t" for true, "nil" for false

;; Make copy and paste to work with other programs
(setq x-select-enable-clipboard t)
(setq interprogram-paste-function 'x-cut-buffer-or-selection-value)

;; Activate colors for syntax highlighting
(cond ((fboundp 'global-font-lock-mode)
;; Turn on font-lock in all modes that support it
(global-font-lock-mode t)
;; Maximum colors
(setq font-lock-maximum-decoration t)))

;; Highlight region between the point and the mark
(transient-mark-mode t)

;; To allow to type y instead of "yes"
(fset 'yes-or-no-p 'y-or-n-p)

;; Moving cursor down at bottom scrolls only a single line, not half page
(setq scroll-step 1)
(setq scroll-conservatively 5)

;; Activate highlight in search and replace
(setq search-highlight t)
(setq query-replace-highlight t)

;; we want fontification in all modes
(global-font-lock-mode t t)

;; maximum possible fontification
(setq font-lock-maximum-decoration t)

;; Provide templates for new files
(auto-insert-mode t)

;; show-paren-mode: subtle blinking of matching paren (defaults are ugly)
(when (fboundp 'show-paren-mode)
(show-paren-mode t)
;(setq show-paren-style 'parenthesis)
)

;; put something different in the scratch buffer
(setq initial-scratch-message
";; scratch buffer created -- start typing...\n")

;; Automatically reload files after they've been modified
;; (typically in Visual C++)
(global-auto-revert-mode 1)

;; Bell instead of annoying beep
(setq visible-bell t)

;; Turn off the bell http://www.emacswiki.org/cgi-bin/wiki?AlarmBell
(setq ring-bell-function 'ignore)

;; Do not add empty lines at the end of our file if we press down key
(setq next-line-add-newlines nil)

;; When in text (or related mode) break the lines at 80 chars
(setq fill-column 77)

;; recentf stuff
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(setq recentf-exclude (append recentf-exclude '("/usr*")))
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
(setq bookmark-save-flag 1)

;; In every buffer, the line which contains the cursor will be fully
;; highlighted
(global-hl-line-mode 1)

;; Set indent to 4 instead of 2
(setq standard-indent 4)

;; Use spaces instead of tab
(setq-default indent-tabs-mode nil)

;; Set tab width
(setq default-tab-width 4)

;; Line by line scrolling
(setq scroll-step 1)

;; Mouse wheel scroll support
(mouse-wheel-mode t)

;; Dont make backup files
;;(setq make-backup-files nil) ;disable backup
;;(setq backup-inhibited t)
;;(setq auto-save-list-file-prefix "~/.emacs-saves/.saves-")
;;(setq auto-save-default nil)

;; redefining the make-backup-file-name function in order to get
;; backup files in ~/.backups/ rather than scattered around all over
;; the filesystem. Note that you must have a directory ~/.backups/
;; made. This function looks first to see if that folder exists. If
;; it does not the standard backup copy is made.
(defun make-backup-file-name (file-name)
"Create the non-numeric backup file name for `file-name'."
(require 'dired)
(if (file-exists-p "~/.emacs-backups")
(concat (expand-file-name "~/.emacs-backups/")
(replace-regexp-in-string "/" "!" file-name))
(concat file-name "~")))

;; redefining the make-auto-save-file-name function in order to get
;; autosave files sent to a single directory. Note that this function
;; looks first to determine if you have a ~/.autosaves/ directory. If
;; you do not it proceeds with the standard auto-save procedure.
(defun make-auto-save-file-name ()
"Return file name to use for auto-saves of current buffer.."
(if buffer-file-name
(if (file-exists-p "~/.emacs-saves/")
(concat (expand-file-name "~/.emacs-saves/") "#"
(replace-regexp-in-string "/" "!" buffer-file-name)
"#")
(concat
(file-name-directory buffer-file-name)
"#"
(file-name-nondirectory buffer-file-name)
"#"))
(expand-file-name
(concat "#%" (buffer-name) "#"))))

;; Preserve the owner and group of the file you're editing
(setq backup-by-copying-when-mismatch t)

;; Show line-number in the mode line
(line-number-mode 1)

;; Show column-number in the mode line
(column-number-mode 1)

;; Remember the position where we closed a file
(setq save-place-file "~/.emacs.d/saveplace") ;; keep my ~/ clean
(setq-default save-place t) ;; activate it for all buffers
(require 'saveplace) ;; get the package

;; Ignore case when looking for a file
(setq read-file-name-completion-ignore-case t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Full-screen mode
(defun djcb-full-screen-toggle ()
"toggle full-screen mode"
(interactive)
(shell-command "wmctrl -r :ACTIVE: -btoggle,fullscreen"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Set up Yasnippet
(when (require 'yasnippet-bundle nil 'noerror) ;; note: yasnippet-bundle
(setq yas/root-directory "~/.emacs.d/yas") ;; my own snippets
(yas/initialize)
(yas/load-directory yas/root-directory)
(setq yas/wrap-around-region t)
(setq yas/prompt-functions '(yas/x-prompt yas/ido-prompt))
(yas/global-mode 1) ;; make it global
(add-to-list 'auto-mode-alist '("~/.emacs.d/yas/.*" . snippet-mode)))
(add-hook 'snippet-mode-hook 'yas/minor-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Insertion of Dates, bind to C-c i
(defun insert-date-string ()
"Insert a nicely formated date string."
(interactive)
(insert (format-time-string "%Y-%m-%d")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ultimate smart-tab.... from: http://gist.github.com/215930
;; Change the default hippie-expand order and add yasnippet to the front.
;; by-default, we only try the hippie expand, but we override the function
;; list for specific buffers...
(setq hippie-expand-try-functions-list
'(yas/hippie-try-expand))
;; try-expand-dabbrev
;; try-expand-dabbrev-all-buffers
;; try-expand-dabbrev-from-kill
;; try-complete-file-name
;; try-complete-lisp-symbol))
;;
;; Helps when debugging which try-function expanded
(setq hippie-expand-verbose t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tramp, for remote access
(require 'tramp)
;; we need a bit more funky pattern, as tramp will start $SHELL
;; (sudo -s), ie., zsh for root user
(setq shell-prompt-pattern "^[^a-zA-Z].*[#$%>] *")
(setq tramp-default-method "ssh")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Activate Cua mode, makes shortkeys to behave as windows
(cua-mode t)
(setq cua-keep-region-after-copy t) ;; Standard Windows behaviour
(global-set-key [(control o)] 'find-file) ; use Ctrl-o to open a (new) file
(global-set-key [(control n)] 'find-file-other-frame) ; open a file in a new window with Ctrl-n
(global-set-key [(control s)] 'save-buffer) ; save with Ctrl-s
(global-set-key [(meta s)] 'write-file) ; 'save file as...' with Alt-s ('meta' is
; just another name for the 'Alt' key)
(global-set-key [(control q)] 'save-buffers-kill-emacs); exit XEmacs with Ctrl-q
(global-set-key [(meta q)] 'kill-this-buffer) ; delete changes (don't save) with Alt-q

(global-set-key [(control t)] 'ispell-buffer) ; spell-check with Ctrl-t
(global-set-key [(control r)] 'replace-string) ; search and replace with Ctrl-r

; A first attempt to make "control z" work as undo.
(global-set-key [(control z)] 'undo)

; search forward with Ctrl-f
(global-set-key [(control f)] 'isearch-forward)
(define-key isearch-mode-map [(control f)] (lookup-key isearch-mode-map "\C-s"))
(define-key minibuffer-local-isearch-map [(control f)]
(lookup-key minibuffer-local-isearch-map "\C-s"))

; search backward with Alt-f
(global-set-key [(meta f)] 'isearch-backward)
(define-key isearch-mode-map [(meta f)] (lookup-key isearch-mode-map "\C-r"))
(define-key minibuffer-local-isearch-map [(meta f)]
(lookup-key minibuffer-local-isearch-map "\C-r"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Brackets matching script
(global-set-key "%" 'match-paren)
(defun match-paren (arg)
"Go to the matching paren if on a paren; otherwise insert %."
(interactive "p")
(cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1))
((looking-at "\\s\)") (forward-char 1) (backward-list 1))
(t (self-insert-command (or arg 1)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Abbrevs
; Use C-xaig to correct common typos
(setq abbrev-file-name "~/.emacs.d/abbrev_defs")
(if (file-exists-p abbrev-file-name)
(quietly-read-abbrev-file))

;; Activate template autocompletion
(set-default 'abbrev-mode t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Helper for compilation. Close the compilation window if
;; there was no error at all.
(defun compilation-exit-autoclose (status code msg)
;; If M-x compile exists with a 0
(when (and (eq status 'exit) (zerop code))
;; then bury the *compilation* buffer, so that C-x b doesn't go there
(bury-buffer)
;; and delete the *compilation* window
(delete-window (get-buffer-window (get-buffer "*compilation*"))))
;; Always return the anticipated result of compilation-exit-message-function
(cons msg code))
;; Specify my function (maybe I should have done a lambda function)
(setq compilation-exit-message-function 'compilation-exit-autoclose)

(setq compilation-scroll-output 1) ;; automatically scroll the compilation window
(setq compilation-window-height 7) ;; Set the compilation window height...
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Adjust Emacs size according to resolution
(defun set-frame-size-according-to-resolution ()
(interactive)
(if window-system
(progn
;; use 130 char wide window for largeish displays
;; and smaller 80 column windows for smaller displays
;; pick whatever numbers make sense for you
(if (> (x-display-pixel-width) 1280)
(add-to-list 'default-frame-alist (cons 'width 140))
(add-to-list 'default-frame-alist (cons 'width 80)))
;; for the height, subtract a couple hundred pixels
;; from the screen height (for panels, menubars and
;; whatnot), then divide by the height of a char to
;; get the height we want
(add-to-list 'default-frame-alist
(cons 'height (/ (- (x-display-pixel-height) 150) (frame-char-height)))))))

(set-frame-size-according-to-resolution)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function to show popups
(defun djcb-popup (title msg &optional icon sound)
"Show a popup if we're on X, or echo it otherwise; TITLE is the title
of the message, MSG is the context. Optionally, you can provide an ICON and
a sound to be played"

(interactive)
(when sound (shell-command
(concat "mplayer -really-quiet " sound " 2> /dev/null")))
(if (eq window-system 'x)
(shell-command (concat "notify-send "

(if icon (concat "-i " icon) "")
" '" title "' '" msg "'"))
;; text only version
(message (concat title ": " msg))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Function to delete a line
;; First define a variable which will store the previous column position
(defvar previous-column nil "Save the column position")

;; Define the nuke-line function. The line is killed, then the newline
;; character is deleted. The column which the cursor was positioned at is then
;; restored. Because the kill-line function is used, the contents deleted can
;; be later restored by usibackward-delete-char-untabifyng the yank commands.
(defun nuke-line()
"Kill an entire line, including the trailing newline character"
(interactive)

;; Store the current column position, so it can later be restored for a more
;; natural feel to the deletion
(setq previous-column (current-column))

;; Now move to the end of the current line
(end-of-line)

;; Test the length of the line. If it is 0, there is no need for a
;; kill-line. All that happens in this case is that the new-line character
;; is deleted.
(if (= (current-column) 0)
(delete-char 1)

;; This is the 'else' clause. The current line being deleted is not zero
;; in length. First remove the line by moving to its start and then
;; killing, followed by deletion of the newline character, and then
;; finally restoration of the column position.
(progn
(beginning-of-line)
(kill-line)
(delete-char 1)
(move-to-column previous-column))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Smartab
(defvar smart-tab-using-hippie-expand nil
"turn this on if you want to use hippie-expand completion.")

(defun smart-tab (prefix)
"Needs `transient-mark-mode' to be on. This smart tab is
minibuffer compliant: it acts as usual in the minibuffer.

In all other buffers: if PREFIX is \\[universal-argument], calls
`smart-indent'. Else if point is at the end of a symbol,
expands it. Else calls `smart-indent'."
(interactive "P")
(if (minibufferp)
(minibuffer-complete)
(if (smart-tab-must-expand prefix)
(if smart-tab-using-hippie-expand
(hippie-expand nil)
(dabbrev-expand nil))
(smart-indent))))

(defun smart-indent ()
"Indents region if mark is active, or current line otherwise."
(interactive)
(if mark-active
(indent-region (region-beginning)
(region-end))
(indent-for-tab-command)))

(defun smart-tab-must-expand (&optional prefix)
"If PREFIX is \\[universal-argument], answers no.
Otherwise, analyses point position and answers."
(unless (or (consp prefix)
mark-active)
(looking-at "\\_>")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Running programs in console
(defun djcb-term-start-or-switch (prg &optional use-existing)
"* run program PRG in a terminal buffer. If USE-EXISTING is non-nil "
" and PRG is already running, switch to that buffer instead of starting"
" a new instance."
(interactive)
(let ((bufname (concat "*" prg "*")))
(when (not (and use-existing
(let ((buf (get-buffer bufname)))
(and buf (buffer-name (switch-to-buffer bufname))))))
(ansi-term prg prg))))

(defmacro djcb-program-shortcut (name key &optional use-existing)
"* macro to create a key binding KEY to start some terminal program PRG;
if USE-EXISTING is true, try to switch to an existing buffer"
`(global-set-key ,key
'(lambda()
(interactive)
(djcb-term-start-or-switch ,name ,use-existing))))

;; terminal programs are under Shift + Function Key
(djcb-program-shortcut "bash" (kbd "") t) ; the ubershell
(djcb-program-shortcut "alpine" (kbd "") t) ; mail client
(djcb-program-shortcut "elinks" (kbd "") t) ; http client
(djcb-program-shortcut "mp3blaster" (kbd "") t) ; mp3 music
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; For using SVN
(require 'psvn)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tabbar mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'tabbar)
(tabbar-mode)

(set-face-attribute 'tabbar-button-face
nil :inherit 'tabbar-default-face
:box '(:line-width 3 :color "gray30")
)

(set-face-attribute 'tabbar-default-face
nil :family "Monospace"
:background "gray80" :foreground
"gray30" :height 0.7)

(set-face-attribute 'tabbar-selected-face
nil :inherit 'tabbar-default-face
:foreground "DarkGreen"
:background "LightGoldenrod"
:box '(:line-width 2 :color "DarkGoldenrod")
;;:overline "black" :underline "black"
:weight 'bold)

(set-face-attribute 'tabbar-unselected-face
nil :inherit 'tabbar-default-face
:box '(:line-width 2 :color "gray70"))

(global-set-key [s-left] 'tabbar-backward)
(global-set-key [s-right] 'tabbar-forward)
(global-set-key [s-up] 'tabbar-forward-group)
(global-set-key [s-down] 'tabbar-backward-group)
(global-set-key "\C-c+" 'tabbar-forward)
(global-set-key "\C-c-" 'tabbar-backward)
(global-set-key "\C-c-" 'tabbar-backward)
(global-set-key "\C-c*" 'other-window)

(defun tabbar-buffer-groups (buffer)
"Return the list of group names BUFFER belongs to.
Return only one group for each buffer."
(with-current-buffer (get-buffer buffer)
(cond
((or (get-buffer-process (current-buffer))
(memq major-mode
'(comint-mode compilation-mode)))
'("Misc")
)
((member (buffer-name)
'("*scratch*"))
'("Main")
)
((member (buffer-name)
'("*Pydocs*"))
'("Main")
)
((member (buffer-name)
'("*terminal*"))
'("Main")
)
((member (buffer-name)
'("*Messages*"))
'("Misc")
)
((member (buffer-name)
'("*SPEEDBAR*"))
'("Misc")
)
((eq major-mode 'dired-mode)
'("Main")
)
((memq major-mode
'(fundamental-mode help-mode apropos-mode Info-mode Man-mode))
'("Misc")
)
((memq major-mode
'(tex-mode latex-mode text-mode xml-mode))
'("Main")
)
((memq major-mode
'(rmail-mode
rmail-edit-mode vm-summary-mode vm-mode mail-mode
mh-letter-mode mh-show-mode mh-folder-mode
gnus-summary-mode message-mode gnus-group-mode
gnus-article-mode score-mode gnus-browse-killed-mode))
'("Mail")
)
(t
'("Main")
)
)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Variables & Rebind keys
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Commands to make my programming environment nice
(global-set-key "\C-l" 'goto-line) ; [Ctrl]-[L]

;; Go easily to other windows
(global-set-key (kbd "") 'other-window)

(global-set-key [f1] 'devhelp-word-at-point)
(global-set-key [f5] 'compile)
(global-set-key [f6] 'next-error)
(global-set-key [f11] 'djcb-full-screen-toggle)
(global-set-key [backtab] 'comment-or-uncomment-region) ;; (un)comment

(global-set-key [kp-prior] 'scroll-down) ; [PgUp]
(global-set-key [prior] 'scroll-down) ; [PgUp]
(global-set-key [kp-next] 'scroll-up) ; [PgDn]
(global-set-key [next] 'scroll-up) ; [PgDn]
(global-set-key "\M-g" 'goto-line)

;; home and end - needed for emacs
(global-set-key [home] 'beginning-of-line)
(global-set-key [end] 'end-of-line)

(global-set-key [delete] 'delete-char)
(global-set-key [(meta delete)] '(lambda () (interactive) (backward-or-forward-kill-word -1)))
(global-set-key [(alt delete)] '(lambda () (interactive) (backward-or-forward-kill-word -1)))

(global-set-key [C-prior] 'tabbar-backward)
(global-set-key [C-next] 'tabbar-forward)

(global-set-key [M-prior] 'tabbar-backward-group)
(global-set-key [M-next] 'tabbar-forward-group)

(global-set-key [(control meta prior)] 'tabbar-forward-group)
(global-set-key [(control meta next)] 'tabbar-backward-group)

(global-set-key [M-up] 'enlarge-window)(add-hook 'makefile-mode-hook
(lambda()
(setq show-trailing-whitespace t)))
(global-set-key [M-down] 'shrink-window)

;; to get the scroll wheel work
(global-set-key [(button5)] '(lambda () (interactive) (scroll-up 3)))
(global-set-key [(button4)] '(lambda () (interactive) (scroll-down 3)))
(global-set-key [(shift button5)] '(lambda () (interactive) (scroll-up-command)))
(global-set-key [(shift button4)] '(lambda () (interactive) (scroll-down-command)))
(global-set-key [(control button5)] '(lambda () (interactive) (scroll-up-command)))
(global-set-key [(control button4)] '(lambda () (interactive) (scroll-down-command)))

(global-set-key [(mouse-5)] '(lambda () (interactive) (scroll-up 3)))
(global-set-key [(mouse-4)] '(lambda () (interactive) (scroll-down 3)))
(global-set-key [(shift mouse-5)] '(lambda () (interactive) (scroll-up)))
(global-set-key [(shift mouse-4)] '(lambda () (interactive) (scroll-down)))
(global-set-key [(control mouse-5)] '(lambda () (interactive) (scroll-up)))
(global-set-key [(control mouse-4)] '(lambda () (interactive) (scroll-down)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now we add color themes support
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(setq my-color-themes (list 'color-theme-emacs-21
'color-theme-arjen 'color-theme-bharadwaj-slate
'color-theme-billw 'color-theme-blue-mood
'color-theme-blue-sea 'color-theme-calm-forest
'color-theme-charcoal-black 'color-theme-clarity
'color-theme-classic 'color-theme-comidia
'color-theme-dark-blue 'color-theme-dark-blue2
'color-theme-dark-erc 'color-theme-dark-laptop
'color-theme-deep-blue 'color-theme-digital-ofs1
'color-theme-emacs-nw 'color-theme-euphoria
'color-theme-feng-shui 'color-theme-fischmeister
'color-theme-gnome 'color-theme-gnome2
'color-theme-goldenrod 'color-theme-gray1
'color-theme-gray30 'color-theme-greiner
'color-theme-hober 'color-theme-infodoc
'color-theme-lawrence 'color-theme-ld-dark
'color-theme-montz 'color-theme-oswald
'color-theme-pok-wob 'color-theme-tty-dark
'color-theme-xp))

;;; Color theme based on Tango Palette. Created by danranx@gmail.com
;;; http://www.emacswiki.org/cgi-bin/emacs/color-theme-tango.el
(defun color-theme-tango ()
"A color theme based on Tango Palette."
(interactive)
(color-theme-install
'(color-theme-tango
((background-color . "#252525")
(background-mode . dark)
(border-color . "#888a85")
(cursor-color . "#fce94f")
(foreground-color . "#eeeeec")
(mouse-color . "#8ae234"))
((help-highlight-face . underline)
(ibuffer-dired-buffer-face . font-lock-function-name-face)
(ibuffer-help-buffer-face . font-lock-comment-face)
(ibuffer-hidden-buffer-face . font-lock-warning-face)
(ibuffer-occur-match-face . font-lock-warning-face)
(ibuffer-read-only-buffer-face . font-lock-type-face)
(ibuffer-special-buffer-face . font-lock-keyword-face)
(ibuffer-title-face . font-lock-type-face))
(border ((t (:background "#888a85"))))
(fringe ((t (:background "grey10"))))
(mode-line ((t (:foreground "#eeeeec" :background "#555753"))))
(region ((t (:background "#555753"))))
(font-lock-builtin-face ((t (:foreground "#729fcf"))))
(font-lock-comment-face ((t (:foreground "#888a85"))))
(font-lock-constant-face ((t (:foreground "#8ae234"))))
(font-lock-doc-face ((t (:foreground "#888a85"))))
(font-lock-keyword-face ((t (:foreground "#729fcf" :bold t))))
;; remove italic from strings
(font-lock-string-face ((t (:foreground "#ad7fa8"))))
(font-lock-type-face ((t (:foreground "#8ae234" :bold t))))
(font-lock-variable-name-face ((t (:foreground "#eeeeec"))))
(font-lock-warning-face ((t (:bold t :foreground "#f57900"))))
(font-lock-function-name-face ((t (:foreground "#edd400" :bold t :italic t))))
;; ECB - matt added
;; see - http://ecb.sourceforge.net/docs/ecb-faces.html
(ecb-default-highlight-face((t (:background "#75507b"))))
;; end ecb
(comint-highlight-input ((t (:italic t :bold t))))
(comint-highlight-prompt ((t (:foreground "#8ae234"))))
(isearch ((t (:background "#f57900" :foreground "#2e3436"))))
(isearch-lazy-highlight-face ((t (:foreground "#2e3436" :background "#e9b96e"))))
(show-paren-match-face ((t (:foreground "#2e3436" :background "#73d216"))))
(show-paren-mismatch-face ((t (:background "#ad7fa8" :foreground "#2e3436"))))
(minibuffer-prompt ((t (:foreground "#729fcf" :bold t))))
(info-xref ((t (:foreground "#729fcf"))))
(info-xref-visited ((t (:foreground "#ad7fa8"))))

)))

;; Default start if no server
(when window-system
(require 'color-theme)
(color-theme-tango)
)

(set-face-foreground 'default "#ffffff")
(set-face-background 'hl-line "#3f3f3f")
(set-face-background 'region "#444444")
(set-face-foreground 'modeline "#002222")
(set-face-background 'modeline "#aaffaa")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Edition of EMACS edition modes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; make text-mode default
;;; Text mode and Auto Fill mode
;; The next three lines put Emacs into Text mode
;; and Auto Fill mode, and are for writers who
;; want to start writing prose rather than code.

(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'text-mode-hook-identify)
(add-hook 'text-mode-hook 'turn-on-auto-fill)

(add-hook 'text-mode-hook (function
(lambda ()(ispell-minor-mode))))

;; Enter changes lines and auto-indents the new line
(add-hook 'c-mode-hook
'(lambda ()
(define-key c-mode-map "\C-m" 'newline-and-indent)))

(add-hook 'c++-mode-hook
'(lambda ()
(define-key c++-mode-map "\C-m" 'newline-and-indent)))

(add-hook 'vhdl-mode-hook
'(lambda ()
(define-key vhdl-mode-map "\C-m" 'newline-and-indent)))

(add-hook 'c++-mode-hook 'turn-on-auto-fill)
(add-hook 'c-mode-hook 'turn-on-auto-fill)
(add-hook 'vhdl-mode 'turn-on-auto-fill)
(add-hook 'python-mode 'turn-on-auto-fill)

;;make a #define be left-aligned
(setq c-electric-pound-behavior (quote (alignleft)))

;; Establece el indexado para el modo .c
;; indexado 0 al abrir una llave
(c-set-offset 'substatement-open 0)

;; Beautify (poner bonito) tabulaciones en nuestro pograma en C/C++
(defun beautify-region (beg end)
(interactive "r")
(setq end (save-excursion (goto-char end) (point-marker)))
(indent-region beg end nil))
(defun beautify-buffer ()
"Beautify buffer by applying indentation, whitespace fixup, alignment, and
case fixing to entire buffer. Calls `vhdl-beautify-region' for the entire
buffer."
(interactive)
(beautify-region (point-min) (point-max))
(when noninteractive (save-buffer)))

(global-unset-key "\C-b")
(global-set-key "\C-b" 'beautify-buffer)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; EMACS for VHDL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defvar vhdl-compiler-options "-work work")

(autoload 'vhdl-mode "vhdl-mode" "VHDL Editing Mode" t);
(setq auto-mode-alist (append '(("\\.vhd$" . vhdl-mode)) auto-mode-alist))
(setq auto-mode-alist (append '(("\\.vhdl$" . vhdl-mode)) auto-mode-alist))

(add-hook 'vhdl-mode-hook
'(lambda ()
;;vhdl-electric enables templates
(setq vhdl-electric-mode t)
(setq vhdl-compiler 'v-system)
(setq vhdl-stutter-mode t)
(setq vhdl-intelligent-tab t)
(setq vhdl-indent-tabs-mode nil)
(setq-default vhdl-end-comment-column 120)
(setq-default vhdl-standard '(93 nil))
(setq vhdl-standard '(93 nil))
(setq-default vhdl-underscore-is-part-of-word t)
(setq vhdl-self-insert-comments nil)
(setq vhdl-actual-port-name '("\"\\(.*\\)$\"" . "s\\1"))
(setq vhdl-argument-list-indent nil)
(setq vhdl-insert-empty-lines 'none)
(setq vhdl-instance-name '(".*" . "\\&_inst_%d"))
))

;; Turn on VHDL automatic templates
(add-hook 'vhdl-mode-hook (function (lambda () (abbrev-mode t))))

(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(case-fold-search t)
'(inverse-video t)
'(safe-local-variable-values (quote ((outline-minor-mode . t))))
'(semantic-idle-scheduler-work-idle-time 3)
'(semantic-self-insert-show-completion-function (lambda nil (semantic-ia-complete-symbol-menu (point))))
'(standard-indent 4)
'(vhdl-argument-list-indent t)
'(vhdl-basic-offset 4)
'(vhdl-clock-edge-condition (quote function))
'(vhdl-clock-name "clk")
'(vhdl-company-name "CHREC UF")
'(vhdl-copyright-string "-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor
-- Boston, MA 02110-1301, USA.
--
-- You can dowload a copy of the GNU General Public License here:
-- http://www.gnu.org/licenses/gpl.txt
--
-- Copyright (c) Abelardo Jara-Berrocal
")
'(vhdl-file-header "-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Title :
-- Project :
-------------------------------------------------------------------------------
-- File :
-- Author :
-- Company :
-- Created :
-- Last update:
-- Platform :
-- Standard :
-------------------------------------------------------------------------------
-- Description:
-------------------------------------------------------------------------------
-- Revisions :
-- Date Version Author Description
-- 1.0 Created
-------------------------------------------------------------------------------

")
'(vhdl-file-name-case (quote downcase))
'(vhdl-highlight-case-sensitive t)
'(vhdl-highlight-special-words t)
'(vhdl-index-menu t)
'(vhdl-optional-labels (quote none))
'(vhdl-platform-spec "Xilinx ISE")
'(vhdl-reset-name "rst")
'(vhdl-standard (quote (93 nil)))
'(vhdl-testbench-declarations " -- constants declaration
constant clock_period : time := 20 ns; --! clock period
constant reset_after : time := 100 ns; --! length of reset pulse
constant simulation_time : time := 1 ms; --! when the simulation stops with standard \"OK\" assertion
")
'(vhdl-testbench-include-configuration nil)
'(vhdl-testbench-initialize-signals t)
'(vhdl-testbench-statements " -- clock generation
clock: process
BEGIN
clk <= '0';
wait for clock_period/2;
clk <= '1';
wait for clock_period/2;
end process;(add-hook 'makefile-mode-hook
(lambda()
(setq show-trailing-whitespace t)))

rst <= '1' after reset_after;

-- stimulus generation
tb : PROCESS
BEGIN
-- Place stimulus here
rst <= '0';
wait until clk'event and clk = '1';
rst <= '1';
wait until clk'event and clk = '1';
wait for simulation_time;
assert false report \"NONE. End of simulation.\" severity failure;
end process;")
'(vhdl-upper-case-constants t)
'(vhdl-use-direct-instantiation (quote never))
'(weblogger-config-alist (quote (("default" "http://pintucoperu.wordpress.com/xmlrpc.php" "pintucoperu" "" "1902721")))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; CEDET AND SEMANTIC PLUGINS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'cedet)
(global-ede-mode 1)

;; smart completion - disabled
(require 'semantic-ia) ;; nil t

;; additional options
(require 'semantic-sb)
(require 'semanticdb)

;; * This turns on which-func support (Plus all other code helpers), remove if not X server
;; (semantic-load-enable-minimum-features)
;;(semantic-load-enable-code-helpers) ;; It is nice but i really dislike completion splitting window in 2
(semantic-load-enable-excessive-code-helpers)
;; (semantic-load-enable-gaudy-code-helpers)
(setq senator-minor-mode-name "SN")

;; Be careful to add lines for semantic-idle because weird tooltip box appears again :(
(global-semantic-idle-summary-mode 1) ;Display a tag summary of the lexical token under the cursor.
(global-semantic-show-unmatched-syntax-mode 1)

;; Add menu to navigate faster between tokens
(add-hook 'semantic-init-hooks (lambda ()
(imenu-add-to-menubar "TAGS")))

;; Enable semantic cache, search functions only first time
(global-semanticdb-minor-mode 1)

(defun semanticdb-cache-directory-p(directory)
(cond
((search "/ArraySaver/" directory) nil)
((search "@@" directory) t)
(t nil)))

(add-hook 'semanticdb-project-predicate-functions 'semanticdb-cache-directory-p)

(setq semanticdb-default-save-directory "~/.emacs.d/semantic")

;; customisation of modes
(define-key function-key-map [S-tab] [backtab])
(defun my-cedet-hook ()
(local-set-key (kbd "") 'semantic-ia-complete-symbol-menu)
(local-set-key (kbd "\C-c/") 'semantic-ia-complete-symbol)
(local-set-key (kbd "") 'smart-tab)
)

(add-hook 'c-mode-hook '(lambda ()
(local-set-key [s-tab] 'tempo-complete-tag)))
(add-hook 'c++-mode-hook '(lambda ()
(local-set-key [s-tab] 'tempo-complete-tag)))

(add-hook 'c-mode-common-hook 'my-cedet-hook)
(add-hook 'c++-mode-common-hook 'my-cedet-hook)
(add-hook 'python-mode-hook 'my-cedet-hook)

(setq-mode-local c-mode semanticdb-find-default-throttle
'(project unloaded system recursive))
(setq-mode-local c++-mode semanticdb-find-default-throttle
'(project unloaded system recursive))
(setq-mode-local python-mode semanticdb-find-default-throttle
'(project unloaded system recursive))

(semantic-add-system-include "/usr/include" 'c-mode)
(semantic-add-system-include "/usr/include" 'c++-mode)
(semantic-add-system-include "/usr/include/c++/4.4" 'c++-mode)
(semantic-add-system-include "/usr/local/include" 'c-mode)
(semantic-add-system-include "/usr/local/include" 'c++-mode)
(semantic-add-system-include "." 'c-mode)
(semantic-add-system-include "." 'c++-mode)

(setq semantic-python-dependency-system-include-path
'("/usr/lib/python2.6/"))
(setq semantic-c-dependency-system-include-path (quote ("/usr/include/gtk-2.0" "/usr/include/glib-2.0" "/usr/include/DeviceKit-power" "/usr/include/QtGui" "/usr/include/Qt" " /usr/include/QtCore" "/usr/include" "/usr/local/include")))
(setq semantic-c++-dependency-system-include-path (quote ("/usr/include/gtk-2.0" "/usr/include/glib-2.0" "/usr/include/DeviceKit-power" "/usr/include/QtGui" "/usr/include/Qt" " /usr/include/QtCore" "/usr/include" "/usr/local/include" "/usr/include/c++/4.4")))

;; Now define what it is displayed after some idle-time
(eval-after-load "semantic-complete" '(setq
semantic-complete-inline-analyzer-displayor-class
semantic-displayor-ghost))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; EMACS for C/C++ modes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Support for many functions from the C Standar libs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(font-lock-add-keywords 'c-mode
'(
;; stdio.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; math.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; ctype.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; string.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; stdlib.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; asert.h
("\\" . font-lock-keyword-face)
;; stdarg.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; setjmp.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; signal.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; time.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; unistd.h
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; gettext
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
("\\" . font-lock-keyword-face)
;; Glib
("\\" . font-lock-keyword-face)
;; GTK
("\\". font-lock-keyword-face)
;; GDK
("\\". font-lock-keyword-face)
;; Glade
("\\". font-lock-keyword-face)
;; Paranoia
("\\". font-lock-keyword-face)
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Definying C coding style
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defconst my-c-style
'((c-tab-always-indent . t)
(c-comment-only-line-offset . 0)
(c-hanging-braces-alist . ((substatement-open after)
(brace-list-open)))
(c-hanging-colons-alist . ((member-init-intro before)
(inher-intro)
(case-label after)
(label after)
(access-label after)))
(c-cleanup-list . (scope-operator
empty-defun-braces
defun-close-semi))
(c-offsets-alist . ((arglist-close . c-lineup-arglist)
(substatement-open . 0)
(case-label . 4)
(block-open . 0)
(defun-block-intro . 0)
(statement-block-intro . 4)
(substatement . 4)
(knr-argdecl-intro . -)))
(c-echo-syntactic-information-p . t)
)
"My C Programming Style")

;; Customizations for all of c-mode, c++-mode, and objc-mode
(defun my-c-mode-common-hook ()
;; add my personal style and set it for the current buffer
(c-add-style "PERSONAL" my-c-style t)
;; offset customizations not in my-c-style
(c-set-offset 'defun-block-intro' +)
;; other customizations
(setq tab-width 4
;; this will make sure spaces are used instead of tabs
indent-tabs-mode nil)
;; we like auto-newline and hungry-delete
(c-toggle-auto-hungry-state 1)
;; keybindings for all supported languages. We can put these in
;; c-mode-base-map because c-mode-map, c++-mode-map, objc-mode-map,
;; java-mode-map, and idl-mode-map inherit from it.
(define-key c-mode-base-map "\C-m" 'newline-and-indent)
)

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

;; This is a way to hook tempo into cc-mode
(defvar c-tempo-tags nil
"Tempo tags for C mode")
(defvar c++-tempo-tags nil
"Tempo tags for C++ mode")

;; C-Mode Templates and C++-Mode Templates (uses C-Mode Templates also)
(require 'tempo)
(setq tempo-interactive t)

(add-hook 'c-mode-hook '(lambda ()
(tempo-use-tag-list 'c-tempo-tags)
))
(add-hook 'c++-mode-hook '(lambda ()
(tempo-use-tag-list 'c-tempo-tags)
(tempo-use-tag-list 'c++-tempo-tags)
))

;; Preprocessor Templates (appended to c-tempo-tags)

(tempo-define-template "c-include"
'("include " > n
)
"include"
"Insert a #include statement"
'c-tempo-tags)

(tempo-define-template "c-ifdef"
'("ifdef " (p "ifdef-clause: " clause) > n> p n
"#else /* !(" (s clause) ") */" n> p n
"#endif /* " (s clause)" */" n>
)
"ifdef"
"Insert a #ifdef #else #endif statement"
'c-tempo-tags)

(tempo-define-template "c-ifndef"
'("ifndef " (p "ifndef-clause: " clause) > n
"#define " (s clause) n> p n
"#endif /* " (s clause)" */" n>
)
"ifndef"
"Insert a #ifndef #define #endif statement"
'c-tempo-tags)

;; C-Mode Templates
(tempo-define-template "c-if"
'(> "if (" (p "if-clause: " clause) ")" n>
"{" > n>
> r n
"}" > n>
)
"if"
"Insert a C if statement"
'c-tempo-tags)

(tempo-define-template "c-else"
'(> "else" n>
"{" > n>
> r n
"}" > n>
)
"else"
"Insert a C else statement"
'c-tempo-tags)

(tempo-define-template "c-if-else"
'(> "if (" (p "if-clause: " clause) ")" n>
"{" > n
> r n
"}" > n
"else" > n
"{" > n>
> r n
"}" > n>
)
"ifelse"
"Insert a C if else statement"
'c-tempo-tags)

(tempo-define-template "c-while"
'(> "while (" (p "while-clause: " clause) ")" > n>
"{" > n
> r n
"}" > n>
)
"while"
"Insert a C while statement"
'c-tempo-tags)

(tempo-define-template "c-for"
'(> "for (" (p "for-clause: " clause) ")" > n>
"{" > n
> r n
"}" > n>
)
"for"
"Insert a C for statement"
'c-tempo-tags)

(tempo-define-template "c-for-i"
'(> "for (" (p "variable: " var) " = 0; " (s var)
" n>
"{" > n
> r n
"}" > n>
)
"fori"
"Insert a C for loop: for(x = 0; x "int main(int argc, char *argv[])" > n>
"{" > n>
> r n
> "return 0 ;" n>
> "}" > n>
)
"main"
"Insert a C main statement"
'c-tempo-tags)

(tempo-define-template "c-if-malloc"
'(> (p "variable: " var) " = ("
(p "type: " type) " *) malloc (sizeof(" (s type)
") * " (p "nitems: " nitems) ") ;" n>
> "if (" (s var) " == NULL)" n>
> "error_exit (\"" (buffer-name) ": " r ": Failed to malloc() " (s var) " \") ;" n>
)
"ifmalloc"
"Insert a C if (malloc...) statement"
'c-tempo-tags)

(tempo-define-template "c-if-calloc"
'(> (p "variable: " var) " = ("
(p "type: " type) " *) calloc (sizeof(" (s type)
"), " (p "nitems: " nitems) ") ;" n>
> "if (" (s var) " == NULL)" n>
> "error_exit (\"" (buffer-name) ": " r ": Failed to calloc() " (s var) " \") ;" n>
)
"ifcalloc"
"Insert a C if (calloc...) statement"
'c-tempo-tags)

(tempo-define-template "c-switch"
'(> "switch (" (p "switch-condition: " clause) ")" n>
"{" > n>
"case " (p "first value: ") ":" > n> p n
"break;" > n> p n
"default:" > n> p n
"break;" > n
"}" > n>
)
"switch"
"Insert a C switch statement"
'c-tempo-tags)

(tempo-define-template "c-case"
'(n "case " (p "value: ") ":" > n> p n
"break;" > n> p
)
"case"
"Insert a C case statement"
'c-tempo-tags)

;; C++-Mode Templates
(tempo-define-template "c++-class"
'("class " (p "classname: " class) p n "{" n "public:" n>

(s class) "();"
(indent-for-comment) "the default constructor" n>

(s class)
"(const " (s class) "&rhs);"
(indent-for-comment) "the copy constructor" n>

(s class)
"& operator=(const " (s class) "&rhs);"
(indent-for-comment) "the assignment operator" n>

n> "// the default address-of operators" n>
"// "(s class)
"* operator&() { return this; };" n>
"// const "(s class)
"* operator&() const { return this; };" n

n > "~" (s class) "();"
(indent-for-comment) "the destructor" n n>
p n
"protected:" n> p n
"private:" n> p n
"};\t// end of class " (s class) n>
)
"class"
"Insert a class skeleton"
'c++-tempo-tags)

(defun latex-letter-skeleton (receivers-address)
"Inserts a LaTeX letter skeleton into current buffer. This
only makes sense for empty buffers."
(interactive "MReceiver's Address? ")
(skeleton-insert
'(nil ;no prompt
"\\documentclass[12pt]{letter}\n"
"\\usepackage[margin=1in]{geometry}\n"
"\\usepackage{pdfsync}\n"
"% Some of the article customisations are relevant for this class\n"
"\n"
"\\name{S.Natsagdorj} % return address on the envelope\n"
"\\signature{S. Natsagdorj} % Goes after the closing\n"
"\\address{Address}\n"
"\n"
"%\\makelabels % this command prints envelope labels on the final\n"
" % page of the document\n"
"\n"
"\\begin{document}\n"
"\\begin{letter}{"receivers-address"}\n"
"\n"
"\\opening{" _ "} % eg Hello.\n"
"\n"
"\n"
"\n"
"\\closing{} % eg Regards,\n"
"\n"
"%\\cc{} % people this letter is cc-ed to\n"
"%\\encl{} % list of anything enclosed\n"
"%\\ps{} % any post scriptums.\n"
"\n"
"\\end{letter}\n"
"\\end{document}\n")))

(define-skeleton latex-simple-text-skeleton
"inserts a simple blank page skeleton."
nil
"\\documentclass{article}\n"
"\\usepackage{geometry}\n"
"\\geometry{margin=1in}\n"
"\\usepackage{graphicx}\n"
"\\usepackage{pdfsync}\n"
"\\usepackage{amssymb, amsmath, latexsym}\n"
"\\setlength{\\parskip}{2.3ex} % vertical space between paragraphs\n"
"\\setlength{\\parindent}{0in} % amount of indentation of paragraph\n"
"%this package allows for hyperlinks within the pdf document\n"
"\\usepackage[colorlinks=true, linkcolor=blue,pdfstartview=FitV,\n"
"citecolor=gray40, urlcolor=blue]{hyperref}\n"
"\n"
"\\begin{document}\n"
"\\thispagestyle{empty}\n"
"\\begin{center}\n"
" \\large{\\textbf{Title}}\n"
"\\end{center}\n"
"\n"
"An example of a\n"
"\\href{http://www.math.umd.edu/research/spotlight}{hyperlink} is\n"
"given here.\n"
_"\n"
"\\end{document}\n")

(define-skeleton latex-foils-skeleton
"Inserts a template for foiltex slides."
nil
"\\documentclass{foils}\n"
"\\usepackage{amssymb, amsmath}\n"
"\\usepackage{graphicx}\n"
"\\usepackage[mathscr]{eucal}\n"
"\\usepackage{pb-diagram}\n"
"\\usepackage{pdfsync}\n"
"\\usepackage{color}\n"
"\\pagenumbering{arabic}\n"
"\n"
"\\title{"_"}\n"
"\\author{S.Natsagdorj}\n"
"\\date{\\today}\n"
"\n"
"\\MyLogo{-- Short Talk Title --}\n"
"%\\Restriction{}\n"
"%\\leftfooter{} \n"
"%\\rightfooter{}\n"
"%\\leftheader{S.Natsagdorj}\n"
"%\\rightheader{\\foiltexdate}\n"
"\n"
"\\begin{document}\n"
"\\maketitle\n"
"\\foilhead{} %References\n"
"\\nocite{chorin2002}\n"
"\\nocite{zwanzig:1960}\n"
"\\nocite{zwanziskeletong:1961}\n"
"\n"
"\\bibliographystyle{amsplain}\n"
"\\bibliography{research}\n"
"\\foilhead{Overview}\n"
"\\begin{itemize}\n"
"\\item \n"
"\\end{itemize}\n"
"\n"
"\\rotatefoilhead{} %landscape slide\n"
"\n"
"\\rotatefoilhead[-1in]{} %landscape with adjustment\n"
"\n"
"\\begin{center}\n"
" \\Large{The End.}\n"
"\\end{center}\n"
"\\end{document}\n")

(define-skeleton latex-AMS-article-skeleton
"Inserts a AMS LaTeX skeleton for an article."
nil
"\\documentclass[10pt]{amsart}\n"
"\\usepackage{amssymb,latexsym}\n"
"\\usepackage{graphicx}\n"
"\\usepackage{pdfsync}\n"
"\\usepackage[mathscr]{eucal}\n"
"\\thispagestyle{empty}\n"
"\n"
"%%% PAGE DIMENSIONS\n"
"\\usepackage{geometry} % to change the page dimensions\n"
"\\geometry{margin=0.75in} % for example, change the margins to 2 inches all round\n"
"%\\geometry{landscape} % set up the page for landscape\n"
"% read geometry.pdf for detailed page layout information\n"
"\n"
"\\newtheorem{theorem}{Theorem}\n"
"\\newtheorem{corollary}[theorem]{Corollary}\n"
"\\newtheorem{definition}{Definition}\n"
"\\newtheorem{lemma}{Lemma}\n"
"\\theoremstyle{remark}\n"
"\\newtheorem{remark}{Remark}\n"
"\n"
"\\begin{document}\n"
"\\title[short-title]{long title}\n"
"\\author{A. Jara}\n"
"\\address{College of Engineering\\\\\n"
" University of Florida\\\\\n"
" Gainesville, FL 32603}\n"
"\\email{halbert@math.umd.edu}\n"
"\\urladdr{http://www.math.umd.edu/$\\sim$halbert}\n"
"\\thanks{This work was done ...}\n"
"\\date{\\today}\n"
"\\begin{abstract}\n"
> _ \n
"\\end{abstract}\n"
"\\maketitle\n"
"\n"
"\n"
"\\bibliographystyle{amsplain}\n"
"\\bibliography{bib-database}\n"
"\\end{document}\n")

(define-skeleton latex-brief-article-skeleton
"Inserts a LaTeX skeleton for a brief article."
"Title: "
"\\documentclass[11pt]{article}\n"
"\\usepackage{geometry} % See geometry.pdf to learn the\n"
" % layout options. There are lots.\n"
"\\geometry{letterpaper} \n"
"% \\geometry{landscape} % Activate for for rotated page geometry\n"
"% \\usepackage[parfill]{parskip} % Activate to begin paragraphs with an\n"
" % empty line rather than an indent\n"
"\\usepackage{graphicx}\n"
"\\usepackage{amssymb}\n"
"\\usepackage{epstopdf}\n"
"\\usepackage{pdfsync}\n"
"\n"
"\\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}\n"
"\n"
"\\title{"str | "Brief Article""}\n"
"\\author{S.Natsagdorj}\n"
"% \\date{} % Activate to display a given date or no date\n"
"\n"
"\\begin{document}\n"
"\\maketitle\n"
"%\\section{}\n"
"%\\subsection{}\n"
"\n"
> _ "\n"
"\n"
"\\end{document}\n")

;; Set up skeletons (see below) in a menu in AUCTeX mode
(add-hook 'LaTeX-mode-hook
(lambda ()
(easy-menu-add-item LaTeX-mode-menu
nil ["Skeletons" nil t])
(easy-menu-add-item LaTeX-mode-menu '("Skeletons")
["Letter" latex-letter-skeleton
t])
(easy-menu-add-item LaTeX-mode-menu '("Skeletons")
["Brief Article"
latex-brief-article-skeleton t])
(easy-menu-add-item LaTeX-mode-menu '("Skeletons")
["AMS Article"
latex-AMS-article-skeleton t])
(easy-menu-add-item LaTeX-mode-menu '("Skeletons")
["Foils" latex-foils-skeleton t])
(easy-menu-add-item LaTeX-mode-menu '("Skeletons")
["Simple"
latex-simple-text-skeleton t])))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; EMACS for LaTeX
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(load "auctex.el" nil t t)
(load "preview-latex.el" nil t t)

(setq auto-mode-alist (cons '("\\.tex$" . latex-mode) auto-mode-alist))

(setq tex-mode-hook
'(lambda ()
(auto-fill-mode 1)
))

(setq latex-mode-hook
'(lambda ()
(auto-fill-mode 1)
))

;; Configuration to use Auctex
(autoload 'reftex-mode "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" t)
(autoload 'LaTeX-preview-setup "preview")
(autoload 'reftex-mode "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" nil)

;(load "tex-site")
(add-hook 'LaTeX-mode-hook 'LaTeX-preview-setup)
(add-hook 'LaTeX-mode-hook 'whizztex-mode t)
(add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
(add-hook 'LaTeX-mode-hook 'LaTeX-math-mode)
(add-hook 'LaTeX-mode-hook global-hl-line-mode nil) ; do not highlight lines in LaTeX

(setq reftex-enable-partial-scans t)
(setq reftex-save-parse-info t)
(setq reftex-use-multiple-selection-buffers t)
(setq reftex-plug-into-AUCTeX t)
(setq bib-cite-use-reftex-view-crossref t)
;(setq LaTeX-mode-hook 'allman-latex-hook)
(setq TeX-source-specials-mode t)

;; spellcheck in LaTex mode
(add-hook `latex-mode-hook `flyspell-mode)
(add-hook `tex-mode-hook `flyspell-mode)
(add-hook `bibtex-mode-hook `flyspell-mode)
(add-hook 'TeX-mode-hook 'turn-on-auto-fill)
(add-hook 'LaTeX-mode-hook 'auto-fill-mode)

(add-hook 'latex-mode-hook '(lambda ()
(define-key latex-mode-map "\C-m" 'newline-and-indent)))

(add-hook 'LaTeX-mode-hook
(lambda()
(setq LaTeX-indent-level 2)
(setq LaTeX-item-indent 2)
(setq TeX-auto-save t)
(setq LaTeX-command-style
(quote (("\\`fontspec\\'" "xelatex ")
("" "%(PDF)%(latex) %S%(PDFout)"))))
(custom-set-variables
'(preview-fast-dvips-command "pdftops -origpagesizes %s.pdf %m/preview.ps"))
(setq TeX-save-query nil)
(setq TeX-parse-self t)
(setq-default TeX-master nil)
(setq TeX-output-view-style
(cons '("^pdf$" "." "evince %o ") TeX-output-view-style))
(set-default 'preview-default-document-pt 12)
(set-default 'preview-scale-function 1.2)
(setq preview-required-option-list
(quote ("active" "tightpage" "auctex" "pdftex" (preview-preserve-counters "counters"))))
(setq preview-default-option-list
(quote ("displaymath" "floats" "graphics" "textmath" "showlabels" "sections" )))
(TeX-global-PDF-mode t)
))

(add-hook
'LaTeX-mode-hook
(lambda ()

(reftex-mode t)
(flyspell-mode t)
(TeX-PDF-mode t)
(whizztex-mode t)
(reftex-enable-partial-scans t)
(reftex-save-parse-info t)
(reftex-use-multiple-selection-buffers t)
(reftex-plug-into-AUCTeX t)
(bib-cite-use-reftex-view-crossref t)
(TeX-source-specials-mode t)
(reftex-enable-partial-scans t)
(reftex-save-parse-info t)
(reftex-use-multiple-selection-buffers t)

(smart-dnd-setup
'(
("\\.tex\\'" . "\\input{%r}\n")
("\\.cls\\'" . "\\documentclass{%f}\n")
("\\.sty\\'" . "\\usepackage{%f}\n")
("\\.eps\\'" . "\\includegraphics[]{%r}\n")
("\\.ps\\'" . "\\includegraphics[]{%r}\n")
("\\.pdf\\'" . "\\includegraphics[]{%r}\n")
("\\.jpg\\'" . "\\includegraphics[]{%r}\n")
("\\.png\\'" . "\\includegraphics[]{%n}\n")
("\\.mov\\'" .
"\\includemovie[\n\tposter,\n\trepeat=1,\n\ttext=(%r)\n\t]{}{}{%r}\n")
("\\.avi\\'" .
"\\includemovie[\n\tposter,\n\trepeat=1,\n\ttext=(%r)\n\t]{}{}{%r}\n")))))

;; Finally this will force refresh on PDF viewer each time after compilation
(add-hook 'doc-view-mode-hook 'auto-revert-mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; More templates for Latex
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar latex-tempo-env-tags nil
"List of LaTeX environments tags.")

(defvar latex-tempo-com-tags nil
"List of LaTeX commands tags.")

;;; latex-mode-hook
(require 'tempo)
(require 'advice)

(setq-default tempo-interactive t)
(setq-default
tempo-match-finder "\\b\\([^\b]+\\)\\=") ;; The definition in tempo.el is false.

;;; install latex-mode and define list for environements and commands.
(add-hook 'LaTeX-mode-hook
'(lambda ()
(tempo-use-tag-list 'latex-tempo-env-tags)
(tempo-use-tag-list 'latex-tempo-com-tags)
))

(add-hook 'LaTeX-math-mode-hook
'(lambda ()
(tempo-use-tag-list 'latex-tempo-env-tags)
(tempo-use-tag-list 'latex-tempo-com-tags)
))

;; modification of tempo for running auctex function
(defadvice tempo-insert (before run-function (element on-region))
"run (auctex) lisp function"
(if (and (consp element)
(eq (car element) 'f))
(progn
(apply (nth 1 element) (nthcdr 2 element))
(ad-set-arg 0 nil))))

;; activate the new tempo-insert
(ad-activate 'tempo-insert t)

;; LaTeX function uses later
;; Insert a environment of the amsthm package.
(defun LaTeX-env-thm (environment)
"Insert ENVIRONMENT with optional argument
usage with AMSTHM ."
(let ((titre (read-string "Title : ")))
(LaTeX-insert-environment environment
(concat
(if (not (zerop(length titre)))
(format "[%s]" titre))))))
;; tempo-user-elements
(defvar tempo-user-elements nil)

;; Function to construct the environments templates.
(defun latex-tempo-env (l)
"Construct tempo-template for LaTeX environment"
(let* ((tag (car l))
(nom (nth 1 l))
(element (nth 2 l)))
(tempo-define-template nom element tag nil 'latex-tempo-env-tags)))

;;; function to construct LaTeX commands
(defun latex-tempo-com (l)
"Construct tempo-template for LaTeX commands."
(let* ((tag (car l))
(element (nth 1 l)))
(tempo-define-template tag element tag nil 'latex-tempo-com-tags)))

;; The templates.
(mapcar
'latex-tempo-env
'(("enu" "enumerate" ((LaTeX-env-item "enumerate")))
("ite" "itemize" ((LaTeX-env-item "itemize")))
("des" "description" ((LaTeX-env-item "description")))
("fig" "figure" ((LaTeX-env-item "figure")))
("pic" "picture" ((LaTeX-env-item "picture")))
("equ" "equation" ((LaTeX-environment-menu "equation")))
("rem" "remarque" ((LaTeX-environment-menu "remarque")))
("eno" "enonce" ((LaTeX-environment-menu "enonce")))
("the" "theorem" ((LaTeX-environment-menu "theorem")))
("pro" "proposition" ((LaTeX-environment-menu "proposition")))
("def" "definition" ((LaTeX-environment-menu "definition")))
("cor" "corollaire" ((LaTeX-environment-menu "corollaire")))
("exe" "exercise" ((LaTeX-environment-menu "exercise")))
("cla" "claim" ((LaTeX-environment-menu "claim")))
("tab" "tabular" ((LaTeX-environment-menu "tabular")))
("cen" "center" ((LaTeX-environment-menu "center")))
("eqn" "eqnarray" ((LaTeX-environment-menu "eqnarray*")))
("mini" "minipage" ((LaTeX-environment-menu "minipage")))
("mul" "multicols" (& >"\\begin{multicols}{"(p "Nbre de cols :")"}%"n>
r >
n>"\\end{multicols}"> %))
("bmini" "boxedminipage" (& >"\\begin{boxedminipage}["(p "Position :")"]{"(p "Largeur :")"}"n>
r >
n>"\\end{boxedminipage}"> %))
))

;; Here you install your LaTeX commands tags
(mapcar
'latex-tempo-com
'(("int" ("\\int_{" (p "liminf :") "}^{" (p "limsup :") "}" p
"\\;d"(p "variable :")))
("abs" ("\\left\\vert "p" \\right\\vert"p))
("norm" ("\\left\\Vert\\vec{"p"}\\right\\Vert"p))
("df" ("\\dfrac{"p"}{"p"}"p))
("bi" ("\\binom{"p"}{"p"}"p))
("fr" ("\\frac{"p"}{"p"}"p))
("sq" ("\\sqrt{"p"}"p))
("sqn" ("\\sqrt["p"]{"p"}"p))
("su" ("\\sum_{"p"}^{"p"}"p))
("coo" ("\\left("p"\\,;\\,"p"\\right)"p))
("coop" ("\\left["p"\\,;\\,"p"\\right]"p))
("coov" (& >"\\left(\\begin{array}[c]{c}%"n
r >
n"\\end{array}\\right)"> %))
("par" ("\\left("p"\\right)"p))
("cro" ("\\left["p"\\right]"p))
("acc" ("\\left\\{"p"\\right\\}"p))
("av" ("\\left(\\vec{"p"}\\,;\\,\\vec{"p"}\\right)"p))
("se" ("\\set{"p"}"p))
("ov" ("\\overline{"p"}"p))
("und" ("\\underline{"p"}"p))
("db" ("\\dbinom{"p"}{"p"}"p))
("te" ("\\text{"p"}"p))
("ve" ("\\vecteur{"p"}"p))
("oij" ("(O\\,;\\,\\vec{\\imath},\\vec{\\jmath})"))
("ouv" ("(O\\,;\\,\\vec{u},\\vec{v})"))
("oijk" ("(O\\,;\\,\\vec{\\imath},\\vec{\\jmath},\\vec{k})"))
("got" ("\\textgoth{"p"}"p))
("fra" ("\\textfrak{"p"}"p))
("act" ((act)))
("fr" ("\\frac{"p"}{"p"}"p))
("iff" ("\\left["p"\\,;\\,"p"\\right]"p))
("ifo" ("\\left["p"\\,;\\,"p"\\right["p))
("iof" ("\\left]"p"\\,;\\,"p"\\right]"p))
("ioo" ("\\left]"p"\\,;\\,"p"\\right["p))
("Df" ("\\mathscr{D}_{f}"))
("Cf" ("\\mathscr{C}_{f}"))
("tgt" ("\\mathscr{T}_{"p"}"))
("cal" ("\\mathscr{"p"}"p))
("ent" ("\\Rightarrow "))
("equ" ("\\Leftrightarrow "))
("nent" ("\\nRightarrow "))
("nequ" ("\\nLeftrightarrow "))
("gui" ("\\og{}"p"\\fg{}"p))
("nn" ("\\mathbb{N}"))
("nne" ("\\mathbb{N}^{\\star}"))
("rr" ("\\mathbb{R}"))
("rre" ("\\mathbb{R}^{\\star}"))
("rrp" ("\\mathbb{R}^{+}"))
("rrm" ("\\mathbb{R}^{-}"))
("rrep" ("\\mathbb{R}^{\\star+}"))
("rrem" ("\\mathbb{R}^{\\star-}"))
("cc" ("\\mathbb{C}"))
("cce" ("\\mathbb{C}^\\star"))
("dd" ("\\mathbb{D}"))
("pp" ("\\mathscr{P}"))
("zz" ("\\mathbb{Z}"))
("dd" ("\\mathbb{D}"))
("qq" ("\\mathbb{Q}"))
("eto" ("^{\\star}"))
("etop" ("^{\\star+}"))
("etom" ("^{\\star-}"))
("qpq" ("\\quad;\\quad"))
("qeq" ("\\quad\\text{et}\\quad"))
("qoq" ("\\quad\\text{o"p"}\\quad"))
("qpq" ("\\quad;\\quad"))
("mpv" ("\\,;\\,"))
("comp" ("\\makebox["(p "longueur (en mm):")"mm][l]{\\dotfill}\\;"))
("limx" ("\\underset{x\\rightarrow{}"p"}{\\lim}"p))
("limn" ("\\underset{n\\rightarrow+\\infty}{\\lim}"))
("lim" ("\\underset{"(p "Variable : ")"\\rightarrow{}"p"}{\\lim}"p))
("limxo" ("\\underset{x\\rightarrow0}{\\lim}"p))
("lims" ("\\underset{"(p "Variable : ")"\\stackrel{>}{\\rightarrow}"p"}{\\lim}"p))
("limi" ("\\underset{"(p "Variable : ")"\\stackrel{<}{\\rightarrow}"p"}{\\lim}"p))
("ten" ("\\xrightarrow[]{\\,"(p "Variable : ")"\\longrightarrow"p"\\,}"p))
("vs" ("\\vspace*{"(p "Length in mm: ")"mm}"))
("hs" ("\\hspace*{0mm}"))
("hf" ("\\hfill"))
("hfs" ("\\hfill\\hspace*{0mm}"))
("hsf" ("\\hspace*{0mm}\\hfill"))
("ct" ("\\cos\\theta"))
("st" ("\\sin\\theta"))
("ca" ("\\cos\\alpha"))
("sa" ("\\sin\\alpha"))
("sol" ("\\mathscr{S}=\\left\\{"p"\\right\\}"p))
("sol2" ("\\mathscr{S}=\\left\\{"p"\\,;\\,"p"\\right\\}"p))
("sol3" ("\\mathscr{S}=\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("sol4" ("\\mathscr{S}=\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("sol5" ("\\mathscr{S}=\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("ens" ("\\left\\{"p"\\right\\}"p))
("ens2" ("\\left\\{"p"\\,;\\,"p"\\right\\}"p))
("ens3" ("\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("ens4" ("\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("ens5" ("\\left\\{"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\,;\\,"p"\\right\\}"p))
("vec" ("\\vec{"r"}"p))
("aor" ("\\left(\\vec{"r"}\\,,\\;\\vec{"r"}\\right)"p))
("aori" ("\\left(\\vec{\\imath}\\,,\\;\\vec{"r"}\\right)"p))
("aoru" ("\\left(\\vec{u}\\,,\\;\\vec{"r"}\\right)"p))
("pis" ("\\frac{"(p "n.pi/q, n= ")"\\pi}{"(p "n.pi/q, q= ")"}"p))
("dpis" ("\\dfrac{"(p "n.pi/q, n= ")"\\pi}{"(p "n.pi/q, q= ")"}"p))
("pinf" ("+\\infty"))
("minf" ("-\\infty"))
("sca" ("\\vec{"p"}\\cdot\\vec{"p"}"p))
("tx" ("\\text{"p"}"p))
("arg" ("\\arg{"p"}"p))
("ass" ("\\longmapsto{}"))
("dp" ("\\["p"\\]"))
("mod" ("\\mod{2\\pi}"))
("ei" ("\\e^{i"p"}"p))
("eipis" ("\\e^{i\\frac{\pi}{"p"}"p))
("eia" ("\\e^{i\\alpha}"))
("eib" ("\\e^{i\\beta}"))
("eit" ("\\e^{i\\theta}"))
("reia" ("r\\e^{i\\alpha}"))
("reib" ("r\\e^{i\\beta}"))
("reit" ("r\\e^{i\\theta}"))
("colo" ("\\colorize"p))
("coloi" ("\\colorizeimp"p))
("colod" ("\\colorizedef"p))
("som" ("\\sum\\limits_{"p"}^{"p"}"))
("dis" ("\\displaystyle"p))
("txt" ("\\text{"p"}"p))
("ince" ("\\subseteq{}"))
("inc" ("\\subset{}"))
("line" ("\\renewcommand{\\baselinestretch}{1.5}\\small\\normalsize"))
));;Here LaTeX commands tags

;; The most important is TAB to complete your tag's.
(add-hook 'LaTeX-mode-hook
(function
(lambda ()
(define-key LaTeX-mode-map "\t" 'smart-tab)
(define-key LaTeX-mode-map "\C-c/" 'tempo-complete-tag)
(define-key LaTeX-mode-map [M-right] 'tempo-forward-mark)
(define-key LaTeX-mode-map [M-left] 'tempo-backward-mark)
(define-key LaTeX-mode-map [s-tab] 'tempo-complete-tag))))

(provide 'latex-tempo)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Python mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'pycomplete)
(autoload 'python-mode "python-mode" "Python Mode." t)
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
(add-to-list 'interpreter-mode-alist '("python" . python-mode))
(require 'python-mode)

(setq-default py-indent-offset 4)
(setq interpreter-mode-alist
(cons '("python" . python-mode)
interpreter-mode-alist)
python-mode-hook
'(lambda () (progn
(set-variable 'py-indent-offset 4)
(set-variable 'py-smart-indentation nil)
(set-variable 'indent-tabs-mode nil)
;(highlight-beyond-fill-column)
(define-key py-mode-map "\C-m" 'newline-and-indent)
(abbrev-mode)
)))

(defun electric-pair ()
"Insert character pair without sournding spaces"
(interactive)
(let (parens-require-spaces)
(insert-pair)))

(defun my-compile ()
"Use compile to run python programs"
(interactive)
(compile (concat "python " (buffer-name))))
(setq compilation-scroll-output t)

(add-hook 'python-mode-hook
(lambda ()
(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s %s.py "
(or (getenv "python") "python")
(file-name-sans-extension file)
))))))

(add-hook 'py-mode-hook
(lambda ()
(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s %s.py "
(or (getenv "python") "python")
(file-name-sans-extension file)
))))))

;; pymacs
(autoload 'pymacs-apply "pymacs")
(autoload 'pymacs-call "pymacs")
(autoload 'pymacs-eval "pymacs" nil t)
(autoload 'pymacs-exec "pymacs" nil t)
(autoload 'pymacs-load "pymacs" nil t)
(pymacs-load "ropemacs" "rope-")
(setq ropemacs-enable-autoimport t)

(when (load "flymake" t)
(defun flymake-pyflakes-init ()
(let* ((temp-file (flymake-init-create-temp-buffer-copy
'flymake-create-temp-inplace))
(local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name))))
(list "pyflakes" (list local-file))))
(add-to-list 'flymake-allowed-file-name-masks
'("\\.py\\'" flymake-pyflakes-init)))

(add-hook 'py-mode-hook
(lambda ()
(require 'flymake)
(setq flymake-mode t)))

(add-hook 'python-mode-hook
(lambda ()
(require 'flymake)
(setq flymake-mode t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Auto-completion
;;; Integrates:
;;; 1) Rope
;;; 2) Yasnippet
;;; all with AutoComplete.el
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(require 'auto-complete)
(global-auto-complete-mode t)

(defun prefix-list-elements (list prefix)
(let (value)
(nreverse
(dolist (element list value)
(setq value (cons (format "%s%s" prefix element) value))))))
(defvar ac-source-rope
'((candidates
. (lambda ()
(prefix-list-elements (rope-completions) ac-target))))
"Source for Rope")
(defun ac-python-find ()
"Python `ac-find-function'."
(require 'thingatpt)
(let ((symbol (car-safe (bounds-of-thing-at-point 'symbol))))
(if (null symbol)
(if (string= "." (buffer-substring (- (point) 1) (point)))
(point)
nil)
symbol)))
(defun ac-python-candidate ()
"Python `ac-candidates-function'"
(let (candidates)
(dolist (source ac-sources)
(if (symbolp source)
(setq source (symbol-value source)))
(let* ((ac-limit (or (cdr-safe (assq 'limit source)) ac-limit))
(requires (cdr-safe (assq 'requires source)))
cand)
(if (or (null requires)
(>= (length ac-target) requires))
(setq cand
(delq nil
(mapcar (lambda (candidate)
(propertize candidate 'source source))
(funcall (cdr (assq 'candidates source)))))))
(if (and (> ac-limit 1)
(> (length cand) ac-limit))
(setcdr (nthcdr (1- ac-limit) cand) nil))
(setq candidates (append candidates cand))))
(delete-dups candidates)))
(add-hook 'python-mode-hook
(lambda ()
(auto-complete-mode 1)
(set (make-local-variable 'ac-sources)
(append ac-sources '(ac-source-rope) '(ac-source-yasnippet)))
(set (make-local-variable 'ac-find-function) 'ac-python-find)
(set (make-local-variable 'ac-candidate-function) 'ac-python-candidate)
(set (make-local-variable 'ac-auto-start) nil)))
;;Ryan's python specific tab completion
(defun ryan-python-tab ()
; Try the following:
; 1) Do a yasnippet expansion
; 2) Do a Rope code completion
; 3) Do an indent
(interactive)
(if (eql (ac-start) 0)
(indent-for-tab-command)))
(defadvice ac-start (before advice-turn-on-auto-start activate)
(set (make-local-variable 'ac-auto-start) t))
(defadvice ac-cleanup (after advice-turn-off-auto-start activate)
(set (make-local-variable 'ac-auto-start) nil))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; End Auto Completion
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; modified from http://www.emacswiki.org/emacs/PythonMode
(add-hook 'py-mode-hook
'(lambda () (eldoc-mode 1)) t)

(add-hook 'python-mode-hook
'(lambda () (eldoc-mode 1)) t)

(defun pydoc (w)
"Launch PyDOC on the Word at Point"
(interactive
(list (let* ((word (thing-at-point 'word))
(input (read-string
(format "pydoc entry%s: "
(if (not word)
""
(format " (default %s)" word))))))
(if (string= input "")
(if (not word) (error "No pydoc args given")
word) ;sinon word
input)))) ;sinon input
(save-window-excursion
(shell-command (concat "pydoc " w) "*Pydocs*"))
;;(view-buffer-other-window "*Pydocs*" nil 'bury-buffer))
(view-buffer "*Pydocs*" 'bury-buffer))

(define-key py-mode-map "\t" 'smart-tab)
(define-key py-mode-map "\C-c\C-c" 'my-compile)
(define-key py-mode-map [f5] 'my-compile)
(define-key py-mode-map [f8] 'pydoc)
(define-key py-mode-map "\t" 'smart-tab)
(define-key py-mode-map "\"" 'electric-pair)
(define-key py-mode-map "\'" 'electric-pair)
(define-key py-mode-map "(" 'electric-pair)
(define-key py-mode-map "[" 'electric-pair)
(define-key py-mode-map "{" 'electric-pair)
(define-key py-mode-map (kbd "") 'ryan-python-tab)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Word files
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; open Word files with antiword
(when (locate-library "no-word")
(require 'no-word)
(add-to-list 'auto-mode-alist '("\\.doc\\'" . no-word)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ORG mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'org-install)
;;
;; Standard key bindings
(global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-ca" 'org-agenda)
(global-set-key "\C-cb" 'org-iswitchb)
(global-set-key "\C-ce" 'org-export-as-html-and-open)

;; Make TAB the yas trigger key in the org-mode-hook and turn on flyspell mode
(add-hook 'org-mode-hook
(lambda ()
;; yasnippet
(make-variable-buffer-local 'yas/trigger-key)
(setq yas/trigger-key [tab])
(define-key yas/keymap [tab] 'yas/next-field-group)
;; flyspell mode to spell check everywhere
(flyspell-mode 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Makefiles
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'makefile-mode-hook
(lambda()
(require 'show-wspace)
(show-ws-highlight-trailing-whitespace)))

;; This is to show trailing space on Makefiles
(add-hook 'makefile-mode-hook
(lambda()
(setq show-trailing-whitespace t)))

(add-to-list 'auto-mode-alist '("\\.make\\'" . makefile-mode))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; JSON files
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(autoload 'js2-mode "js2" nil t)
(add-to-list 'auto-mode-alist '("\\.json" . js2-mode))
(add-to-list 'auto-mode-alist '("\\.js$" . js2-mode))

(setq js2-bounce-indent-p t)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Doxygen
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'c-mode-common-hook
(lambda ()
(require 'doxymacs)
(doxymacs-mode t)
(doxymacs-font-lock)))

(add-hook 'c++-mode-common-hook
(lambda ()
(require 'doxymacs)
(doxymacs-mode t)
(doxymacs-font-lock)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Fixing problems when calling the compilers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Detecting error in Modelsim
;; For Modelsim: vcom error format:
;;** Error: switch.vhd(68): near ")": expecting: IDENTIFIER

(eval-after-load "compile"
'(setq compilation-error-regexp-alist
(cons '("^\*\* Error: \\([^(]+\\)\(\\([0-9]+\\)\):" 1 2)
compilation-error-regexp-alist)))

;; Fixing the problems with compile in VHDL/C/C++
(require 'compile)
(add-hook 'vhdl-mode-hook
(lambda ()
(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
;; $(VHDL) -work work $<
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s -work work %s.vhd"
(or (getenv "VHDL") "/opt/modeltech/bin/vcom")
(file-name-sans-extension file)
file))))))

(add-hook 'c-mode-hook
(lambda ()

(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
;; emulate make's .c.o implicit pattern rule, but with
;; different defaults for the CC, CPPFLAGS, and CFLAGS
;; variables:
;; $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $<
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s -c -o %s.o %s %s %s"
(or (getenv "CC") "gcc")
(file-name-sans-extension file)
(or (getenv "CPPFLAGS") "-DDEBUG=9")
(or (getenv "CFLAGS") "-ansi -pedantic -Wall -g")
file))))))

(add-hook 'c++-mode-hook
(lambda ()
(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
;; emulate make's .c.o implicit pattern rule, but with
;; different defaults for the CC, CPPFLAGS, and CFLAGS
;; variables:
;; $(CC) -c -o $@ $(CPPFLAGS) $(CFLAGS) $<
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s -c -o %s.o %s %s %s"
(or (getenv "C++") "g++")
(file-name-sans-extension file)
(or (getenv "CPPFLAGS") "-DDEBUG=9")
(or (getenv "CFLAGS") "-ansi -pedantic -Wall -g")
file))))))

(add-hook 'LaTeX-mode-hook
(lambda ()
(unless (file-exists-p "Makefile")
(set (make-local-variable 'compile-command)
(let ((file (file-name-nondirectory buffer-file-name)))
(format "%s %s"
(or (getenv "LaTeX") "latex")
file))))))

(add-hook 'vhdl-mode-hook
(lambda ()

(setq explicit-shell-file-name "bash")
(setq shell-file-name explicit-shell-file-name)

(defun vhdl-simulate () (interactive)
;; $(VHDL) -work work $\n]* wrote:[ \n]+")
(funcall find "^>>>>>")
(funcall find "^ *>.*\n *>")
(funcall find "^-----Original Message-----")))))
(save-restriction

(narrow-to-region start end)
(filladapt-mode 1)
(fill-region (point-min) (point-max)))))
(message "Message re-filled"))
(message "No message to re-fill")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; General useful functions defined by user
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun insert-date-spanish (dayincr)
"Inserts a date-stamp at point - Format: \"DD-MM-YYYY (wd)\""
(interactive "p")
(if (null current-prefix-arg) (setq dayincr 0))
(let* ((base 65536.0)
(nowlist (current-time))
(datenum (+ (* (nth 0 nowlist) base) (nth 1 nowlist)
(* dayincr 60.0 60.0 24.0)))
(s (current-time-string
(list (truncate( / datenum base)) (truncate(mod datenum base)))))
(date))
(if (equal current-prefix-arg '(4))
(progn
(let ((bound (line-beginning-position))
(datenum)
(datestring))
(goto-char (min (point-max) (+ (point) 10)))
(re-search-backward "[0-9][0-9]\\.[0-9][0-9]\\.[0-9][0-9][0-9][0-9]" bound)
(setq datestring (buffer-substring (point) (+ (point) 10)))
(setq datenum (calendar-absolute-from-gregorian
(list
(string-to-number (substring datestring 3 5))
(string-to-number (substring datestring 0 2))
(string-to-number (substring datestring 6 10)))))
(setq dayincr (string-to-number (read-string "Increment by days: " "7")))
(delete-region (point) (+ 10 (point)))
(setq date (calendar-gregorian-from-absolute (+ datenum dayincr)) datestring)))
(setq date (list (length (member (substring s 4 7)
'("Dec" "Nov" "Oct" "Sep" "Aug" "Jul"
"Jun" "May" "Apr" "Mar" "Feb" "Jan")))
(string-to-number (substring s 8 10))
(string-to-number (substring s 20 24)))))

(insert (format "%02d.%02d.%04d" (nth 1 date) (nth 0 date) (nth 2 date)))))

;; Taken from vhdl-mode
(defun remove-trailing-spaces ()
"Remove trailing spaces in the whole buffer."
(interactive)
(save-match-data
(save-excursion
(let ((remove-count 0))
(goto-char (point-min))
(while (re-search-forward "[ \t]+$" (point-max) t)
(setq remove-count (+ remove-count 1))
(replace-match "" nil nil))
(message (format "%d Trailing spaces removed from buffer." remove-count))))))

;; Convert DOS cr-lf to UNIX newline
(defun dos2unix () (interactive) (goto-char (point-min))
(while (search-forward "\r" nil t) (replace-match "")))
;;Convert UNIX newline to DOS cr-lf
(defun unix2dos () (interactive) (goto-char (point-min))
(while (search-forward "\n" nil t) (replace-match "\r\n")))
(defun remove-hard-wrap-paragraph ()
"Replace newline chars in current paragraph by single spaces."
(interactive)
(let ((fill-column 90002000))
(fill-paragraph nil)))
(defun remove-hard-wrap-region (start end)
"Replace newline chars in region by single spaces."
(interactive "r")
(let ((fill-column 90002000))
(fill-region start end)))

(defun count-words-region (start end)
"Print number of words in the region."
(interactive "r")
(save-excursion
(let ((n 0))
(goto-char start)
(while (< (point) end)
(if (forward-word 1)
(setq n (1+ n))))
(message "Region has %d words" n)
n)))

(defun find-next-double-word ()
"move to next doubled word, ignoring tags and any
whitespace (including new lines)."
(interactive)
(re-search-forward "\\<\\([a-z]+\\)\\([\n \t]\\|]+>\\)+\\1\\>"))

(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)

Coloca este archivo en tu directorio $HOME. Tiene activados varios plugins muy buenos como CUA (atajos de editores de Windows, me refiero a usar Ctrl+C para copiar y Ctrl+V para pegar :) , edicion rectangular pulsando Ctrl+Enter), CEDET (autocompletado de codigo), Yasnipets (plantillas para codigo), Ropemacs (refactorizacion de codigo Python).

Algunos de los plugins que veras que tiene activados es:

Alt+<tecla de + del teclado numerico> —-> asistente inteligente de completado de funciones

Ctrol+<Enter> —-> modo de edicion rectangular

<TAB> ——-> autocompletado inteligente basado en palabras previas o auto-tabulacion

2. Instalando Rope y Ropemacs para edicion de Python

La version de Rope y Ropemacs (autocompletado de codigo en Python) que vienen en Ubuntu no son las mas recientes, para poder este archivo .emacs necesitamos tener las ultimas versiones instaladas. Para esto debemos ir a terminal y tipear lo siguiente:

sudo apt-get install mercurial
mkdir /tmp/rope && cd /tmp/rope
hg clone http://bitbucket.org/agr/rope
hg clone http://bitbucket.org/agr/ropemacs
hg clone http://bitbucket.org/agr/ropemode
sudo easy_install rope
ln -s ../ropemode/ropemode ropemacs/
sudo easy_install ropemacs

3. Configurando Wanderlust

Wanderlust es un modo para envio y recepcion de correos en EMACS.  Si desean configurar Wanderlust les remito a:

http://emacs-fu.blogspot.com/2009/06/e-mail-with-wanderlust.html

En todo caso, configurar Wanderlust es un poco complicado. En las maquinas que he probado no configurar Wanderlust y usar los archivos de Rapidshare que adjunto al inicio de este post ha funcionado bien. Sin embargo, si tienes errores puedes tratar de comentar (o mejor borrar) todas las lineas entre 2555 y 2634 (inclusives) del archivo .emacs. O simplemente puedes borrarlas.

4. Mejorando el tipo de letra (con antialias)

Primero requerimos instalar las fuentes de Office 2007, dado que usaremos el font Consolas, a mi criterio uno de los mejores para programadores.

Instalar fuentes de Office 2007 en Ubuntu

Luego en consola tipeamos:

$ gedit .Xresources

E introducimos:

Emacs.font: LMTypewriter12-13
Emacs.fontBackend: xft
Xft.antialias: 1
Xft.hinting: 1
! ================
! Emacs
! ================
Emacs.Foreground: wheat
Emacs.Background: #222222
Emacs.menu.attributeForeground: wheat
Emacs.menu.attributeBackground: #222222
!Emacs.cursorColor: Darkgrey
! modeline
Emacs.mode-line.attributeForeground: white
Emacs.mode-line.attributeBackground: grey15
Emacs.modeline.attributeForeground: white
Emacs.modeline.attributeBackground: grey15
! selection
Emacs.region.attributeBackground: lightblue
Emacs.region.attributeForeground: Yellow
Emacs.primary-selection.attributeBackground: blue
Emacs.secondary-selection.attributeBackground: darkslateblue
Emacs.show-paren-match-face.attributeBackground: Aquamarine
Emacs.show-paren-match-face.attributeForeground: SlateBlue
Emacs.show-paren-mismatch-face.attributeBackground: Red
Emacs.show-paren-mismatch-face.attributeForeground: White

Grabamos y salimos, luego tipeamos:

$ xrdb -merge .Xresources

Listo.

Al final EMACS lucira asi:

Emacs 23 en Ubuntu

Navegando Internet con W3M y EMACS

Navegando Internet con W3M y EMACS

5. El modo CUA

El modo de edicion CUA en EMACS permite el uso de Ctrl-X/C/V para cortar / copiar / pegar, como es habitual en muchos programas de computadora. Esto lo hace a EMACS mucho mas amigable para quienes estamos acostumbrados a estos atajos del teclado. Sin embargo el problema es Ctrol-X tambien se usa en EMACS para ejecutar comandos especiales. CUA-modo tiene un truco inteligente para resolver este problema - Cx para cortar sólo funciona cuando la selección está activa, y cuando no hay otra tecla que se pulsa en breve. De lo contrario, Cx se comporta como de costumbre. Véase, aqui -> CuaMode para más información.

CUA tiene tambien algunas funcionalidades muy agradables para edicion rectangular.

En los archivos de configuracion .emacs que adjunto arriba, el modo CUA esta activado. Para usar el muy vistoso modo rectangular de EMACS, basta con poner el cursor en cualquier lugar, y presiona C-RET (Ctrl + Enter). Ahora ha comenzado una selección rectangular! El resto es bastante sencillo, se puede cortar, copiar y pegar con los enlaces normales, ademas de editar varias lineas de codigo, todas a la vez :D . Les recomiendo probarlo es impresionante (y muy util).

6. Para finalizar una demostracion de EMACS editanto Python

Instalar Google Earth 5 en Ubuntu e integrarlo con tu tema GTK preferido

Veremos aqui como instalar Google Earth 5 en Ubuntu y ademas como hacer que se integre al tema GTK que usamos :)

Medibuntu (Multimedia, Entertainment & Distractions in Ubuntu, es decir, Multimedia, entretenimiento y distracciones en Ubuntu) es un repositorio de paquetes de software que no pueden ser incluidos en la distribución Ubuntu por motivos como problemas legales de copyright, licenciamiento o restricciones de patentes.

Existe una gran cantidad de programas excelentes (libres y no libres) a los que afectan estas restricciones en ciertas partes del mundo, lo que impide que se incluyan en los repositorios estándar de Ubuntu. Hay que tener en cuenta, además, que la política de Canonical, además de su compromiso con la libertad en el software, incluye la opción por crear discos de instalación en cedés, en lugar hacerlo en discos DVD como otras distribuciones.

Ahora que ya sabes de que se trata Medibuntu vamos a instalar los codecs multimedianecesarios para que tu Ubuntu reproduzca de todo.

Lo primero que haremo es agregar el repositorio de Medibuntu esto lo hacemos ejecutando lo siguiente en una terminal, si así de fácil. Solo copia y pega:

sudo wget http://www.medibuntu.org/sources.list.d/karmic.list –output-document=/etc/apt/sources.list.d/medibuntu.list
sudo apt-get -q update
sudo apt-get –yes -q –allow-unauthenticated install medibuntu-keyring
sudo apt-get -q update

Ahora para instalar Google Earth
sudo apt-get install googleearth

Les recomiendo hacerlo de esta forma y no descargar el instalador de la pagina de Google, porque viene con un set de librerias  (Qt4) que no se integran bien con el tema de GTK que estan usando en su Ubuntu.

Lo ejecutamos en el menu Internet -> GoogleEarth, luce asi:

Google Earth 5 - instalado desde repositorios de Medibuntu

Simulador Modelsim 6.2 SE NATIVO para Ubuntu Linux 32 y 64

Modelsim 6.2 SE para Linux

Modelsim 6.2 SE para Linux

NOTA IMPORTANTE: Las nuevas versiones de Modelsim para Linux las pueden descargar de aqui (funcionan tambien) esta hasta version 6.5, solo deben registrarse y les dan un link de descarga.

http://www.model.com/downloads/default.asp

Hola amigos, aqui les traigo instruccions para instalar Modelsim 6.2 en tu Ubuntu Linux (gracias a Alvaro que lo ha subido a Mediafire). Modelsim SE (Standard Edition) es la version mas potente de simulador VHDL de Mentor Graphics, esta version es mejor que la XE, o AE (que son especificias para Xilinx y Altera) y que tienen limitaciones en el tamanho de disenho VHDL. Los links de descarga son:

Los archivos necesarios estan aqui:
http://www.mediafire.com/?sharekey=e290b748dd2172eb8c9e7c56ba37815f08d0e788b1bf39ad

O los puedes encontrar en un solo archivo Modelsim_linux6.2.rar (tiene todos los archivos incluidos, pero falta generador de licencia, lo puedes descargar del primer link):
http://www.gigasize.com/get.php?d=7n0qmkj4v4b

Bueno, primero crea una carpeta dentro de tu directorio HOME y descarga los archivos alli, en mi caso era /home/abelardo/tempo

Abre un terminal y entramos a esa carpeta:

$ cd tempo

$ unrar x modelsim_linux6.2.rar (este paso solo necesario si descargaste el RAR en lugar de varios archivos)

$ chmod +x

$ chmod +x modelsim-linux.exe

$ ./modelsim-linux.exe (Esto ejecutara el instalador, sigue los pasos normalmente)

$ tar xzvf modelsim-base.tar.gz

$ tar xzvf modelsim-gcc-4.0.2-rhe21.tar.gz

$ tar xzvf modelsim-docs.tar.gz

Estos pasos descomprimen el Modelsim en un carpeta llamado “modeltech”. Ahora moveremos esta carpeta a /opt (es el mejor directorio para tener aplicaciones que no son parte del sistema operativo. Una recomendacion es tener /opt en una particion separada, de modo que si reinstalamos el SO, mantenemos nuestras aplicaciones en /opt

$ sudo mv modeltech /opt

$ cd ~

$ gedit .bashrc

Busca alguna linea que diga export $PATH y debajo anhades:

export PATH=$PATH:.:/opt/modeltech/bin:/opt/modeltech/linux

export LM_LICENSE_FILE=/home/[TU NOMBRE DE USUARIO]/flexlm/license.dat

Graba y sal. Listo, pero ahora falta el license. Para ello abre una nueva terminal (no cierres la primera) y tipeas:

$ lmhostid

lmhostid – Copyright (c) 1989-2006 Macrovision Europe Ltd. and/or Macrovision Corporation. All Rights Reserved.
The FLEXlm host ID of this machine is “[AQUI TE SALDRA UN CODIGO]

Copia el codigo y regresa al primer terminal y tipeas:

$ wine keygenmodelsimlinux.exe

Te pedira un codigo, introduce el codigo generado antes por lmhostid. Este paso generara un archivo license.dat en el mismo directorio.

Ahora tipea:

$ mkdir ~/flexlm

$ mv license.dat ~/flexlm

Listo, cierra los terminales. Ahora para ejecutar el programa, abre un nuevo terminal y tipea:

$ vsim

Un screenshot del programa:

Ventana que reporta que make finalizó exitosamente

Nota: Modelsim tambien se puede ejecutar en linea de comandos con:

Para compilar nuestros archivos VHDL, nos vamos dentro del directorio donde estan los archivos VHDL de nuestro proyecto y creamos primero una librerìa work donde compilaremos nuestro diseño:

>>vlib work

>>vmap work work

Para ver si trabaja bien, llamamos al compilador del Modelsim VCOM

>>vcom -93 -work work top.vhd (Habra que ir compilando los archivos VHDL uno por uno)

Para simular, necesitas crear archivos VHDL tipo Testbench y compilarlos tambien. Usaremos VSIM, pero en modo consola:

>>vsim -c work.[testbench_top] -do “run -all; exit;”

testbench_top es el nombre de nuestro archivo testbench_top.vhd que debe también haber sido compilado previamente con VCOM y dentro de nuestra librerìa WORK.

Instalar fuentes de Office 2007 en Ubuntu

Windows Vista y Microsoft Office 2007 tienen un nuevo tipo de fuentes: Calibri, Cambria, Candara, Consolas, Constantia, y Corbel. Ellas reemplazan los clasicos Times New Roman, Arial, Courier New, etc.

El problema es cuando queremos abrir documentos de OpenXML (Office 2007) en OpenOffice y estas fuentes no estan disponibles. Veamos como instalarlas:

The Office 2007 / Windows Vista shown in OpenOffice.org 2.3.1 on Linux

Cuestiones de licencia:

En el instalador de Powerpoint Viewer dice:

You may use the fonts that accompany the PowerPoint Viewer only to display and print content from a device running a Microsoft Windows operating system.

Lo que indica que solo puede usarse si usan Microsoft Windows. Esperemos que Ubuntu o Redhat saquen un juego de fuentes equivalentes para Linux.

Pasos a seguir:

Luego instalas cabextract, abres una consola y tipea:

  1. sudo apt-get install cabextract
  2. Download PowerPoint Viewer 2007. No te pide Windows Genuine Advantage validation.
  3. Extract the .exe: cabextract -F ppviewer.cab PowerPointViewer.exe
  4. Prepara el directorio de destino de tus fuentessudo mkdir /usr/share/fonts/vista
  5. Extrae las fuentes: sudo cabextract -F '*.TT?' -d /usr/share/fonts/vista ppviewer.cab
  6. Actualiza el cache de fuentes: fc-cache -fv

Listo, con esto ya tendras las fuentes de Office 2007 instaladas en tu Ubuntu.

Fuente: http://www.oooninja.com/2008/01/calibri-linux-vista-fonts-download.html

Tema de KDE 4 para Gnome

Con frecuencia me gusta visitar la pagina de Gnome-Look

Alli nos podemos descargar temas para nuestro escritorio de Ubuntu. Generalmente nos descargamos el tema como un archivo de extension .TAR.GZ y lo instalmos en System->Preference->Appearance y luego presionamos el boton de Install…

Encontre que han publicado un tema para que Gnome luzca como KDE 4. Lo he probado y realmente me ha gustado mucho. Es de tonos grises y muy facil para quienes gustan de un escritorio sobrio y elegante.

Oxygen (KDE 4.2) for GNOME

Despues de instalarlo hacen Click en el boton Customize… (la misma ventana de Apariencia) y en la pestanha Appearance lo pueden buscar como kde4-oxygen.

El tema queda asi:

Combinado con un bonito de tema iconos y de borde de ventana RazorFX (Metacity) queda muy bien :)

RazrFX GNOME-Look.org

Tema de GTK con motivo KDE 4

Tema de GTK con motivo KDE 4

Como empezar a programar microcontroladores PIC en Ubuntu Hardy

Primero, se supone que tienes Ubuntu Hardy o posterior, aunque seguro que funciona con versiones anteriores, también debes tener un programador de los habitualmente utilizados.

Solo tienes que instalar los siguientes paquetes disponibles en los repositorios:

Para programar solo en ASM: gputils, gpsim, piklab
Para programar en C, además de los anteriores: sdcc (Piklab también se integra con otros compiladores C )

Esto lo puedes hacer desde synaptic o mucho más rápido desde una terminal:
_____________________________________________

$ sudo apt-get install gputils gpsim sdcc
_____________________________________________
Ahora tambien necesitas Piklab, el cual puedes descargar el paquete DEB de: http://pikdev.free.fr/

O tambien de: pikdev_1.1.0-1_i386.deb

Descargan el DEB y lo instalan con $ sudo dpkg -i pikdev_1.1.0-1_i386.deb (en caso que usen Ubuntu 64 tambien esta el codigo fuente como .tar.gz pero deberan compilarlo separadamente)

Para programar en BASIC no hay ninguna herramiente opensource (actualizado 23/01/09: ver GCBASIC), pero se puede utilzar el software de SourceBoost, que tiene una versión gratuita, completamente funcional aunque con algunas limitaciones de memoria utilizada y las versiones de pago tienen precios razonables.
BoostBasic corre bajo windows, pero funciona perfectamente integrado en Piklab con Wine:

1- Instalar los paquetes anteriormente mencionados.
2- Instalar wine desde repositorios.
3- descargar y ejecutar el instalador de SourceBoost: SourceBost V 6.90 (También trae un compilador C, otro C++ y Novo, un Rtos para PIC).

Una vez instalado todo lo necesario busca Piklab en el menú “Aplicaciones” y lo lanzas.
Ahora puedes actuar de dos maneras:

- Crear un proyecto (RECOMENDADO) donde indicas el compilador y PIC a utilizar y añadir los archivos utilizados. Una vez que los archivos estan listos, en el menú “construir (Build)” seleccionar “Construir proyecto”…. vuestro archivo .hex ya está listo para ser grabado al pic.

- Compilar un archivo suelto (algunos compiladores requieren abrir un proyecto), entonces no creas ningún proyecto sino que directamente abres el archivo a compilar, tienes que seleccionar el compilador que quieres en el menú abajo a la derecha; luego en el menú “construir (Build)” seleccionar “Compilar archivo” …. vuestro archivo .hex ya está listo para ser grabado al pic.

Ahora tienes que seleccionar el programador que estés usando en el menú de abajo, a la izquierda de los compiladores; entonces darle al icono que se vé un chip con la flechita hacia adentro o hacerlo desde el menú: “Programador – programar”.

Si en vez de seleccionar un programador seleccionas “GPSim” (en el menú de abajo donde los programadores) entras en modo simulación, se activan los iconos de comenzar simulación, avanzar un paso, etc. En la ventana de izquierda, al lado de “proyecto” hay una pestaña donde puedes seleccionar los registros que quieres seguir.
Gpsim también se puede lanzar independientemente de Piklab, ofreciendo más posiblidades.

Un amigo hizo un video de como hacer estos pasos:

Si conocen alguna otra herramienta o prueban estas, por favor, no duden en comentar.
Fuente: http://pic-linux.foroactivo.net/linux-f15/como-empezar-a-programar-pics-en-ubuntu-en-10-minutos-asm-c-basic-t41.htm

Instalar MARS: ensamblador y simulador del procesador MIPS para cursos de Arquitectura de Computadoras en Ubuntu

MARS es un entorno de desarrollo integrado (IDE) liviano para programar con el ensamblador del procesador MIPS y su proposito es para cursos de Arquitectura de Computadora que usen el libro de Patterson y Hennessy’s Computer Organization and Design. Actualmente acaba de salir la version 3.6.

Caracteristicas:

  • Interface grafica con “point-and-click” e IDE integrado

  • Poder editar facilmente valores de registros y de memoria, parecido a una hoja de calculo

  • Muestra valores en decimal o hexadecimal

  • Linea de comandos para el profesor para que pueda evaluar facilmente el programa hecho por el alumno
  • Registros de punto flotante, coprocessor1 y coprocessor2.

  • Ejecucion paso-a-paso con velocidad variable

  • Utilidad para analisis de performance de cache (screenshot).

  • Retroceso (solo un paso)

Para instalarlo en Ubuntu tienes que asegurarte que tienes los repositorios de Getdeb:

Agregar Getdeb en nuestros repositorios de Ubuntu Hardy

Si los tienes, tipea:

$ sudo apt-get update

$ sudo apt-get install mars

Lo ejecutas simple con $ mars

Usando el compilador de Microsoft Visual C++ 2005/2008 en Ubuntu Linux

En Ubuntu Linux ya tenemos GCC 4.2 para programar en C++ pero hay ocasiones en que queremos asegurarnos que nuestro codigo compila tanto en Linux como en Windows. Sin embargo lamentablemente Wine aun no puede ejecutar Microsoft Visual C++ 2005.

Sin embargo, un amigo hizo un truco para poder ejecutar solo el compilador y el enlazador del Visual C++ 2005 bajo Wine y con excelentes resultados, es posible compilar y crear ejecutables desde Linux usando el compilador del Visual C++ 2005.

Su reporte esta aqui:

WineHQ – Visual C++ 8.0 (2005)

Primero lo que necesitamos tener es una instalacion valida de Microsoft Visual C++ 2005 en algun Windows. Necesitaras copiar a tu directorio de Wine los siguientes directorios

  • c:/Program Files/Microsoft Visual Studio 8/VC/include
  • c:/Program Files/Microsoft Visual Studio 8/VC/lib
  • c:/Program Files/Microsoft Visual Studio 8/VC/bin
  • c:/Program Files/Microsoft Visual Studio 8/Platform SDK/Include
  • c:/Program Files/Microsoft Visual Studio 8/Platform SDK/Lib

PASO 0: Verifica que tienes instalado wine

$ sudo apt-get install wine

$ winecfg —-> Elige como version Windows XP y acepta

PASO 1: Primero crea las carpetas de destino dentro de tu instalacion de Wine:

mkdir -p $HOME/.wine/drive_c/Program\ Files/Microsoft\ Visual\ Studio\ 8/VC
mkdir -p $HOME/.wine/drive_c/Program\ Files/Microsoft\ Platform\ SDK\ for\ Windows\ Server\ 2003\ R2/

Debes haber instalado antes Wine y haberlo ejecutado una vez al menos.

PASO 2: Ahora, necesitaras las librerias para ejecutar Visual C++ 2005. Eso lo arreglamos usando Winetricks (ES UN SCRIPT PARA RECUPERAR DLLs de Windows):

$ wget http://www.kegel.com/wine/winetricks

Le damos permisos de ejecucion:

$ chmod +x ./winetricks

Y si quisieramos ya instalar una determinada libreria, podriamos hacerlo directamente. Por ejemplo:

$ sh winetricks corefonts vcrun6 vcrun2005sp1

PASO 3: Listo, ahora copia el archivo (de la otra maquina o de la particion de Windows):

C:\Program Files\Microsoft Visual Studio 8\CommoN7\IDE\mspdb80.dll —-> a esta carpeta —–> $HOME/.wine/drive_c/windows/system32

PASO 4: Copia las carpetas bin, lib e include que estan dentro de:

c:/Program Files/Microsoft Visual Studio 8/VC/ —–> a esta carpeta ———–>

$HOME/.wine/drive_c/Program\ Files/Microsoft\ Visual\ Studio\ 8/VC

PASO 5: Copia las carpetas Include y Lib que estan dentro de:

c:/Program Files/Microsoft Visual Studio 8/Platform SDK/ ——> a esta carpeta ———–>

$HOME/.wine/drive_c/Program\ Files/Microsoft\ Platform\ SDK\ for\ Windows\ Server\ 2003\ R2/

PASO 6: Marca como ejecutables el compilador y el enlazador de Visual C++ 2005:

chmod +x “/home/[tu nombre de usuario]/.wine/drive_c/Program Files/Microsoft Visual Studio 8/VC/bin/link.exe”

chmod +x “/home/[tu nombre de usuario]/.wine/drive_c/Program Files/Microsoft Visual Studio 8/VC/bin/cl.exe”

PASO 7: Anhade variables necesarias de entorno para Visual C++:

En mi caso anhadi estas lineas a mi .bashrc (tienes que ponerlas cerca de las lineas donde esta definidos PATH, IMPORTANTE: no es anhadirlas al final).

gedit ~/.bashrc y copia y pega esto:

#This is for Visual C++ 2005
export MSVC=”c:/Program Files/Microsoft Visual Studio 8/VC/”
export MSSDK=”c:/Program Files/Microsoft Platform SDK for Windows Server 2003 R2/”
export INCLUDE=”c:/Program Files/Microsoft Visual Studio 8/VC/include:c:/Program Files/Microsoft\Platform SDK for Windows Server 2003 R2/Include”
export PATH=$PATH:”/home/[tu usuario]/.wine/drive_c/Program Files/Microsoft Visual Studio 8/VC/bin”
export LIB=”c:/Program Files/Microsoft Visual Studio 8/VC/lib” #:c:/Program Files/Microsoft Platform SDK for Windows Server 2003 R2/Lib”

alias clc=’cl.exe /c /I”c:/Program Files/Microsoft Visual Studio 8/VC/include” /I”c:/Program Files/Microsoft\Platform SDK for Windows Server 2003 R2/Include” /EHsc ‘

alias cll=’cl.exe /I”c:/Program Files/Microsoft Visual Studio 8/VC/include” /I”c:/Program Files/Microsoft\Platform SDK for Windows Server 2003 R2/Include” /EHsc ‘

Listo graba y sale. Cierra la consola y iniciala de nuevo.

Listo, ahora cuando quieras compilar un programa tipeas

$ cll myprograma.cpp /omyprograma.exe

Espero que les sea muy util.

Y aqui tienen el resultado de un programa compilando en Ubuntu Hardy :)

Compilando un programa con Visual C++ 2005 en Ubuntu Linux

Compilando un programa con Visual C++ 2005 en Ubuntu Linux

Y podemos ejecutar el programa directamente de la linea de comandos con: $wine miprograma.exe

La salida por ejemplo se ve aqui:

Ejecutando el programa con Wine y compilado con Visual C++ 2005

Ejecutando el programa con Wine y compilado con Visual C++ 2005

Si les interesa saber mas de las opciones de linea de cl.exe (el compilador) y link.exe (el enlazador) del Visual C++ 2005, aqui les dejo una tabla:

Para cl.exe:

     /Od
     /D "WIN32"
     /D "_DEBUG"
     /D "_WINDOWS"
     /D "_USE_MATH_DEFINES"
     /D "_CRT_SECURE_NO_DEPRECATE"
     /FD
     /MT
     /Fo"Debug\\"
     /Fd"Debug\vc80.pdb"
     /W2 /nologo
     /c
     /TP
     /errorReport:prompt

Para link.exe:

     /VERBOSE
     /OUT:"Debug\pipmak .exe"
     /INCREMENTAL
     /NOLOGO
     /LIBPATH:"D:\Projects\Lib"
     /LIBPATH:"D:\Projects\Microsoft Platform SDK\Lib"
     /MANIFEST
     /MANIFESTFILE:"Debug\pipmak .exe.intermediate.manifest"
     /NODEFAULTLIB
     /DEBUG
     /ASSEMBLYDEBUG
     /PDB:"d:\Projects\pipmak-SVN\Debug\pipmak .pdb"
     /SUBSYSTEM:WINDOWS
     /MACHINE:X86
     /ERRORREPORT:PROMPT
      vorbisfile_static_d.lib vorbis_static_d.lib ogg_static_d.lib zlib.lib
      physfs.lib opengl32.lib glu32.lib OpenAL32.lib
      SDL_ttf.lib SDL.lib SDLmain.lib SDL_image.lib
      oldnames.lib msvcrtd.lib libcmtd.lib lua50.lib
      kernel32.lib user32.lib gdi32.lib winspool.lib
      comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib

Espero que les sea util :)

Extraer el contenido de un archivo RPM sin instalar en Ubuntu

Muchas veces necesitamos extraer el contenido de un paquete de instalación de Linux llamados .rpm (de Redhat), en este caso es sufuciente aplicar un comando y podremos extraer todo el contenido del rpm sin necesidad de instalarlo en el sistema operativo.

El comando a utilizar es rpm2cpio que convierte los archivos .rpm en una salida simple de archivos.

Por ejemplo si tenemos ejemplo.rpm y aplicamos el comando:

rpm2cpio ejemplo.rpm | cpio -idmv

Nos extraera todo el contenido de ejemplo.rpm en el directorio en el cual se encuentre.

Notas:  Las opciones del comando rpm2cpio son:
i: Restaura el archivo.
d: Crea los directorios principales si fuese necesario.
m: Mantiene los archivos en el caso que los mismos ya existan.
v: Muestra el progreso.

Instalar LabView 8.5 en Ubuntu Hardy y posteriores

Labview proporciona un excelente ambiente grafico de programacion ademas de ser muy poderoso.

Por 20 años los cientificos han estado usando National Instruments LABVIEW,un poderoso ambiente de desarrollo gráfico, para la adquisición de señal, análisis de medición, y la presentación de los datos. LabVIEW también le proporciona la flexibilidad de un lenguaje de programación sin la complejidad de las herramientas de desarrollo tradicionales.

NI LabVIEW es un entorno abierto diseñado para hacer interfaz con cualquier hardware de medición simple. Con los asistentes interactivos, generación de código, y la conectividad a miles de dispositivos, LabVIEW hace que la recopilación de datos lo más simple posible.

Para muchos de nosotros este programa es una herramienta muy importante, pero que tal dejar a un lado windows y usarla en linux . En Linux Ubuntu funciona  a la perfeccion, (no se necesita serial ni licencia)

Labview 8.5 Para Linux

http://cid-db6787a7550c72af.skydrive.live.com/browse.aspx/Programas/LabView%20Linux%208.5
http://rapidshare.com/files/197035561/LV86LINUX.part2.rar

Se le puede encontrar tambien aqui: http://thepiratebay.org/torrent/4410831/LabVIEW_8.5_for_Linux

Labview 8.6 Para Linux

http://cid-db6787a7550c72af.skydrive.live.com/browse.aspx/Programas/LabView%20Linux%208.6

Ademas esta ultima version, incluyo mas paquetes para el desarrollo de sistemas de control como lo son los sistemas PID
Son 3 partes y los links estan aqui:
http://cid-db6787a7550c72af.skydrive.live.com/browse.aspx/Programas/LabView%20Linux%208.6/Control%20Desing%20and%20Simulation%20Module

Tambien esta disponible en Rapidshare:

Aqui estan los links:
http://rapidshare.com/files/197028153/LV86LINUX.part1.rar
http://rapidshare.com/files/197035561/LV86LINUX.part2.rar
http://rapidshare.com/files/197399537/LV86LINUX.part3.rar
http://rapidshare.com/files/197411128/LV86LINUX.part4.rar
http://rapidshare.com/files/197432644/LV86LINUX.part5.rar
http://rapidshare.com/files/197771359/LV86LINUX.part6.rar
http://rapidshare.com/files/197782647/LV86LINUX.part7.rar
http://rapidshare.com/files/197789684/LV86LINUX.part8.rar

Instalacion en Ubuntu Linux (Incluye soporte para AMD64):

Cuando se descarga los paquetes y descomprime generara varios archivos con extension .rpm (para Redhat).

Para poder instalarlo usaremos el siguiente comando:

$ su —-> con esta cambiamos a usuario root

$ rpm2cpio <paquete>.rpm | cpio -idvm

Esto debemos hacerlo paquete por paquete (uno por uno). Al final generara un directorio llamado /usr/local (esto dentro del directorio donde ejecutamos el comando anterior).

Ahora para tener buen orden copiaremos parte de este directorio a un directorio dentro de /opt (/opt es un buen directorio para instalar programas que no son parte del SO, es recomendable que /opt fuera incluso una particion separada, pero esto se debe haber hecho desde cuando se instalo el SO al comienzo).

$ mkdir /opt/labview

$ mv usr/local/natinst /opt/labview

$ mv usr/local/lib /opt/labview

$ exit (regresamos a nuestro usuario normal)

Ahora debemos anhadir Labview a nuestra variable de PATH.

$ cd ~

$ gedit .bashrc

Y modifica las variables PATH y LD_LIBRARY_PATH (anhade estas lineas cerca de donde esten declaradas)

Para LD_LIBRARY_PATH:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/labview/lib:/opt/labview/lib/LabVIEW-8.5

Para PATH:

export PATH=$PATH:/opt/labview/natinst/LabVIEW-8.5

Graba y sal. Luego cierra el terminal y empieza otro nuevo, puedes ahora tipear:

$ labview

Espero que les sea util. Muchos saludos.

Uso de los paquetes .diff.gz para compilar aplicaciones en Linux/Ubuntu

Fuente:

Uso de los ficheros *.diff.gz a la hora de compilar aplicaciones en GNU/Linux

Cuando nos disponemos a descargar paquetes de código fuente de alguna aplicación de los repositorios de Debian, nos percatamos de que nos ofrecen 3 tipos de ficheros distintos:

Paquete.orig.tar.gz -> Es el paquete de fuentes original (Como el autor lo creo, sin modificaciones).
Paquete.diff.gz -> Contiene las modificaciones realizadas por los mantenedores de Debian.
Paquete.dsc -> Fichero de información (Versión, Md5, Firma PGP,…).

No solo en Debian nos encontrarnos con este tipo de ficheros diff.gz, cuando queremos compilar algún software de otras distros podemos encontrarnos con ellos como vemos en la imagen, es algo muy común. Estos ficheros diff.gz añaden, modifican o eliminan cierto código en el paquete de fuentes, ya sea para permitir una compilación sin errores, tapar algún bug, aumentar la seguridad del código fuente, etc..

Esto de retocar los paquetes por parte del equipo Debian, es algo muy común, lo hacen otras distros también, en principio siempre se trata de mejoras, sobre todo en lo relativo a la seguridad, pero a veces no todo sale como se esperaba y en vez de mejorarlos se crean problemas de seguridad. Los paquetes .deb que instalamos al hacer uso de Apt / Aptitude vienen ya previamente parcheados.

Vamos a ver como se aplican estos parches diff.gz a los tarballs que necesitamos parchear, mostraremos un método, pero realmente se puede hacer de muchas y distintas maneras, supongamos que tenemos estos dos ficheros: paquete_0.2.1-2.diff.gz y paquete_0.2.1.orig.tar.gz, el parche lo podríamos aplicar así.

$ tar -zxvf ccze_0.2.1.orig.tar.gz
$ cd ccze-0.2.1/
$ zcat ../ccze_0.2.1-2.diff.gz | patch -p1

En pantalla se nos mostraran frases con “patching file XXXX”. Una vez parcheado podemos proceder a la compilación.

Optimizar el uso de bateria en Ubuntu

Fuente: http://onoametal.wordpress.com/2009/01/20/maximiza-el-consumo-de-energia-en-ubuntu/

Siempre ví como desventaja (por lo menos en mi caso) que cuando usaba mi portatil con Windows (gracias a Dios no lo volví a hacer) la batería me duraba alrededor de 2 horas, pero con Ubuntu escasamente llegaba a la hora y media. Pero existen varias herramientas que combinadas me dieron algo mas de dos horas de batería en Ubuntu, a continuación:

- Powertop

Es una herramienta que diagnostica y te da soluciones sobre esas cosas que hacen que tu equipo consuma mucha energía. Lo instalas con un sencillo

sudo apt-get install powertop

Lo ejecutas con

sudo powertop

Y llegarás a una ventana como esta, solo sigue las recomendaciones en pantalla

- Reducir el swap

Podemos reducir la cantidad de memoria swap que usa nuestro Ubuntu, siguiendo estos pasos:

Consultamos el valor inicial de swap

sudo cat /proc/sys/vm/swappiness

Si nos muestra 60, lo debemos cambiar a 10. Si ya dice 10, deja así…

sudo sysctl -w vm.swappiness=10

Lo probamos a ver que tal va, y si nos parece bien hacemos que el cambio sea definitivo abriendo el archivo

sudo gedit /etc/sysctl.conf

Y agregando esta línea al final

vm.swappiness=10

- Ubuntu Tweak

Este ya lo había explicado en otro post. Incluye herramientas de gestión de energía. Puede ser útil…

- Kpowersave

Es una herramienta de consumo de energía diseñada para entornos KDE (personalmente no recomiendo usarla en Ubuntu, pero si, en caso uses Kubuntu)

sudo apt-get install kpowersave

Y una vez hecho esto podemos configurar la gestión de energía según el portatil  este o no conectado a la corriente (por ejemplo, y entre muchas opciones)

NOTA IMPORTANTE (Por Abelardo): Hay un problema entre el script powertop de Intel y los scripts de administracion de bateria de Ubuntu (pm-utils).

Por defecto pm-utils sobreescribe los valores que powertop escribe. En particular tenemos el problema con que Powertop sugiere incrementar dirty writeback centisecs:

Suggestion: increase the VM dirty writeback time from 5.00 to 15 seconds with:
echo 1500 > /proc/sys/
vm/dirty_writeback_centisecs
This wakes the disk up less frequenty for background VM activity

Q – Quit R – Refresh W – Increase Writeback time

El problema es que aunque lo activamos, cuando reiniciamos Ubuntu vuelve a estar el valor anterior, para hacer permanente esta recomendacion, editamos:

$  sudo gedit /usr/lib/pm-utils/power.d/laptop-tools

Buscamos esta seccion:

echo “**SetLowPower OFF”
DISK_IDLE_SECS=0
DIRTY_WRITEBACK=500
DIRTY_EXPIRE=3000
DIRTY_RATIO=40
DIRTY_BACKGROUND_RATIO=10
setlowpowermode

Y cambiamos DIRTY_WRITEBACK=500 a DIRTY_WRITEBACK=1500

Grabamos y salimos. Listo, esto resuelve el problema.