Procedure definition was interpreted as variable definition in sicp interpreter? - interpreter

I'm reading sicp 4.1.4. After I run the interpreter, and then type the append function into my interpreter, it says ok. But when I call append as the example on 4.1.4, it returns "Unbound variable append". I thought my interpreter take it as variable definition instead of procedure definition. But I don't know why.
I have checked my code to the example code for several times, but still cannot figure it out. I posted my code below, really a long file.
Would you help me to find out where the problem is? Thanks.
#lang sicp
;;
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
;;
(define (eval-if exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
;;
(define (eval-sequence exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
;;
(define (eval-assignment exp env)
(set-variable-value! (assignment-variable exp)
(eval (assignment-value exp) env)
env))
;;
(define (eval-definition exp env)
(define-variable! (definition-variable exp)
(eval (definition-value exp) env)
env)
'ok)
;;
(define (self-evaluation? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
;;
(define (variable? exp)
(symbol? exp))
;;
(define (quoted? exp)
(tagged-list? exp 'quote))
(define (text-of-quotation exp)
(cadr exp))
;;
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
;;
(define (assignment? exp)
(tagged-list? exp 'set!))
(define (assignment-variable exp)
(cadr exp))
(define (assignment-value exp)
(caddr exp))
;;
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caddr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp)
(cddr exp))))
;;
(define (lambda? exp)
(tagged-list? exp 'lambda))
(define (lambda-parameters exp)
(cadr exp))
(define (lambda-body exp)
(cddr exp))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
;;
(define (if? exp)
(tagged-list? exp 'if))
(define (if-predicate exp)
(cadr exp))
(define (if-consequent exp)
(caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (make-if predicate
consequent
alternative)
(list 'if
predicate
consequent
alternative))
;;
(define (begin? exp)
(tagged-list? exp 'begin))
(define (begin-actions exp)
(cdr exp))
(define (last-exp? seq)
(null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-begin seq) (cons 'begin seq))
;;
(define (application? exp)
(pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
;;
(define (cond? exp)
(tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last -- COND->IF" clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (true? x) (not (eq? x false)))
(define (false? x) (eq? x false))
(define (make-procedure parameters body env)
(list 'procedure parameters body env))
(define (compound-procedure? p)
(tagged-list? p 'procedure))
(define (procedure-parameters p) (cadr p))
(define (procedure-body p) (caddr p))
(define (procedure-environment p) (cadddr p))
;
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
; 有些重复代码,习题里要求抽象。这里就不写了。
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(car vals))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable -- SET!" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame)
(frame-values frame))))
(define (primitive-procedure? proc)
(tagged-list? proc 'primitive))
(define (primitive-implementation proc) (cadr proc))
(define primitive-procedures
(list (list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'null? null?)
(list '+ +)))
(define (primitive-procedure-names)
(map car primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (proc) (list 'primitive (cadr proc)))
primitive-procedures))
(define (apply-primitive-procedure proc args)
(apply-in-underlying-scheme
(primitive-implementation proc) args))
(define apply-in-underlying-scheme apply)
(define input-prompt ";;; M_Eval input:")
(define output-prompt ";;; M-Eval value:")
(define (driver-loop)
(prompt-for-input input-prompt)
(let ((input (read)))
(let ((output (eval input the-global-environment)))
(announce-output output-prompt)
(user-print output)))
(driver-loop))
(define (prompt-for-input string)
(newline) (newline) (display string) (newline))
(define (announce-output string)
(newline) (display string) (newline))
(define (user-print object)
(if (compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>))
(display object)))
;
(define (setup-environment)
(let ((initial-env
(extend-environment (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(define-variable! 'true true initial-env)
(define-variable! 'false false initial-env)
initial-env))
; apply
(define (metacircular-apply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(eval-sequence
(procedure-body procedure)
(extend-environment (procedure-parameters procedure)
arguments
(procedure-environment procedure))))
(else (error "Unknown procedure type -- APPLY" procedure))))
;; eval
(define (eval exp env)
(cond ((self-evaluation? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp)
(make-procedure (lambda-parameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (begin-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
((application? exp)
(metacircular-apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else (error "Unknown expression type -- EVAL" exp))))
(define the-global-environment (setup-environment))
(driver-loop)

I think the issue is with definition-variable. The alternate should be caadr not caddr. I.e. it should be:
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
^
After that change it seems to work.

Related

K Framework: Cannot convert to subtype

I'm trying evaluate Expressions to Values (Exps ::= Values) for function calls.
Here's a simple example:
module ERL-SYNTAX
imports INT-SYNTAX
imports STRING
syntax Atom ::= "main" | "f"
syntax Exp ::= Atom | Int
syntax Exp ::= Exp "(" Exps ")" [seqstrict]
syntax Exps ::= List{Exp, ","} [seqstrict]
endmodule
module ERL-CONFIGURATION
imports ERL-SYNTAX
imports MAP
syntax Value ::= Atom | Int | "{" Values "}"
syntax Values ::= List{Value, ","}
syntax Exp ::= Value
syntax Exps ::= Values
syntax KResult ::= Value
syntax KResult ::= Values
configuration <cfg color="yellow">
<k color="green"> $PGM:Exp </k>
<fundefs> //some default function definitions
.Map (f |-> 5 , .Exps
main |-> f ( 2 , 3 , .Exps ) , .Exps )
</fundefs>
</cfg>
endmodule
module ERL
imports ERL-SYNTAX
imports ERL-CONFIGURATION
//rule .Exps => .Values
rule <k>F:Atom(_:Values) => L ...</k>
<fundefs>... F |-> L ...</fundefs>
endmodule
This gets stuck at
.Exps ~> #freezer_(_)ERL-SYNTAX1 ( main )
So I tried with this rule: .Exps => .Values to evaluate main().
To me, the strange thing is that this time heating 3 is ok:
.Values ~> #freezer_,ERL-SYNTAX1 ( 3 ) ~> #freezer,_ERL-SYNTAX1 ( 2 ) ~> ...
will be
3 , .Values ~> #freezer_,_ERL-SYNTAX1 ( 2 ) ~> ..
but here it gets stuck again.
How should I approach this problem?
Put the productions for Exps and Vals in the same module and give them the same klabel attribute. This will make them overload one another, at which point in time, the fact that .Values is a KResult should solve your problem.

How to use local variable in Elisp defmacro?

I write a elisp macro in my configuration file of emacs, but like something shown below ,(intern (format "%s-display-table" name)) is used several times, how can I use a something like variable to represent it?
;; Change the glyphs of "wrap", "truncation" and "vertical-border" in the display table specified by
;; parameter "name", obviously "↩", "…" and "ǁ" is better choice than the default values "\", "$"
;; and "|".
(defmacro change-glyphs-of-display-table (name)
`(lambda ()
(interactive)
(unless ,(intern (format "%s-display-table" name))
(setq ,(intern (format "%s-display-table" name)) (make-display-table)))
(set-display-table-slot ,(intern (format "%s-display-table" name)) 'wrap ?\↩)
(set-display-table-slot ,(intern (format "%s-display-table" name)) 'truncation ?\…)
(set-display-table-slot ,(intern (format "%s-display-table" name)) 'vertical-border ?\ǁ)))
With name being an argument to the macro, you know it's always available at expansion time, and so you can process it outside of the backquoted form:
;; Change the glyphs of "wrap", "truncation" and "vertical-border" in the display table specified by
;; parameter "name", obviously "↩", "…" and "ǁ" is better choice than the default values "\", "$"
;; and "|".
(defmacro change-glyphs-of-display-table (name)
(let ((namedisplaytable (intern (format "%s-display-table" name))))
`(lambda ()
(interactive)
(unless ,namedisplaytable
(setq ,namedisplaytable (make-display-table)))
(set-display-table-slot ,namedisplaytable 'wrap ?\↩)
(set-display-table-slot ,namedisplaytable 'truncation ?\…)
(set-display-table-slot ,namedisplaytable 'vertical-border ?\ǁ))))

How to match the same number of different atoms in Perl 6 regex?

Should be very simple, but I can't cope with it.
I want to match exactly the same number of as as bs. So, the following
my $input = 'aaabbbb';
$input ~~ m:ex/ ... /;
should produce:
aaabbb
aabb
ab
UPD: The following variants don't work, perhaps because of the :ex bug , mentioned in #smls's answer (but more likely because I made some mistakes?):
> my $input = "aaabbbb";
> .put for $input ~~ m:ex/ (a) * (b) * <?{ +$0 == +$1 }> /;
Nil
> .put for $input ~~ m:ex/ (a) + (b) + <?{+$0 == +$1}> /;
Nil
This one, with :ov and ?, works:
> my $input = "aaabbbb";
> .put for $input ~~ m:ov/ (a)+ (b)+? <?{+$0 == +$1}> /;
aaabbb
aabb
ab
UPD2: The following solution works with :ex as well, but I had to do it without <?...> assertion.
> $input = 'aaabbbb'
> $input ~~ m:ex/ (a) + (b) + { put $/ if +$0 == +$1 } /;
aaabbb
aabb
ab
my $input = "aaabbbb";
say .Str for $input ~~ m:ov/ (a)+ b ** {+$0} /;
Output:
aaabbb
aabb
ab
It's supposed to work with :ex instead of :ov, too - but Rakudo bug #130711 currently prevents that.
my $input = "aaabbbb";
say .Str for $input ~~ m:ov/ a <~~>? b /;
Works with ex too
my $input = "aaabbbb";
say .Str for $input ~~ m:ex/ a <~~>? b /;
Upd: explanation
<~~> means call myself recursively see Extensible metasyntax. (It is not yet fully implemented.)
Following (longer, but maybe clearer) example works too:
my $input = "aaabbbb";
my token anbn { a <&anbn>? b}
say .Str for $input ~~ m:ex/ <&anbn> /;

Error while installation of spacemacs

I am facing the following error while trying to install spacemacs. I am presently on ubuntu 17.04.
Warning (initialization): An error occurred while loading '/home/User/.emacs.d/init.el'
File error: Searching for program, Is a directory,
Here is the error code I get while opening on --debug-init:
Debugger entered--Lisp error: (file-error "Searching for program" "Is a directory" "")
call-process("" nil t nil "-c" "/usr/bin/timeout --help")
apply(call-process "" nil t nil ("-c" "/usr/bin/timeout --help"))
process-file("" nil t nil "-c" "/usr/bin/timeout --help")
shell-command-to-string("/usr/bin/timeout --help")
(string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))
(and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help"))))
(if (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) (progn prog))
(when (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) prog)
(let ((prog (or (executable-find "timeout") (executable-find "gtimeout")))) (when (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) prog))
eval((let ((prog (or (executable-find "timeout") (executable-find "gtimeout")))) (when (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) prog)))
custom-initialize-reset(package-build-timeout-executable (let ((prog (or (executable-find "timeout") (executable-find "gtimeout")))) (when (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) prog)))
custom-declare-variable(package-build-timeout-executable (let ((prog (or (executable-find "timeout") (executable-find "gtimeout")))) (when (and prog (string-match-p "^ *-k" (shell-command-to-string (concat prog " --help")))) prog)) "Path to a GNU coreutils \"timeout\" command if available.\nThis must be a version which supports the \"-k\" option." :group package-build :type (file :must-match t))
eval-buffer(#<buffer *load*-807180> nil "/home/sujit/.emacs.d/core/libs/package-build.el" nil t) ; Reading at buffer position 3283
load-with-code-conversion("/home/sujit/.emacs.d/core/libs/package-build.el" "/home/sujit/.emacs.d/core/libs/package-build.el" nil t)
require(package-build)
eval-buffer(#<buffer *load*-522675> nil "/home/sujit/.emacs.d/core/libs/quelpa.el" nil t) ; Reading at buffer position 1420
load-with-code-conversion("/home/sujit/.emacs.d/core/libs/quelpa.el" "/home/sujit/.emacs.d/core/libs/quelpa.el" nil t)
require(quelpa)
configuration-layer//configure-quelpa()
(let ((display-buffer-alist (quote (("\\(\\*Compile-Log\\*\\)\\|\\(\\*Warnings\\*\\)" (display-buffer-in-side-window) (inhibit-same-window . t) (side . bottom) (window-height . 0.2)))))) (configuration-layer//configure-quelpa) (let* ((upkg-names (configuration-layer//get-uninstalled-packages packages)) (not-inst-count (length upkg-names)) installed-count) (if upkg-names (progn (spacemacs-buffer/set-mode-line "Installing packages...") (spacemacs//redisplay) (let ((delayed-warnings-backup delayed-warnings-list)) (spacemacs-buffer/append (format "Found %s new package(s) to install...\n" not-inst-count)) (configuration-layer/retrieve-package-archives) (setq installed-count 0) (spacemacs//redisplay) (let ((--dolist-tail-- upkg-names) pkg-name) (while --dolist-tail-- (setq pkg-name ...) (setq installed-count ...) (configuration-layer//install-package ...) (setq --dolist-tail-- ...))) (spacemacs-buffer/append "\n") (if init-file-debug nil (setq delayed-warnings-list delayed-warnings-backup)))))))
configuration-layer//install-packages((ace-jump-helm-line ace-link ace-window adaptive-wrap aggressive-indent async auto-compile auto-highlight-symbol avy bind-key bind-map clean-aindent-mode column-enforce-mode define-word desktop diminish dumb-jump elisp-slime-nav eval-sexp-fu evil evil-anzu evil-args evil-ediff evil-escape evil-exchange evil-iedit-state evil-indent-plus evil-lisp-state evil-matchit evil-mc evil-nerd-commenter evil-numbers evil-search-highlight-persist evil-surround evil-tutor evil-unimpaired evil-visual-mark-mode evil-visualstar exec-path-from-shell expand-region eyebrowse fancy-battery fill-column-indicator flx-ido golden-ratio google-translate helm helm-ag helm-descbinds helm-flx ...))
(let ((packages (append (configuration-layer/filter-objects configuration-layer--used-distant-packages (function (lambda (x) (let ... ...)))) (if (eq (quote all) dotspacemacs-install-packages) (progn (let (all-other-packages) (let ... ...) (configuration-layer//get-distant-packages all-other-packages nil))))))) (configuration-layer//install-packages packages) (if (and (or (eq (quote used) dotspacemacs-install-packages) (eq (quote used-only) dotspacemacs-install-packages)) (not configuration-layer-force-distribution) (not configuration-layer-exclude-all-layers)) (progn (configuration-layer/delete-orphan-packages packages))))
(if no-install nil (let ((packages (append (configuration-layer/filter-objects configuration-layer--used-distant-packages (function (lambda ... ...))) (if (eq (quote all) dotspacemacs-install-packages) (progn (let ... ... ...)))))) (configuration-layer//install-packages packages) (if (and (or (eq (quote used) dotspacemacs-install-packages) (eq (quote used-only) dotspacemacs-install-packages)) (not configuration-layer-force-distribution) (not configuration-layer-exclude-all-layers)) (progn (configuration-layer/delete-orphan-packages packages)))))
configuration-layer/sync()
(if (not (version<= spacemacs-emacs-min-version emacs-version)) (error (concat "Your version of Emacs (%s) is too old. " "Spacemacs requires Emacs version %s or above.") emacs-version spacemacs-emacs-min-version) (load-file (concat (file-name-directory load-file-name) "core/core-load-paths.el")) (require (quote core-spacemacs)) (spacemacs/init) (configuration-layer/sync) (spacemacs-buffer/display-startup-note) (spacemacs/setup-startup-hook) (require (quote server)) (if (server-running-p) nil (server-start)))
eval-buffer(#<buffer *load*> nil "/home/sujit/.emacs.d/init.el" nil t) ; Reading at buffer position 1264
load-with-code-conversion("/home/sujit/.emacs.d/init.el" "/home/sujit/.emacs.d/init.el" t t)
load("/home/sujit/.emacs.d/init" t t)
#[0 "\205\266\00 \306=\203\00\307\310Q\202?\00 \311=\204\00\307\312Q\202?\00\313\307\314\315#\203*\00\316\202?\00\313\307\314\317#\203>\00\320\321\322!D\nB\323\202?\00\316\324\325\324\211#\210\324=\203e\00\326\327\330\307\331Q!\"\325\324\211#\210\324=\203d\00\210\203\247\00\332!\333\232\203\247\00\334!\211\335P\336!\203\201\00\211\202\214\00\336!\203\213\00\202\214\00\314\262\203\245\00\337\"\203\243\00\340\341#\210\342\343!\210\266\f?\205\264\00\314\325\344\324\211#)\262\207" [init-file-user system-type delayed-warnings-list user-init-file inhibit-default-init inhibit-startup-screen ms-dos "~" "/_emacs" windows-nt "/.emacs" directory-files nil "^\\.emacs\\(\\.elc?\\)?$" "~/.emacs" "^_emacs\\(\\.elc?\\)?$" initialization format-message "`_emacs' init file is deprecated, please use `.emacs'" "~/_emacs" t load expand-file-name "init" file-name-as-directory "/.emacs.d" file-name-extension "elc" file-name-sans-extension ".el" file-exists-p file-newer-than-file-p message "Warning: %s is newer than %s" sit-for 1 "default"] 7]()
command-line()
normal-top-level()
Try setting the SHELL environment variable:
SHELL=/bin/bash emacs
I had the same problem and I have found the solution thanks to Seanjamesking
Add
(require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/")) (package-initialize)
to the top of the ~/.emacs.d/init.el file.
*I am using Emacs 25.2.2 on Ubuntu 18.04.3

How to stop auto-complete from overwriting a file that is similarly named

I am a new user to Emacs and have gotten a .emacs file from someone in my field that introduced me to this programming platform. However, I have been having some issues while trying to save or create new files that are named similar to those that already exist. If I attempt to create a new file that has a name that is relatively similar to one that exists, even if it is in a different directory, the existing file will be opened. When attempting to save a file with a shorter or similar name to an already existing file, Emacs attempts to overwrite the file instead of creating a new one.
For example, I am attempting to save the file growth_loglike.tpl but I already have the file growth_loglike_ADMB2_End.tpl in the directory. When I go to save and write in growth_loglike.tpl it shows [growth_loglike_ADMB2_End.tpl] in green to the right. When I hit enter it asks me if I want to overwrite growth_loglike_ADMB2_End.tpl. I think this is an issue with the auto-complete plugin. Is there a way to temporarily turn off the auto-complete? Looking at the auto-complete.el file my guess is that I need to change this variable but I'm not sure to what (or if that is even correct). Any help with this would be extremely helpful.
(defcustom ac-use-overriding-local-map nil
"Non-nil means `overriding-local-map' will be used to hack for overriding key events on auto-copletion."
:type 'boolean
:group 'auto-complete)
Below is the .emacs file that I am using.
;; This emacs configuration file will activate common packages
and
;; functionality used in the QFC Reproducable Reseach Workshop.
;; change this path to point to emacs directory in workshop on your computer:
;; (don't forget to include a trailing slash!)
(defvar workshop-root "C:/Users/vince151/Documents/workshop/")
(defvar emacs-root (concat (file-name-as-directory workshop-root) "emacs/"))
;;=============================================================================
;;=============================================================================
;; 1. Misc Plug-ins
;; here are some paths to look for additional scripts and functions:
(add-to-list 'load-path (concat emacs-root "plugins/"))
;;=============================================================================
;; 2. YASnippet
(add-to-list 'load-path (concat emacs-root "plugins/yasnippet"))
(require 'yasnippet) ;; not yasnippet-bundle
(setq yas-snippet-dirs (concat emacs-root "plugins/yasnippet/snippets"))
(yas-global-mode 1)
;; timestamp used in some yasnippets
(defun now ()
"Insert string for the current time formatted like '2:34 PM'."
(interactive) ; permit invocation in minibuffer
(insert (format-time-string "%D %-I:%M %p")))
;;=============================================================================
;; 3. Swap Slashes
;; swap slashes and backslashes in current line -- useful for converting paths to be Windows-readable
;;http://www.xsteve.at/prg/emacs/.emacs.txt
(defun xsteve-exchange-slash-and-backslash ()
"Exchanges / with \ and in the current line or in the region when a region-mark is active."
(interactive)
(save-match-data
(save-excursion
(let ((replace-count 0)
(eol-pos (if mark-active (region-end) (progn (end-of-line) (point))))
(bol-pos (if mark-active (region-beginning) (progn (beginning-of-line) (point)))))
(goto-char bol-pos)
(while (re-search-forward "/\\|\\\\" eol-pos t)
(setq replace-count (+ replace-count 1))
(cond ((string-equal (match-string 0) "/") (replace-match "\\\\" nil nil))
((string-equal (match-string 0) "\\") (replace-match "/" nil nil)))
(message (format "%d changes made." replace-count)))))))
(global-set-key (kbd "M-\\") 'xsteve-exchange-slash-and-backslash)
;;==============================================================================
;; 4. Parenthesis highlighting
(require 'highlight-parentheses)
(setq hl-paren-colors '("DodgerBlue1" "IndianRed" "cyan" "ForestGreen" "magenta" "SlateGrey"))
(defun hpm-on ()
(highlight-parentheses-mode t))
(add-hook 'admb-mode-hook 'hpm-on)
(add-hook 'ess-mode-hook 'hpm-on)
(add-hook 'inferior-ess-mode-hook 'hpm-on)
(add-hook 'latex-mode-hook 'hpm-on)
(add-hook 'LaTeX-mode-hook 'hpm-on)
;;=============================================================================
;; 5. ESS
;; path to current version of R: (This shouldn't be needed if PATH is correct)
;;(setq-default
;; inferior-R-program-name
;; "C:/R/R-2.15.0/bin/i386/Rterm.exe")
(load (concat emacs-root "ESS/ess-13.09/lisp/ess-site"))
(setq ess-fancy-comments nil)
;; make pdflatex the default sweave compiler (removes texi2pdf)
(setq ess-swv-pdflatex-commands '("pdflatex" "xelatex" "make"))
;;=============================================================================
;; 6. ADMB-ide
;; don't forget to edit setADMBpaths.bat to point to your admb installation
(setq admb-init (concat emacs-root "setADMBpaths & "))
;; these commands were cut from admb.el
(load (concat emacs-root "plugins/admb"))
;; Edit .emacs so that `admb-mode' is autoloaded and assigned to *.tpl files:
(autoload 'admb-mode "admb" "Edit ADMB code." t)
(add-to-list 'auto-mode-alist '("\\.tpl$" . admb-mode))
;; If you're running Emacs in MS Windows, add a line so *.tpl files are not treated as binary:
(setq file-name-buffer-file-type-alist nil)
;; You may want to assign a mode that recognizes #comments in *.dat files (perl-mode, conf-space-mode, or R-mode):
(add-to-list 'auto-mode-alist '("\\.dat$" . perl-mode))
;;(add-to-list 'auto-mode-alist '("\\.dat$" . admb-mode))
;;(add-to-list 'auto-mode-alist '("\\.dat$" . easy-admb-hook))
;;added Monday, March 29, 2010 so that we can run models from within dat files
(add-hook 'perl-mode-hook
(lambda()
(define-key perl-mode-map [f9] 'admb-run)))
;;these commands were taken from Arni Magnusen's emacs file distributed with ADMB-IDE
(defun easy-admb-hook ()
(local-set-key [f1] 'admb-help ) ; prefix
(local-set-key [f2] 'admb-mode ) ; prefix
;;(global-set-key [f3] 'conf-space-mode ) ; kmacro-start-macro-or-insert-counter
(local-set-key [f4] 'admb-toggle-window ) ; kmacro-end-or-call-macro
(local-set-key [f7] 'admb-tpl2cpp )
(local-set-key [f8] 'admb-build )
(local-set-key [f9] 'admb-run )
(local-set-key [S-f9] 'admb-run-args )
(local-set-key [f10] 'admb-rep ) ; menu-bar-open
(local-set-key [S-f10] 'admb-cor )
(local-set-key [?\C-.] 'admb-toggle-section))
(add-hook 'admb-mode-hook 'easy-admb-hook)
;;----------
;; C++
;;----------
(defun easy-gdb-hook ()
(message nil)
(setq indent-line-function 'gud-gdb-complete-command)
;;(setq gdb-show-main t)
(local-set-key [f5] 'gdb-restore-windows)
(local-set-key [M-up] 'gdb-io-buffer-off )
(local-set-key [M-down] 'gdb-io-buffer-on )
(local-set-key [?\C-c ?\C-q] 'comint-quit-subjob )
(defun gdb-io-buffer-off () "Enable separate IO buffer." (interactive)(gdb-use-separate-io-buffer nil))
(defun gdb-io-buffer-on () "Disable separate IO buffer." (interactive)(gdb-use-separate-io-buffer t)))
(add-hook 'gdb-mode-hook 'easy-gdb-hook)
;;=================
;; enable YASnippet
(add-hook 'admb-mode-hook 'yas/minor-mode-on)
(add-hook 'admb-mode-hook
(let ((original-command (lookup-key admb-mode-map [tab])))
`(lambda ()
(setq yas/fallback-behavior '(apply ,original-command))
(local-set-key [tab] 'yas/expand))))
;;==============================================================================
;; 7. Git
;; path to git executable: (This shouldn't be needed if PATH is correct)
;; (setq-default
;; magit-git-executable
;; "C:/gnu/git/bin/git.exe")
;;(require 'git)
(add-to-list 'load-path (concat emacs-root "plugins/git/magit"))
(load (concat emacs-root "plugins/git/magit/magit.el"))
(require 'magit)
;; use Ctrl-C G to start Git:
(global-set-key "\C-c\C-g" 'magit-status)
;; from: http://readystate4.com/2011/02/22/emacs-changing-magits-default-diff-colors/
;; change magit diff colors
(eval-after-load 'magit
'(progn
(set-face-foreground 'magit-diff-add "green3")
(set-face-foreground 'magit-diff-del "red3")
(when (not window-system)
(set-face-background 'magit-item-highlight "black"))))
;;==============================================================================
;; 8. autocomplete
(require 'auto-complete)
(add-to-list 'ac-dictionary-directories (concat emacs-root "plugins/ac-dict"))
(require 'auto-complete-config)
(ac-config-default)
;;========================================
;; 9. Bibtex database:
(setq reftex-default-bibliography
'("C:/Users/vince151/Documents/workshop/utils/references.bib"))
(setq reftex-default-bibliography
(concat workshop-root "utils/references.bib"))
(defvar reftex-file
(concat
(file-name-as-directory workshop-root) "utils/references.bib"))
(setq reftex-default-bibliography reftex-file)
;; Make TeX and RefTex aware of Snw and Rnw files
(setq reftex-file-extensions
'(("snw" "rnw" "Snw" "Rnw" "nw" "tex" ".tex" ".ltx") ("bib" ".bib")))
(setq TeX-file-extensions
'("snw" "rnw" "Snw" "Rnw" "nw" "tex" "sty" "cls" "ltx" "texi" "texinfo"))
(add-hook 'latex-mode-hook 'turn-on-reftex)
;;========================================
;; 10. Some functions to run bibtex and latex
(defun ac-run-bibtex ()
"Run BibTex on the current file."
(interactive)
(save-excursion
(let* ((latex-filename (file-name-sans-extension (buffer-file-name)))
(tex-buf (get-buffer-create " *ESS-bibtex-output*")))
(message "Running BibTex on '%s' ..." latex-filename)
(switch-to-buffer tex-buf)
(call-process "bibtex" nil tex-buf 1 latex-filename)
(switch-to-buffer (buffer-name))
(display-buffer tex-buf)
(message "Finished running BibTeX" ))))
(defun ac-run-pdflatex ()
"Run pdflatex on the current file."
(interactive)
(save-excursion
(let* ((namestem (file-name-sans-extension (buffer-file-name)))
(latex-filename (concat namestem ".tex"))
(tex-buf (get-buffer-create " *pdflatex-output*")))
(message "Running pdflatex on '%s' ..." latex-filename)
(switch-to-buffer tex-buf)
(call-process "pdflatex" nil tex-buf 1 latex-filename)
(switch-to-buffer (buffer-name))
(display-buffer tex-buf)
(message "Finished running pdflatex" ))))
;; terms associated with base name were added to create index files using makeindex
;; this function impliments the following sequence of calls:
;; pdflatex -> bibtex -> pdflatex -> makeindex -> pdflatex
(defun ac-run-lbll ()
"Run LaTeX-BibTex-Latex-Latex on the current file."
(interactive)
(save-excursion
(let* ((namestem (file-name-sans-extension (buffer-file-name)))
(latex-filename (concat namestem ".tex"))
(basename (file-name-nondirectory namestem))
(tex-buf (get-buffer-create " *lbll-output*")))
(message "Running LaTeX-BibTex-Latex-Latex on '%s' ..." latex-filename)
(switch-to-buffer tex-buf)
(call-process "pdflatex" nil tex-buf 1 latex-filename)
(call-process "bibtex" nil tex-buf 1 namestem)
(call-process "pdflatex" nil tex-buf 1 latex-filename)
(call-process "makeindex" nil tex-buf 1 basename)
(call-process "pdflatex" nil tex-buf 1 latex-filename)
(switch-to-buffer (buffer-name))
(display-buffer tex-buf)
(message "Finished running LaTeX-BibTex-Latex-Latex" ))))
(add-hook 'latex-mode-hook
(lambda ()
(define-key latex-mode-map [f9] 'ac-run-pdflatex)
)
)
;;========================================
;; 10. Other useful functions below this point
;;ispell - super cool spell checker for emacs
(setq-default ispell-program-name (concat emacs-root "aspell/bin/aspell.exe"))
;; get itspell to skip sweave chunks:
(add-to-list 'ispell-skip-region-alist '("^<<.*>>=" . "^#"))
;;=============================================================================
;; use string rectangle for indentng blocks/regions of code
(global-set-key (kbd "C->") 'string-insert-rectangle)
;;=============================================================================
;;ido (from: http://www.emacswiki.org/emacs/InteractivelyDoThings)
(require 'ido)
(ido-mode t)
(setq ido-enable-flex-matching t) ;; enable fuzzy matching
;;=============================================================================
;; use ibuffer anytime we would have use buffer-list
(defalias 'list-buffers 'ibuffer)
; get rid of prompt that forces you to type full "yes" or "no".
; y or n is enough
(defalias 'yes-or-no-p 'y-or-n-p)
;;==============================================================================
;; from http://www.joegrossberg.com/archives/000182.html
;; enable recent file list - bound to C-x C-r
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
;;==============================================================================
;; from http://www.stokebloke.com/wordpress/2008/04/17/emacs-refresh-f5-key/
;; use f3 to refresh file in current buffer
;;(defun refresh-file ()
;; (interactive)
;; (revert-buffer t t t)
;; )
;;(global-set-key [f3] 'refresh-file)
;;
;;==============================================================================
;; copy path of current buffer to kill ring
;; from:http://stackoverflow.com/questions/3669511/
(defun copy-full-path-to-kill-ring ()
"copy buffer's full path to kill ring"
(interactive)
(when buffer-file-name
(kill-new (file-truename buffer-file-name))))
(global-set-key "\C-cz" 'copy-full-path-to-kill-ring)
;;==============================================================================
;; keep emacs from cluttering working directories with tilde files by
;; placing them here:(concat emacs-root "tildes") instead of
;; wherever we're working.
(defvar user-temporary-file-directory
(concat emacs-root "tildes/"))
(make-directory user-temporary-file-directory t)
(setq backup-by-copying t)
(setq backup-directory-alist
`(("." . ,user-temporary-file-directory)
(,tramp-file-name-regexp nil)))
(setq auto-save-list-file-prefix
(concat user-temporary-file-directory ".auto-saves-"))
(setq auto-save-file-name-transforms
`((".*" ,user-temporary-file-directory t)))
;;;============================================================================
; try to improve slow performance on windows.
;;Got this from a website that said this would help.
(setq w32-get-true-file-attributes nil)
This is the default behaviour of ido-mode. There are two things you can do about it:
Once you've typed the filename you want, hit C-j instead of RET. This makes ido-mode use the filename exactly as you typed it.
You can temporarily switch back to the "normal" minibuffer behaviour by hitting C-f. Then you can tab-complete the old filename, and edit it as needed.