Adding a ERC Command

Filed under:Emacs — posted by rwanderley on 9 April, 2008 @ 7:38 pm

Today I was trying to count the users on #emacs channel. Since I couldn’t find an already available command at this great IRC client I added one to do this.

At first I thought it would give me some headaches, but it ended being a pretty easy task.

The first thing is that the users on a channel are recorded at a hash table, called erc-channel-users. So, in order to count the users on a channel I just have to maphash it and do the counting, I did it like this:

(defun rsw/erc-count-users ()
"Count the users in current channel"
(interactive)
(let ((n 0))
(maphash '(lambda (nick data) (incf n)) erc-channel-users)
(message (format "%d users on this Channel." n))))

After evaluating this function I just go to a channel and type “M-x rsw/erc-count-users” and a message will appear at the minibuffer. Now, in order to make a command named COUNT out of this function I just have to create a function like:

(defun erc-cmd-COUNT ()
"Count command just counts how many users are on the channel
showing the results on minibuffer"

(rsw/erc-count-users))

And that’s it, erc internally knows that erc-cmd-COUNT is the the function representing the COUNT command (it builds the name of the function to be called dynamically).

The Best Day Planner Howto I’ve Seen

Filed under:Assuntos Gerais, Emacs — posted by rwanderley on 7 March, 2008 @ 3:02 pm

Today I finally found an Emacs day Planner howto that I really liked, it is the one from John Wiegley.

After a few minutes I changed the whole configuration I spent weeks doing to the one he showed in the site and now there seems to be order on the mess it was before I read the article.

Recommend it to everyone, even non Emacs users.

Editing ID3 tags with Emacs and EMMS

Filed under:Emacs — posted by rwanderley on 29 January, 2008 @ 9:09 am

This video shows how to edit ID3 tags from your MP3 files using Emacs keyboard macros and EMMS.

This link points to the high quality version in Ogg Video format.

EMMS Browser, o vídeo :-)

Filed under:Emacs — posted by rwanderley on 24 January, 2008 @ 7:11 am

Meu primeiro vídeo usando o recordmydesktop. Ele mostra o uso do
browser do EMMS, um gerenciador de mídias para o Emacs.

Link para baixar

Vídeo com qualidade mais baixa no google videos:

Gnus + Gmail (Part II - Adding Multiple SMTP Accounts)

Filed under:Emacs, LISP — posted by rwanderley on 21 January, 2008 @ 5:25 pm

Unfortunately there is no native method to add multiple SMTP servers on Gnus. But after taking a quick look at the wiki I found this link. I changed it a little bit, so the passwords are searched at the ~/.authinfo file instead of being in your .gnus file.

Here is the code found on my .gnus file:

;; Available SMTP accounts.
(defvar smtp-accounts
  '((ssl   "mymail@gmail.com" "smtp.gmail.com" 587 "key" nil)
    (ssl   "mymail@otherserver.com" "smtp.otherserver.com" 25 "key" nil)))

This lists my SMTP accounts, one line for each server, as you can see both the servers are using SSL.

