Blog de Abelardo Jara Berrocal: Ubuntu, electronica y software libre

Abril 5, 2009

Configurar EMACS con atajos de Windows (MODO CUA) y varios trucos utiles adicionales (plugins CEDET y SEMANTIC)

Archivado en: Linux Ubuntu Administracion, Linux Ubuntu Basico, Linux en general — Abelardo Jara @ 3:35 pm

Archivo:Emacs-screenshot.png

En los entornos UNIX, tenemos el famoso editor de textos EMACS. Realmente es sumamente potente y tiene una cantidad enorme de scripts que se le pueden instalar y que lo hacen muy potente.

Nota previa:

a. En EMACS se le llama tecla “Meta” a la tecla “Alt”

b. EMACS trabaja con el concepto de “frames” (marcos) y “windows” (ventanas). Los frames vienen a ser como PAGINAS, en cada pagina puedes tener varias ventanas abiertas.

Aqui te daremos un script para navegar rapidamente entre tus FRAMES (MARCOS) y tus WINDOWS (VENTANAS)

Primero vamos a instalarlo: (MUY IMPORTANTE)

$ sudo apt-get install emacs-snapshot-gtk semantic cedet*

Ojo muy importante: No instalen el paquete normal emacs, porque tiene problemas con las fuentes y no se ve bien. Les recomiendo mucho mas este paquete emacs-snapshot-gtk que se integra muy bien con Ubuntu.

Aqui comentare varios trucos que utilizo y que (al menos a mi punto de ver) lo hacen mucho mas comodo de utilizar:

1. Usar las teclas de atajo de los editores de Windows

Con esto nos referimos a usar Shift+<flechas de direccion> para seleccionar texto y Ctrl-C para copiar, Ctrl-V para pegar y Ctrl-X para cortar.

Bueno en las ultimas versiones de EMACS existe un modo de edicion llamado Cua-Mode, el cual utiliza las teclas rapidas de los editores de Windows dentro de EMACS. Los puristas diran que horror, jajaja, pero realmente se hace mucho mas comodo. Ademas no afecta las otras combinaciones de teclas de EMACS que empiezan con Ctrl-C o Ctrl-X porque Cua-Mode solo se activa cuando has seleccionado un texto. Para activar CUA mode, debes anhadir estas lineas a tu archivo .emacs

$ gedit .emacs (y anhade alli estas lineas)

;; Activate Cua mode, makes shortkeys to behave as windows

(cua-mode t)

(transient-mark-mode 1) ;; No region when it is not highlighted

(setq cua-keep-region-after-copy t) ;; Standard Windows behaviour

Ahora lo mas interesante es que este modo CUA te permite editar varias lineas de tu codigo (y todas a la vez :O)

Les presento este video:

Emacs Column Editing from Mark Mansour on Vimeo.

2. Problemas con la fuentes de Emacs

Ahora otro problema que es molesto en Emacs para Ubuntu, son las fuentes, para cambiarla debes crear en tu carpeta de usuario un archivo llamado .Xdefaults

Lo puedes hacer, entra a terminal y tipea:

$ gedit .Xdefaults

Y puedes tipear lo siguiente:

Emacs.font: Monospace-16

Emacs.FontBackend: xft

Como fuente puedes utilizar cualquiera de las que tienes instalada en tu Ubuntu

3. Hacerlo correr en consola:

Si lo deseas ejecutar en consola puedes anhadir este linea a tu archivo .bashrc. Inicias una terminal y tipeas

$ gedit .bashrc

Y busca las lineas donde esten definidos los “alias”. Anhade esta linea:

alias emacs=’emacs-snapshot-gtk’

Si quieres ejecutar en modo consola tipeas: (remueve -nw si lo quieres ejecutar normal en ventana)

$ emacs -nw myprograma.cpp (-nw es para indicar que se ejecute dentro del terminal, es muy util porque tiene un background oscuro, para descansar la vista para gente que programa mucho).

4. Mi archivo .emacs recopilado

Finalmente les dejo todo mi archivo .emacs. Ya tiene activado el modo CUA (asi que pueden copiar, pegar, cortar con las teclas de atajo de Windows), pero le he puesto varios trucos mas

