Showing posts with label 맞춤법 검사. Show all posts
Showing posts with label 맞춤법 검사. Show all posts

Wednesday, June 3, 2015

Emacs Spell-checker English/Korean

Emacs Spell-checker English/Korean

Emacs Spell-checker English/Korean


This post is written with e[ ⎋Esc ]m[ ⌥Meta ]a[ ⌥Alt ]c[ ^Ctrl ]s[ ⇧Shift ] org-mode.

이 문서는 e[ ⎋Esc ]m[ ⌥Meta ]a[ ⌥Alt ]c[ ^Ctrl ]s[ ⇧Shift ] org-mode로 작성된 글입니다.


System Environments

Operating Systems

  • Main- : OS X Yosemite (10.10.3)
  • Sub- : Debian GNU/Linux Wheezy (7.8)
  • Server: Debian GNU/Linux Wheezy || Squeeze
  • Mobile: iOS 7.1.2

Ispell-word and the secondary click within Flyspell on

Needless to say, the GIF below is self-explanatory.

English/Korean spell-checker in Emacs 24.3, OS X

The work-flow was captured under Hunspell with Emacs Cocoa 24.3 in OSX. Hunspell was activated for English/Korean. Shortcuts I set are ⌘d for ispell-word and ⌘2⌘2 for the spell-checking pop-up window. For the former, you can select a word you want by typing a digit. The latter is technically nothing but the secondary click(or right click) at a mouse point on a word underscored by Flyspell On. I made the key-binding for it by ⌘2⌘2. Though the gif above shows way in Emacs Cocoa under OSX, it is completely possible in GNU Emacs under Linux.

FYI) ⌘⎵ in the gif indicates the shortcut I set for ispell-change-dictionary.

Requirements

  • Hunspell for Emacs cocoa 24.3 in OSX or for GNU Emacs 23.4/24.3 in Debian GNU/Linux

It is not dealt with in this post, because I explained it already. You can see the details by clicking one of the links followed.

There are descriptions for a simple way to change both input methods and hunspell dictionaries as well.

Instruction

