NavegaciónBúsquedas |
Canales externosnarrowing buffer contents'Narrowing' is yet another of those many useful emacs features that took me years to appreciate, mostly because I never really tried it. I may not be the only one, so here's a short introduction. Narrowing is the concept of hiding the buffer contents except for what you are currently working on. This is useful when you don't want to be distracted, but also because it allows you to execute commands only on the narrowed part. You can narrow different things: what's shownnamebinding region (selection)narrow-to-regionC-x n n current pagenarrow-to-pageC-x n p functionnarrow-to-defunC-x n d everythingwidenC-x n wI never used narrowing for the current page, but apparently it's used by e.g. Info-Mode to show only one page. That last one is pretty important to remember; it's not totally obvious how to get back to 'normal' mode where you can see everything. For this very reason ('where the #>*$@ did my text go'), always-helpful emacs by defaults disables narrow-to-region (but, for some reason, not the other ones). To enable it, put the following in your .emacs: (put 'narrow-to-region 'disabled nil)Also note that the mode-line will show 'Narrow' when you're in narrow mode, lest you forget. When you're using org-mode there is an additional one you might want to memorize: what's shownnamebinding subtreeorg-narrow-to-subtreeC-x n sI'm using that last one quite often; I have org-files where I keep meeting notes etc., and when in a certain meeting, I only want to see the notes for that specific meeting. One bug? feature? of narrowing is that line-numbering is relative to the narrowed area rather than the full buffer. I'd prefer to have the real line numbers.
Categorías: Trucos y consejos Emacs
some handy key bindingsEmacs offers many handy key bindings; every now and then I come across a new one, which has been hiding there somewhere for a decade or more… Here are some of my favorites – I'm listing those that are (a) often useful, (b) might not be known by everyone already (c) don't require any external packages or setup.
What are your favorites? Please share them in the comments.
Categorías: Trucos y consejos Emacs
navigating through files and buffers with the lusty explorerI think quite a few people are using ido-mode to navigate through files an and buffers; we discussed it here already a long time ago. I am a happy ido-user myself – it took me some time to fully get full accustomed to the key bindings, but now it feels very natural. Definitely an improvement of my emacs user experience. However, I am always looking for new things – and one of those is a sort-of ido-mode substitute. It's called the Lusty Explorer and it's the emacs implementation of an existing vim-plugin. It's quite similar to ido-mode; the difference is mainly that it shows all the files or buffers at the same time, in the way that shells (say, bash or zsh) do auto-completion. The best way to show how it works is using an screencast (note, this is of a slightly older version). Lusty Explorer uses fuzzy matching; that means that I can type /etc/fo, and all items in /etc/ with names f.*o match. To install lusty-explorer, simply copy lusty-explorer.el to your load-path, and put something like the following in your .emacs:0 (when (require 'lusty-explorer nil 'noerror) ;; overrride the normal file-opening, buffer switching (global-set-key (kbd "C-x C-f") 'lusty-file-explorer) (global-set-key (kbd "C-x b") 'lusty-buffer-explorer))Side-note, the (when (require 'lusty-explorer nil 'noerror) ...) is there just make sure that no error is raised when lusty-explorer is not found, and the rest is ignored in that case. I use this construct for all packages that are not necessarily available everywhere I use my .emacs; thus, they will simply be ignored and not cause startup errors. I've been using Lusty Explorer for about a week now, and I am quite happy with it. I still need some time (and maybe some more customization) to get used to the way it works - for example, I found the way ido-mode handles backspace a bit smarter. Also, ido-mode can be customized to a much greater extent. That might merely be a factor of the relative age of the packages – and I haven't really felt the need to customize Lusty Explorer too much. For now, I think I'm going to keep on using it. It's worth a try at least!
Categorías: Trucos y consejos Emacs
keyboard macrosKeyboard macros are a truly classic emacs feature. Still, I only started to use them years after I got sucked into emacs – not so uncommon for emacs features… There may be more people like me, so let's raise the awareness a bit. Keyboard macros allow you to record a number of keystrokes, and replay those at some later point. This can be a great time-saver when you need to do repetitive things. In many cases, they are an easy alternative to writing some elisp to get a job done. Note, keyboard macros are should not be confused with elisp-macros, which are something else altogether. an exampleSo, when would we want to use a keyboard macro? Let's take some tedious task -- for example, we have a list of a few hundred names: Newton, Isaac Einstein, Albert Maxwell, James Turing, Alan ...and we want to turn that into: Isaac Newton James Maxwell Alan Turing ...so, roughly, put the last name after the first name, and remove the comma. We can solve this in different ways; we could simple change each line by hand. That's a fine solution if there are only a few lines, but it gets boring rather quickly. Another way is to use regular expressions (see Building regular expressions); in this case, it's fairly easy to come up with one (assuming you know regular expressions). But let's see how we can solve it with a keyboard macro. Schematically, we can solve this with the following: actionkey go to beginning of a lineC-a kill (cut) the first wordM-d delete the next two charactersDEL DEL go to the end of the lineC-e insert a spaceSPC yank (paste)C-y go to the next lineC-nThis may look like some magical incantation, but it comes quite natural when you are actually doing the editing. An important thing to remember when working with keyboard macros is that you do your commands in such a way that they can be repeated for each line. Suppose you would select Newton with shift-select, i.e., C-SPC at the beginning of the line and pressing the right arrow key 6 times – that works for Newton, but not for Einstein. Instead, we need to use M-d ('kill-word') instead. defining a macroNow that we have solved the problem for a single line, let's make a keyboard macro. We move the cursor to the first line, and start the definition by pressing C-x (, or alternatively, F3. Then, we press the commands C-a, M-d, DEL DEL, C-e, SPC, C-y, C-n (as in the list above). To finish the definition, press C-x ), (or F4). Hurray, we have our macro. Now, let's use it. using the macroNow, to execute the last defined macro, you press C-x e. We could repeat that for our whole list, but fortunately there's an easier way to repeat a macro n times, using a prefix argument. For example, to repeat the macro 123 times, you first press C-u 123 and then C-x e. There's a slightly shorter way to do this: instead of C-u 123 we can write M-123, and for C-x e we can use F4 (kmacro=end-or-call-macro). You can even repeat the macro until the end of the buffer is reached with C-u 0 C-x e; this only makes sense if the macros ever reaches the end of the buffer of course. (Remember that you can always terminate with C-g, keyboard-quit) You can also apply your keyboard macro to all lines in the selected area (region) with M-x apply-macro-to-region-lines (or C-x C-k r). Important to remember: this will actually move the cursor (point) to the start of each line, and then execute the macro. If you want your macro like that, the go-to-the-next-line should not be part of your macro, or you will be skipping lines. saving macros for later useIf you want to use multiple macros, you can name them. You can do this with M-x name-last-kbd-macro. If you name your macro, say, foo (inventive as we are), you can then execute it after that as M-x foo, which will be available until you exit emacs. If you want to have the macro for future emacs sessions as well, you can use insert-kbd-macro, which will give you an elisp version of your macro. For our example, this will look like: (fset 'foo [?\C-a ?\M-d delete delete ?\C-e ? ?\C-y ?\C-n])Not very readable, but we can put this in .emacs, and we can use it the next time we start emacs as well. We can also add a key binding for this, for example: (global-set-key (kbd "C-c f") 'foo)This will bind foo to C-c f. final notesKeyboard macros can be useful and easy, but they are fundamentally connected to key presses – so, if you remap your keys to something different, your macros may not work anymore. Also, the macros are pretty much write-only in the way we use them here. You can edit them in the macro editor though, with M-x edit-kbd-macro M-x foo; we'll then get something like: ;; Keyboard Macro Editor. Press C-c C-c to finish; press C-x k RET to cancel. ;; Original keys: C-a M-d 2*<delete> C-e SPC C-y C-n Command: foo Key: none Macro: C-a ;; move-beginning-of-line M-d ;; kill-word 2*<delete> ;; delete-char C-e ;; move-end-of-line SPC ;; self-insert-command C-y ;; yank C-n ;; next-lineKeyboard macros can be quite a useful trick in your arsenal. And I have not even gone into more advanced tricks like macros with variations or the macro ring. Please refer to the section Keyboard macros in the emacs manual (C-h r) for all the details. And, finally, don't let the text-based example limit your imagination – you can turn just about any repetitive sequence of tasks into a macro.
Categorías: Trucos y consejos Emacs
Org-mode: propiedades y columnasEn este articulo nos adentraremos un poco mas en org-mode, basicamente en que se pueden aplicar propiedades a distintas areas, que luego veremos que utilidad tiene. Para entender este post es necesario entender como trabajar con tablas en org-mode y como crear listas en org-mode (relacionadas o no con las tareas o TODO). Es posible asignar propiedades a columnas o elementos de una lista, estas propiedades tendran un valor (por eso son pares) por ejemplo: * Coleccion de CD Se puede definir una lista de posibles valores para una propiedad en particular, para ello se le debe anadir el sufijo _ALL al nombre de la propiedad. Esto tendra una consecuencia especial a nivel de herencia, que si se marca una entrada, se aplicara para el arbol entero. Ademas definiendo una lista de posibles valores permitira evitar errores a la hora de escribir, por ejemplo: * Coleccion de CD Para definir posibles valores para propiedades de forma global podemos hacerlo de la siguiente manera (o mediante la variable global org-global-properties): #+PROPERTY: NDisks_ALL 1 2 3 4 Los siguientes keybindings son usados para trabajar con propiedades:
Propiedades especiales Las propiedades especiales permiten acceder de forma alternativa a estas funcionalidades, por ejemplo: TODO : Tarea TODO de la entrada. Busqueda de propiedades Al crear estos arboles y listas especiales con una seleccion basada en propiedades podemos usar los siguientes keystrokes:
Herencia de propiedades Como bien dijimos anteriormente, si un padre tiene una propiedad determinada, su hijo la puede heredar. Por defecto esto esta deshabilitado, debido a que puede retardar bastante las busquedas, asi que si se quiere habilitar tendremos que configurar la variable org-use-property-inheritance. Ademas org tiene algunas propiedades hardcodeadas por defecto a nivel hereditario, que son: COLUMNS : Define el formato de la vista de la columna. Vista de columnas Mediante la vista de columnas podremos tener un modo comodo para ver y editar propiedades de una columna, donde cada nodo sera convertido en una fila tabulable. Por lo que podemos usar:
Podemos definir el formato de una columna para un solo fichero de la siguiente forma: #+COLUMNS: %25ITEM %TAGS %PRIORITY %TODO Para especificar que dicho formato solo se aplique a un arbol especifico deberiamos hacer algo asi: ** Alto del nodo para vista de columnas Los atributos que podemos conceder a las columnas se definen con la siguiente sintaxis: %[ancho]propiedad[(titulo)][{tipo_sumario}] Todos los elementos son opcionales a excepcion del simbolo % y el nombre de la propiedad: ancho un valor entero que indicara el ancho de la columna en caracteres. El siguiente ejemplo muestra que cada elemento tendra 25 caracteres de ancho como linea de cabecera, los siguientes especificardores tendran las columnas Dueno, Estado y Aprobados: :COLUMNS: %25ITEM %9Aprobados(Aprobados?){X} %Duenos %11Estado %10Tiempo_Estimado{:} %CLOCKSUM Podremos acceder a la vista de columnas usando los siguientes keystrokes: Para activar/desactivar:
Para editar valores:
Para modificar la estructura de la tabla:
La vista de columnas es tan solo un overlay sobre un buffer, por lo que este no puede ser exportado o impreso directamente, para ello debemos usar bloques dinamicos de vistas de columnas, tal que asi: * La vista de columna El bloque dinamico tiene los siguientes parametros: :id Es el identificador, que puede ser local, global, file:ruta-al-fichero o directamente el ID. Los siguientes comandos permiten insertar o actualizar un bloque dinamico:
Es posible anadir formulas a la columna de una vista de una tabla en caso de querer hacer plotting sobre la tabla, por lo que incluir #+TBBLFM: despues de la tabla, recalculara la tabla automaticamente despues de una actualizacion. Para mas informacion sobre la captura y proceso de valores de propiedades en una tabla es interesante ver el script org-collector.el, que provee una API para coleccionar propiedades de una entrada para un ambito concreto.
Categorías: Trucos y consejos Emacs
Org-mode : Graficas / trazas (plot)En el articulo anterior referente a spreadsheet u hojas de calculo, explicamos como es posible realizar hojas de calculo mediante org-mode de GNU/emacs. Como bien muchos saben, estas las hojas de calculo son datos tabulados en los que se pueden incluir referencias y demas, por lo que este software generalmente incluye lo que se llama plotting o traza de estos datos, o lo que es lo mismo realizar graficas haciendo uso de estos datos. GNU/emacs no es para menos, y tambien permite realizar lo mismo. He preferido separarlo en dos articulos (aunque este segundo me ha quedado algo corto), ya que en muchos casos no estamos para nada interesados en esta funcionalidad, pero si creo que es un aditivo a la funcionalidad anterior y esta estrechamente relacionada. Plot Se puede producir graficos en 2D y 3D mediante gnuplot, lo cual requiere de tener gnuplot y gnuplot-mode instalado. Se debe agregar a la primera linea de la tabla algo tal que asi (por ejemplo): #+PLOT: title:”foobar” ind:1 deps:(3) type:2d with:histograms set:”yrang [0:]“. Existen otras funciones para plot tal que: set: especifica cualquier opcion de gnuplot a ser modificada. Los resultados son excepcionales, podeis probarlos, podeis encontrar mas informacion dedicada al tema en: http://cars9.uchicago.edu/~ravel/software/gnuplot-mode.html tambien podeis encontrar informacion interesante sobre gnuplot en su web oficial.
Categorías: Trucos y consejos Emacs
Org-mode : spreadsheet (hojas de calculo)Y aqui estamos con un nuevo articulo sobre org-mode, como no, org-mode permite la creacion y uso de hojas de calculo (en ingles spreadsheet). Parece increible como un software que a simple vista parece tan simple, pueda llegar a tener tanta potencia, todo esto no seria posible sin el magnifico grupo de desarrolladores de org-mode y en general a la comunidad tan activa de GNU/emacs, sin mas dilacion comenzamos explicando el uso de referencias. Antes de comenzar, debe conocer un minimo el uso de tablas en org-mode, ya que las hojas de calculo se emplean mediante dicho uso, por lo que es necesario leer el articulo sobre Org-mode: tablas para poder aplicar luego hojas de calculo sobre el. Referencias Se puede referenciar un campo para computarlo con otros. Se puede referenciar dado su nombre, sus coordenadas absolutas o coordenadas relativas. Para saber las corrdenadas de un campo debemos presionar C-c ? que mostrar las coordenadas de dicho campo o bien C-c } que hara toggle de las coordenadas del grid. La notacion que usa org es @fila$columna, si es relativa debemos anadir + o - delante del numero. Tambien se puede especificar ‘I‘ para referirse a la primera linea, ‘II‘ a la segunda linea, ‘-I‘ a la (n)anterior linea o bien ‘III+2‘ para referirse al segundo dato de la tercera linea de la tabla. 0 se referira a la columna y fila actual. Existen referencias especiales como ‘$LR5‘ que pueden ser usadas para referirse al 5o campo de la ultma fila de la tabla. @2$3 -> 2a fila, 3a columna Rangos $1..$3 -> Los primeros 3 campos de la fila actual Referencias con nombre Se puede asignar un nombre a una referencia mediante la variable org-table-formula-constants, o localmente mediante el fichero de configuracion: #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6 Es posible usar referencias remotas mediante: remote(NAME-OR-ID,REF) Donde nombre es el nombre de la tabla dado por #+TBLNAME: NAME o su ID. REF es la direccion absoluta o rango de referencias valido en la tabla. Las formulas pueden ser usadas como expresiones algebraicas mediante el paquete calc de emacs (importante saber que usa convencion no estandar donde / tiene menos precedencia que *) mediante la funcion calc-eval se puede realizar esta evaluacion. Mediante org-calc-default-modes se usara el modo standard de calc (precision 12, unidades angulares graduales, fracciones y los modos simbolicos deshabilitados). p20 -> cambia la precision interna a 20 digitos Ademas se puede usar printf como especificador de formato para reformatear el resultado final: $1+$2 : suma el primero y el segundo campo Tambien se pueden contener expresiones logicas tales como: if($1<20,teen,string(“”)) : teen, si la edad de $1 es menor que 20, en cualquier otro caso vacio. Si lo que queremos es usar mas potencia podemos escribir formulas para la manipulacion de cadenas y el control de estrucutras tales como: Intercambia los primeros dos caracteres de la columna 1: Suma columnas 1 y 2, equivalnete a calc $1 y $2: Calcula la suma de las columnas 1 a 4: Para asignar una formula a un campo en particular, debe ir precedido por “:=“. Las formulas son guardadas en el formato especial con #+TBLFM: directamente debajo de la tabla. Ademas debemos usar el comando C-u C-c = si queremos insertar una nueva formula en el campo actual. Es frecuente usar la misma formula para todos los campos de una columna, esto es posible mediante TAB, INTRO o C-c C-c para pasar guardar la formula en la columna usada. Una vez se sale a la siguiente fila tan solo debemos pulsar C-c =, e insertara la nueva formula en la columna actual, reemplazandola por el resultado, tambien es posible usar prefijos para aplicarlo en muchas celdas consecutivas de la columna actual. Para editar y depurar (o debuggear) existe:
Cuando se evalua una forma que contiene errores se mostrara la cadena ‘#ERROR‘ para conocer que ocurrio en la substitucion de variables y calculos se puede emplear C-u C-u C-c = INTRO. Para actualizar la tabla se pueden emplear los siguientes comandos:
Existen otras funciones avanzadas con tablas como:
Las tablas especiales que comiencen con C-u C-c * solo afectara a filas marcadas por ‘#‘ y ‘*‘. Las marcas tienen los siguientes significados: ! : Define nombres para las columnas, por lo que es posible usar $nombre en lugar de $6. Basicamente este es el uso de hojas de calculo con emacs, aunque en el siguiente articulo anadire una funcionalidad interesante que sabiendo esto puedan crearse graficos sobre dichos datos.
Categorías: Trucos y consejos Emacs
console apps in emacs with multi-term
multi-term
updated Whenever it makes sense, I try to use emacs for my computer-based activities; surely, programs like The Gimp or a graphical web browser cannot yet be replace by emacs, but I'm making progress. I like the ways emacs gives me to automate and speed-up my tasks; I get some return-on-time-investment. 2010 or not, I still spend quite a bit of time on the console. So why not do that from within emacs? There different ways to run shells within emacs. The simplest one is shell (i.e,, M-x shell), which starts a simple shell, which does not support which does not support 'graphical' console applications, such as mutt, mc, htop. Then there are term and ansi-term (M-x ansi-term) that do support such applications, which ansi-term supporting colors as well (it seems to have become the default for term in recent emacs versions). Another one is the nifty EShell (included with emacs), which is not just a (simple) terminal, but also a full shell environment, and has integration with other things in emacs. It's nice, but has some of the limitations that shell has - you cannot run 'graphical' applications; also, I don't really need a shell, as I am quite happy with zsh (zed shell) already, which is more powerful, and I prefer a shell that works both inside and outside emacs. For all these reasons, I am using MultiTerm, which has 'graphical' support that ansi-term has, but adds a nice extra, namely support for multiple terminals within emacs. I'm not fully up to date with the exact difference in the terminal support between the two, but I haven't had any problems so far. You can install multi-term (put it in your load-path), and add the following to your .emacs: (autoload 'multi-term "multi-term" nil t) (autoload 'multi-term-next "multi-term" nil t) (setq multi-term-program "/bin/bash") ;; use bash ;; (setq multi-term-program "/bin/zsh") ;; or use zsh... ;; only needed if you use autopair (add-hook 'term-mode-hook #'(lambda () (setq autopair-dont-activate t))) (global-set-key (kbd "C-c t") 'multi-term-next) (global-set-key (kbd "C-c T") 'multi-term) ;; create a new oneWith this, C-c t will jump through your multi-term buffers (create a new one if it doesn not exist yet), while C-c T unconditionally creates a new terminal.
Categorías: Trucos y consejos Emacs
Org-mode : TAGS (etiquetas)Despues de un tiempo inactivo (unos 6 meses); algunos de ellos por estar viajando y sin conexion a Internet y otras veces por otras razones personales por fin vuelvo para continuar con este blog sobre GNU/Emacs, asi que pido disculpas a todos por este retraso y tiempo inactivo. Tambien quiero pedir disculpas debido a que los ultimos articulos necesitan ser revisados, ya que contienen frases que no son del todo entendibles o con algunos ejemplos poco claros, asi que intentare revisarlos lo antes posible. Por otro lado decir que hemos migrado a nuevos servidores de OVH (antes estaban en 1&1) con mejores servicios, asi pues, hemos instalado nuevas versiones de software mas modernas mas seguras y con mas funcionalidades. Gracias a |[TDP]| ya que ha cargado con la parte pesada y se ha encargado de todo ello. Sin mas dilacion, pasamos a la parte tecnica y especifica de GNU/Emacs, en el cual hablare de los TAGS (o etiquetas) en org-mode. Una forma de relacionar informacion cruzada es usar TAGS en las lineas de cabecera. Cada linea de cabecera contiene una lista de TAGS (que deben tener un formato alfanumerico o bien ‘-‘ o ‘_‘) por ejemplo: * Reunion con el grupo Frances :work: Herencia Para usar los TAGS definidos en un solo fichero podemos usar: #+FILETAGS: :Peter:Boss:Secret: Que ademas pueden usar herencia (o no) si se configuran las variables org-use-tag-inheritance y org-tags-exclude-from-inheritance. Cuando una linea de cabecera coincide durante una busqueda de TAGS y la herencia esta activada (o habilitada), todos los subniveles del mismo nivel heredaran este mismo TAG, por lo que esto puede provocar muchos resultados en algunos casos, asi que si solo se quiere encontrar la primera coincidencia en un subarbol podemos configurar la variable org-tags-match-list-sublevels (aunque esto no se recomienda segun la web oficial de org-mode). Creando TAGS Generalmente los TAGS se escriben a mano despues de la linea de cabecera, aunque despues de pulsar ‘:‘ podemos usar M-TAB para autocompletion de TAGS, ademas existen algunos keystrokes interesantes relacionados: C-c C-q ó C-c C-c : Crea TAGS para la linea de cabecera actual. Ademas despues de presionar INTRO el TAG sera alineado, pero con C-u INTRO todos los tags seran alineados respecto la variable org-tags-column. Org soporta insercion basada en listas de TAGS, para ello debemos especificar de forma global org-tag-alist con una lista de TAGS o bien para un fichero especifico mediante: #+TAGS: @work @home @tennisclub En el caso de que la lista sea dinamica usando la variable org-tag-alist debemos dejar la lista de TAGS en blanco tal que asi: #+TAGS: Podemos especificar una lista de TAGS en la variable org-tag-persistent-alist, lo que usara automaticamente en cada fichero dicha lista de TAGS, a excepcion de si se anade esta linea: #+STARTUP: noptag Existe ademas un metodo de seleccion de TAGS ultrarapido llamado fast tag selection, que permite deseleccionar y seleccionar TAGS simplemente presionando una tecla, por lo que deberemos asignar teclas unicas a cada TAG. Tambien se pueden configurar de forma global configurando la variable org-tag-alist en nuestro .emacs: (setq org-tag-alist ‘((“@work” . ?w) (“@home” . ?h) (“laptop” . ?l))) Se puede configurar de manera local (solo relevante para un fichero) de la siguiente forma: #+TAGS: @work(w) @home(h) @tennisclub(t) \n laptop(l) pc(p) Especificando ‘\n‘ comenzara una nueva linea despues de un TAG especifico, que seria lo equivalente a: #+TAGS: @work(w) @home(h) @tennisclub(t) Se pueden agrupar los TAGS mediante llaves, indicando asi que al menos uno de los 3 encerrado entre llaves debe ser seleccionado: #+TAGS: { @work(w) @home(h) @tennisclub(t) } laptop(l) pc(p) Para activar los cambios debemos pulsar C-c C-c. Es posible crear TAGS de exclusion mutua configurando la variable org-tags-alist: (setq org-tag-alist ‘((:startgroup . nil) Presionando C-c C-c y cualquier tecla de las siguientes:
Es posible modificar la variable org-fast-tag-selection-single-key para evitar tener que presionar INTRO para TAGS demasiado usados y asi tener el mismo efecto. Busqueda en tags Es posible extraer cierta informacion a partir de los TAGS. Por ejemplo:
Estos comandos se pueden usar para buscar empleando logica booleana como por ejemplo ‘+boss+urgent-project1‘ para encontrar todas las cabeceras de linea que tengan el TAG de ‘jefe’ y el de ‘urgente’ pero no para el ‘proyecto1′. Recordad que este articulo es interesante combinarlo con los anteriores referentes a org-mode (tablas, hiperenlaces y tareas). Al principio el uso de org-mode puede resultar algo complejo (sobretodo si no estamos habituados o no lo hemos estado al antiguo outline-mode) pero con un poco de practica, ignorando aquellos comandos que usemos con menos frecuencia y usando solo aquellos que mas nos interesen en cada momento, al final conseguiremos dominar este modo de manera mecanica.
Categorías: Trucos y consejos Emacs
automatic pairing of brackets and quotesSome text-editors, notably TextMate for MacOS, have a nice feature where inserting a opening ( will automatically insert the closing ), and put the cursor in between them (and does same for [], {}, and various quote-marks). Not surprisingly, there are some implementations for emacs as well; the best one I have found so far is called autopair, which was written by João Távora. It usually does things just right. Do things 'just right' is essential for such a tool; even small annoyances can disturb your flow. Autopair tries to do whatever makes the most sense for a given mode (programming language etc.), but it can be tuned as well. After installation, you can automatically activate it for all modes with (in your .emacs): (require 'autopair) (autopair-global-mode 1)Now, evaluate this or restart emacs, and enjoy the autopairing-magic! Except for autopairing, autopair also takes care of autocleaning; that is, if I press ( it turns that into () (the pairing part), and if I press Backspace then, it removes the whole () (the cleaning part). This makes things much less annoying if you type a pair by accident. Autopairing is the kind of thing that can get annoying quickly if it does not things exactly right – and autopair succeeds! Another nice trick it offers is autowrapping – that is, I select a word, press ", and automatically it's turned into "word". To enable that, you need to add the following: (setq autopair-autowrap t)Note: you might want to see the notes below about delete-selection-mode and cua-mode. Anyway, autopair with autowrap makes for a really smooth editing experience, I love it! There are two small issues for me though. First, when the cursor in front of some non-whitespace, I'd like autopairing not to happen, and second, somehow I can't seem to get "-autopairing to work in org-mode; of course, that could be my own fault. These things might be tunable; I haven't tried very hard yet. delete-selection-modeImportant to mention here is that autopair is (by default) not fully compatible with delete-selection-mode. As you may know, that is the mode that causes emacs to replace the current selection with a character typed, similar to what most other programs do. I think many people have it enabled in their .emacs with something like: (delete-selection-mode 1)If you want to keep on using that together with autopair, add the following to your .emacs: (put 'autopair-insert-opening 'delete-selection t) (put 'autopair-skip-close-maybe 'delete-selection t) (put 'autopair-insert-or-skip-quote 'delete-selection t) (put 'autopair-extra-insert-opening 'delete-selection t) (put 'autopair-extra-skip-close-maybe 'delete-selection t) (put 'autopair-backspace 'delete-selection 'supersede) (put 'autopair-newline 'delete-selection t)But, not that that still won't give you the autowrap behavior mentioned above. For that, we can use cua-mode. cua-modeWe discussed CUA-mode before, focusing on its nice rectangle-editing features. But CUA-mode can also be an alternative for delete-selection-mode, and it goes together more nicely with autopair; so, instead of delete-selection-mode and the put's, add the following to your .emacs: (setq cua-enable-cua-keys nil) ;; don't add C-x,C-c,C-v (cua-mode t) ;; for rectangles, CUA is niceSee the linked CUA-mode article for the 'why' of that first line. With this change, autopair should be working smoothly, including autowrap. further customizationAs I have hinted at, autopair can be tuned for different modes, and can differentiate between it's behaviour in literal strings, code, comments etc. The default are usually sane, but if you're interested, have a look at the documentation, in particular autopair-extra-pairs and the More tricks-section in the documentation.
Categorías: Trucos y consejos Emacs
worldcup games in your org-mode agendaA significant part of the world population will be watching the Football World Cup in South-Africa this month. For people who use org-mode to organize their lives, find the schedule of all the games in this message I sent to the org-mode mailing list. In order to have the games show up in your agenda, make sure the file is in your org-agenda-files. If needed, you could add it with something like in your org-mode settings: (add-to-list 'org-agenda-files "~/org/fifa-worldcup-2010.org")One small issue with the schedule is that it use the South-African times, and there is no automatic way to adjust times for the local time zone. As a work-around, Juan Pechiar provided the following function which makes it easy to update all org-timestamps in a file: (defun uphours (n) "update all timestamps n hours" (interactive "nAdd hours: ") (save-excursion (goto-char (point-min)) (while (re-search-forward "[[<]" nil t) (when (org-at-timestamp-p t) (org-timestamp-change n 'hour) ))))Evaluate this function (in emacs, put your cursor after the last ")"), then press C-x C-e. After that, you can go to the file with the world cup schedule, and give an M-x uphours, provide the offset for your timezone, compare to South-African time (positive or negative).
Categorías: Trucos y consejos Emacs
Go: El nuevo lenguaje de programación de Google
En google han dedicido que necesitamos otro "lenguaje de sistemas", y nos traen "Go". Go promueve la creación de sistemas y servidores como si fueran un conjunto de procesos que se comunican, llamados goroutines. Puedes arrancar miles de goroutines y olvidarte de los desbordamientos (stack overflows). Ha sido liberado con licencia BSD.
Categorías: Noticias generales
100th post
100
With that last post, emacs-fu reached the 100 posts milestone! Hurray! Thank you for all the support, it's been a great ride so far, and there's so much more to write about - if only there were 36 hours in a day. Anyway, to celebrate, I'll be off for the coming weeks (Korea), and I'm not sure if I have much time to blog from there. So, let's take this opportunity for a small reader poll: what would you be interested to read about? More programming-related stuff, more org-mode, more about integration with other programs, more interviews, more …? Please leave your ideas in the comments. I'd be interested to hear! Update: I am back now; thanks for all the replies. It seems that many people are interested in CEDET. In fact, I am interested in it myself as well, but am not using it right now, so it will take a while. For the time being, Alex Ott's Gentle Introduction might be the best way to get started.
Categorías: Trucos y consejos Emacs
zenburn for org-mode-generated htmlIf you read this blog directly, instead of through some aggregator or feed-reader, you can now see the code blocks rendered in the nice zenburn color theme that I discussed before. I'm really enjoying it, so I added some style sheet definitions, so org-mode #+BEGIN_SRC / #+END_SRC blocks look as such in the web page (and just like they look on my screen), for instance: (defun fibo (n) "calculate the Nth (N>=0) fibonacci number in a simple yet inefficient way" (cond ((= n 0) 0) ((= n 1) 1) (t (+ (fibo (- n 1)) (fibo (- n 2)))))) ;; now, gimme a list of fibo numbers 0..20 (mapcar 'fibo (number-sequence 0 20))Note, I discussed the use of such code blocks earlier; it's one of many nice features of org-mode. Only quite recently I found that I can press C-c ' in such a code block to edit them in a mode-specific little buffer… something new and obvious to learn every day. Anyhow, to get the nice zenburn-output in the generated HTML, you can use the following CSS (note, so far I have only done the code blocks): /* zenburnesque code blocks in for html-exported org mode */ pre.src { background: #3f3f3f; color: #dcdccc; } .org-preprocessor { color: #8cd0d3; } .org-preprocessor { color: #8cd0d3; } .org-variable-name { color: #f0dfaf; } .org-string { color: #cc9393; } .org-type { color: #dfdfbf; font-weight: bold; } .org-function-name { color: #8cd0d3; font-weight: bold; } .org-keyword { color: #f0dfaf; font-weight: bold; } .org-comment { color: #7f9f7f; } .org-doc { color: #afd8af; } .org-comment-delimiter { color: #708070; } .org-constant { color: #dca3ac; font-weight:bold; } .org-builtin { color: #7f9f7f; }You can save the above CSS-blob in a file (say, zenburn-code.css), and set the style sheet for the org-html export by putting a #+STYLE:-line in your org files: #+STYLE: <link rel="stylesheet" type="text/css" href="zenburn-code.css" />
Categorías: Trucos y consejos Emacs
emacs 23.2Recently, emacs version 23.2 was released. It's a quick update after 23.1 came out (July 29 of 2009); it seems Chong Yidong / Stefan Monnier (interview) are doing releases more often than before they took over emacs maintainership. A welcome change, I would say. The amount of changes is obviously also a bit smaller than in 23.1, but there are still some interesting updates. Let's go through a couple of those here; I am not striving for completeness, and I won't really go into the biggest change (inclusion of the CEDET IDE-framework), as I haven't been using that enough to say anything about it. Instead, let's look at some of the other highlights; for the full list of changes, please refer to the NEWS-file. If you have some other cool new feature that deserves mentioning, please add a comment. Some highlights
Summarizing, 23.2 provides us with some nice updates all around and brings CEDET to the masses. Chong Yidong / Stefan Monnier have done a very good job in making faster releases, while still keeping an eye on the quality. On the other hand, the previous version (23.1) is a very solid release, and if you don't need CEDET, there is no real need to hurry to 23.2. Future releasesA lot is happening in the world of GNU/Emacs, with changes being proposed and implemented in many different places. There's Eli Zaretskii's way work on making emacs support bidirectional languages (for right-to-left writing systems such as Hebrew and Arabic; the /bi/directional part is that one should be able to mix left-to-right and right-to-left). There is Jan Djärv's work on adding UI-tabs to emacs (like e.g. Firefox has them). There is Ken Raeburn and Andy Wingo's work on adding Guile Scheme support to emacs - possibly replacing the current Emacs Lisp implementation in the future. These are just a few of the more prominent projects. Nobody knows in which release these items will be available (if at all), but it's exciting to see all the directions people are taking emacs.
Categorías: Trucos y consejos Emacs
|