;; Default smtpmail.el configurations.
(require 'smtpmail)
(setq send-mail-function 'smtpmail-send-it
      message-send-mail-function 'smtpmail-send-it
      mail-from-style nil
      user-full-name "Rodrigo S. Wanderley"
      user-mail-address "mymail@gmail.com"
      message-signature-file "~/emacs/signature"
      smtpmail-debug-info t
      smtpmail-debug-verb t)

The code above just sets some default values. My mail signature is found on the file ~/emacs/signature, I also specify my user name user-full-name and my e-mail address user-mail-address so that Gnus can fill the From header field automatically for me.

The Debug options is also nice so that you get some feedback about what is happening while Gnus is sending the e-mail for you.

(defun set-smtp-plain (server port)
  "Set related SMTP variables for supplied parameters."
  (setq smtpmail-smtp-server server
    smtpmail-smtp-service port
    smtpmail-auth-credentials "~/.authinfo"
    smtpmail-starttls-credentials nil)
  (message "Setting SMTP server to `%s:%s'."
       server port address))

(defun set-smtp-ssl (server port key cert)
  "Set related SMTP and SSL variables for supplied parameters."
  (setq starttls-use-gnutls t
    starttls-gnutls-program "gnutls-cli"
    starttls-extra-arguments nil
    smtpmail-smtp-server server
    smtpmail-smtp-service port
    smtpmail-starttls-credentials (list (list server port key cert))
    smtpmail-auth-credentials "~/.authinfo")
  (message
   "Setting SMTP server to `%s:%s'. (SSL enabled.)"
   server port address))

Those are two functions used to send mail, one with and one without SSL support. Note that smtpmail-auth-credentials is telling Gnus where to find the username and password.

(defun change-smtp ()
  "Change the SMTP server according to the current from line."
  (save-excursion
    (loop with from = (save-restriction
            (message-narrow-to-headers)
            (message-fetch-field "from"))
      for (acc-type address . auth-spec) in smtp-accounts
      when (string-match address from)
      do (cond
          ((eql acc-type 'plain)
           (return (apply 'set-smtp-plain auth-spec)))
          ((eql acc-type 'ssl)
           (return (apply 'set-smtp-ssl auth-spec)))
          (t (error "Unrecognized SMTP account type: `%s'." acc-type)))
      finally (error "Cannot interfere SMTP information."))))

(add-hook 'message-send-hook 'change-smtp)

Finally we create a hook for when me message is going to be sent. This hook basically tries to match the From header with the e-mail address you specified at smtp-account variable and chooses the server accordingly.

Selecionando encoding correto no ERC

Filed under:Administração Linux, Emacs, LISP — posted by rwanderley on 14 January, 2008 @ 7:50 pm

A algum tempo venho tendo problemas de codificação de caracteres no ERC,
o cliente de irc que uso.

Uso o ERC tanto para conectar em servidores IRC, geralmente o freenode,
como para conectar ao MSN e Google talk, usando o bitlbee para converter
os protocolos destes dois últimos para o do IRC.

O problema está que o MSN e o Google talk usam ISO-8859-1 como encoding,
enquanto que o pessoal no freenode usa UTF-8. Eu conhecia a variável
erc-server-coding-system, que na minha configuração estava setada
para “‘(utf-8 . undecided)”, ou seja, eu enviava texto usando UTF-8 e
usava o encoding especial do emacs undecided como o encoding de entrada.

O problema dessa solução é obvio, funciona para o freenode mas não funciona para o MSN. O que eu não sabia é que a variável erc-server-coding-system também pode ser uma função! Como o servidor do bitlbee é o localhost a configuração é trivial. erc-server-announced-name é uma variável dinâmica contendo o nome do servidor IRC sendo usado no momento.

(setq erc-server-coding-system
      '(lambda (target)
     (if (and erc-server-announced-name
          (string-match "localhost" erc-server-announced-name))
         '(iso-8859-1 . undecided)
       '(utf-8 . undecided))))

Essa função apenas checa se erc-server-announced-name bate com a string localhost, ou seja, se é o servidor do bitlbee, caso for seta o encoding para iso-8859-1, caso contrário usa utf8.

Atualizando ID3 no EMMS

Filed under:Emacs, LISP, Uncategorized — posted by rwanderley on 12 January, 2008 @ 8:24 am

Hoje passei umas duas horas atualizando tags ID3. E só
consegui editar as tags dos Guns n’ Roses e metade do
Pink Floyd (1969 até 2005 é muito tempo de carreira :-))

Aqui vai uma dica para se editar tags direto do emacs
usando o playlist buffer do EMMS.

Primeiro configure o EMMS seguindo os passos do Post
anterior, depois adicione uma arvore de diretório
na playlist com o comando M-x emms-add-directory-tree.
Aconselho comecar adicionando um artista apenas e editar
as tags deste artista, depois ir adicionando mais
com o tempo.

Agora precisamos mudar para o buffer contendo a playlist
do emms, para isso usa-se o comando M-x emms-playlist-mode-go,
como uso bastante este comando criei um atalho para ele
no meu arquivo emms.el (ver post anterior):

(global-set-key "\C-xppg" 'emms-playlist-mode-go)

Como não tenho só esse atalho no meu emms.el usei o prefixo C-x p
(’p’ de player) para indicar atalhos do emms, nesse caso eu decoro
o comando da seguinte forma C-x p (prefixo do emms), p (playlist) e
g (go). Você poderá escolher o atalho que quiser.

Na playlist você irá ver que o EMMS já interpretou as ID3 do arquivo
e está exibindo os nomes de acordo com elas. Caso alguma das
ID3 estejam mal formadas basta colocar o cursor em cima da
faixa com problema e digitar a tecla ‘E’. O Emacs irá abrir um
novo buffer, como esse:

Guns N' Roses - It's So Easy name = /home/mp3/Guns'n Roses/Appetite for Destruction (1987)/02 - Guns N' Roses - It's So Easy.mp3 info-artist = Guns N' Roses info-title = It's So Easy info-album = Appetite for Destruction info-tracknumber = 2 info-year = 1987 info-genre = Hard Rock info-note =

Caso alguma das informacoes estejam erradas basta editar e,
quando tudo estiver OK, aperte C-c C-c para salvar as
informacões.

Uma dica para melhorar o desempenho é usar Macros de teclado.
Eu geralmente crio uma macro para inserir o nome do artista,
album, numero da faixa, ano e genero; depois passo manualmente
pelas faixas e adiciono apenas o nome da faixa.

Segue um screenshot mostrando o browser EMMS na parte superior
da tela:

Test drive no EMMS

Filed under:Administração Linux, Emacs, LISP — posted by rwanderley on 11 January, 2008 @ 6:15 pm

Fazem algumas semanas venho testando o EMMS, um sistema multimidia para o Emacs.  Ele atua como frontend para aplicacoes como o mpg321, mplayer e mp3info.  Para quem nao gosta de sair do Emacs ele é perfeito, possui um bom browser, como praticamente tudo no Emacs é bastante configurável e permite que você gerenciar playlists de forma fácil.

Neste post irei mostrar como configurar o EMMS.  Estou usando GNU Emacs 22.1, portanto se você ainda estiver usando o Emacs 21 provavelmente algumas das configuracões a seguir poderão não funcionar.  Também será necessário pelo menos ter o mpg321 e o mp3info instalados.

Se você possui Debian ou Ubuntu é bastante fácil instalar, apenas digite apt-get install emms e pronto!  Em outras distros o processo pode ser diferente, provavelmente vocês terão que baixar os fontes direto do site do emms e instalar na mão, não irei falar desse tipo de instalacão aqui, mas os interessados podem postar suas dúvidas ou me mandar um e-mail.

A configuracão básica também é fácil.  Primeiro colocamos uma linha no .emacs informando onde está o arquivo de configuracao, apenas abra o seu ~/.emacs e coloque o seguinte em algum lugar no inicio do arquivo:

(load-file "~/.emacs.d/emms.el")

Essa linha apenas está dizendo ao emacs para carregar o arquivo ~/.emacs.d/emms.el quando o mesmo for iniciado.

Agora abra ou crie o arquivo ~/.emacs.d/emms.el e insira as seguintes linhas nele:

(require 'emms-setup) (emms-devel) (emms-default-players)

Digite M-x eval-buffer e pronto!  Seu EMMS está configurado.  Para testar digite M-x emms-play-directory e selecione um diretório contendo algumas mp3, o EMMS deverá comecar a tocar as MP3 e mostrar o nome da música na barra de estatus.É só isso?  Não, ainda tem muito mais, ainda tem o browser do emms, algumas funcões de expansão que permitem que você faca forward, pausa, use o dired para selecionar faixas, …  Mas vou dar um tempinho para vocês testarem essa versão básica antes de postar uma configuracão
mais avancada.



image: detail of installation by Bronwyn Lace