Typing ispell-word after ⌥x (M-x in typical Emacs notation) would be enough for some users to check spelling. However, what I want to say is how to set up a key-stroke for the spell-checking pop-up window once the flyspell is on.

  1. Set flyspell-mode on for text-mode by adding the line
    '(text-mode-hook (quote (turn-on-flyspell text-mode-hook-identify)))
    

    into your Emacs preference file, i.e. ~/.emacs. For instance,

    (custom-set-variables
    ;; custom-set-variables was added by Custom.
    ;; If you edit it by hand, you could mess it up, so be careful.
    ;; Your init file should contain only one such instance.
    ;; If there is more than one, they won't work right.
    '(cua-mode t nil (cua-base)) ;;<--- let c-x c-c c-v work
    '(text-mode-hook (quote (turn-on-flyspell text-mode-hook-identify))) ;;<--- flyspell
    )
    

    The basic to read an elisp source is that anything after ;; is a comment, so that doesn't affect Emacs at all.

  2. Activate ⌘2⌘2 for the secondary click(or right click) at an underscored word by adding the following elisp code to ~/.emacs
    ;; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    ;; \\\\\[Body III-a.] For keyboard strokes for spelling check
    ;; \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
    (global-set-key [\s-mouse-2] 'flyspell-correct-word)   ;; <--- step 0/2 for s-2 s-2
    ;; ------------------------------
    ;; ---> function 1
    ;; ------------------------------
    (defun make-mouse-event-at-point (base-event)
    (let ((posn (posn-at-point))
      (prefix "")
      (basic-type (event-basic-type base-event))
      (modifiers (event-modifiers base-event)))
    (cond
    ((and (integerp basic-type) (>= basic-type ?0) (<= basic-type ?9))
    ;; click
    (let* ((mouse-type (intern (format "%smouse-%d" prefix (- basic-type ?0))))
           (click-count 1)
           (type (event-convert-list (append modifiers (list mouse-type)))))
      (list type posn click-count)))
    (t
    (error "Unsupported key for mouse event: %s" (event-basic-type base-event)))
    ))
    )
    ;; ------------------------------
    ;; ---> function 2
    ;; ------------------------------
    (defun simulate-mouse-event-at-point ()
    (interactive)
    (let ((event (make-mouse-event-at-point last-input-event)))
    (setq unread-command-events (cons event unread-command-events))))
    ;; ------------------------------
    ;; ---> function 3
    ;; ------------------------------
    (defvar simulate-mouse-event-map (make-sparse-keymap))
    (global-set-key (kbd "s-2") simulate-mouse-event-map)   ;; <--- step 1/2 for s-2 s-2
    ;; ------------------------------
    ;; #####!!! final step, i.e step 2/2 for keyboard stroke for mouse#-click
    ;; ------------------------------
    (define-key simulate-mouse-event-map [t] 'simulate-mouse-event-at-point)
    

    When you use the exactly same elisp above in GNU Emacs under Linux, the shortcut must be ⊞Win-2 ⊞Win-2 in a non-apple keyboard. If you want to change it to C-2 C-2, then it can be done after replacing s- and \s- with C- and \C- respectively.

FYI) In GNU Emacs under Linux, C, M, S, and s stand for Ctrl, Meta, Shift, and super-key (a.k.a. Windows key) respectively.

Acknowledgement

I acknowledge Gilles from StackExchange's debt to almost every elisp code here. You can find his source code explicitly in HERE.

Epilog, 한글 사용자를 위하여

Emacs에서 맞춤법 검사는, ⌥x (M-x Emacs 기본 표기) 후 ispell-word 로 간단히 실행할 수 있다. Flyspell mode(틀린 맞춤법에 밑줄 그어짐)이 켜있는 경우에는, 밑줄 그어진 단어 위에서 우클릭하면 팝업창이 뜨고 화살표키로 선택하는 방법으로도 사용할 수 있다. 영어의 경우는 특별한 사전을 설치하지 않아도 바로 검사할 수 있음은 물론이다. 한글 맞춤법 검사는 현재로는 hunspell이 거의 유일무이한 대안인데, 영어와 함께 이를 활성화 하는 방법은 지난 Posts에서 설명했다.

OSX Yosemite 전까지는 Aquamacs에서 ispell-word (or ispell-region)으로 영어/한글 맞춤법 모두를 해결해 왔었다. 바람입력기로 OSX 차원이 아닌 Aquamacs 자체에서 입력소스를 변경하고, 영어 맞춤법은 Aquamacs에서 기본으로 제공하는 것으로 한글 맞춤법은 OSX 차원에서 설치한 Korean hunspell dictionary로 약간은 변칙을 써왔었다. 당시에도 Aquamacs에서 Hunspell을 동작하게 하는 방법을 많이 시도했으나 다 무위로 돌아갔었고, 이 변칙 방법으로도 잘 작동하니 문제 없이 사용했었다. 물론, OSX 단에서 설치한 이 한글 사전은 Aquamacs는 물론 다른 프로그램에서도 잘 돌았었다.

OSX Yosemite 후, 모든 것이 달라졌다. OSX 단에서 설치한 한글 사전은 어디에서도 제대로 동작하지 않았다. BACK TO THE MAC에서 항상 추천하는 한글 맞춤법 검사기 "단디" 역시 나에게는 해당 사항이 없었다. 왜냐하면, 단축키를 지정해도 Emacs던 Aquamacs던 동작하지 않고, 설혹 가능해도 단순히 확인할 수 있을 뿐 수정은 직접 해주어야 하는 점 때문이다. 나에게는 Hunspell이 필요했다.

모든 문제의 시작은 Hunspell임을 직감하고, 어떻게 해도 이를 활성화 할 수 없었던 Aquamacs를 포기하고 Original GNU Emacs에 가장 가깝다고 하는 Emacs Cocoa로 전환하기로 결정했다. 다행히, OSX Yosemite Emacs Cocoa에서 Hunspell을 쓰는 방법을 찾았다. (Linux에서 GNU Emacs로 hunspell 이용은 사실 자명하다.) 이는 위에서 언급한 지난 두 글에서 자세히 설명했지만, 핵심은 OS 마다 적절한(?) Emacs version을 써야 하는 점이다. 그러면 문제 해결은 비교적 간단하다.

언제나 그렇듯이, 한글이 항상 문제(?)다. 어지간히 Emacs에서 한글을 써본 사람은 다 알겠지만, Linux를 제외한 OS에서 OS 단에서 제공하는 한/영 변환은 항상 문제를 일으키므로, Emacs 자체에서 제공하는 입력 소스 변환을 쓰는 것이 항상 추천된다. 이는 OSX Yosemite에서도 바람입력기를 통해 간단히 해결할 수 있다. Hunspell을 Emacs에서 쓸 수 있게 된다 하더라도 문제는 크게 두 가지가 남아있다.

첫째, ⌥x (M-x Emacs 기본 표기) ispell-word*Choices* buffer 에서 한글이 잘린다

한글 잘림 in *Choices* buffer

이는 한글과 영어를 다른 크기로 지정함으로써, 어느 정도 해결 가능하다. 아래는 영어는 Anonymous Pro 10으로, 한글은 HCR Dotum LVT 16으로 만든 경우이다.

;; Setup different font family and size for English/Korean
(setq default-frame-alist
      '(
	(top . 0) (left . 182) (width . 96) (height . 36)   ---> window position and size
	))