CTRL+BARRA ESPACIADORA=> Empezar a marcar una seccion de texto (el mismo efecto que Shift mas flechas de cursor, el problema es que Shift+flechas no funciona en terminal puro, es decir si vas a Ctrl+Alt+F1) y este atajo si funcionara alli, los demas atajos de CUA mode si funcionan directos.

CTRL+L=> Ir a una linea especifica de tu programa, muy util para programadores

CTRL+G => Cancela el comando que estas haciendo (semejante a hacer un Esc en un editor Windows)

CTRL+F => Buscar una cadena de texto hacia adelante

CTRL+R => Busca texto para reemplazar

ALT+F => Buscar una cadena de texto hacia atras

CTRL+O => Abre un archivo

CTRL+S => Graba el archivo

CTRL+Q => Salir

CTRL+Z => Deshacer un cambio (undo)

ALT+<FLECHA ARRIBA> => Hace que la ventana que estas se haga una linea mas grande (es util para cuando estas compilando un programa y tienes tu programa en la ventana de arriba y la salida del compilador en la ventana de abajo)

ALT+<FLECHA ABAJO> => Igual que el anterior pero hace la ventana mas chica.

ALT+<PageDown> => Salta a la siguiente ventana, util para el caso que comentamos, tienes tu codigo en una ventana y la salida del compilador en la otra

ALT+<PageUp> => Igual que el anterior

F2 => Activa la ventana del administrador de archivos, muy util si estas trabajando en un directorio que contiene varios (multiples) archivos de codigo

F3 => Te creara un nuevo marco (FRAME) o pagina donde abrir ventanas, por defecto el marco se abre cargando el archivo inicial cargado en el primer marco.

Escape y despues presiona F3 => Cierra todos los marcos, excepto en el que estas

Control + Alt + <PageUp o PageDown> => Navega entre todos tus marcos (frames) que tienes abiertos. Puedes saber en que marco (frame) estas mirando a la izquierda en la barra de estado, dice la letra “Fx” donde x es el numero del marco.

F4 => Divide tu marco en 2 ventanas o mas VERTICALMENTE (util para editar 2 codigos a la vez).

Alt+<flecha a la derecha o flecha a la izquierda> => Navega entre las ventanas de tu marco actual

Escape y despues presiona F4 => Cierra todas las ventanas excepto en la que estas

F5 => Compilar tu programa, por defecto esta configurado como “make -f”, si tienes un Makefile pero si solo tienes un archivo de codigo, lo puedes reemplazar por “gcc miprograma.cpp -o miprograma”.

F7 => Establacer un bookmark (etiqueta). Establece etiquetas que seran usadas por la tecla anterior (F9), basta con poner el nombre de la etiqueta que se grabara en el archivo ~/.emacs.bmk.

F9 => Saltar a bookmark (etiqueta). Esta es una opcion muy util porque permite ponerle “etiquetas” a nuestro codigo que se salvan en el archivo ~/.emacs.bmk.

F12 => LLAMA A CORRECTOR ORTOGRAFICO, MUY UTIL

Ctrl+x 1 => Cierra todas tus ventanas excepto la que tienes actualmente activada editando.

Ctrl+x 2 => Divide la ventana en que estas trabajando en 2 ventanas separadas horizontalmente

Ctrl+x 3 => Divide la ventana en que estas trabajando en 2 ventanas separadas verticalmente

Y tienes otros scripts muy utiles ya listos:

Ctrl-C y luego Ctrl-B => “Beautify”, embellece tu codigo y arregla las tabulacions (muy estetico para programadores)

Alt-X y tipea “unix2dos” => remueve el caracter \n para que tu codigo quede en formato Linux/UNIX

Alt-X y tipea “dos2unix” => Anhade de vuelta el caracter \n  para que tu codigo quede en formato Windows

Alt-X es un atajo al modo “ejecutar”, aqui puedes ejecutar los scripts que tienes instalados en tu EMACS, para hacerlo tipeas “Alt-x” y luego tipeas el comando que quieres ejecutar, lo util es que tiene autocompletado, asi que tipeas una parte del comando y puedes presionar Tab para autocompletarlo.

