Posts tagged "emacs,":
Prot asks Carlos
Hace un par de días grabé con Protesilaos el primer vídeo de su serie "Prot asks". Es una serie de vídeos que se ha propuesto hacer en los que simplemente charla durante una hora con gente sobre cosas relacionadas con Emacs y con la vida en general.
En el vídeo que ha hecho conmigo hablamos sobre Emacs en la ingeniería, fútbol, España y la libertad de acceso a las publicaciones en el mundo académico, entre otras cosas.
El enlace al vídeo está aquí.
Writing on Emacs (Escribiendo en Emacs)
Nota: Este post tiene una versión en inglés para participar en el Emacs Carnival. La versión en castellano está tras la inglesa.
Writing on Emacs
Org-mode
Everything I write in Emacs I write it in org-mode. It's core is very simple, but is very powerful. At first, I used just the bullets to create hierarchical texts, but step by step I discovered all the things that org-mode can do.
Now I use it to track time, write journals, take notes, write blog posts…
Journal
I keep a register of what I do every day. For this, I just simply use an org template, and then, when I'm done, I encrypt the file just naming it with a .org.gpg extension and Emacs take care of the rest.
Notes
I use the org-roam package to take notes. Again, I use a template, but instead of writing everything to the same file as in the journal, org-roam is best suited to take short notes and then connect them, just like in the Zettelkasten method.
I can then search for my notes with org-roam-node-find, visualize a graph with org-roam-graph and do a lot of things.
Blog
For my blog I use org-blog-static. I write an org file, and when the post is finished I publish it with org-static-blog-publish. The process of publishing exports the org file to an html with the css that I have for my blog.
That's it, very simple, so that I can focus on writing.
Conclusion
Writing on Emacs is a very pleasant experience. With org-mode, I have all I need to write (links, export options, templates, organization) and with Emacs I have the keybindings to move through the text, the dictionary, and the same workflow that I have for the rest of things that are not writing.
Escribiendo en Emacs
Modo Org
Todo lo que escribo en Emacs lo hago con el modo Org. Su base es muy simple, pero aún así es muy potente. Empecé usando sólo lo básico, la estructura de asteriscos que tiene Org que te permite crear diferentes apartados dentro de un mismo archivo (sería lo análogo a crear una jerarquía tipo 1.2.3 pero sustituyendo los números por asteriscos), pero poco a poco fui descubriendo el resto de cosas que tiene este paquete de Emacs.
Ahora lo uso para prácticamente todo lo que sea escribir en Emacs: entradas de notas, archivos de blog, registros…
Diario
Llevo un registro diario de lo que hago cada día. Para automatizarlo, uso una plantilla de Org, y luego, cuando he terminado de escribirlo, lo guardo con extensión .org.gpg para que Emacs lo encripte.
Notas
Para tomar notas uso el paquete org-roam, con otra plantilla, sólo que esta vez está configurada para que cada nota la meta en un archivo distinto, y el paquete org-roam se encarga de crear enlaces entre los distintos archivos de forma sencilla.
Cuando he terminado le puedo echar un vistazo a mis notas con org-roam-node-find, o incluso crear un diagrama de bolas con org-roam-graph, para ver todas mis notas de un vistazo de forma gráfica.
Blog
Para el blog uso org-blog-static. Simplemente escribo un archivo .org normal, y luego lo publico con org-static-blog-publish. Al hacer la publicación, el archivo .org se convierte en .html y coge el css que tengo para mi blog.
Es todo muy sencillo, así me puedo centrar en escribir sin preocuparme de nada más.
Conclusión
Escribir en Emacs es muy agradable. Con el modo Org, tengo todo lo que necesito (enlaces, exportación a otros formatos, plantillas, organización…) y con Emacs tengo los atajos de teclado que me permiten editar texto fácilmente, además de las demás facilidades que proporciona Emacs.
Take two on Emacs (Toma dos de Emacs)
Nota: Este post tiene una versión en inglés para participar en el "Emacs Carnival" (https://christiantietze.de/posts/2025/06/emacs-carnival-2025-06-take-two/
). La versión en castellano está tras la inglesa.
Take Two on Emacs
I first discovered Emacs back at middle school, because it was installed on the school's computers. I have no idea what Emacs was, and the description on the splash screen wasn't really helpful for me.
I find it weird, the mouse experience was not smooth, and every time I wanted to closed it, it said something about "modified buffers". What is a buffer? Why was it modified if I hadn't not touched anything?
It wasn't until several years later, in a conference that Richard Stallman gave in Seville, that I discovered what Emacs was. I was then decided to try again Emacs, and find out whether it was worth it or not.
I really didn't like that you have to learn yet another programming language to really dive into Emacs, but when I discovered Emacs Lisp I was really impressed. Today is one of my favorite computer languages, and it is really a pleasure to play with Elisp.
My first steps with Emacs were magical. When I started the tutorial and scrolled to the next screen with C-v I discovered a whole new world. From there, the omnipresence of the terminal and keyboard-driven UI was born for me. I no longer looked backwards. I moved from a normal desktop environment to a tiling window manager (i3wm), and hopefully some day I will move into EXWM, if only to try it when I have time.
I struggle a little bit to become a proficient Emacs user. At first I saw all the wonderful Planet Emacs posts, but I didn't even know how to install packages or try the things the different posts explained.
But after reading the fine manual (and also after discovering info, which is now my favorite program to read manuals) a little bit, I started to grow confidence and started to understand the language in which the "Emacs people" talk.
From that point, the rest was very enjoyable, and I am still a noob in the Emacs world but I learn a little every day, and now I use Emacs for almost everything.
Toma dos de Emacs
Descubrí Emacs en el instituto, porque era parte de la distribución de Guadalinex que tenían todos los ordenadores. Cuando lo abrí por primera vez no tenía ni idea de qué era, simplemente vi un icono que no sabía qué era en el menú de aplicaciones y pinché sobre él.
Me pareció bastante feo a primera vista, además el ratón no funcionaba como yo esperaba, y encima cada vez que lo quería cerrar me decía algo de "existen búfers modificados". Pero yo no tenía ni idea de qué era un búfer y además ni siquiera había modificado nada, ¿por qué salía esa advertencia?
Hasta varios años después, en una conferencia de Richard Stallman en la Escuela Técnica Superior de Ingeniería Informática de Sevilla, no descubrí realmente qué era Emacs. Después de la magistral charla de Stallman decidí que tenía que probarlo y ver si realmente merecía la pena.
No me gustó lo de tener que aprender otro lenguaje de programación más para poder sacarle todo el partido a Emacs, pero cuando descubrí Emacs Lisp me quedé alucinado. Hoy es uno de mis lenguajes de programación favoritos, y es una experiencia muy placentera jugar con Elisp.
Mis primeros pasos con Emacs fueron algo mágico. Cuando empecé el tutorial integrado y pasé a la siguiente pantalla con C-v algo dentro de mi cabeza hizo clic, y a partir de ahí mi visión sobre la informática cambió. Empecé a hacerlo todo con la terminal y a manejar el ordenador casi exclusivamente con el teclado. Nunca más volví a usar interfaces gráficas como opción predeterminada. Pasé de usar un entorno de escritorio normal y corriente a un gestor de ventanas tipo i3wm, y espero algún día tener tiempo de probar EXWM.
Me costó un poco aprender a ser un usuario en condiciones de Emacs. Al principio veía los posts de webs como https://planet.emacslife.com/
y no entendía nada, no sabía cómo aplicar las configuraciones que ponía la gente o cómo probar los consejos que daban.
Pero después de leer el manual un poco (y de paso descubrir info, mi forma favorita de ver manuales), empecé a soltarme más y a entender la jerga de Emacs en la que hablan los que lo usan.
A partir de ahí, como ya tenía la base, aprender el resto ya fue mucho más divertido, y, aunque sigo siendo un principiante en el mundo de Emacs, ya lo uso casi para todo.
Calendarios en pdf
En Emacs hay varias formas de organizar las tareas usando
calendarios. Por un lado está el calendario ya integrado (M-x
calendar
), en el que podemos señalar fechas con ayuda de un fichero
de texto que hace de diario. Por otro lado está el calendario que nos
crea la org-agenda
, el cual podremos visualizar en forma de calendario
con el paquete cfw:calendar
.
Sin embargo, a la hora de exportar a pdf un calendario para
imprimirlo, la mejor opción que he descubierto es el comando "t m" una
vez dentro del calendario integrado que se invoca con M-x calendar
(también está la opción H m para exportar a html).
Una vez exportado el calendario, podemos usar el comando C-c C-b
dentro del archivo .tex exportado, y esto nos generará un archivo
.dvi. Con la orden dvi2pdf podemos convertir finalmente el .dvi a pdf
para después imprimirlo.
Según el manual de Emacs, también se puede exportar el calendario de la org-agenda pero el proceso parece bastante más complicado.
Antes de exportar el calendario, sobre el mismo archivo .tex, podemos modificar las diferentes fechas para incluir los eventos que queramos. De momento no he encontrado la forma de incluir los eventos del archivo diario para integrarlos automáticamente, pero si no son muchos no es difícil hacerlo a mano.
Calendario para la org-agenda
La agenda del org-mode de Emacs muestra por defecto una lista diaria,
semanal o mensual de las citas o tareas que tengamos en nuestro
archivo de agenda. Sin embargo no tiene una vista tipo calendario por
defecto. Para ello se puede usar el paquete calfw-org
, disponible en
MELPA.
Después de instalarlo sólo hay que cargarlo con (require 'calfw-org)
y ejecutar la orden M-x cfw:open-org-calendar
para ver nuestra
agenda en formato calendario.
Además, aprovechando que el x270 que tengo tiene pantalla táctil he decidido probar a asignarle esta orden a un toque de la pantalla para que aparezca la agenda en modo calendario.
Para la asignación en vez de código he usado Embark. Una vez abierto
el menú de Emacs con M-x
, y estando sobre la orden
cfw:open-org-calendar
, invoco Embark con C-.
y luego pulso g
para asignar un atajo de teclado global. Después pulso la pantalla y
ya tengo configurado todo para poder ver mi agenda al toque.
Tablas en org-mode
En el modo Org de Emacs se pueden hacer muchísimas cosas, y una de ellas es la creación de tablas. Sin embargo, al exportarlas, por defecto se omiten las separaciones verticales entre columnas, según el manual por claridad visual.
En mi caso prefiero tener separación vertical entre cada columna, así
que miré el manual para ver cómo solucionarlo. Hay que insertar una
fila vacía con el carácter de control /
y luego un carácter menor
que seguido de uno mayor que <>
en cada columna de la tabla.
Ahora al exportar el archivo .org
a html o pdf ya tendremos nuestra
tabla correctamente formateada.
2FA en Eshell
Ahora que la universidad pide el código de verificación en dos pasos hasta para respirar, decidí hacer una función en Eshell que me facilitara la obtención de dicho código.
Tenía una función básica, que no recuerdo dónde la saqué, pero requería tener un búfer de Eshell en segundo plano para que funcionara.
(defun eshell2fa () (interactive) "Devuelve el id del 2FA en el portapapeles." (with-current-buffer "*eshell*" (eshell-return-to-prompt) (insert "id > /dev/kill") (eshell-send-input)) )
La línea del insert
es la que se encarga de obtener la clave a
través del alias id
, que usa oathtool
para obtener el
código. Luego se redirige al portapapeles con > /dev/kill
.
El alias se define de la siguiente forma:
alias id oathtool --counter=30 --totp=SHA1 -d 6 -b "clave-de-2FA"
Para mejorarla he añadido una línea que crea el búfer de Eshell si no
ha sido creado anteriormente, con un unless
(defun eshell2fa () (interactive) "Devuelve el id del 2FA en el portapapeles." (unless (gnus-buffer-live-p "*eshell*") (eshell) (switch-to-prev-buffer)) (with-current-buffer "*eshell*" (eshell-return-to-prompt) (insert "id > /dev/kill") (eshell-send-input)) )
Y luego sólo queda asignarla (por ejemplo a f12
) para poder tener el
código pulsando un botón.
(global-set-key (kbd "<f12>") 'eshell2fa)
VHDL en Emacs
Emacs tiene un modo para programar en VHDL sin necesidad de instalar paquetes externos, pero como además quería tener un corrector de sintaxis, estuve mirando algunas soluciones.
Decidí instalar Flycheck, y lo configuré según la web de forma muy
sencilla. Lo que más me costó fue dar con el motor para comprobar la
sintaxis, pero al final lo único que hay que instalar es ghdl (en
Debian viene en los repositorios). Una vez instalado y activado el
modo con M-x flycheck-mode
, seleccioné el motor de sintaxis en un
búfer con el modo VHDL pulsando C-c ! v
.
Por último me instalé el paquete Perspective para poder tener todo lo relacionado con VHDL en un espacio de trabajo aparte, y que no se mezcle con el resto de mis búferes de Emacs.
En menos de 5 minutos ya tenía todo funcionando, y así evito tener que usar el horrible editor de texto de ISE, el entorno propietario para programar FPGAs de Xilinx.
Temporizador
Ayer estaba en el césped de la Escuela en un tiempo muerto entre clases y se me ocurrió practicar un poco con el cubo 3x3 que tengo (un Yuxin Little Magic magnético, si no recuerdo mal), cronometrando mis tiempos.
Pero desde hace un tiempo no consigo que me funcione la red de la universidad, y, como hace relativamente poco que me instalé Debian 12 en mi Thinkpad X230, no tenía ningún programa para cronometrar el tiempo que tardo en hacer el cubo.
Miré el manual de Elisp, pero los temporizadores que hay sólo llegan a precisión de segundos, y yo necesitaba hasta las centésimas de segundo. Recordé que en informática de cuarto dimos temporizadores POSIX, pero no tenía ganas de ponerme a hacer un programa en C y tener que mirarme el estándar sólo para hacer un pequeño programa.
Me acordé de que existe un programa en GNU/Linux que se llama time
,
que cronometra el tiempo que tarda en ejecutarse un comando. Estuve
mirando entre los programas en C que tenía de informática hechos por
el profesor, y había uno que se llamaba pierde_tiempo.c
.
El programa es tan sólo un bucle infinito, y sirve para demostrar el
funcionamiento de los hilos y los procesos en C + POSIX. Pero lo
interesante es que al combinarlo con time puedo saber con precisión
de milésimas de segundo cuánto tiempo ha estado ejecutándose el
programa hasta que lo pare con C-c
.
Así, con una sola línea en la terminal, improvisé un cronómetro casero
para poder cronometrarme con una precisión de centésimas de
segundo. Añadí una macro de Emacs para poder pausar el programa con
F12 y no perder tiempo pulsando C-c
, y ya tenía todo listo, y sin
usar internet en ningún momento.
Tetris
Introducción
Últimamente le he echado muchas horas al Tetris 99 en la Switch, y, aunque parezca mentira, las distintas versiones del Tetris que existen en el mundo pueden llegar a ser muy diferentes. Hay incluso una serie de normas estándar para poder homogeneizar los distintos juegos.
En Emacs hay una implementación del Tetris (tetris.el
), pero le
falta la mecánica de reservar una pieza y algunos pequeños detalles
para que se parezca más al resto de versiones.
Configurando tetris.el
En primer lugar, tocando opciones de tetris.el
se puede hacer que la
generación de piezas sea tal que nunca se puedan repetir las piezas
más de dos veces (se van creando bolsas de 7 piezas).
Desactivando la opción de permitir repeticiones de piezas tenemos ya un generador de piezas aleatorio estándar.
(setq tetris-allow-repetitions nil)
Los colores de las piezas también siguen un estándar.
;;Shape 1 (O) Yellow ;;Shape 2 (L) Orange ;;Shape 3 (J) Dark blue ;;Shape 4 (S) Green ;;Shape 5 (Z) Red ;;Shape 6 (T) Magenta ;;Shape 7 (I) Light blue (setq tetris-x-colors [[1 1 0] [1 0.27 0] [0 0 0.55] [1 0 0] [0 1 0] [1 0 1] [0 0.86 0.9]] )
Con estos dos cambios podemos usar el tetris.el
de Emacs y jugar con
los colores estándar y la generación de piezas, pero queda por
implementar la funcionalidad de reservar piezas.
Reservar piezas
Como quiero aprender Emacs Lisp y poder jugar al Tetris en Emacs con la reserva de piezas, he improvisado sobre la marcha una solución chapucera y rápida para poder jugar a mi manera.
Funciones modificadas
Lamentablemente ni la librería que usa tetris.el
(gamegrid.el
), ni
el propio tetris.el
están bien documentados. Así que me miré el
código por encima, y con ayuda de una explicación de la librería que
encontré en internet, me puse a toquetear cosas hasta conseguir lo que
quería.
En primer lugar, estuve probando funciones que cogí del código y las fui probando y modificando en el búfer de Scratch para que fueran haciendo lo que quería.
(defun tetris-hold-shape () "Con esta función se puede dibujar una pieza cualquiera por la cara en el tetris. Pones setq tetris-shape al número de la pieza que quieras y listo." (interactive) (setq tetris-next-holded-piece tetris-shape) (setq tetris-shape tetris-holded-piece) (setq tetris-rot 0) (setq tetris-next-shape (if tetris-allow-repetitions (random 7) (tetris--seven-bag))) (setq tetris-pos-x (/ (- tetris-width (tetris-shape-width)) 2)) (setq tetris-pos-y 0) (if (tetris-test-shape) (tetris-end-game) (tetris-draw-shape) (tetris-draw-next-shape) (tetris-update-score)) (setq tetris-holded-piece tetris-next-holded-piece)) (defun tetris-erase-shape () "Con esta función se puede eliminar una pieza cualquiera del juego." (interactive) (dotimes (i 4) (let ((c (tetris-get-shape-cell i))) (gamegrid-set-cell (+ tetris-top-left-x tetris-pos-x (aref c 0)) (+ tetris-top-left-y tetris-pos-y (aref c 1)) tetris-blank)))) (defun tetris-reserva() "Función para implementar la reserva de piezas en el tetris." (interactive) (progn (tetris-erase-shape) (tetris-hold-shape) (tetris-update-score) ) ) (global-set-key (kbd "C-ñ") 'tetris-reserva) ;;Shape 0 (O) Yellow ;;Shape 1 (L) Orange ;;Shape 2 (J) Dark Blue ;;Shape 3 (S) Green ;;Shape 4 (Z) Red ;;Shape 5 (T) Magenta ;;Shape 6 (I) Light Blue
Estuve probando cómo se ponen y se quitan piezas y luego hice una función más simple que hacía todo lo necesario para implementar la mecánica de reserva.
Modificación del archivo tetris.el
Además, cogí el código original, y lo copié en otro archivo,
mitetris.el
, y sobre este archivo definí algunas nuevas variables y
creé la "previsualización" en ASCII de la pieza en reserva, ya que era
lo más rápido.
;;; etris.el ---implementation of Tetris for Emacs -*- lexical-binding:t -*- ;; Copyright (C) 1997, 2001-2024 Free Software Foundation, Inc. ;; Author: Glynn Clements <glynn@sensei.co.uk> ;; Old-Version: 2.01 ;; Created: 1997-08-13 ;; Keywords: games ;; This file is part of GNU Emacs. ;; GNU Emacs 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 3 of the License, or ;; (at your option) any later version. ;; GNU Emacs 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>. ;;; Commentary: ;;; Code: (eval-when-compile (require 'cl-lib)) (require 'gamegrid) ;; ;;;;;;;;;;;;; customization variables ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgroup tetris nil "Play a game of Tetris." :prefix "tetris-" :group 'games) (defcustom tetris-use-glyphs t "Non-nil means use glyphs when available." :type 'boolean) (defcustom tetris-use-color t "Non-nil means use color when available." :type 'boolean) (defcustom tetris-draw-border-with-glyphs t "Non-nil means draw a border even when using glyphs." :type 'boolean) (defcustom tetris-default-tick-period 0.3 "The default time taken for a shape to drop one row." :type 'number) (defcustom tetris-update-speed-function 'tetris-default-update-speed-function "Function run whenever the Tetris score changes. Called with two arguments: (SHAPES ROWS) SHAPES is the number of shapes which have been dropped. ROWS is the number of rows which have been completed. If the return value is a number, it is used as the timer period." :type 'function) (defcustom tetris-mode-hook nil "Hook run upon starting Tetris." :type 'hook) (defcustom tetris-tty-colors ["blue" "white" "yellow" "magenta" "cyan" "green" "red"] "Vector of colors of the various shapes in text mode." :type '(vector (color :tag "Shape 1") (color :tag "Shape 2") (color :tag "Shape 3") (color :tag "Shape 4") (color :tag "Shape 5") (color :tag "Shape 6") (color :tag "Shape 7"))) (defcustom tetris-x-colors [[0 0 1] [0.7 0 1] [1 1 0] [1 0 1] [0 1 1] [0 1 0] [1 0 0]] "Vector of RGB colors of the various shapes." :type '(vector (vector :tag "Shape 1" number number number) (vector :tag "Shape 2" number number number) (vector :tag "Shape 3" number number number) (vector :tag "Shape 4" number number number) (vector :tag "Shape 5" number number number) (vector :tag "Shape 6" number number number) (vector :tag "Shape 7" number number number))) (defcustom tetris-buffer-name "*Tetris*" "Name used for Tetris buffer." :type 'string) (defcustom tetris-buffer-width 30 "Width of used portion of buffer." :type 'natnum) (defcustom tetris-buffer-height 22 "Height of used portion of buffer." :type 'natnum) (defcustom tetris-width 10 "Width of playing area." :type 'natnum) (defcustom tetris-height 20 "Height of playing area." :type 'natnum) (defcustom tetris-top-left-x 3 "X position of top left of playing area." :type 'natnum) (defcustom tetris-top-left-y 1 "Y position of top left of playing area." :type 'natnum) (defcustom tetris-allow-repetitions t "If non-nil, use a random selection for each shape. If nil, put the shapes into a bag and select without putting back (until empty, when the bag is repopulated." :type 'boolean :version "29.1") (defvar tetris-next-x (+ (* 2 tetris-top-left-x) tetris-width) "X position of next shape.") (defvar tetris-next-y tetris-top-left-y "Y position of next shape.") (defvar tetris-score-x tetris-next-x "X position of score.") (defvar tetris-score-y (+ tetris-next-y 6) "Y position of score.") ;; It is not safe to put this in /tmp. ;; Someone could make a symlink in /tmp ;; pointing to a file you don't want to clobber. (defvar tetris-score-file "tetris-scores" ;; anybody with a well-connected server want to host this? ;(defvar tetris-score-file "/anonymous@ftp.pgt.com:/pub/cgw/tetris-scores" "File for holding high scores.") ;; ;;;;;;;;;;;;; display options ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar tetris-blank-options '(((glyph colorize) (t ?\040)) ((color-x color-x) (mono-x grid-x) (color-tty color-tty)) (((glyph color-x) [0 0 0]) (color-tty "black")))) (defvar tetris-cell-options '(((glyph colorize) (emacs-tty ?O) (t ?\040)) ((color-x color-x) (mono-x mono-x) (color-tty color-tty) (mono-tty mono-tty)) ;; color information is taken from tetris-x-colors and tetris-tty-colors )) (defvar tetris-border-options '(((glyph colorize) (t ?\+)) ((color-x color-x) (mono-x grid-x) (color-tty color-tty)) (((glyph color-x) [0.5 0.5 0.5]) (color-tty "white")))) (defvar tetris-space-options '(((t ?\040)) nil nil)) ;; ;;;;;;;;;;;;; constants ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defconst tetris-shapes [[[[0 0] [1 0] [0 1] [1 1]]] [[[0 0] [1 0] [2 0] [2 1]] [[1 -1] [1 0] [1 1] [0 1]] [[0 -1] [0 0] [1 0] [2 0]] [[1 -1] [2 -1] [1 0] [1 1]]] [[[0 0] [1 0] [2 0] [0 1]] [[0 -1] [1 -1] [1 0] [1 1]] [[2 -1] [0 0] [1 0] [2 0]] [[1 -1] [1 0] [1 1] [2 1]]] [[[0 0] [1 0] [1 1] [2 1]] [[1 0] [0 1] [1 1] [0 2]]] [[[1 0] [2 0] [0 1] [1 1]] [[0 0] [0 1] [1 1] [1 2]]] [[[1 0] [0 1] [1 1] [2 1]] [[1 0] [1 1] [2 1] [1 2]] [[0 1] [1 1] [2 1] [1 2]] [[1 0] [0 1] [1 1] [1 2]]] [[[0 0] [1 0] [2 0] [3 0]] [[1 -1] [1 0] [1 1] [1 2]]]] "Each shape is described by a vector that contains the coordinates of each one of its four blocks.") ;;the scoring rules were taken from "xtetris". Blocks score differently ;;depending on their rotation (defconst tetris-shape-scores [[6] [6 7 6 7] [6 7 6 7] [6 7] [6 7] [5 5 6 5] [5 8]] ) (defconst tetris-shape-dimensions [[2 2] [3 2] [3 2] [3 2] [3 2] [3 2] [4 1]]) (defconst tetris-blank 7) (defconst tetris-border 8) (defconst tetris-space 9) (defun tetris-default-update-speed-function (_shapes rows) (/ 20.0 (+ 50.0 rows))) ;; ;;;;;;;;;;;;; variables ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar-local tetris-shape 0) (defvar-local tetris-rot 0) (defvar-local tetris-next-shape 0) (defvar-local tetris-n-shapes 0) (defvar-local tetris-n-rows 0) (defvar-local tetris-score 0) (defvar-local tetris-pos-x 0) (defvar-local tetris-pos-y 0) (defvar-local tetris-paused nil) (defvar-local tetris--bag nil) ;; ;;;;;;;;;;;;; keymaps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar-keymap tetris-mode-map :doc "Keymap for Tetris games." :name 'tetris-mode-map "n" #'tetris-start-game "q" #'tetris-end-game "p" #'tetris-pause-game "SPC" #'tetris-move-bottom "<left>" #'tetris-move-left "<right>" #'tetris-move-right "<up>" #'tetris-rotate-prev "<down>" #'tetris-move-down) (defvar-keymap tetris-null-map :doc "Keymap for finished Tetris games." :name 'tetris-null-map "n" #'tetris-start-game "q" #'quit-window) (defconst tetris--menu-def '("Tetris" ["Start new game" tetris-start-game :help "Start a new Tetris game"] ["End game" tetris-end-game :active (tetris-active-p) :help "End the current Tetris game"] ;; FIXME: Pause and resume from the menu currently doesn't work ;; very well and is therefore disabled. The game continues ;; running while navigating the menu. See also ;; `snake--menu-def' which has the same problem. ;; ["Pause" tetris-pause-game ;; :active (and (tetris-active-p) (not tetris-paused)) ;; :help "Pause running Tetris game"] ;; ["Resume" tetris-pause-game ;; :active (and (tetris-active-p) tetris-paused) ;; :help "Resume paused Tetris game"] ) "Menu for `tetris'. Used to initialize menus.") (easy-menu-define tetris-mode-menu tetris-mode-map "Menu for running Tetris games." tetris--menu-def) (easy-menu-define tetris-null-menu tetris-null-map "Menu for finished Tetris games." tetris--menu-def) (setq tetris-holded-piece 1) (setq tetris-next-holded-piece 1) (setq tetris-holded-siguiente "s") ;; ;;;;;;;;;;;;;;;; game functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun tetris-display-options () (let ((options (make-vector 256 nil))) (dotimes (c 256) (aset options c (cond ((= c tetris-blank) tetris-blank-options) ((and (>= c 0) (<= c 6)) (append tetris-cell-options `((((glyph color-x) ,(aref tetris-x-colors c)) (color-tty ,(aref tetris-tty-colors c)) (t nil))))) ((= c tetris-border) tetris-border-options) ((= c tetris-space) tetris-space-options) (t '(nil nil nil))))) options)) (defun tetris-get-tick-period () (let ((period (apply tetris-update-speed-function tetris-n-shapes tetris-n-rows nil))) (and (numberp period) period))) (defun tetris-get-shape-cell (block) (aref (aref (aref tetris-shapes tetris-shape) tetris-rot) block)) (defun tetris-shape-width () (aref (aref tetris-shape-dimensions tetris-shape) 0)) (defun tetris-shape-rotations () (length (aref tetris-shapes tetris-shape))) (defun tetris-draw-score () (let ((strings (vector (format "Shapes: %05d" tetris-n-shapes) (format "Rows: %05d" tetris-n-rows) (format "Score: %05d" tetris-score)))) (dotimes (y 3) (let* ((string (aref strings y)) (len (length string))) (dotimes (x len) (gamegrid-set-cell (+ tetris-score-x x) (+ tetris-score-y y) (aref string x))))))) (defun tetris-draw-hold () (if (eq tetris-holded-piece 0) (setq tetris-holded-siguiente "O") ) (if (eq tetris-holded-piece 1) (setq tetris-holded-siguiente "J") ) (if (eq tetris-holded-piece 2) (setq tetris-holded-siguiente "L") ) (if (eq tetris-holded-piece 3) (setq tetris-holded-siguiente "Z") ) (if (eq tetris-holded-piece 4) (setq tetris-holded-siguiente "S") ) (if (eq tetris-holded-piece 5) (setq tetris-holded-siguiente "T") ) (if (eq tetris-holded-piece 6) (setq tetris-holded-siguiente "I") ) (let ((strings (vector (format "Shapes: %05d" tetris-n-shapes) (format "Rows: %05d" tetris-n-rows) (format "Hodl: %05s" tetris-holded-siguiente)))) (dotimes (y 3) (let* ((string (aref strings y)) (len (length string))) (dotimes (x len) (gamegrid-set-cell (+ 15 x) (+ 15 y) (aref string x))))))) (defun tetris-update-score () (tetris-draw-score) (tetris-draw-hold) (let ((period (tetris-get-tick-period))) (if period (gamegrid-set-timer period)))) (defun tetris--shuffle (sequence) (cl-loop for i from (length sequence) downto 2 do (cl-rotatef (elt sequence (random i)) (elt sequence (1- i)))) sequence) (defun tetris--seven-bag () (when (not tetris--bag) (setq tetris--bag (tetris--shuffle (list 0 1 2 3 4 5 6)))) (pop tetris--bag)) (defun tetris-new-shape () (setq tetris-shape tetris-next-shape) (setq tetris-rot 0) (setq tetris-next-shape (if tetris-allow-repetitions (random 7) (tetris--seven-bag))) (setq tetris-pos-x (/ (- tetris-width (tetris-shape-width)) 2)) (setq tetris-pos-y 0) (if (tetris-test-shape) (tetris-end-game) (tetris-draw-shape) (tetris-draw-next-shape) (tetris-update-score))) (defun tetris-draw-next-shape () (dotimes (x 4) (dotimes (y 4) (gamegrid-set-cell (+ tetris-next-x x) (+ tetris-next-y y) tetris-blank))) (dotimes (i 4) (let ((tetris-shape tetris-next-shape) (tetris-rot 0)) (gamegrid-set-cell (+ tetris-next-x (aref (tetris-get-shape-cell i) 0)) (+ tetris-next-y (aref (tetris-get-shape-cell i) 1)) tetris-shape)))) (defun tetris-draw-shape () (dotimes (i 4) (let ((c (tetris-get-shape-cell i))) (gamegrid-set-cell (+ tetris-top-left-x tetris-pos-x (aref c 0)) (+ tetris-top-left-y tetris-pos-y (aref c 1)) tetris-shape)))) (defun tetris-erase-shape () (interactive) (dotimes (i 4) (let ((c (tetris-get-shape-cell i))) (gamegrid-set-cell (+ tetris-top-left-x tetris-pos-x (aref c 0)) (+ tetris-top-left-y tetris-pos-y (aref c 1)) tetris-blank)))) (defun tetris-test-shape () (let ((hit nil)) (dotimes (i 4) (unless hit (setq hit (let* ((c (tetris-get-shape-cell i)) (xx (+ tetris-pos-x (aref c 0))) (yy (+ tetris-pos-y (aref c 1)))) (or (>= xx tetris-width) (>= yy tetris-height) (/= (gamegrid-get-cell (+ xx tetris-top-left-x) (+ yy tetris-top-left-y)) tetris-blank)))))) hit)) (defun tetris-full-row (y) (let ((full t)) (dotimes (x tetris-width) (if (= (gamegrid-get-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y)) tetris-blank) (setq full nil))) full)) (defun tetris-shift-row (y) (if (= y 0) (dotimes (x tetris-width) (gamegrid-set-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y) tetris-blank)) (dotimes (x tetris-width) (let ((c (gamegrid-get-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y -1)))) (gamegrid-set-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y) c))))) (defun tetris-shift-down () (dotimes (y0 tetris-height) (when (tetris-full-row y0) (setq tetris-n-rows (1+ tetris-n-rows)) (cl-loop for y from y0 downto 0 do (tetris-shift-row y))))) (defun tetris-draw-border-p () (or (not (eq gamegrid-display-mode 'glyph)) tetris-draw-border-with-glyphs)) (defun tetris-init-buffer () (gamegrid-init-buffer tetris-buffer-width tetris-buffer-height tetris-space) (let ((buffer-read-only nil)) (if (tetris-draw-border-p) (cl-loop for y from -1 to tetris-height do (cl-loop for x from -1 to tetris-width do (gamegrid-set-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y) tetris-border)))) (dotimes (y tetris-height) (dotimes (x tetris-width) (gamegrid-set-cell (+ tetris-top-left-x x) (+ tetris-top-left-y y) tetris-blank))) (if (tetris-draw-border-p) (cl-loop for y from -1 to 4 do (cl-loop for x from -1 to 4 do (gamegrid-set-cell (+ tetris-next-x x) (+ tetris-next-y y) tetris-border)))))) (defun tetris-reset-game () (gamegrid-kill-timer) (tetris-init-buffer) (setq tetris-next-shape (random 7)) (setq tetris-shape 0 tetris-rot 0 tetris-pos-x 0 tetris-pos-y 0 tetris-n-shapes 0 tetris-n-rows 0 tetris-score 0 tetris-paused nil) (tetris-new-shape)) (defun tetris-shape-done () (tetris-shift-down) (setq tetris-n-shapes (1+ tetris-n-shapes)) (setq tetris-score (+ tetris-score (aref (aref tetris-shape-scores tetris-shape) tetris-rot))) (tetris-update-score) (tetris-new-shape)) (defun tetris-update-game (tetris-buffer) "Called on each clock tick. Drops the shape one square, testing for collision." (if (and (not tetris-paused) (eq (current-buffer) tetris-buffer)) (let (hit) (tetris-erase-shape) (setq tetris-pos-y (1+ tetris-pos-y)) (setq hit (tetris-test-shape)) (if hit (setq tetris-pos-y (1- tetris-pos-y))) (tetris-draw-shape) (if hit (tetris-shape-done))))) (defun tetris-move-bottom () "Drop the shape to the bottom of the playing area." (interactive nil tetris-mode) (unless tetris-paused (let ((hit nil)) (tetris-erase-shape) (while (not hit) (setq tetris-pos-y (1+ tetris-pos-y)) (setq hit (tetris-test-shape))) (setq tetris-pos-y (1- tetris-pos-y)) (tetris-draw-shape) (tetris-shape-done)))) (defun tetris-move-left () "Move the shape one square to the left." (interactive nil tetris-mode) (unless tetris-paused (tetris-erase-shape) (setq tetris-pos-x (1- tetris-pos-x)) (if (tetris-test-shape) (setq tetris-pos-x (1+ tetris-pos-x))) (tetris-draw-shape))) (defun tetris-move-right () "Move the shape one square to the right." (interactive nil tetris-mode) (unless tetris-paused (tetris-erase-shape) (setq tetris-pos-x (1+ tetris-pos-x)) (if (tetris-test-shape) (setq tetris-pos-x (1- tetris-pos-x))) (tetris-draw-shape))) (defun tetris-move-down () "Move the shape one square to the bottom." (interactive nil tetris-mode) (unless tetris-paused (tetris-erase-shape) (setq tetris-pos-y (1+ tetris-pos-y)) (if (tetris-test-shape) (setq tetris-pos-y (1- tetris-pos-y))) (tetris-draw-shape))) (defun tetris-rotate-prev () "Rotate the shape clockwise." (interactive nil tetris-mode) (unless tetris-paused (tetris-erase-shape) (setq tetris-rot (% (+ 1 tetris-rot) (tetris-shape-rotations))) (if (tetris-test-shape) (setq tetris-rot (% (+ 3 tetris-rot) (tetris-shape-rotations)))) (tetris-draw-shape))) (defun tetris-rotate-next () "Rotate the shape anticlockwise." (interactive nil tetris-mode) (unless tetris-paused (tetris-erase-shape) (setq tetris-rot (% (+ 3 tetris-rot) (tetris-shape-rotations))) (if (tetris-test-shape) (setq tetris-rot (% (+ 1 tetris-rot) (tetris-shape-rotations)))) (tetris-draw-shape))) (defun tetris-end-game () "Terminate the current game." (interactive nil tetris-mode) (gamegrid-kill-timer) (use-local-map tetris-null-map) (gamegrid-add-score tetris-score-file tetris-score)) (defun tetris-start-game () "Start a new game of Tetris." (interactive nil tetris-mode) (tetris-reset-game) (use-local-map tetris-mode-map) (let ((period (or (tetris-get-tick-period) tetris-default-tick-period))) (gamegrid-start-timer period 'tetris-update-game))) (defun tetris-pause-game () "Pause (or resume) the current game." (interactive nil tetris-mode) (setq tetris-paused (not tetris-paused)) (message (and tetris-paused "Game paused (press p to resume)"))) (setq tetris-current-shape nil tetris-hold-shape nil) (defun tetris-hold-piece () (interactive nil tetris-mode) (let ((current-shape tetris-current-shape) (current-rot tetris-rot)) (if tetris-hold-shape (progn (setq tetris-current-shape tetris-hold-shape tetris-rot 0) (setq tetris-hold-shape current-shape tetris-piece-held t)) (progn (tetris-draw-next-shape) (setq tetris-hold-shape current-shape tetris-rot 0 tetris-piece-held t)))) ) (defun tetris-active-p () (eq (current-local-map) tetris-mode-map)) (put 'tetris-mode 'mode-class 'special) (define-derived-mode tetris-mode nil "Tetris" "A mode for playing Tetris." :interactive nil (add-hook 'kill-buffer-hook 'gamegrid-kill-timer nil t) (use-local-map tetris-null-map) (setq show-trailing-whitespace nil) (setq gamegrid-use-glyphs tetris-use-glyphs) (setq gamegrid-use-color tetris-use-color) (gamegrid-init (tetris-display-options))) ;;;###autoload (defun mitetris () "Play the Tetris game. Shapes drop from the top of the screen, and the user has to move and rotate the shape to fit in with those at the bottom of the screen so as to form complete rows. `tetris-mode' keybindings: \\<tetris-mode-map> \\[tetris-start-game] Start a new game of Tetris \\[tetris-end-game] Terminate the current game \\[tetris-pause-game] Pause (or resume) the current game \\[tetris-move-left] Move the shape one square to the left \\[tetris-move-right] Move the shape one square to the right \\[tetris-rotate-prev] Rotate the shape clockwise \\[tetris-rotate-next] Rotate the shape anticlockwise \\[tetris-move-bottom] Drop the shape to the bottom of the playing area" (interactive) (select-window (or (get-buffer-window tetris-buffer-name) (selected-window))) (switch-to-buffer tetris-buffer-name) (gamegrid-kill-timer) (tetris-mode) (tetris-start-game)) (provide 'mitetris) ;;; tetris.el ends here
Conclusión
Finalmente, para poder probarlo todo, basta con evaluar los trozos de
Elisp que he ido poniendo a lo largo del post, y ejecutar M-x
mitetris
. Funciona por lo menos en las versiones 29.1.9 y 29.2 de Emacs, que
son en las que lo he probado.
Así que, en tan sólo un rato, y sin tener mucha idea de Elisp, he conseguido hacer una solución chapucera que me permite jugar con una funcionalidad extra al Tetris de Emacs.
Me he divertido mucho haciéndolo, y además tengo muchas ideas de cómo mejorarlo para poder convertirlo en código en condiciones. Junto con mi modo menor, ya tengo una experiencia de juego completamente personalizada :).
Configuración de Emacs con macros
Este verano tuve un par de sesiones de "coaching" con Protesilaos (https://www.protesilaos.com/). Aprendí varias cosas sobre elisp, y además creé mi propia macro para configurar Emacs.
El problema que estaba teniendo es que siempre que intentaba instalar Emacs desde cero en otro ordenador, la gestión de paquetes me daba problemas, y tenía que reiniciar Emacs varias veces para completar la instalación.
Mi objetivo es que con mi archivo de configuración pueda coger un ordenador cualquiera, iniciar Emacs y tenerlo todo configurado y listo, como si estuviera en mi propio ordenador (excepto en lo referente a archivos personales, claro).
Así que la solución a la que llegué con Prot fue hacerme mi propia macro, para gestionar así todo lo que tenga que ver con los paquetes, y saber qué está pasando en cada momento. La macro a la que he llegado es:
(defmacro my-package-install (package &rest body) "Installs PACKAGE. If the package cannot be installed, remind the user to add the package-archives. Then, the user can configure the PACKAGE." `(progn ;;First stage; package installation (unless (package-installed-p ,package) (unless package-archive-contents (package-refresh-contents)) (or (ignore-errors (package-install ,package)) (message "Did you add MELPA to the `package-archives'"))) ;;Second stage; package configuration (require ,package) ,@body ) )
Básicamente lo que hace es comprobar si un paquete está instalado, y si lo está, lo configura con los argumentos que se le pasen. Además para evitar el error que tenía anteriormente, la macro te da una posible solución al error.
Con todo esto listo, ahora sólo tengo que implementar la macro con los paquetes de mi configuración. Una vez lo tenga todo hecho, debería poder usar Emacs en cualquier ordenador con sólo pulsar un botón.
Publicación de un paquete en MELPA
El otro día estaba mirando la lista de paquetes de MELPA, y vi que había varios paquetes que añadían al calendario de Emacs los días festivos de varios países. Sin embargo no encontré por ningún lado los festivos de España, y pensé en hacer yo mismo el paquete.
Primer paso: creación del paquete
Como es un paquete muy simple, no me llevó mucho tiempo. Me basé en el paquete de mexican-holidays y copié su estructura. Luego fui a la página del gobierno donde están publicados los festivos de 2023.
Segundo paso: formato del paquete
Una vez creado, le di al paquete el formato requerido por
MELPA. Siguiendo las instrucciones de
https://github.com/melpa/melpa/blob/master/README.md#contributing
y
https://github.com/melpa/melpa/blob/master/CONTRIBUTING.org
.
Al ser un paquete de un sólo archivo, sin dependencias, lo único que hice fue pasarle el package-lint y checkdoc para comprobar que todo estaba correcto y con buena documentación y estructura.
Tercer paso: creación del recipe y pull request
Para integrar el paquete en MELPA, hay que hacer un git clone
del
repositorio de MELPA, añadir un archivo llamado recipe donde se
incluye el nombre del paquete así como el repositorio fuente, y por
último solicitar un pull request en Github.
Cuarto paso: comprobación del merge
Antes de hacer un merge en MELPA, un revisor comprobará que el paquete cumple todos los requerimientos, hará algún comentario por si falta algo y luego finalmente se hará el merge. En mi caso me faltaba añadir el archivo de licencia, tras añadirlo el paquete fue incluido en MELPA.
Conclusión
Todo el proceso se realizó en menos de 24 horas. Todas las instrucciones fueron muy claras, y el revisor muy amable. Incluso sin saber mucho de elisp, he podido crear y contribuir con un paquete al entorno de GNU Emacs.
Creando un modo menor en Emacs
Aprovechando la versatilidad de Emacs he decidido crear un "modo menor" para poder jugar de forma más cómoda al tetris dentro del propio Emacs. Seguramente haya formas menos complicadas de hacer lo mismo, pero haciendo esto se aprende un poco mejor cómo funcionan los modos menores.
He adaptado el código de System Crafters (https://systemcrafters.cc/learning-emacs-lisp/creating-minor-modes), y he creado sendas funciones para asignar el movimiento de las piezas del tetris a las teclas "j" y "k". El modo se llama "tetritecla-basic-mode" y básicamente sólo sirve para añadir esos atajos de teclas, junto a "k" para rotar piezas y "h" para bajarlas.
Si ahora activo el modo "tetritecla-basic-mode" con un hook al iniciar el programa "tetris", ya obtengo las nuevas teclas de forma automática cada vez que quiera jugar. ¡Fácil y cómodo!
A continuación dejo el código:
(make-variable-buffer-local (defvar tetritecla-basic-mode nil "Alterna tetritecla-basic-mode.")) (defvar tetritecla-basic-mode-map (make-sparse-keymap) "El keymap para tetritecla-basic-mode") ;; Definición de las teclas para jugar. (define-key tetritecla-basic-mode-map (kbd "j") (lambda () (interactive) (tetris-move-left))) (define-key tetritecla-basic-mode-map (kbd "k") (lambda () (interactive) (tetris-rotate-prev))) (define-key tetritecla-basic-mode-map (kbd "h") (lambda () (interactive) (tetris-move-down))) (define-key tetritecla-basic-mode-map (kbd "l") (lambda () (interactive) (tetris-move-right))) (add-to-list 'minor-mode-alist '(tetritecla-basic-mode " tetritecla")) (add-to-list 'minor-mode-map-alist (cons 'tetritecla-basic-mode tetritecla-basic-mode-map)) (defun tetritecla-basic-mode (&optional ARG) (interactive (list 'toggle)) (setq tetritecla-basic-mode (if (eq ARG 'toggle) (not tetritecla-basic-mode) (> ARG 0))) ;; Aviso de activación de modo (if tetritecla-basic-mode (message "tetritecla-basic-mode activado") (message "tetritecla-basic-mode desactivado")))
Publicación de una entrada con scp II
Para automatizar el despliegue del blog después de publicar una entrada con org-static-blog, se puede combinar la función async-shell-command
con el hook que tiene org blog.
Antes que nada, para que funcione es necesario configurar la conexión de ssh para poder acceder a través de una clave al servidor. Por ejemplo, si ya tenemos la clave generada podemos usar:
ssh-copy-id -i ~/.ssh/id_ed25519.pub pi@192.168.1.125
Ahora, configuramos el hook:
(add-hook 'org-publish-after-publishing-hook '(lambda () ((async-shell-command "scp -r ~/blog pi@192.168.1.125:/var/www/html/publish" "publicando"))))
Y listo, cada vez que se publique una entrada con org-static-blog-publish
se subirá el contenido al servidor automáticamente.
Edit: Me he confundido con el hook, el org-publish-after-publishing-hook
es un hook de org-publish
no de org-static-publish
, por lo tanto su configuración es un poco más complicada y el hook que he puesto arriba no funciona. La función lambda sin embargo sí que es válida, la usaré en una futura entrada en la que configuré el hook correctamente.
Octave en Emacs
Octave es la alternativa libre a Matlab®, que te permite hacer todo lo que hace Matlab pero sin tener que pagar miles de euros y descargar decenas de gigas.
Para integrarlo en mi flujo de trabajo en Emacs, decidí usar popper.el https://github.com/karthink/popper
. Esto me permite tener a mano la consola de Octave con solo pulsar un botón.
Primero lo activo con popper-mode
, después elijo el búfer que contiene la consola de Octave (por ejemplo el búfer que se crea al usar run-octave
) y una vez en ese búfer con popper-toggle-type
se convierte en un búfer fijado.
Luego se puede asignar popper-toggle-latest
a cualquier tecla (por ejemplo f9), y al pulsar esa tecla la consola de Octave aparece y desaparece.
Es una buena forma de tener una consola de lo que sea siempre a mano.