Emacs настройка для windows

Время на прочтение13 мин

Количество просмотров128K

Доброго времени суток, Читатель!

В данной статье хочу подробно рассказать про настройку текстового редактора GNU Emacs.

Операционная система

GNU Emacs — программируемый текстовый редактор для программистов, написанный на программируемом языке программирования.

Для расширения Emacs используется диалект языка Lisp — Emacs Lisp.
Строго говоря, Emacs нельзя назвать просто текстовым редактором. Emacs — это интерпретатор языка Emacs Lisp, конструктор текстового редактора, заточенного именно под Вас. Малая часть программы реализована на языке Си (около 30% — отвечает за базовое взаимодействие с ОС, ввод-вывод, отрисовку окон), а весь основной функционал — на Emacs Lisp (далее, elisp). Именно такая архитектура отличает GNU Emacs от других профессиональных текстовых редакторов — он, до неприличия, расширяем.

Функционал этого редактора настолько огромен и разнообразен, что новичку в этой среде крайне сложно освоиться. Чего стоит только процесс настройки — на это могут уйти годы,

или вся жизнь

. Именно поэтому я решил написать эту статью — подробное руководство по начальной настройке Emacs, для тех кто:

  • хочет начать использовать GNU Emacs, но не знает как;
  • пишет на языках, поддержка которых в IDE оставляет желать лучшего или её вообще нет;
  • пишет на разных языках, «программист-полиглот»;
  • хочет иметь универсальную среду разработки на работе и дома, на нескольких компьютерах сразу;
  • хочет иметь функциональную и мощную среду для plain/text заметок (organizer), ведения справочной информации, управления проектами, организации базы знаний и т.д. — org-mode;
  • хочет автоматизировать процесс обработки большого числа текстовых файлов;
  • хочет иметь нетребовательную к аппаратным ресурсам, кроссплатформенную среду для работы с любой текстовой информацией;
  • хочет среду, которую можно без особых усилий, буквально «на лету», настроить под себя, свою конкретную задачу, расширить, самостоятельно добавив новый функционал;
  • любит универсальность и расширяемость;
  • пишет для web, на скриптовых языках: Python, Ruby, Perl и т.п.;
  • хочет приобщиться к вечному, к Emacs — одному из самых долгоживущих проектов Open Source сообщества;
  • etc.

Стоит сказать, что в современной IT-индустрии все чаще появляются различные амбициозные проекты, связанные с разработкой «текстовых редакторов XXI века»,

убийц

замен Emacs и/или Vim:

  • Light Table;
  • Sublime Text;
  • Atom от GitHub.

Ну что сказать… Удачи им в этом нелегком труде. А мы, пожалуй, займемся настройкой GNU Emacs.

Да. Вы не ошиблись. Фильм «Трон: Наследие». GNU Emacs используют и там. Кто бы мог подумать…

Забыл предупредить: я пишу на Common Lisp (ещё один диалект языка Lisp), поэтому часть материала будет про то, как превратить Emacs в полноценную IDE

с картами и девушками

для этого языка программирования. Хороший пример, к стати…

Итак, поехали!

Установка

Для MS Windows:

  • скачать архив с официального сайта;
  • создать директорию C:\emacs\ и распаковать в него скаченный архив;
  • запустить файл C:\emacs\bin\addpm.exe (создаст пункт в меню Пуск для запуска Emacs).

Для дистрибутивов GNU/Linux (на примере deb-based дистрибутивов) есть четыре способа:

  • в терминале выполнить команду:
    sudo aptitude install emacs emacs-goodies-el
    

  • через менеджер пакетов synaptic;
  • через центр приложений дистрибутива;
  • собрать из исходников.

Для Mac OS X:

  • посмотри тут;
  • или здесь;
  • можно глянуть вот сюда.

На момент написания статьи последняя версия редактора — Emacs-24.4. Вот ее и берите для Mac OS X или MS Windows. Для GNU/Linux советую использовать ту версию, которая представлена в стандартных репозиториях Вашего дистрибутива.

Настройка