Ademas estoy incluyendo el codigo para iniciar los plugins CEDET y SEMANTIC, que son para autocompletado de codigo y busqueda de la sintaxis de una funcion que estas tipeando en C/C++:

Para utilizar Semantic y CEDET te colocas sobre una palabra que su nombre es parte del nombre de una funcion y presionas estas teclas:

SHIFT+TAB => AUTOCOMPLETA LA PALABRA QUE ESTAS TIPEANDO, SUPER UTIL CUANDO PROGRAMAS PORQUE TAMBIEN TE EXPANDE LA FUNCION EN QUE ESTAS TRABAJANDO

Ctrl+c y luego presionas ? => busca la definicion de la funcion en todos los archivos de cabecera .h especificados en directorios de busqueda

Para anhadir esto edita tu archivo .emacs y puedes copiar el contenido del que uso:

;; -*- mode: emacs-lisp -*-
(add-to-list 'load-path "~/.emacs.d")

;; Set paper size
(if (or (string-match "XEmacs" emacs-version)
(string-match "20." emacs-version))
(setq ps-paper-type 'a4)
(setq ps-paper-type 'ps-a4))

;; 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)

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

;; 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)

; The above does not work on newer versions of XEmacs. Then, highjack
; Xemacs's zap-up-to-char function itself and force it to work as "undo".
(defun zap-up-to-char ()
(interactive)
(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"))

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

;; 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)

;; 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)))))

;; 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)

;; Save space
;(menu-bar-mode nil)

;; 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)

;; 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)

;; 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)

;; Highlight matching parentheses. Very useful for coding.
(show-paren-mode 1)

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

;; 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)

;; ===== Set the highlight current line minor mode =====

;; In every buffer, the line which contains the cursor will be fully
;; highlighted

(global-hl-line-mode 1)

;; ===== Set standard indent to 2 rather that 4 =======

(setq standard-indent 2)
; No sangra si estamos en literales
;(setq c-tab-always-indent "other")
; Espacios en vez de tabuladores
(setq-default indent-tabs-mode nil)

;; ========== Line by line scrolling ==================

;; This makes the buffer scroll by only a single line when the up or
;; down cursor keys push the cursor (tool-bar-mode) outside the
;; buffer. The standard emacs behaviour is to reposition the cursor in
;; the center of the screen, but this can make the scrolling confusing

(setq scroll-step 1)

;; ========== Support Wheel Mouse Scrolling ==========

(mouse-wheel-mode t)

;; ========== Prevent Emacs from making backup files ==========

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

;; ========== Enable Line and Column Numbering ==========

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

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

;; ===== 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))))

