Emacs의 가장 큰 차별점이라고 할 수 있는 emacs lisp를 활용한 버퍼 현실 조작에 필요한 내용을 정리해보았다.


사용자 함수 정의

  • .emacs 파일에 아래와 같은 방법으로 사용자 함수를 정의할 수 있다.
    (defun 함수명 ()
     (interactive)
     함수 내용
     )
    
    다음은 미니버퍼창에 간단히 메세지를 표시하는 예제이다.
    (defun my-func ()
      (interactive)
      (message "hello")
      )
    
  • 이렇게 정의한 함수는 언제든지 M-x를 누른 후, 함수명을 입력하여 실행할 수 있다.
  • 그런데 사용자 함수를 .emacs 파일에 직접 정의할 경우, 함수 내부에서 한글 사용시 문제가 발생한다. 이 경우, <emacs 설치 경로>/site-lisp 위치에 외부 파일을 생성하고 이 파일에 사용자 함수를 정의한 뒤, 아래와 같이 .emacs 파일에서 이를 읽어들이면 문제가 생기지 않는다.
    (load-library "외부 파일명")
    
    ==> [참고] UTF–8 한글 정상적으로 표시되도록 설정 방법
  • Emacs 실행 중에 위의 외부 정의 파일을 수정했을 경우에, 수정 내용을 바로 반영하기 위해서는, M-x를 누른 후 load-file을 입력하고 해당 파일의 경로를 입력하면 된다.

버퍼 조작 관련 유용한 함수들

외부 프로그램에서 함수 실행

  • emacsclient 실행시에 -e 인수를 사용하면 외부에서 내장 함수 혹은 사용자 함수를 실행할 수 있다.
     
    emacsclientw.exe -e "emacs lisp 표현식"
    
  • 윈도우 환경이라면, 아래와 같은 내용으로 배치파일을 작성하여 사용하는 것도 편리하다.
    emacsclientw.exe -n -e "%1"
    


    <테스트 환경>
     - OS : Windows 7 (32bit)
     - Emacs 버전 : Emacs 24.3 윈도우용
    
,

위의 두 글을 참고하면 웹페이지의 특정 class에 해당하는 부분을 추출하여 텔레그램 채널로 보내는 것이 가능하다.


사전 준비사항

  1. app template을 사용하여 프로젝트를 생성한다.

    lein new app clj-test-02
    

  2. project.clj 파일의 dependencies 부분에 아래와 같이 필요한 모듈을 정의한다.

    (defproject clj-test-02 "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "Eclipse Public License"
                :url "http://www.eclipse.org/legal/epl-v10.html"}
      :dependencies [[org.clojure/clojure "1.8.0"][clj-http "2.2.0"] [enlive "1.1.6" :exclusions [org.clojure/clojure]]]
      :main ^:skip-aot clj-test-02.core
      :target-path "target/%s"
      :profiles {:uberjar {:aot :all}})
    
    

예제

(ns clj-test-02.core
 (:gen-class)
 (:require [net.cgrand.enlive-html :as html])
 (:require [clj-http.client :as client]))

(use 'clojure.pprint)

(defn html-data []
  ;; clj-html 모듈을 사용하여 웹페이지의 내용을 가져온다.

  (html/html-resource (java.io.StringReader.
      (:body (client/get "http://httpbin.org"))))
)

(defn -main [& args]
  
  (pprint (client/post "https://api.telegram.org//bot<텔레그램 봇 토큰>/sendMessage" 
    {:body (format "{\"chat_id\": \"@<채널 ID>\", \"text\": \"%s\"}"
             (first (:content (first (html/select (html-data) [:.bash])))))
     :headers {"Content-Type" "application/json"}}))
)


<테스트 환경>
- OS : Windows 7
- Leiningen 버전 : 1.0.0
,

사전 준비사항

  1. app template을 사용하여 프로젝트를 생성한다.

    lein new app clj-test-01
    

  2. project.clj 파일의 dependencies 부분에 아래와 같이 필요한 모듈을 정의한다.

    (defproject clj-test-01 "0.1.0-SNAPSHOT"
      :description "FIXME: write description"
      :url "http://example.com/FIXME"
      :license {:name "Eclipse Public License"
                :url "http://www.eclipse.org/legal/epl-v10.html"}
      :dependencies [[org.clojure/clojure "1.8.0"] [clj-http "2.2.0"] [enlive "1.1.6" :exclusions [org.clojure/clojure]]]
      :main ^:skip-aot clj-test-01.core
      :target-path "target/%s"
      :profiles {:uberjar {:aot :all}})
    
    

HTML 파싱 예제

(ns clj-test-01.core
  (:gen-class) 
  (:require [net.cgrand.enlive-html :as html])
  (:require [clj-http.client :as client]))

(use 'clojure.pprint)

(defn html-data []
  ;; clj-html 모듈을 사용하여 웹페이지의 내용을 가져온다.

  (html/html-resource (java.io.StringReader.
      (:body (client/get "http://httpbin.org"))))
)

(defn -main [& args]
  
  ;; 태그로 찾기
  (pprint (html/select (html-data) [:a]))
  
  ;; id로 찾기
  (pprint (html/select (html-data) [:#AUTHOR]))
  
  ;; class로 찾기
  (pprint (html/select (html-data) [:.bash]))
  
  ;; 태그와 class를 조합해서 찾기
  (pprint (html/select (html-data) [:code.bash]))

)

반환값

html/select 함수의 결과는 아래와 같이 맵의 리스트 형태로 반환된다.

({:tag :a, :attrs {:href "http://httpbin.org"}, :content ("HTTP")}
  ... )

각각의 맵은 태그에 대한 정보를 담고 있는데, 태그의 내용물(content)이 단순 텍스트일 경우에 :content 부에 문자열의 리스트의 형태로 들어가며, 또다른 태그일 경우는 :content 부에 다시 맵의 리스트 형태로 들어간다.


태그의 내용물이 단순 텍스트일 때, 그 첫번째 문자열을 얻는 구문은 아래와 같이 된다.
(first (:content (first (html/select (html-data) [:.bash]))))

참고사이트


<테스트 환경>
- OS : Windows 7
- Leiningen 버전 : 1.0.0
,

react-native init시 아래와 같이 Unexpected token … 에러가 발생하는 경우

SyntaxError: Unexpected token ...
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Module._extensions..js (module.js:416:10)
    at Object.require.extensions.(anonymous function) [as .js] (C:\example01\node_modules\babel-register\lib\node.js:152:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:/example01/node_modules/react-native/local-cli/server/runServer.js:18:18)
    at Module._compile (module.js:409:26)

node.js를 최신 버전으로 재설치하여 해결이 되었다.

기존 버전: 4.4.7
업그레이드후 최신 버전: 6.11.2
,
  1. .emacs 파일에 다음과 같이 함수를 정의한다.
    (defun delete-this-buffer-and-file ()
      "Removes file connected to current buffer and kills buffer."
      (interactive)
      (let ((filename (buffer-file-name))
            (buffer (current-buffer))
            (name (buffer-name)))
        (if (not (and filename (file-exists-p filename)))
            (error "Buffer '%s' is not visiting a file!" name)
          (when (yes-or-no-p "Are you sure you want to remove this file? ")
            (delete-file filename)
            (kill-buffer buffer)
            (message "File '%s' successfully removed" filename)))))
    


  2. 위 함수에 키를 바인딩한다.(C-c k)
    (global-set-key (kbd "C-c k") 'delete-this-buffer-and-file)
    


<테스트 환경>
OS : Windows 7
Emacs 버전 : Emacs 24.3 윈도우
,