(when (eq system-type 'darwin)
  (set-face-attribute 'default nil :family "Anonymous Pro")
  default font size (point * 10)
  (set-face-attribute 'default nil :height 195)
  (set-fontset-font t 'hangul (font-spec :name "HCR Dotum LVT-16"))
  )

이렇게 하면 한글 폰트 크기가 전반적으로 바뀌면서, *Choices* buffer 에서도 한글이 잘리지 않는다. 두벌식 사용자라면, ispell-word 단축키만 따로 지정해도 적당히 쓸 만한 환경을 구축할 수 있다.

나는 세벌식390 사용자다. 문제가 심각해졌다. Emacs 자체 입력 소스를 설정하면 한글 세벌식 입력 환경에서 *Choices* buffer 안에서 단어 선택이 안된다. Emacs 자체 입력 소스를 끄고, OSX 입력 소스를 쓰면 *Choices* buffer 안에서 단어 선택은 되지만, ⌥x 같은 Emacs 단축키가 안먹는다!!! 어떤 세벌식을 쓰는 지와는 무관하게 세벌식 모두(보통, 390, 최종)에서 다 안된다. 이는 Yosemite 이전에 Aquamacs (Aquamacs 2.5x 이하 버전) 사용 시는 발생하지 않는 문제였다.이 문제를 해결하기 위해서 Flyspell-mode에서 마우스 우클릭하면 팝업창이 뜨는 것에 착안, 이를 키보드로 쓸 수 있는 방법을 여기서 기술했다. 이 방법은 당연하게도 두벌식이든 세벌식이든 상관없다. 게다가 ispell-word 를 쓸 때에도 불만이었던, "화살표키로 단어선택이 안되던 문제"에서 자유롭다. 가능한 한 키보드로 모든 것을 해결하려는 이들에게 숫자키로 가는 손가락은 화살표키보다 불편하다.

지난 글과 여기에서 설명하려한 방법의 목적을 다시 정리하자면, " 어떤 한글 입력 방법을 쓰던 상관 없이 Emacs에서 맞춤법 검사 과정 전부를 키보드로 해결하자! "이다. Emacs 버전을 타는 경향이 있지만, 이는 OSX 전반은 물론 Debian GNU/Linux에서도 큰 수정 없이 바로 쓸 수 있는, 현재로써는 가장 완벽한 해결책이다.


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Created: 2015-06-04 Thu 11:21

Emacs 24.3.1 (Org mode 8.2.10)

Thursday, November 28, 2013

Emacs spell-checker

Emacs 한글 맞춤법 검사기

Emacs 한글 맞춤법 검사기


;; =================================================
;; εμαcs is ⎋[esc]⌘[meta]⌥[alt]⌃[ctrl]⇧[shift].
;; =================================================

이 문서는 emacs org-mode로 작성된 글입니다.

Operating System Environments

  • Main- : OS X Mavericks (10.9)
  • Sub- : Debian GNU/Linux Wheezy (7.2)
  • Server: Debian GNU/Linux Squeeze || Lenny
  • Mobile: iOS 7.0.4

Emacs 사용 환경

  • OS X: Aquamacs + OS X dictionaries
  • Debian GNU/Linux: Emacs + Hunspell

emacs_lisp in .emacs

OS X: Aquamacs + OS X dictionaries

Aquamacs한글 맞춤법 검사기는 아래에서 다운 받는다.

ko-aff-dic-0.5.6.zip 파일의 압축을 풀어, ko.affko.dic~/Library/Spelling/ (Finder에서 ⌘⇧G) 아래에 복사해 넣는다. 전체 사용자에게 한글 맞춤법 검사기가 동작하게 하려면, /Library/Spelling/ 에 복사해 붙이자. 시스템을 재부팅한다.

여기까지 하면, TextEdit.app이나 Mail.app 등에서 한글 맞춤법 검사기가 잘 동작하는 것을 볼 수 있다. 하지만 여기서 목표는 Aquamacs에서 이를 사용할 수 있게 하는 것이다. Aquamacs에서는 TextEdit.app이나 Mail.app 등과는 다르게 어떤 언어를 사용하여 맞춤법 검사를 할 지를 editor 차원에서 일일이 변경해야 함에 주의하자. 즉, 한글 맞춤법을 검사할 때는 한글로 해서 검사해야 하고, 영문 맞춤법을 검사할 때는 영어로 맞춤법 검사기를 바꾸어 주어야 한다. 또한, 아래의 기술할 방법으로 Aquamacs에서 한글 맞춤법을 쓰게 되면, TextEdit.app이나 Mail.app에서도 한 가지 언어로만 맞춤법 검사를 할 수 있게 됨에도 주의하자. 1

그럼에도 불구하고 Aquamacs에서 한글 및 다른 언어들의 맞춤법 검사를 쓰고 싶으면 다음을 진행하자. 사실, 아래 Emacs Lisp code에 다 적어 놨지만 간단히 방법을 기술하면 아래와 같다.

0째, Aquamacs에서 원할한 한글 사용을 하려면 바람 입력기 사용을 추천한다. 자세한 설치법은 지난 Post를 참고하자. -> "Emacs에서의 한글환경" 바로 가기

첫째, Aquamacs에서 영어 맞춤법을 검사하기를 기본으로 지정하자. 2

  1. OS X Mavericks에서는 System Preferences 을 열어 Keyboard 를 클릭, Text 페널에서 Spelling:U.S. English 로 선택하자.
  2. OS X Mountain Lion에서는 System Preferences 을 열어 Language & Text 를 클릭, Text 페널에서 Spelling:U.S. English 로 선택하자.

여기까지하면 Aquamacs 뿐만 아니라 TextEdit.app이나 Mail.app 등에서도 영어 맞춤법 검사만 가능해진다.

둘째, 이제 아래 Emacs Lisp code를 ~/.emacs 를 열어 적어넣자.

;; -------------------------------------------
;; Aquamacs spell-checker
;; -------------------------------------------
;; ###
;; pre-settings for Mountain Lion: System Preferences -> Language & Text -> [Text: Spelling: U.S. English]
;; pre-settings for Mavericks    : System Preferences -> Keyboard        -> [Text: Spelling: U.S. English]
;; ###
;; ### korean-english-german
;; (let ((langs '("ko" "en" "de")))
;;   (setq lang-ring (make-ring (length langs)))
;;   (dolist (elem langs) (ring-insert lang-ring elem)))
;; (defun cycle-ispell-languages ()
;;   (interactive)
;;   (let ((lang (ring-ref lang-ring -1)))
;;     (ring-insert lang-ring lang)
;;     (ispell-change-dictionary lang)))
;; ###
;; ### korean-english
(let ((langs '("ko" "en")))
  (setq lang-ring (make-ring (length langs)))
  (dolist (elem langs) (ring-insert lang-ring elem)))
(defun cycle-ispell-languages ()
  (interactive)
  (let ((lang (ring-ref lang-ring -1)))
    (ring-insert lang-ring lang)
    (ispell-change-dictionary lang)))
;; ###
;; ### key bindings
(global-set-key (kbd "S-SPC") 'cycle-ispell-languages)
(global-set-key (kbd "A-D") 'ispell-region)   ;; cmd+shift+d
(global-set-key (kbd "A-d") 'ispell-word)     ;; cmd+d

한글과 영어로 맞춤법 검사하기를 활성화 하였고, 맞춤법 검사기 변환은 ⇧SPC 로 지정하였다. 영어로 시작되었을 것이므로 ⇧SPC 한 번 누르면 한글로, 또 누르면 영어로, 또 다시 누르면 다시 한글로 바뀐다. 글을 쓰다가 빨간줄이 그어지면, ⌘d 를 누르면 올바른 단어가 Aquamacs 최상단에 뜬다. 예를 들어, "적어놨지만"이라고 적은 부분에서 ⌘d 하면 아래 화면을 볼 수 있다.

11104767174_46ee950f40_z.jpg

여기서 0 을 누르면 "적어냈지만"으로, 3 을 누르면 "적어 놨지만"으로 바뀐다. Shift-Selction으로 지정한 영역 전체의 맞춤법 검사는 ⌘⇧d (or ⌘D)로 지정해 놓았다. 물론 이 key bindings가 싫으면, 사용자 취향에 따라 원하는 것으로 바꾸면 된다. 세 개 이상의 언어로 맞춤법 검사를 하고 싶으면 이를 확장하면 된다. 위의 Emacs Lisp code에서 주석 처리(;;)해놓은 부분이 바로 "한국어-영어-독어"의 사용 예이다.

Debian GNU/Linux: Emacs + Hunspell

Emacs는 깔려 있는 것으로 가정한다. 역시, 아래 Emacs Lisp code에 다 적어 놨지만 간단히 방법을 기술하면 아래와 같다. 여기서는 "한국어-영어-독어"를 사용하는 것으로 예를 들었다.3

  1. 아래를 실행하여 hunspell, hunspell-en-us, hunspell-ko, hunspell-de-de 를 설치한다.
    $ sudo apt-get install hunspell hunspell-en-us hunspell-ko hunspell-de-de
    
  2. 아래 Emacs Lisp code를 ~/.emacs 를 열어 적어넣자.
    ;; -------------------------------------------
    ;; GNU Emacs spell-checker in Debian GNU/Linux
    ;; -------------------------------------------
    ;; ###
    ;; pre-settings: sudo apt-get install hunspell hunspell-en-us hunspell-ko hunspell-de-de
    (setq ispell-local-dictionary-alist
          '(
            ("korean"
             "[가-힣]" "[^가-힣]" "[0-9a-zA-Z]" nil
             ("-d" "ko_KR")
             nil utf-8)
            ("english"
             "[A-Za-z]" "[^A-Za-z]" "[0-9a-zA-Z]" nil
             ("-d" "en_US")
             nil utf-8)
            ("german"
             "[a-zäöüßA-ZÄÖÜ]" "[^a-zäöüßA-ZÄÖÜ]" "[']" t
             ("-d" "de_DE")
             nil utf-8)
            )
          )  ;; =====> Mandatory I.
    (if (file-exists-p "/usr/bin/hunspell")
        (progn
          (setq ispell-program-name "hunspell")
          (eval-after-load "ispell"
            '(progn (defun ispell-get-coding-system () 'utf-8))))
      )      ;; =====> Mandatory II.
    (setq ispell-local-dictionary "english")
    ;; ###
    ;; ### korean-english-german
    (let ((langs '("korean" "english" "german")))
      (setq lang-ring (make-ring (length langs)))
      (dolist (elem langs) (ring-insert lang-ring elem)))
    (defun cycle-ispell-languages ()
      (interactive)
      (let ((lang (ring-ref lang-ring -1)))
        (ring-insert lang-ring lang)
        (ispell-change-dictionary lang)))
    ;; ###
    ;; ### korean-english
    ;; (let ((langs '("korean" "english")))
    ;;   (setq lang-ring (make-ring (length langs)))
    ;;   (dolist (elem langs) (ring-insert lang-ring elem)))
    ;; (defun cycle-ispell-languages ()
    ;;   (interactive)
    ;;   (let ((lang (ring-ref lang-ring -1)))
    ;;     (ring-insert lang-ring lang)
    ;;     (ispell-change-dictionary lang)))
    ;; ###
    ;; ### key bindings
    (global-set-key (kbd "S-SPC") 'cycle-ispell-languages) ;; shift-spacebar
    (global-set-key (kbd "s-D") 'ispell-region)            ;; cmd+shift+d
    (global-set-key (kbd "s-d") 'ispell-word)              ;; cmd+d
    ;; ### key bindings for windows keyboard
    ;; (global-set-key (kbd "S-SPC") 'cycle-ispell-languages) ;; shift-spacebar
    ;; (global-set-key (kbd "M-D") 'ispell-region)            ;; alt+shift+d
    ;; (global-set-key (kbd "M-d") 'ispell-word)              ;; alt+d
    

key bindings와 사용법은 위와 동일하다. Debian GNU/Linux를 Windows keyboard와 쓰는 경우(대부분은 그렇겠지만)는 위 code의 ;; ### key bindings for windows keyboard 위의 세줄을 주석(;;) 처리하고, 아래 세 줄은 주석(;;) 해제하여 쓰면 된다. 위에서 보다시피 이 경우에는 '단어 검사'와 '영역 검사'를 각각 ⌥d⌥⇧d (or ⌥D)로 지정되었다.

Epilog

Cocoa emacs에서 한글 맞춤법 검사기 사용은 시도해 보았으나… 실패했다. Cocoa emacs에서 OS X 사전을 사용하는 방법도 모르겠고, MacPorts에서 Hunspell port에 한글도 없어서 쓰려면 직접 설치해야 하는데, 귀찮아서 안해봤다. 어차피 Cocoa emacs는 자잘한 bugs가 많아서 쓰지도 않고 추천하지도 않는다.


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Footnotes:

1

원래 TextEdit.app이나 Mail.app 등에서는 Input sources에서 지정해준 언어들로 자동으로 그 언어에 맞게 알아서 맞춤법 검사를 해준다.

2

이유는 모르겠지만, 이렇게 하지 않으면 Aquamacs에서 맞춤법을 검사할 사전(⌥x ispell-change-dictionary)이 바뀌지 않는다.

3

참고 사이트들: Ref. #1, Ref. #2, Ref. #3

Created: 2013-11-28 Thu 21:35

Emacs 23.4.1 (Org mode 8.0.2)

Validate XHTML 1.0