;;=============================================================================
;; * Set Variables & Rebind keys
;;=============================================================================
;; Commands to make my programming environment nice
(global-set-key "\C-l" 'goto-line) ; [Ctrl]-[L]

(global-set-key [f1] 'help-command)
;;(global-set-key [f2] 'undo)
(global-set-key [f2] 'speedbar-get-focus)
(global-set-key [f3] 'make-frame)
(define-key esc-map [f3]     'delete-other-frames)
(global-set-key [f4] 'split-window-horizontally)
(define-key esc-map [f4]     'delete-other-windows)
(global-set-key [f5] 'compile)
(global-set-key [f6] 'next-error)

(setq bookmark-save-flag 1)
(global-set-key [f7] 'bookmark-set)
(global-set-key [f8] 'bookmark-jump)
;(global-set-key [f12] 'nuke-line)
(global-set-key [f12] 'ispell-buffer)

(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 [M-prior]     'other-window)
(global-set-key [M-next]      'other-window)

(global-set-key [(control meta prior)]     'other-frame)
(global-set-key [(control meta next)]      'other-frame)

(global-set-key [M-up] 'enlarge-window)
(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)))

;;;=============================================
;; Smart Tab
;; =============================================
(defvar smart-tab-using-hippie-expand nil
"turn this on if you want to use hippie-expand completion.")
(define-key function-key-map [S-tab] [backtab])
(global-set-key [(backtab)] 'smart-tab)
(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 "\\_>")))

;==========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))

(when window-system
(require 'color-theme)
;;(load-file "~/.emacs.d/color-theme-blue.el")
(color-theme-euphoria)
)

;; ======================Modes for EMACs=========================

;; make text-mode default
(setq default-major-mode 'text-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)

;;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)

;;;VHDL-Mode
;   this variable is buffer local, you can set it for every vhdl-file
;   seperately by putting the following as first line in the vhdl-file:
;   -- -*- mode: vhdl; vhdl-compiler-options: \"-93 -work ../work -quiet\" -*-
(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))

(defvar vhdl-standard '(93 nil))
(defvar vhdl-clock-name "clk")
(defvar vhdl-reset-name "rst")

(defvar vhdl-file-header "\
-------------------------------------------------------------------------------
-- Title      : <title string>
-- Project    : <project>
-------------------------------------------------------------------------------
-- File       : <filename>
-- Author     : <author>
-- Company    : <company>
-- Created    : <date>
-- Last update: <date>
-- Platform   : <platform>
<projectdesc>-------------------------------------------------------------------------------
-- Description: <cursor>
<copyright>-------------------------------------------------------------------------------
-- Revisions  :
-- Date        Version  Author    Description
-- <date>  1.0      <login>  Created
-------------------------------------------------------------------------------

")

(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))))

;; =======Enable CEDET and semantic plugins=========
(require 'cedet)

;; smart completion
(require 'semantic-ia)
(require 'semantic-sb)
(require 'semanticdb)
(global-ede-mode t)

;; 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)

;; * This enables the database and idle reparse engines
(semantic-load-enable-minimum-features)

;; * This enables some tools useful for coding, such as summary mode
;;   imenu support, and the semantic navigator
(semantic-load-enable-code-helpers)

(global-semantic-idle-scheduler-mode 1)
(global-semantic-idle-completions-mode 1)
(global-semantic-idle-summary-mode 1)
(global-semantic-show-unmatched-syntax-mode -1)

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

;; customisation of modes
(defun my-cedet-hook ()
;;(local-set-key "\C-c/" 'semantic-ia-complete-symbol)
(local-set-key [backtab] 'semantic-ia-complete-symbol)
(local-set-key "\C-c?" 'semantic-ia-complete-symbol-menu)
(local-set-key "\C-c>" 'semantic-complete-analyze-inline)
(local-set-key "\C-c=" 'semantic-decoration-include-visit)
(local-set-key "\C-cj" 'semantic-ia-fast-jump)
(local-set-key "\C-cq" 'semantic-ia-show-doc)
(local-set-key "\C-cs" 'semantic-ia-show-summary)
(local-set-key "\C-cp" 'semantic-analyze-proto-impl-toggle)
)

(add-hook 'c-mode-common-hook 'my-cedet-hook)
(add-hook 'c++-mode-common-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))

(semantic-add-system-include "/usr/include" 'c-mode)
(semantic-add-system-include "/usr/include" 'c++-mode)
(semantic-add-system-include "/usr/include/c++/4.2" '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)

;;====Adding C/C++ templates hooked into C/C++ mode================================
;; 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 ()
(local-set-key [f11] 'tempo-complete-tag)))
(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 <" r ".h>" > 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)
" < "(p "upper bound: " ub)"; " (s var) "++)" >  n>
"{" > n
> r n
"}" > n>
)
"fori"
"Insert a C for loop: for(x = 0; x < ..; x++)"
'c-tempo-tags)

(tempo-define-template "c-main"
'(> "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)
;; =====================================================================
;; Latex improvements
(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)
))

(autoload 'reftex-mode    "reftex" "RefTeX Minor Mode" t)
(autoload 'turn-on-reftex "reftex" "RefTeX Minor Mode" t)

(add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
;  (add-hook 'latex-mode-hook 'turn-on-reftex)) ; with Emacs latex mode

(setq reftex-enable-partial-scans t)
(setq reftex-save-parse-info t)
(setq reftex-use-multiple-selection-buffers t)

;; To integrate with AUCTeX, use
(setq reftex-plug-into-AUCTeX t)
(setq LaTeX-mode-hook 'allman-latex-hook)

;;===================== Functions defined by user =============================
;;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")))

Aún no hay comentarios »

Aún no hay comentarios.

Canal RSS de los comentarios de la entrada. URI para TrackBack.

Deja un comentario

Blog de WordPress.com.