Showing posts with label emacs. Show all posts
Showing posts with label emacs. Show all posts

Wednesday, March 02, 2011

Advanced Emacs Commands

Common default Emacs key prefixes

Key prefix Description C-c Commands particular to the current editing mode C-x Commands for files and buffers C-h Help commands M-x Literal function name C-h b Show key bindings

Emacs window-manipulation commands

Key Function Description C-x 4 f find-file-other-window Open a new file in a new buffer, drawing it in a new vertical window. undefined scroll-all-mode Toggle the scroll-all minor mode. When it's on, all windows displaying the buffer in the current window are scrolled simultaneously and in equal, relative amounts. C-x 3 split-window-horizontally Split the current window in half down the middle, stacking the new buffers horizontally. undefined follow-mode Toggle follow, a minor mode. When it's on in a buffer, all windows displaying the buffer are connected into a large virtual window. C-x ^ enlarge-window Make the current window taller by a line; preceded by a negative, this makes the current window shorter by a line. C-x } shrink-window-horizontally Make the current active window thinner by a single column. C-x { enlarge-window-horizontally Make the current active window wider by a single column. C-x - shrink-window-if-larger-than-buffer Reduce the current active window to the smallest possible size for the buffer it contains. C-x + balance-windows Balance the size of all windows, making them approximately equal. undefined compare-windows Compare the current window with the next window, beginning with point in both windows and moving point in both buffers to the first character that differs until reaching the end of the buffer.

Emacs text manipulation commands

Key Function Description C-x Tab indent-rigidly This command indents lines in the region (or at point). undefined fill-region This command fills all paragraphs in the region. M-q fill-paragraph This command fills the single paragraph at point. M-\ delete-horizontal-space This command removes any horizontal space to the right and left of point. C-o open-line This command opens a new line of vertical space below point, without moving point. C-t transpose-chars This command transposes the single characters to the right and left of point. M-t transpose-words This command transposes the single words to the right and left of point. C-x C-t transpose-lines This command transposes the line at point with the line before it. M-^ delete-indentation This command joins the line at point with the previous line. Preface with C-1 to join the line at point with the next line (C-1 M-^) M-u uppercase-word This command converts the text at point to the end of the word to uppercase letters. M-l downcase-word This command converts the text at point to the end of the word to lowercase letters. C-x C-l downcase-region This command converts the region to lowercase letters. C-x C-u upcase-region This command converts the region to uppercase letters. M-m back-to-indentation This command, given anywhere on a line, positions point at the first non blank character on the line. C-s C-w This command, add the (rest of the) word at the pointer for search

Emacs commands for using registers

Emacs registers are general-purpose storage mechanisms that can store one of many things, including text, a rectangle, a position in a buffer, or some other value or setting. Every register has a label, which is a single character that you use to reference it. A register can be redefined, but it can contain only one thing at a time. Once you exit Emacs, all registers are cleared. Key Function Description C-x r space X point-to-register Save point to register named X. C-x r s X copy-to-register Save the region to register named X. C-x r r X copy-rectangle-to-register Save the selected rectangle to register named X. undefined view-register View the contents of a given register. C-x r j X jump-to-register Move point to the location given in register named X. C-x r i X insert-register Insert the contents of register named X at point.

Emacs commands for using bookmarks

Emacs has another facility for saving positions in buffers. These Emacs bookmarks work the same as registers, but their labels can be longer than a single character, and they're more permanent: If you save them, you can use them between sessions. They persist until you remove them. As their name implies, bookmarks are handy for saving your position in a buffer so that you can return to it at a later time, most often during a later Emacs session. Key Function Description C-x r m Bookmark bookmark-set Set a bookmark named Bookmark. C-x r l bookmarks-bmenu-list List all saved bookmarks. undefined bookmark-delete Delete a bookmark. C-x r b Bookmark bookmark-jump Jump to the location set in the bookmark named Bookmark. undefined bookmark-save Save all bookmarks to the bookmark file, ~/.emacs.bmk. (you can redefine it)

Emacs commands for using rectangles

Did you ever wish you could select a box of text from a document for copying, killing, or yanking purposes? You can. In Emacs, a selection of text specified by any two opposite of its four corners is called a rectangle. Key Function Description C-space set-mark-command Marks one corner of a rectangle (point marks the opposite corner). C-x r k kill-rectangle Kills the current rectangle and saves it in a special rectangle buffer. C-x r d delete-rectangle Deletes the current rectangle and doesn't save it for yanking. C-x r c clear-rectangle Clears the current rectangle, replacing the entire area with whitespace. C-x r o open-rectangle Opens the current rectangle, filling the entire area with whitespace and moving all text from the rectangle to the right. C-x r M-w Copy text without deleting the text from the buffer. C-x r y yank-rectangle Yanks the contents of the last-killed rectangle at point, moving all existing text to the right.

Mark rings

You should never have to scroll around randomly in a buffer to find "that place you were just looking at". Whenever you take a diversion (e.g. by searching, or pressing M-< or M->), Emacs uses the mark to save your previous position, kind of like sticking your finger behind one page of a book while you go to glance at another page. You can return to the mark with C-x C-x. However, Emacs saves up to 16 previous values of the mark, and you can jump to previous ones with C-u C-SPC. This makes mark and the mark ring a valuable navigation tool. You can use it somewhat mindlessly: if you ever find yourself asking "where was I just now?" you can often just press C-u C-SPC until you find yourself back in the right place.

Programming

Key Function Description M-x check-parens Checking for unmatched parentheses C-x w h REGEXP FACE Highlight matches of pattern REGEXP in current buffer with FACE. C-x w p PHRASE FACE Highlight matches of phrase PHRASE in current buffer with FACE. (PHRASE can be any REGEXP, but spaces will be replaced by matches to whitespace and initial lower-case letters will become case insensitive.) C-x w l REGEXP FACE Highlight lines containing matches of REGEXP in current buffer with FACE. C-x w r REGEX Remove highlighting on matches of REGEXP in current buffer Tips: C-SPC Make mark in some place and then disable it with C-g Go somewhere else and do it again and again etc. C-u C-SPC Back to previous mark, and back and back etc. M-x re-builder Helps you to create needed regular expression.

Highlighting Regexps, Phrases, And Lines

Key Function Description M-s h p highlight-phrase It will ask you for a phrase and highlighting color and then highlight all the matching phrases in the buffer. M-s h r highlight-regexp Highlight anything that matches an arbitrary regexp M-s h l highlight-lines-matching-regexp Highlights the entire line that contains the match to the regular expression M-s h u unhighlight-regexp Un-highlight the matches Useful references: Emacs Tutorial Beyond Emacs Tutorial Reference Card

Sunday, November 12, 2006

Lisp environment

Update: This environment evaluate to this - Pecan Emacs

Средата за разработка е била винаги важна и затова доста си играя с настройките. Все искам кода да е добре подреден, да имам лесен начин да достъпвам документацията, да има code completion и разни други глезотийки. Така и стана с Lisp средата за разработка. Просто задължителните неща са: SBCL, Linux и Emacs. Въпроса е как ще напаснем тези три неща и колко бързо ще свикнем с Emacs.
Аз използвам Debian и нещата, които се инсталират допълнително са:

sudo aptitude install sbcl
sudo aptitude install w3
sudo aptitude install w3-el-e21
sudo aptitude install hyperspec
sudo aptitude install emacs-goodies-el


Другото "важно" е да се смени клавишната комбинация за превключване от/към кирилица. В emacs "alt-shift" e много застъпена, така че "alt-alt"(Gnome default) или "ctrl-ctrl" e за предпочитане.
Аз не обичам много да пиша така,че искам да използвам и history-то на REPL-a. Както в моя shell. Като изплзвам стрелките да виждам какво е било. Затова инсталирам linedit:
> sbcl
* (require :asdf-install)
* (asdf-install:install :linedit)   ;first-time installation only

* (require :linedit)                ;if already installed
* (linedit:install-repl) 

Готови ли сте и за моя dot.emacs:
;;; Can use now Common Lisp functions                                                                                                                                                                
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                                                                                                                                                             

(require 'cl)                                                                                                                                                                                        

;;; Art                                                                                                                                                                                              
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                                                                                                                                                             

(set-background-color "black")                                                                                                                                                                       
(set-face-background 'default "black")                                                                                                                                                               
(set-face-background 'region "black")                                                                                                                                                                
(set-face-foreground 'default "white")                                                                                                                                                               
(set-face-foreground 'region "gray60")                                                                                                                                                               
(set-foreground-color "white")                                                                                                                                                                       
(set-cursor-color "red")                                                                                                                                                                             

;;; System settinngs                                                                                                                                                                                 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                                                                                                                                                             

;; Misc customizations                                                                                                                                                                               
(setq inhibit-startup-message t)        ;no splash screen                                                                                                                                            

(auto-compression-mode t)               ;turn on auto file uncompression                                                                                                                             

(menu-bar-mode 0)                       ;turn off unused UI                                                                                                                                          

(setq tab-width 4)                      ;tab size                                                                                                                                                    

(setq display-time-24hr-format t)       ;display the current time                                                                                                                                    
(display-time)                                                                                                                                                                                       

(global-font-lock-mode t)               ;colorize all buffers                                                                                                                                        
(setq font-lock-maximum-decoration t)                                                                                                                                                                

(show-paren-mode t)                     ;highlight parens                                                                                                                                            
(defconst query-replace-highlight t)    ;highlight during query                                                                                                                                      
(defconst search-highlight t)           ;highlight incremental search                                                                                                                                
(transient-mark-mode t)                 ;higlight the marked region (C-SPC)                                                                                                                          

;; Some useful key bindings                                                                                                                                                                          
(global-set-key [home] 'beginning-of-line)                                                                                                                                                           
(global-set-key [end] 'end-of-line)                                                                                                                                                                  

;; Column & line numbers in mode bar                                                                                                                                                                 
(column-number-mode t)                                                                                                                                                                               
(line-number-mode t)                                                                                                                                                                                 

(setq frame-title-format "%b")          ;set title to buffer name                                                                                                                                    

;; Ediff customizations                                                                                                                                                                              
(defconst ediff-ignore-similar-regions t)                                                                                                                                                            
(defconst ediff-use-last-dir t)                                                                                                                                                                      
(defconst ediff-diff-options " -b ")                                                                                                                                                                 

(setq dired-listing-switches "-l")      ;better list display                                                                                                                                         
(setq ls-lisp-dirs-first t)             ;display dirs first in dired                                                                                                                                 

;; Specify where backup files are stored                                                                                                                                                             
(setq backup-directory-alist (quote ((".*" . "~/.backups"))))                                                                                                                                        

(setq custom-file "~/.emacs-custom.el") ;what to load if error                                                                                                                                       
(load custom-file 'noerror)                                                                                                                                                                          

;; Type brackets in pairs                                                                                                                                                                            
(setq skeleton-pair t)                                                                                                                                                                               
(global-set-key (kbd "[") 'skeleton-pair-insert-maybe)                                                                                                                                               
(global-set-key (kbd "{") 'skeleton-pair-insert-maybe)                                                                                                                                               
(global-set-key (kbd "\"") 'skeleton-pair-insert-maybe)

;;; Common Lisp                                                                                                                                                                                      
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                                                                                                                                                             

;; Specify modes for Lisp file extensions                                                                                                                                                            
(setq auto-mode-alist                                                                                                                                                                                
(append '(                                                                                                                                                                                     
("\\.lisp$" . lisp-mode)                                                                                                                                                             
("\\.lsp$" . lisp-mode)                                                                                                                                                              
("\\.cl$" . lisp-mode)                                                                                                                                                               
("\\.asd$" . lisp-mode)                                                                                                                                                              
("\\.system$" . lisp-mode)                                                                                                                                                           
)auto-mode-alist))                                                                                                                                                                   

;; SLIME and generic Common Lisp.                                                                                                                                                                    
(require 'slime)                                                                                                                                                                                     

(setq slime-edit-definition-fallback-function 'find-tag)                                                                                                                                             

(setq inferior-lisp-program "sbcl"                                                                                                                                                                   
lisp-indent-function 'common-lisp-indent-function                                                                                                                                               
slime-complete-symbol-function 'slime-fuzzy-complete-symbol                                                                                                                                     
common-lisp-hyperspec-root "file:/usr/share/doc/hyperspec/" ;; Debian                                                                                                                           
slime-startup-animation t)                                                                                                                                                                      

(add-hook 'lisp-mode-hook (lambda () (slime-mode t)))                                                                                                                                                
(add-hook 'slime-repl-mode-hook (lambda () (slime-mode t)))                                                                                                                                          
(add-hook 'inferior-lisp-mode-hook (lambda () (inferior-slime-mode t)))                                                                                                                              

(defun customised-lisp-keyboard()                                                                                                                                                                    
(local-set-key [C-tab] 'slime-fuzzy-complete-symbol)                                                                                                                                               
(local-set-key [return] 'newline-and-indent))                                                                                                                                                      

(add-hook 'lisp-mode-hook 'customised-lisp-keyboard)                                                                                                                                                 

(global-set-key "\C-cs" 'slime-selector)                                                                                                                                                             

;; Search in lispdoc.org                                                                                                                                                                             
(defun lispdoc ()                                                                                                                                                                                    
"Searches lispdoc.com for SYMBOL, which is by default the symbol                                                                                                                                   
currently under the curser. Use M-x lispdoc"                                                                                                                                                         
(interactive)                                                                                                                                                                                      
(let* ((word-at-point (word-at-point))                                                                                                                                                             
(symbol-at-point (symbol-at-point))                                                                                                                                                         
(default (symbol-name symbol-at-point))                                                                                                                                                     
(inp (read-from-minibuffer                                                                                                                                                                  
(if (or word-at-point symbol-at-point)                                                                                                                                                
(concat "Symbol (default " default "): ")                                                                                                                                         
"Symbol (no default): "))))                                                                                                                                                      
(if (and (string= inp "") (not word-at-point) (not                                                                                                                                               
symbol-at-point))                                                                                                                              
(message "you didn't enter a symbol!")                                                                                                                                                       
(let ((search-type (read-from-minibuffer                                                                                                                                                       
"full-text (f) or basic (b) search (default b)? ")))                                                                                                                     
(browse-url (concat "http://lispdoc.com?q="                                                                                                                                                  
(if (string= inp "")                                                                                                                                                 
default                                                                                                                                                          
inp)                                                                                                                                                       
"&search="                                                                                                                                                       
(if (string-equal search-type "f")                                                                                                                           
"full+text+search"                                                                                                                                       
"basic+search")))))))
;; Fontify *SLIME Description* buffer                                                                                                                                                                
(defun slime-description-fontify ()                                                                                                                                                                  
"Fontify sections of SLIME Description."                                                                                                                                                           
(with-current-buffer "*SLIME Description*"                                                                                                                                                         
(highlight-regexp                                                                                                                                                                                
(concat "^Function:\\|"                                                                                                                                                                         
"^Macro-function:\\|"                                                                                                                                                                   
"^Its associated name.+?) is\\|"                                                                                                                                                        
"^The .+'s arguments are:\\|"                                                                                                                                                           
"^Function documentation:$\\|"                                                                                                                                                          
"^Its.+\\(is\\|are\\):\\|"                                                                                                                                                              
"^On.+it was compiled from:$")                                                                                                                                                          
'hi-green-b)))                                                                                                                                                                                  

(defadvice slime-show-description (after slime-description-fontify activate)                                                                                                                         
"Fontify sections of SLIME Description."                                                                                                                                                           
(slime-description-fontify))                                                                                                                                                                       

;; Use W3M                                                                                                                                                                                           
(require 'w3m)                                                                                                                                                                                       

(defun w3m-browse-url-other-window (url &optional newwin)                                                                                                                                            
(interactive                                                                                                                                                                                       
(browse-url-interactive-arg "w3m URL: "))                                                                                                                                                         
(let ((pop-up-frames nil))                                                                                                                                                                         
(switch-to-buffer-other-window                                                                                                                                                                   
(w3m-get-buffer-create "*w3m*"))                                                                                                                                                                
(w3m-browse-url url)))                                                                                                                                                                           

(setq browse-url-browser-function                                                                                                                                                                    
(list (cons "^ftp:/.*"  (lambda (url &optional nf)                                                                                                                                             
(call-interactively #'find-file-at-point url)))                                                                                                                      
(cons "."  #'w3m-browse-url-other-window)))                                                                                                                                          

;;; JavaScript                                                                                                                                                                                       
;;; http://web.comhem.se/~u34308910/emacs.html#javascript                                                                                                                                            
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;                                                                                                                                                             

(autoload 'javascript-mode "javascript" nil t)                                                                                                                                                       
(add-to-list `auto-mode-alist `("\\.js\\'" . javascript-mode)) 

;;; Helper functions                                                                                                                                                                                 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 


Сега нещата стоят по друг начин, писането на Lisp е песен. Ето и командите, които най-често използвам:
LISP RELATED

; Parants
M-( Prints ()

; Compilation
C-c M-k slime-compile-file
C-c C-c slime-compile-defun

; Evaluation
C-M-x slime-eval-defun

; Documentation
C-c C-d a slime-apropos
C-c C-d h slime-hyperspec-lookup
C-c C-m slime-macroexpand-1

; Cross-reference
C-c C-w r slime-who-references

; Manage Slime
M-x slime start slime
C-c C-c slime compile defun
C-c C-k slime compile and load file
C-c M-g slime quit

C-c C-t slime clear repl
M-p slime prev command
M-n slime next command

M-r slime search prev commands
M-s slime search next commands

C-c C-z go to lisp buffer
C-c C-q close all parens


Ето един много добър линк за Emacs командите: Beyond Emacs Tutorial

Oстана да се добави малко творчество и нещата добиват завършен вид. Горе долу подхода ми е следния:

   1. Всичко(functions, classes, special variables, and constants) го слагам в defun, за да мога лесно да го проверя дали има грешки с С-с С-с. Ако нещо много ме усъмни(да проверя нещо как работи) се прехвърлям на REPL с C-c C-z и го изпълнявам.


   2. Програмата трябва да е lоаdable, сиреч да не се прави нищо допълнително, за да може да се стартира самостоятелно. Ако програмата да кажем, че се казва proba.lisp не ползва допълнителни библиотеки, тогава няма нищо за правене. По-сложнен е другия случай, да иска. Да кажем ползва cl-ppcre. Тогава в кода има:
(defpackage #:proba
(:use #:cl #:cl-ppcre))

Това само по себе си не е достатъчно. Ако направим:
(load (compile-file "proba"))

Получаваме следната грешка: The name "CL-PPCRE" does not designate any package. Ха сега де.
По някакъв начин трябва да съм сигурен, че cl-ppcre ще се зареди и компилира преди моя файл proba.lisp. Най-лесния вариант е да изплзвам ASDF. Създавам един файл proba.asd и в него слагам:
(asdf:defsystem #:proba
:depends-on (#:cl-ppcre)
:components ((:file "proba")))

Ако пък работя в REPL-a ще използвам: ,load-system или (asdf:oos 'asdf:load-op 'proba)


   3. Ами ако проета от един файл нарасне и стане проект? Тогава ще се наложи да разделяме на малки файлове и да ги "вържем" по някакъв начин. Да речем proba.lisp нарасне много и аз реша да го рефакторирам и изкарам някои операции в друг файл - operations.lisp. За целта ще се наложи да работя с пакети. Създавам файла package.lisp и в началото на proba.lisp и operations.lisp указвам, на кой пакет пренадлежат.
(in-package #:proba)

Послендия файл ще изглежда малко променен:
(asdf:defsystem #:proba
:depends-on (#:cl-ppcre)
:components ((:file "package")
(:file "operations"
:depends-on ("package"))
(:file "proba"
:depends-on ("package"
"operations"))))


   4. Приготвям се за финиширане като се попитам: А какви са нещата от проекта, които могат да се използеват дирекно(кои са интерфейсите)? Определям ги и променям пакетната дефиниция в package.cl:
(defpackage #:proba
(:use #:cl #:cl-ppcre)
(:export #:blah
#:blah2
#:useful-thing3
#:*logfile-directory*))


   5. И накрая малко хитрости. Винаги стартирам проета си от неговата директория. Ако съм направил нещо наистина полезно правя нещата още по-глобални като линквам .asd в ~/.sbcl/systems/.
cd ~/.sbcl/system
ln -s ../../Lisp/proba/proba.asd .

Така много лесно мога да си ползвам проета отвсякъде като пиша просто:(require 'proba). Или ако от друг проект ми притрябват моите "полезни" неща от proba. Просто:
(asdf:defsystem #:useful_thing3
:depends-on (#:proba #:drakma)
:components (...))


В общи линии така върви моя Лисп път.

algorithms (1) cpp (3) cv (1) daily (4) emacs (2) freebsd (4) java (3) javascript (1) JSON (1) linux (2) Lisp (7) misc (8) programming (16) Python (4) SICP (1) source control (4) sql (1) думи (8)