Есть, как минимум, четыре способа настройки Emacs:

  • написанием конфигурационного файла .emacs;
  • через меню программы;
  • с помощью команды M-x customize (C-x означает Control-x, M-x означает Meta-x, где Meta может означать: «нажать-отпустить Esc» или «нажать-держать Alt». (например, Meta-x это или нажать Esc, затем x, или, удерживая Alt, нажать x);
  • спереть позаимствовать чужой файл .emacs и начать работать (не советую).

Мы не ищем легких путей! Будем писать конфигурационный файл на языке elisp!
Сказано — сделано!

Файл конфигурации .emacs

После того, как Вы успешно установили GNU Emacs на свой компьютер, необходимо создать файл с названием .emacs и уже в нем прописать основные настройки.
Обозначения, используемые в статье (повторение — мать учения):

  • C-a: Ctrl-a;
  • M-a: Meta-a (Если у Вас нет клавиши Meta (Alt), используете клавишу Esc);
  • C-M-a: Ctrl-Meta-a.

Итак, запускаем Emacs. С помощью комбинации клавиш C-x C-f создаем новый файл .emacs и начинаем в нем писать. Не обижайтесь, но вдаваться в синтаксис языка elisp не стану — это превратит статью в монстра. В конце просто приведу ссылки на необходимые ресурсы.

Для начала, расскажем Emacs о том, в какой операционной системе он запустился. Для этого напишем на elisp две функции, которые нам в этом помогут:

;; System-type definition
(defun system-is-linux()
    (string-equal system-type "gnu/linux"))
(defun system-is-windows()
    (string-equal system-type "windows-nt"))

Теперь, вызывая эти функции как условия для операторов ветвления, мы можем настроить кроссплатформенный файл конфигурации для Emacs (результатом наших трудов будет файл .emacs, который прекрасно работает в ОС MS Windows и дистрибутивах GNU/Linux. На Mac OS X не проверял).

IDE для Common Lisp

Для превращения Emacs в полноценную среду разработки для языка Common Lisp нам понадобится два пакета:

  • реализация Common Lisp. Я выбрал SBCL;
  • Slime — режим Emacs для разработки приложений на языке Common Lisp.

Если Вы пользователь ОС MS Windows и,

вдруг

, пишете на Common Lisp, то Вам нужно:

  • скачать SBCL;
  • установить в C:\sbcl\ скаченный SBCL;
  • скачать Slime;
  • разместить в C:\slime\ скаченный Slime.

На GNU/Linux все проще: выполнить из командной строки:

sudo aptitude install slime sbcl

Поехали дальше

Если Вы счастливый пользователь Mac OS X или дистрибутива GNU/Linux, то Emacs полезно запустить как сервер:

;; Start Emacs as a server
(when (system-is-linux)
    (require 'server)
    (unless (server-running-p)
        (server-start))) ;; запустить Emacs как сервер, если ОС - GNU/Linux

Далее, укажем Emacs пути по которым но сможет найти установленные дополнения (в частности, пакеты Slime и SBCL):

;; MS Windows path-variable
(when (system-is-windows)
    (setq win-sbcl-exe          "C:/sbcl/sbcl.exe")
    (setq win-init-path         "C:/.emacs.d")
    (setq win-init-ct-path      "C:/.emacs.d/plugins/color-theme")
    (setq win-init-ac-path      "C:/.emacs.d/plugins/auto-complete")
    (setq win-init-slime-path   "C:/slime")
    (setq win-init-ac-dict-path "C:/.emacs.d/plugins/auto-complete/dict"))

;; Unix path-variable
(when (system-is-linux)
    (setq unix-sbcl-bin          "/usr/bin/sbcl")
    (setq unix-init-path         "~/.emacs.d")
    (setq unix-init-ct-path      "~/.emacs.d/plugins/color-theme")
    (setq unix-init-ac-path      "~/.emacs.d/plugins/auto-complete")
    (setq unix-init-slime-path   "/usr/share/common-lisp/source/slime/")
    (setq unix-init-ac-dict-path "~/.emacs.d/plugins/auto-complete/dict"))

Давайте расскажем Emacs о том, кто мы такие (мало-ли, решите через Emacs почту отправлять или в jabber‘e переписываться…):

;; My name and e-mail adress
(setq user-full-name   "%user-name%")
(setq user-mail-adress "%user-mail%")

Мой любимый dired-mode. Настроим его:

;; Dired
(require 'dired)
(setq dired-recursive-deletes 'top) ;; чтобы можно было непустые директории удалять...

Теперь можно запустить dired-mode комбинацией клавиш C-x d. Для удаления папки в dired-mode наведите курсор на эту папку, нажмите d, затем x. Чтобы убрать с папки отметку на удаление нажмите u.

Замечательный способ «прыгать» по определениям функций почти для всех языков программирования — Imenu. Предположим, что у Вас файл с программой на

100500

строк с кучей функций. Не беда! Нажимаем F6 и в минибуфере вводим часть имени искомой функции и TAB‘ом дополняем. Нажали Enter — и мы на определении искомой функции:

;; Imenu
(require 'imenu)
(setq imenu-auto-rescan      t) ;; автоматически обновлять список функций в буфере
(setq imenu-use-popup-menu nil) ;; диалоги Imenu только в минибуфере
(global-set-key (kbd "<f6>") 'imenu) ;; вызов Imenu на F6

Пишем название открытого буфера в шапке окна:

;; Display the name of the current buffer in the title bar
(setq frame-title-format "GNU Emacs: %b")

Помните, что мы определили пути, по которым Emacs ищет дополнения и внешние программы? Пусть «пройдется» по этим путям (где дополнения) при запуске:

;; Load path for plugins
(if (system-is-windows)
    (add-to-list 'load-path win-init-path)
    (add-to-list 'load-path unix-init-path))

Еще не забыли, что Emacs предоставляет Вам прекрасную среду для plain/text заметок (organizer), ведения справочной информации, управления проектами, организации базы знаний и т.д. — org-mode? Настроим:

;; Org-mode settings
(require 'org) ;; Вызвать org-mode
(global-set-key "\C-ca" 'org-agenda) ;; поределение клавиатурных комбинаций для внутренних
(global-set-key "\C-cb" 'org-iswitchb) ;; подрежимов org-mode
(global-set-key "\C-cl" 'org-store-link)
(add-to-list 'auto-mode-alist '("\\.org$" . Org-mode)) ;; ассоциируем *.org файлы с org-mode

Наведем

аскетизм

красоту — уберем экраны приветствия при запуске:

;; Inhibit startup/splash screen
(setq inhibit-splash-screen   t)
(setq ingibit-startup-message t) ;; экран приветствия можно вызвать комбинацией C-h C-a

Выделим выражения между {},[],(), когда курсор находится на одной из скобок — полезно для программистов:

;; Show-paren-mode settings
(show-paren-mode t) ;; включить выделение выражений между {},[],()
(setq show-paren-style 'expression) ;; выделить цветом выражения между {},[],()

В новых версиях Emacs внедрили electic-mod‘ы. Первый из них автоматически расставляет отступы (работает из рук вон плохо), второй — закрывает скобки, кавычки и т.д. Отключим первый (

Python программисты меня поймут…

) и включим второй:

;; Electric-modes settings
(electric-pair-mode    1) ;; автозакрытие {},[],() с переводом курсора внутрь скобок
(electric-indent-mode -1) ;; отключить индентацию  electric-indent-mod'ом (default in Emacs-24.4)

Хотим иметь возможность удалить выделенный текст при вводе поверх? Пожалуйста:

;; Delete selection
(delete-selection-mode t)

Уберем лишнее: всякие меню, scroll-bar‘ы, tool-bar‘ы и т.п.:

;; Disable GUI components
(tooltip-mode      -1)
(menu-bar-mode     -1) ;; отключаем графическое меню
(tool-bar-mode     -1) ;; отключаем tool-bar
(scroll-bar-mode   -1) ;; отключаем полосу прокрутки
(blink-cursor-mode -1) ;; курсор не мигает
(setq use-dialog-box     nil) ;; никаких графических диалогов и окон - все через минибуфер
(setq redisplay-dont-pause t)  ;; лучшая отрисовка буфера
(setq ring-bell-function 'ignore) ;; отключить звуковой сигнал

Никаких автоматических сохранений и резервных копий! Только hardcore:

;; Disable backup/autosave files
(setq make-backup-files        nil)
(setq auto-save-default        nil)
(setq auto-save-list-file-name nil) ;; я так привык... хотите включить - замените nil на t

Самое больное и сложное место в настройке — кодировки:

;; Coding-system settings
(set-language-environment 'UTF-8)
(if (system-is-linux) ;; для GNU/Linux кодировка utf-8, для MS Windows - windows-1251
    (progn
        (setq default-buffer-file-coding-system 'utf-8)
        (setq-default coding-system-for-read    'utf-8)
        (setq file-name-coding-system           'utf-8)
        (set-selection-coding-system            'utf-8)
        (set-keyboard-coding-system        'utf-8-unix)
        (set-terminal-coding-system             'utf-8)
        (prefer-coding-system                   'utf-8))
    (progn
        (prefer-coding-system                   'windows-1251)
        (set-terminal-coding-system             'windows-1251)
        (set-keyboard-coding-system        'windows-1251-unix)
        (set-selection-coding-system            'windows-1251)
        (setq file-name-coding-system           'windows-1251)
        (setq-default coding-system-for-read    'windows-1251)
        (setq default-buffer-file-coding-system 'windows-1251)))

Включаем нумерацию строк:

;; Linum plugin
(require 'linum) ;; вызвать Linum
(line-number-mode   t) ;; показать номер строки в mode-line
(global-linum-mode  t) ;; показывать номера строк во всех буферах
(column-number-mode t) ;; показать номер столбца в mode-line
(setq linum-format " %d") ;; задаем формат нумерации строк

Продолжаем наводить красоту:

;; Fringe settings
(fringe-mode '(8 . 0)) ;; органичиталь текста только слева
(setq-default indicate-empty-lines t) ;; отсутствие строки выделить глифами рядом с полосой с номером строки
(setq-default indicate-buffer-boundaries 'left) ;; индикация только слева

;; Display file size/time in mode-line
(setq display-time-24hr-format t) ;; 24-часовой временной формат в mode-line
(display-time-mode             t) ;; показывать часы в mode-line
(size-indication-mode          t) ;; размер файла в %-ах

Автоматический перенос длинных строк:

;; Line wrapping
(setq word-wrap          t) ;; переносить по словам
(global-visual-line-mode t)

Определим размер окна с Emacs при запуске:

;; Start window size
(when (window-system)
    (set-frame-size (selected-frame) 100 50))

Интерактивный поиск и открытие файлов? Пожалуйста:

;; IDO plugin
(require 'ido)
(ido-mode                      t)
(icomplete-mode                t)
(ido-everywhere                t)
(setq ido-vitrual-buffers      t)
(setq ido-enable-flex-matching t)

Быстрая навигация между открытыми буферами:

;; Buffer Selection and ibuffer settings
(require 'bs)
(require 'ibuffer)
(defalias 'list-buffers 'ibuffer) ;; отдельный список буферов при нажатии C-x C-b
(global-set-key (kbd "<f2>") 'bs-show) ;; запуск buffer selection кнопкой F2

Цветовые схемы. Как без них? Для этого:

  • скачаем пакет color-theme для Emacs отсюда;
  • создадим директории .emacs.d/plugins/color-theme;
  • распакуем туда содержимое архива с темами;
  • расположить папку .emacs.d в:
    • для MS Windows в корень диска C:\.emacs.d
    • для GNU/Linux в домашнюю директорию ~/.emacs.d
  • запишем в наш .emacs следующие строки:

;; Color-theme definition <http://www.emacswiki.org/emacs/ColorTheme>
(defun color-theme-init()
    (require 'color-theme)
    (color-theme-initialize)
    (setq color-theme-is-global t)
    (color-theme-charcoal-black))
(if (system-is-windows)
    (when (file-directory-p win-init-ct-path)
        (add-to-list 'load-path win-init-ct-path)
        (color-theme-init))
    (when (file-directory-p unix-init-ct-path)
        (add-to-list 'load-path unix-init-ct-path)
        (color-theme-init)))

Подсветка кода:

;; Syntax highlighting
(require 'font-lock)
(global-font-lock-mode             t) ;; включено с версии Emacs-22. На всякий...
(setq font-lock-maximum-decoration t)

Настройки отступов:

;; Indent settings
(setq-default indent-tabs-mode nil) ;; отключить возможность ставить отступы TAB'ом
(setq-default tab-width          4) ;; ширина табуляции - 4 пробельных символа
(setq-default c-basic-offset     4)
(setq-default standart-indent    4) ;; стандартная ширина отступа - 4 пробельных символа
(setq-default lisp-body-indent   4) ;; сдвигать Lisp-выражения на 4 пробельных символа
(global-set-key (kbd "RET") 'newline-and-indent) ;; при нажатии Enter перевести каретку и сделать отступ
(setq lisp-indent-function  'common-lisp-indent-function)

Плавный скроллинг:

;; Scrolling settings
(setq scroll-step               1) ;; вверх-вниз по 1 строке
(setq scroll-margin            10) ;; сдвигать буфер верх/вниз когда курсор в 10 шагах от верхней/нижней границы  
(setq scroll-conservatively 10000)

Укоротить сообщения в минибуфере:

;; Short messages
(defalias 'yes-or-no-p 'y-or-n-p)

Общий с ОС буфер обмена:

;; Clipboard settings
(setq x-select-enable-clipboard t)

Настройки пустых строк в конце буфера:

;; End of file newlines
(setq require-final-newline    t) ;; добавить новую пустую строку в конец файла при сохранении
(setq next-line-add-newlines nil) ;; не добавлять новую строку в конец при смещении 
						            ;; курсора  стрелками

Выделять результаты поиска:

;; Highlight search resaults
(setq search-highlight        t)
(setq query-replace-highlight t)

Перемещение между сплитами при помощи комбинаций M-arrow-keys (кроме org-mode):

;; Easy transition between buffers: M-arrow-keys
(if (equal nil (equal major-mode 'org-mode))
    (windmove-default-keybindings 'meta))

Удалить лишние пробелы в конце строк, заменить TAB‘ы на пробелы и выровнять отступы при сохранении буфера в файл, автоматически:

;; Delete trailing whitespaces, format buffer and untabify when save buffer
(defun format-current-buffer()
    (indent-region (point-min) (point-max)))
(defun untabify-current-buffer()
    (if (not indent-tabs-mode)
        (untabify (point-min) (point-max)))
    nil)
(add-to-list 'write-file-functions 'format-current-buffer)
(add-to-list 'write-file-functions 'untabify-current-buffer)
(add-to-list 'write-file-functions 'delete-trailing-whitespace)

Пакет CEDET — работа с C/C++/Java (прекрасная статья Alex Ott’a по CEDET):

;; CEDET settings
(require 'cedet) ;; использую "вшитую" версию CEDET. Мне хватает...
(add-to-list 'semantic-default-submodes 'global-semanticdb-minor-mode)
(add-to-list 'semantic-default-submodes 'global-semantic-mru-bookmark-mode)
(add-to-list 'semantic-default-submodes 'global-semantic-idle-scheduler-mode)
(add-to-list 'semantic-default-submodes 'global-semantic-highlight-func-mode)
(add-to-list 'semantic-default-submodes 'global-semantic-idle-completions-mode)
(add-to-list 'semantic-default-submodes 'global-semantic-show-parser-state-mode)
(semantic-mode   t)
(global-ede-mode t)
(require 'ede/generic)
(require 'semantic/ia)
(ede-enable-generic-projects)

Автодополнение ввода. Для этого:

  • скачаем пакет auto-complete для Emacs отсюда;
  • создадим директории .emacs.d/plugins/auto-complete;
  • распакуем туда содержимое архива с auto-complete;
  • расположить папку .emacs.d в:
    • для MS Windows в корень диска C:\.emacs.d
    • для GNU/Linux в домашнюю директорию ~/.emacs.d
  • запишем в наш .emacs следующие строки:

;; Auto-complete plugin <http://www.emacswiki.org/emacs/AutoComplete>
(defun ac-init()
    (require 'auto-complete-config)
    (ac-config-default)
    (if (system-is-windows)
        (add-to-list 'ac-dictionary-directories win-init-ac-dict-path)
        (add-to-list 'ac-dictionary-directories unix-init-ac-dict-path))
    (setq ac-auto-start        t)
    (setq ac-auto-show-menu    t)
    (global-auto-complete-mode t)
    (add-to-list 'ac-modes   'lisp-mode)
    (add-to-list 'ac-sources 'ac-source-semantic) ;; искать автодополнения в CEDET
    (add-to-list 'ac-sources 'ac-source-variables) ;; среди переменных
    (add-to-list 'ac-sources 'ac-source-functions) ;; в названиях функций
    (add-to-list 'ac-sources 'ac-source-dictionary) ;; в той папке где редактируемый буфер
    (add-to-list 'ac-sources 'ac-source-words-in-all-buffer) ;; по всему буферу
    (add-to-list 'ac-sources 'ac-source-files-in-current-dir))
(if (system-is-windows)
    (when (file-directory-p win-init-ac-path)
        (add-to-list 'load-path win-init-ac-path)
        (ac-init))
    (when (file-directory-p unix-init-ac-path)
        (add-to-list 'load-path unix-init-ac-path)
        (ac-init)))

Настроим среду для Common Lisp — Slime:

;; SLIME settings
(defun run-slime()
    (require 'slime)
    (require 'slime-autoloads)
    (setq slime-net-coding-system 'utf-8-unix)
    (slime-setup '(slime-fancy slime-asdf slime-indentation))) ;; загрузить основные дополнения Slime
;;;; for MS Windows
(when (system-is-windows)
    (when (and (file-exists-p win-sbcl-exe) (file-directory-p win-init-slime-path))
        (setq inferior-lisp-program win-sbcl-exe)
        (add-to-list 'load-path win-init-slime-path)
        (run-slime)))
;;;; for GNU/Linux
(when (system-is-linux)
    (when (and (file-exists-p unix-sbcl-bin) (file-directory-p unix-init-slime-path))
        (setq inferior-lisp-program unix-sbcl-bin)
        (add-to-list 'load-path unix-init-slime-path)
        (run-slime)))

Настроим Bookmark — закладки, которые помогают быстро перемещаться по тексту:

;; Bookmark settings
(require 'bookmark)
(setq bookmark-save-flag t) ;; автоматически сохранять закладки в файл
(when (file-exists-p (concat user-emacs-directory "bookmarks"))
    (bookmark-load bookmark-default-file t)) ;; попытаться найти и открыть файл с закладками
(global-set-key (kbd "<f3>") 'bookmark-set) ;; создать закладку по F3 
(global-set-key (kbd "<f4>") 'bookmark-jump) ;; прыгнуть на закладку по F4
(global-set-key (kbd "<f5>") 'bookmark-bmenu-list) ;; открыть список закладок
(setq bookmark-default-file (concat user-emacs-directory "bookmarks")) ;; хранить закладки в файл bookmarks в .emacs.d

Собственно, всё! Можно нажать C-x C-s и сохранить файл .emacs. Куда положить файл .emacs и папку .emacs.d (если использовать пути из моего .emacs):

MS Windows:

  • .emacs в C:\Users\%username%\AppData\Roaming\
  • папку .emacs.d в корень диска C:\

GNU/Linux:

  • .emacs в домашнюю директорию: /home/%username%/
  • папку .emacs.d в домашнюю директорию: /home/%username%/

Мой .emacs можно скачать с моей странички на GitHub.

Мой Emacs:

image

Полезные ссылки

Множество полезных статей по GNU Emacs на Хабрахабр. Также есть серия замечательных скринкастов на YouTube про Emacs, опубликованных Дмитрием Бушенко:

  • Изучаем Emacs. Эпизод 01
  • Изучаем Emacs. Эпизод 02
  • Изучаем Emacs. Эпизод 03
  • Изучаем Emacs. Эпизод 04
  • Изучаем Emacs. Эпизод 05
  • Изучаем Emacs. Эпизод 06
  • Изучаем Emacs. Эпизод 07
  • Изучаем Emacs. Эпизод 08: Инструменты работы с ELisp-кодом
  • Изучаем Emacs. Эпизод 09: ediff, magit, psvn и emacs —daemon
  • Изучаем Emacs. Эпизод 10: Базовые возможности Org-mode, literate programming и экспорт в html/pdf
  • Изучаем Emacs. Эпизод 11: Средства работы с Clojure-кодом
  • Изучаем Emacs. Эпизод 12: Макросы, ООП, DSL
  • Изучаем Emacs: Эпизод 13. Управление проектами при помощи EDE

Cерия скринкастов (на англ. языке) Emacs Rocks.

Невероятно огромная, подробная и полезная статья (на англ. языке): Sacha Chua’s Emacs configuration.

Огромное разнообразие цветовых тем для Emacs. Смотреть тут.

Чтобы не оставить без внимания пользователей другого редактора — Vim, вот ссылка на мой .vimrc на GitHub. Там все подробно описано (если что, могу и по Vim статью написать…).

С нетерпением жду Ваших комментариев, уважаемые читатели. Надеюсь, Вы нашли что-то полезное/новое для себя.

Да пребудет с Вами Emacs…

Спасибо за внимание.

Как же я дошёл до жизни такой?

В связи со сменой работы мне пришлось взять новый ноут (корпоративный забрали).
Требования к ноуту у меня были достаточно понятные: 16 гиг оперативы, 512 гиг жёсткого диска (или больше) и — это самое противное — чтобы на нём завёлся Linux без особых танцев.
Я не очень долго выбирал, потому что несколько лет работал на Lenovo X1 Carbon (вроде как 4 поколения), взяв Lenovo X1 Carbon но уже 9 поколения.

Когда мне пришёл ноут, я запустил Windows 10 Pro, которая шла в комплекте, и … решил не ставить Linux. Почему? Потому что тут внезапно(!) оказался тачскрин, работающий сканер отпечатков пальцев, профили питания для экономии батареи… Короче, я понял, что заводить всё это в лялихе мне неохота, а отказываться от таких удобств чисто ради виндекапца я не готов.

Настроил за пару дней WSL2, Docker, Emacs, всё завелось, я смог работать.

Но тут по работе пришлось скачивать кучу файлов, смотреть/редактировать их, затем отправлять назад. Так как все приложения кроме докера и Emacs’а у меня запущены в винде, открывать всё это в Emacs, который работает изнутри WSL не очень удобно. Я решил попробовать запустить Emacs в винде. Так как на многие мои вопросы ответы в интернете ищутся не по первой ссылке, я решил часть всего этого описать тут.

Установка

Ну тут всё просто: идём на сайт https://www.gnu.org/software/emacs/, качаем, ставим.

Складываем конфиги

По-умолчанию Emacs ищет конфиги не в C:\Users\<Username>, а в C:\Users\<Username>\AppData\Roaming. Туда их и сложим, чтобы не извращаться с особенностями винды.

Так как я держу конфиги в Git, я склонировал репозиторий в C:\Users\<Username>\Code\emacs_config, а затем сделал символические ссылки в PowerShell (запущенном под админом):

 C:\Users\Valen> mkdir .emacs.d
 C:\Users\Valen> New-Item -ItemType SymbolicLink -Path C:\Users\Valen\ -Name .emacs -Value 'C:\Users\Valen\Code\emacs_config\.emacs'
 C:\Users\Valen> New-Item -ItemType SymbolicLink -Path C:\Users\Valen\.emacs.d\ -Name settings -Value 'C:\Users\Valen\Code\emacs_config\.emacs.d\settings'

Меняем домашнюю директорию

Так как emacs по-умолчанию считает домашней директорией C:\Users\<Username>\AppData\Roaming, открывать файлы в emacs не очень удобно (нужно постоянно возвращаться в C:\Users\<Username>). Чтобы с этим побороться есть несколько способов:

  1. Перенастроить переменную HOME
    Не мой вариант, потому что мне лень возиться с тем, чтобы объяснять Emacs’у, где у него HOME из винды
  2. Переопределить переменную HOME
    Вот это мой варик, тут мне всё понятно

Для этого в конец .emacs дописываем следующий код:

(if (string= system-type "windows-nt")
    (setenv "HOME" "C:\\Users\\Valen"))

emacs –daemon и emacsclient

Я достаточно долго (пару часов) гуглил, чтобы решить ряд непонятных ошибок, поэтому в этом разделе, думаю, самое ценное.

Во-первых, мне бы хотелось пользоваться emacsclient, потому что в 2021 году emacs всё ещё стартует непозволительно долго.
Во-вторых, мне не хотелось запускать emacs --daemon при каждом старте системы. Ну просто потому что.

Выход я нашёл следующий: если запускать emacsclient с ключом -a (который запускает альтернативный редактор, если emacsclient не запустился) равным пустой строке, то emacsclient сам пытается запустить emacs --daemon и подключиться к нему. Наш вариант!

Для того, чтобы это всё заработало, надо удалить папку C:\Users\Valen\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Emacs-<version>, в которой находятся ярлыки, созданные при установке Emacs.

Далее в папке C:\Users\Valen\AppData\Roaming\Microsoft\Windows\Start Menu\Programs нужно создать ярлык с названием Emacs и в свойстве target указать следующее:

"C:\Program Files\Emacs\x86_64\bin\emacsclient.exe" -c -n -f "c:\Users\Valen\.emacs.d\server\server" -a=

Где -f "c:\Users\Valen\.emacs.d\server\server" указывает на файл сокета. Помните, мы меняли домашнюю директорию? Так вот да, есть последствия.

Перенастройка

Linux’овый конфиг Emacs’а не давал нормально запускаться. Пришлось искать и лечить.

В частности, пришлось отключить pinentry-интеграция (в винде она всё равно не актуальна):

(if (string= system-type "gnu/linux")
    (progn (setenv "INSIDE_EMACS" (format "%s,comint" emacs-version))
           (setq epa-pinentry-mode 'loopback)
           (pinentry-start)))

PowerShell

Для полного счастья не хватало только PowerShell в shell-mode. Делается это добавлением следующего в конфиг Emacs:

(if (string= system-type "windows-nt")
    (setq
     shell-file-name "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
     explicit-powershell.exe-args '("-InputFormat" "Text" "-NoLogo")))

Правда, автодополнение не завелось пока что.

Что ещё?

Очевидно, не завелись ни grep, ни silversearcher-ag, что печалит. Но наверняка найдётся выход и из этого положения.
Плюс я не занимался вопросом интеграции с git, потому что, очевидно, под виндой не занимаюсь написанием кода.

Небольшое заключение

В WSL2 он (Emacs) всё ещё работает быстрее а пользоваться им удобнее. Поэтому я всё-таки сделал symlink /mnt/c/Users/Valen → ~/winhome и пользуюсь WSL’ным.

А, да, на днях вышел анонс Surface Laptop Studio, так что я пожалел, что взял Lenovo Carbon. Но теперь я знаю, что на винде есть жизнь.

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

This article describes how to install Emacs on Windows 10, including supporting packages. This article is part of the Emacs Writing Studio which explains how to use Emacs to undertake research and write and publish articles, books, and websites.

This article is part of Emacs Writing Studio, a book that explains how to use Emacs to undertake research and write and publish articles, books, and websites. Emacs Writing Studio is also available as an e-book from your favourite retailer.

The source files of the book and EWS configuration are also freely available on GitHub.

Installing Emacs on Windows 11

The first step is to download Emacs for Windows directly from its makers on the GNU website. You need the emacs-$VERSION-x86_64-installer.exe, where version is currently 29.4. This file contains a 64-bit build of Emacs with dependencies as an installer package.

Download this file and run the program to install Emacs on your system. You can now run Emacs like any other Windows software.

To upgrade Emacs in future, simply repeat this process.

But wait there is more. Emacs is neatly integrated with Linux systems, but to make it function properly on Windows some additional configuration steps and additional software is required.

Directories

Home Directory

The next step is to set the default folder for Emacs by setting the HOME variable. This variable instructs Emacs to use the C:\users\username\ folder as your home location. Open Powershell in administrator mode and enter this line:

You can also set this variable through the Windows Control Panel. Search for «environment» and click Edit System Variables and select Environment variables. Create a new variable called HOME and select your home folder and click OK.

In Emacs, your home folder is indicated with a tilde symbol. So lets say that your home folder is C:\Users\peter\ and you need the Downloads folder, then in Emacs refers to this location as ~/Downloads.

 

Emacs configuration folder

The location of the configuration folder depends on your operating system and Emacs version. If you are unsure where to store the init.el file, then you can use the Emacs help functionality. In most cases it will be something like ~/.emacs.d/. The dot at the start of the folder name means that it is hidden from view. To view the content of this folder in Windows you need to enable «Show hidden items» in the file explorer.

Type C-h v for help on variables and type user-emacs-directory and enter. The help buffer that now appears provides the correct folder name.

Read my article on configuring Emacs for more information.

External Software

Emacs is not a text editor, it is a computing platform with a built-in text editor. Emacs can also act as an interface to other Open Source free software. Most of these packages are included in common Linux distributions. Windows users need to use a bit more effort to install these.

Reading documents and ebooks

Emacs is great at displaying plain text but needs some assistance with reading other formats. The basic emacs package to view documents other than plain text is Doc-View. The image below explains the external packages required to read ebooks and articles.

For PDF documents you need to install Ghostscript or MuPDF. The pdftotext program from the Poppler software helps with finding and copying text in a PDF.

To read and export to office documents (MS Office and LibreOffice), Emacs needs to have acces to the LibreOffice software. Emacs uses this software to convert office documents to PDF and display them with the DocView package. LibreOffice can also assist with exporting Org mode files to office formats or to PDF.

To view EPub files you need a version of the zip and unzip programs. You can find these programs, and many others, in the GnuWin32 project.

You also need to tell Emacs where these tools live, so you need to customise the exec-path variable.

Document conversion in Doc-View.

For more information on reading non-text files in Emacs see my article on reading ebooks.

 

Spellcheck

The Flyspell package performs spell checking on Emacs. Read the distraction-free writing for more information on how to configure spell-checking.

The ezwinports project maintains a large collection of useful open source software compiled for Windows computers, including Hunspell.

To install Hunspell on Windows, download the software from ezwinports. Extract the files in a folder on your drive, for example: C:\ProgramData\ezwinports\.

You need to add the bin folder to your path environment variable. A simple workaround is to add the full path of the Hunspell variable to your configuration, as such:

(setq-default ispell-program-name "C:/ProgramData/ezwinports/bin/hunspell")

Note that Emacs uses a forward slash /, not the Windows backslash \.

The binary distribution includes dictionaries for US English and UK English. You can find the dictionaries for other languages on the Internet; install them into share/hunspell directory in your Hunspell installation directory.

Using Emacs on Windows 11

This article only discussed how to install Emacs on Windows 11. The other articles on this website show you how to configure Emacs and how to use Emacs to research, write and publish articles, books and websites.

The EWS GitHub repository contains the latest information about the required external software.

Emacs is a malleable system, so everybody will have their personal preferences to undertake a task. Any article on how to be productive with Emacs is thus opinionated. If you have a different way of doing things, please share your views and leave a comment below, or complete the contact form to send me an email.

These notes summarize some of my discoveries (re-)learning GNU Emacs. Since these are my personal notes, it may help to briefly describe my background. I used Emacs on Unix from somewhere around 1990 until 1995. Then in 1995 I began using Windows as my primary operating system and stopped using Emacs. In 2010 I decided to give Emacs on Windows another try. I may not mention some basic things just because I remember them from my initial experience.

These notes are not a thorough introduction to Emacs. For a more systematic reference, the Emacs Wiki is a good place to start. I wanted to write these things down for future reference, and I put this file up on my website in case someone else finds it useful. If you have comments or corrections, please let me know.

Table of contents

  • Installation and configuration
    • Installing Emacs and setting up .emacs
    • Backup files
    • Recycle bin
    • Integration with the Windows File Explorer
    • Getting rid of the start-up screen and toolbar
    • Changing fonts
    • Enabling commands to change case
    • Spell check
    • Installing color-theme
    • Installing nXhtml
    • Installing powershell-mode
    • Remapping my keyboard
    • Line wrapping
    • Column position
  • Emacs vocabulary
  • Editing LaTeX
  • Editing source code
  • Selecting and deleting text
  • Searching and replacing
    • Searching for strings
    • Regular expressions
    • Replacing
  • Saving text and positions
    • Saving text
    • Saving positions
  • The Emacs help system
  • Navigating files, buffers, and windows
    • Files
    • Buffers
    • Windows
  • Miscellaneous commands
  • Emacs resources

Installation and configuration

Installing Emacs and setting up .emacs

I install all my Unix-like software under C:\bin and have that directory in my Windows PATH environment variable. I installed Emacs 23.1 in C:\bin\emacs-23.1 and created an environment variable HOME set to C:\bin. The significance of HOME is that Emacs can find your configuration file if you put it there. This file is called “dot emacs” because the traditional name for the file on Unix systems is .emacs. On Windows, it is more convenient to name the file _emacs. (You can also name the file _emacs.el. Giving the file the .el extension causes Emacs to open the file in Lisp mode. And if someday the file becomes huge, you can compile it to make startup faster.)

Backup files

Emacs automatically saves backup versions of file and by default leaves these backup files beside the files being edited. This can be annoying. Some people call these extra files “Emacs droppings.” Adding the following lines to .emacs instructs Emacs to put all backup files in a temporary folder.

(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))

Recycle Bin

The following line configures Emacs so that files deleted via Emacs are moved to the Recycle.

(setq delete-by-moving-to-trash t)

More details here.

Integration with the Windows File Explorer

The following registry script creates an “Open with Emacs” option in the Windows file explorer context menu.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\Shell\Open In Emacs\Command]
@="\"C:\\bin\\Emacs-23.1\\bin\\emacsclientw.exe\" -a \"C:\\bin\\Emacs-23.1\\bin\\runemacs.exe\" \"%1\""

See also this blog post for how to open a file in a running instance of Emacs rather than starting a new instance for each file.Putting these two lines in .emacs creates a menu item File -> Open recent.

(require 'recentf)
(recentf-mode 1)

If you have a desktop shortcut to runemacs, you can open a file in Emacs by dropping it on the shortcut icon.

Getting rid of the start-up screen and toolbar

I turned off initial start-up screen by adding (setq inhibit-startup-screen t) to .emacs. This had the pleasant side effect of making the “Open with Emacs” context menu work as expected. (Before, Emacs would open with a split window. Now it opens with just the “sent” file.)

Got rid of the toolbar by using the configuration editor under Options / Customize Emacs.

Changing fonts

I used the Options menu to change the default font to Consolas.

Enabling commands to change case

The commands for converting the text in a region to upper or lower case are disabled by default. (The GNU Emacs manual says beginners find these commands confusing and so you have turn them on. That seems very strange. Many other Emacs commands are more confusing.) The following turns the commands on.

(put 'upcase-region 'disabled nil)
(put 'downcase-region 'disabled nil)

Once this is enabled, you can make the text in a region lowercase with C-x C-l or uppercase with C-x C-u.

Spell check

GNU Emacs does not provide a spell checker. Instead, it provides hooks to install your own spell checker, usually Aspell. I downloaded Aspell version 0.50.3 (win32) from here. I then installed the English dictionary from the same page. The dictionary installer warned me that Aspell was already installed and suggested that I uninstall it. I did, thinking that it might install a newer version. That didn’t work. I re-installed Aspell, then installed the dictionary, ignoring the warning. Everything worked fine.

After installing Aspell, I let Emacs know where to find it by adding these lines to my .emacs file.

(setq-default ispell-program-name "C:/bin/Aspell/bin/aspell.exe")
(setq text-mode-hook '(lambda() (flyspell-mode t) ))

The command M-x ispell will run the spell checker on your file. If flyspell-mode is turned on, as it is in the lines above, misspelled words are underlined in red as you type.

Installing color-theme

It was difficult to find a more direct way to configure the color schemes that Emacs uses, so I installed color-theme version 6.60. I then used color theme creator to create a basic theme then tweaked the colors.

Installing nXhtml

The default support for editing HTML files was less than I expected. I heard good things about nXhtml and decided to go with it. Notice that it inserts extra menus when you open a file in nXhtml mode. You can use the commands from the menu until you learn their keyboard shortcuts.

nXhtml mode requires HTML to be valid XHTML. If your HTML is not valid, you can use HTML Tidy to bring it into standard compliance. HTML Tidy appears as a menu option under nXhtml, but it must be installed separately. Installing HTML Tidy is very simple: download two files, the executable and a DLL, and copy them to somewhere in your path. Once HTML Tidy is installed, it will continually check the validity of the XHTML. It will display its status in the mode line and will turn angle brackets red that are not in the correct place.

Incidentally, the table of contents for this page was automatically generated using nXhtml. Just give every <h> tag an id. Then you can use commands from the nXhtml menu to insert the table of contents and its style sheet.

NB: Apparently the nXhtml code does not allow a space on either side of the equal sign when specifying the id value.

Installing powershell-mode

I installed a mode for editing PowerShell code by copying powershell-mode.el, downloaded from here, by copying the file to C:\bin\emacs-23.1\site-lisp, which is in my Emacs load-path. I tried installing some code that would allow me to run PowerShell as a shell inside Emacs. That did not work on the first try and I did not pursue it further.

Remapping my keyboard

Many Emacs users recommend remapping your keyboard so that the caps lock key becomes a control key. I don’t like the idea of changing my keyboard just to accommodate one program, even a program I may use very often. However, I recently bought a laptop that came with a Fn key right where my muscle memory expects the left control key. I hardly ever use the caps lock key, so I made it a control key for the sake of Emacs and for making it easier to use my laptop. I mapped the scroll lock key, a key I have not used in a decade or two, to caps lock in case I ever need a caps lock key. My initial intention was to keep the original left control key as an addition control key, but then I disabled it to force myself to get into the habit of using my new control key. I mapped the keyboard of every computer I use to be the same. This has been hard to get used to.

I don’t know what I want to do for my “Meta” key. For now I’m using the Esc key. Some recommend using the original Control key after remapping the Caps Lock key. I have two problems with that: it will not work on my laptop, and I first have to break my habit of using the original Control key as a Control key. (Why not just remap the Fn key on my laptop? Unfortunately this key cannot be remapped like an ordinary key.) I may try to get in the habit of using the right Alt key as my Meta key.

Line wrapping

I set global-visual-line-mode as the default way to handle line wrap. I did this through the menu sequence Options / Customize Emacs / Specific Option. This causes text to flow as it does in most Windows programs.

Column position

By default, Emacs displays the current line number in the mode line but not the current column number. To display the column number, add the following to your .emacs file.

(setq column-number-mode t)

Emacs vocabulary

Emacs uses a set of terminology that is not commonly used elsewhere. The following correspondences are not exact, but they are a good first approximation.

Emacs terminology Common terminology
fill word wrap
yank paste
kill cut
kill ring clipboard
mode line status bar
point cursor
font lock syntax coloring

The “echo area” is the very bottom of an Emacs window. It echoes commands, displays the minibuffer, and provides a place to type extra arguments for commands.

Editing LaTeX

One of the most useful key sequences for editing LaTeX files are C-c C-o to insert a \begin and \end pair. Emacs will prompt you for the keyword to put inside the \begin{} statement. Another useful key sequence is C-c C-f to run latex on a file. (Emacs can detect whether a file is plain TeX or LaTeX. I use LaTeX exclusively.)

There is Emacs package AUCTex for editing (La)TeX files, but I have not tried it.

I would like to have C-c C-f run pdflatex rather than latex, but I have not found out how to configure that.

Editing source code

Here are a few useful commands for editing source code files.

Command Explanation
C-M-a Go to beginning of a function definition
C-M-e Go to end of a function definition
C-M-h Put a region around a function definition
C-j Insert a newline and properly indent the next line

I put these lines in my .emacs file to make the C++ mode behave more like what I am accustomed to.

(add-hook 'c++-mode-hook
  '(lambda ()
     (c-set-style "stroustrup")
     (setq indent-tabs-mode nil)))

Selecting and deleting text

C-x h selects the entire current buffer.

You select a region by using C-SPACE at one end of the region and a selection command and moving the point (cursor) to the other end of the region. Then you can use C-w to cut or M-y to copy. The paste command is C-y. Emacs maintains a “kill ring”, something analogous to the Windows clipboard but containing more than just the latest cut or copy. For example, C-y M-y. lets you paste the next-to-last thing that was cut. Use M-y again to paste the cut before that, etc.

You can kill all but one whitespace character with M-SPACE. You can kill all but one blank line with C-x C-o.

Emacs has commands for working with rectangular regions, analogous to vertical selection in some Windows programs. Specify a rectangular region by setting the mark at one corner and the point at the opposite corner. All commands for working with rectangular regions start with C-x r. Here are a few rectangular region commands.

Command Explanation
C-x r k Kill the rectangle
C-x r d Delete the rectangle
C-x r c Clear the rectangle, i.e. fill the region with whitespace
C-x r y Yank (paste) the rectangular region

Searching and replacing

Searching for strings

Use C-s for forward incremental search, C-r for backward incremental search. Type another C-s or C-r to repeat the search. Type RET to exit search mode.

Regular expressions

C-M-s and C-M-r are the regular expression counterparts of C-s and C-r.

Emacs regular expressions must escape the vertical bar | and parentheses. For example, the Perl regular expression (a|b) becomes \(a\|b\) in Emacs.

Emacs regular expressions do not support lookaround.

The whitespace patterns \s and \S in Perl are written as \s- and \S- in Emacs. There is no equivalent of Perl’s \d except to use the range [0-9].

Replacing

Use M-x replace-string and M-x replace-regex for replacing text. There are also interactive counterparts M-x query-replace and M-x query-replace-regex.

Saving text and positions

Saving text

You can save a region of text to a named register for later pasting. Register names can be any single character. The command to save to a register a is C-x r s a. The command to insert the contents of register a is C-x r i a .

Saving positions

Bookmarks are named positions in a buffer. The command to create a bookmark is C-x r m bookmark_name. The command to go to a bookmark is C-x r b bookmark_name.

The Emacs help system

All help commands start with C-h. If you don’t know a more specific location to go to, you can start by typing C-h C-h to get to the top of a navigation system for help.

C-h m is very useful. It displays all active modes and describes key bindings.

C-h k tells what command is bound to a key and gives documentation on how it is used. C-h w is a sort of opposite: given a command, it sells what keys are bound to that command.

Navigating files, buffers, and windows

Files

The command to open a file is C-x C-f. The command for ‘save as” is C-x C-w.

Emacs has a sort of File Explorer named Dired. You can open Dired with the command C-x d. You can move up and down in the Dired buffer by using p and n just as you can use C-p and C-n in any other buffer. You can still use the control key, but you do not have to.

Here are a few of the most important Dired commands.

Dired command Action
RET Visit selected file (or directory)
C Copy
D Delete immediately
d Mark for deletion. Use x to carry out deletions.
R Rename a file
! Specify a shell command to carry out on a file

Adding the following two lines to your .emacs file will create an Open Recent submenu under the File menu.

(require 'recentf)
(recentf-mode 1)

Buffers

The command C-x b takes you to your previous buffer.

The command C-x C-b creates a new window with a list of open buffers. You can navigate this list much as you would the Dired buffer.

You can type the letter o to open the file on the current line in another window. You can type the number 1 to open the file as the only window.

The command M-x kill-some-buffers lets you go through your open buffers and select which ones to kill.

Windows

The command C-x 1 closes all windows except the current one.

C-x 2 splits the current window horizontally, one buffer on top of the other.

C-x 3 splits the current window vertically, one beside the other.

C-x o cycles through windows.

Miscellaneous commands

Command Explanation
M-g g Go to line number
M-= Report line and character count of region
M-/ Autocomplete based on text in current buffer
C-x C-e Evaluate the Lisp expression to the left of the cursor
M-x eval-region Evaluate the selected region as Lisp code
M-x shell Run a shell inside Emacs
M-! Run a single shell command
M-x sort-lines Sort the lines in a region
M-x desktop-save Save an Emacs session
C-t Transpose characters
M-t Transpose words, works across punctuation and tags

Emacs resources

One program to rule them all
Emacs cursor movement
Emacs and Unicode
Emacs kill (cut) commands
Real Programmers (xkcd cartoon)
10 Specific Ways to Improve Your Productivity With Emacs from Steve Yegge

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как активировать офис 2021 на windows 11 бесплатно
  • Как переключаться между вкладками windows
  • Как поставить автосохранение на компьютере windows
  • C windows system32 с расширением
  • Основные компоненты windows live не устанавливается