if exists("g:autoloaded_timl_type")
finish
endif
let g:autoloaded_timl_type = 1
function! s:freeze(...) abort
return a:000
endfunction
if !exists('g:timl#nil')
let g:timl#nil = s:freeze()
lockvar 1 g:timl#nil
endif
" Section: Blessing
if !exists('g:timl_tag_sentinel')
let g:timl_tag_sentinel = s:freeze('blessed object')
lockvar 1 g:timl_tag_sentinel
endif
if !exists('s:types')
let s:types = {}
endif
function! timl#type#find(name) abort
return get(s:types, timl#string#coerce(a:name), g:timl#nil)
endfunction
function! timl#type#create(name, ...) abort
let munged = tr(a:name, '-./', '_##')
if !has_key(s:types, a:name)
let s:types[a:name] = timl#type#bless(s:type_type, {
\ 'str': a:name,
\ 'location': 'g:'.munged,
\ 'slots': g:timl#nil,
\ '__call__': function('timl#type#constructor')})
endif
let s:types[a:name].slots = a:0 ? a:1 : g:timl#nil
let g:{munged} = s:types[a:name]
return s:types[a:name]
endfunction
function! timl#type#core_create(name, ...) abort
return timl#type#create('timl.lang/'.a:name, a:0 ? a:1 : g:timl#nil)
endfunction
function! timl#type#core_define(name, slots, methods) abort
let ns = timl#namespace#create(timl#symbol#intern('timl.core'))
let type = timl#type#core_create(a:name, a:slots)
for [k, v] in items(a:methods)
call timl#type#define_method(ns, timl#symbol#intern(k), type, function(v))
endfor
return type
endfunction
function! timl#type#constructor(_) dict abort
if get(self, 'slots') is# g:timl#nil
throw 'timl: constructor not implemented'
endif
if len(a:_) != len(self.slots)
throw 'timl: arity error'
endif
let object = {}
for i in range(len(a:_))
let object[self.slots[i]] = a:_[i]
endfor
return timl#type#bless(self, object)
endfunction
if !has_key(s:types, 'timl.lang/Type')
let s:types['timl.lang/Type'] = {
\ 'str': 'timl.lang/Type',
\ 'location': 'g:timl#lang#Type',
\ 'slots': g:timl#nil,
\ '__call__': function('timl#type#constructor')}
endif
let s:type_type = s:types['timl.lang/Type']
function! timl#type#define(ns, var, slots) abort
let str = timl#namespace#name(a:ns).name . '/' . timl#symbol#cast(a:var).name
let type = timl#type#create(str)
if a:slots isnot# g:timl#nil
let type.slots = map(timl#array#coerce(a:slots), 'timl#symbol#cast(v:val).name')
endif
return timl#namespace#intern(a:ns, a:var, type)
endfunction
let s:builtins = {
\ 0: 'vim/Number',
\ 1: 'vim/String',
\ 2: 'vim/Funcref',
\ 3: 'vim/List',
\ 4: 'vim/Dictionary',
\ 5: 'vim/Float'}
function! timl#type#objectp(obj) abort
return type(a:obj) == type({}) && get(a:obj, '__flag__') is g:timl_tag_sentinel
endfunction
function! timl#type#string(val) abort
let type = get(s:builtins, type(a:val), 'vim/Unknown')
if a:val is# g:timl#nil
return 'timl.lang/Nil'
elseif type ==# 'vim/Dictionary'
if get(a:val, '__flag__') is g:timl_tag_sentinel
return a:val.__type__.str
endif
endif
return type
endfunction
let s:proto = {
\ '__call__': function('timl#type#dispatch_call'),
\ '__flag__': g:timl_tag_sentinel}
function! timl#type#bless(type, ...) abort
let obj = a:0 ? a:1 : {}
call extend(obj, s:proto, 'keep')
let obj.__type__ = a:type
return obj
endfunction
function! timl#type#dispatch_call(_) dict
return g:timl#core.call.__call__([self, a:_])
endfunction
call timl#type#bless(s:type_type, s:type_type)
" Section: Hierarchy
" Cribbed from clojure.core
function! timl#type#parents(key) abort
return timl#set#coerce(values(get(g:timl_hierarchy.parents, timl#string#coerce(a:key), {})))
endfunction
function! timl#type#ancestors(key) abort
return timl#set#coerce(values(get(g:timl_hierarchy.ancestors, timl#string#coerce(a:key), {})))
endfunction
function! timl#type#descendants(key) abort
return timl#set#coerce(values(get(g:timl_hierarchy.descendants, timl#string#coerce(a:key), {})))
endfunction
function! s:tf(m, source, sources, target, targets) abort
for k in [a:source] + values(get(a:sources, a:source[0], {}))
if !has_key(a:targets, k[0])
let a:targets[k[0]] = {}
endif
let a:targets[k[0]][a:target[0]] = a:target
for j in values(get(a:targets, a:target[0], {}))
let a:targets[k[0]][j[0]] = j
endfor
endfor
endfunction
function! s:isap(tag, parent) abort
return a:tag ==# a:parent || has_key(get(g:timl_hierarchy.ancestors, a:tag, {}), a:parent)
endfunction
function! timl#type#isap(tag, parent) abort
return timl#keyword#cast(a:tag) is# timl#keyword#cast(a:parent)
\ || has_key(get(g:timl_hierarchy.ancestors, a:tag[0], {}), a:parent[0])
endfunction
function! timl#type#derive(tag, parent) abort
let tp = g:timl_hierarchy.parents
let td = g:timl_hierarchy.descendants
let ta = g:timl_hierarchy.ancestors
let tag = timl#keyword#cast(a:tag)
let parent = timl#keyword#cast(a:parent)
if !has_key(tp, tag[0])
let tp[tag[0]] = {}
endif
if !has_key(tp[tag[0]], parent[0])
if has_key(get(ta, tag[0], {}), parent[0])
throw "timl#type: :".tag[0]." already has :".parent[0]." as ancestor"
endif
if has_key(get(ta, parent[0], {}), tag[0])
throw "timl#type: :".parent[0]." has :".tag[0]." as ancestor"
endif
let tp[tag[0]][parent[0]] = parent
call s:tf(ta, tag, td, parent, ta)
call s:tf(td, parent, ta, tag, td)
endif
let g:timl_hierarchy = copy(g:timl_hierarchy) " expire caches
return g:timl_hierarchy
endfunction
" Section: Dispatch
function! timl#type#canp(obj, this) abort
return s:get_method(a:this, timl#type#string(a:obj)) isnot# g:timl#nil
endfunction
function! s:get_method(this, type) abort
if a:this.hierarchy isnot# g:timl_hierarchy
let a:this.cache = {}
let a:this.hierarchy = g:timl_hierarchy
endif
if !has_key(a:this.cache, a:type)
let _ = {'preferred': g:timl#nil}
for [_.type, _.fn] in items(a:this.methods)
if s:isap(a:type, _.type)
if _.preferred is g:timl#nil || s:isap(_.type, _.preferred[0])
let _.preferred = [_.type, _.fn]
elseif !s:isap(_.preferred[0], _.type)
throw 'timl#type: ambiguous'
endif
endif
endfor
if _.preferred is# g:timl#nil
let a:this.cache[a:type] = get(a:this.methods, ' ', g:timl#nil)
else
let a:this.cache[a:type] = _.preferred[1]
endif
endif
return get(a:this.cache, a:type, g:timl#nil)
endfunction
let s:t_function = type(function('tr'))
let s:t_dict = type({})
function! timl#type#apply(_) dict abort
let type = timl#type#string(a:_[0])
if self.hierarchy isnot# g:timl_hierarchy
let self.cache = {}
let self.hierarchy = g:timl_hierarchy
endif
let Dispatch = has_key(self.cache, type) ? self.cache[type] : s:get_method(self, type)
let t = type(Dispatch)
if t == s:t_function
return call(Dispatch, a:_)
elseif t == s:t_dict
return Dispatch.__call__(a:_)
endif
throw 'timl#type: no '.self.ns.__name__[0].'/'.self.name[0].' dispatch for '.type
endfunction
function! timl#type#dispatch(this, _) abort
return call('timl#type#apply', [a:_], a:this)
endfunction
" Section: Method Creation
function! timl#type#define_method(ns, name, type, fn) abort
let var = timl#namespace#maybe_resolve(a:ns, timl#symbol#cast(a:name))
if var is# g:timl#nil || timl#type#string(timl#var#get(var)) isnot# 'timl.lang/MultiFn'
unlet var
if !empty(a:name.namespace)
throw "timl: no such method ".a:name.str
endif
let fn = timl#type#bless(s:multifn_type, {
\ '__call__': function('timl#type#apply'),
\ 'ns': a:ns,
\ 'name': a:name,
\ 'cache': {},
\ 'hierarchy': g:timl_hierarchy,
\ 'methods': {}})
let var = timl#namespace#intern(a:ns, a:name, fn)
endif
let multi = timl#var#get(var)
let multi.methods[a:type is# g:timl#nil ? ' ' : a:type.str] = a:fn
let multi.cache = {}
return var
endfunction
let s:multifn_type = timl#type#core_create('MultiFn')
" Section: Initialization
if !exists('g:timl_hierarchy')
let g:timl_hierarchy = {'parents': {}, 'descendants': {}, 'ancestors': {}}
endif
" vim:set et sw=2:
================================================
FILE: autoload/timl/var.vim
================================================
" Maintainer: Tim Pope
if exists('g:autoloaded_timl_var')
finish
endif
let g:autoloaded_timl_var = 1
function! timl#var#get(var) abort
return eval(a:var.location)
endfunction
function! timl#var#call(var, _) abort
return timl#call(eval(a:var.location), a:_)
endfunction
function! timl#var#test(this) abort
return timl#type#string(a:this) ==# 'timl.lang/Var'
endfunction
function! timl#var#find(sym) abort
let sym = timl#symbol#cast(a:sym)
let ns = empty(sym.namespace) ? timl#namespace#name(g:timl#core._STAR_ns_STAR_).str : sym.namespace
return get(timl#namespace#find(ns).__mappings__, sym.name, g:timl#nil)
endfunction
function! timl#var#funcref(var) abort
return function(a:var.munged)
endfunction
function! timl#var#reset_meta(var, meta) abort
let a:var.meta = a:meta
return a:var
endfunction
" Section: Munging
" From clojure/lang/Compiler.java
let s:munge = {
\ '.': "#",
\ ',': "_COMMA_",
\ ':': "_COLON_",
\ '+': "_PLUS_",
\ '>': "_GT_",
\ '<': "_LT_",
\ '=': "_EQ_",
\ '~': "_TILDE_",
\ '!': "_BANG_",
\ '@': "_CIRCA_",
\ "'": "_SINGLEQUOTE_",
\ '"': "_DOUBLEQUOTE_",
\ '%': "_PERCENT_",
\ '^': "_CARET_",
\ '&': "_AMPERSAND_",
\ '*': "_STAR_",
\ '|': "_BAR_",
\ '{': "_LBRACE_",
\ '}': "_RBRACE_",
\ '[': "_LBRACK_",
\ ']': "_RBRACK_",
\ '/': "_SLASH_",
\ '\\': "_BSLASH_",
\ '?': "_QMARK_"}
let s:demunge = {}
for s:key in keys(s:munge)
let s:demunge[s:munge[s:key]] = s:key
endfor
unlet! s:key
function! timl#var#munge(var) abort
let var = type(a:var) == type('') ? a:var : a:var[0]
return tr(substitute(substitute(var, '[^[:alnum:]:#_-]', '\=get(s:munge,submatch(0), submatch(0))', 'g'), '_SLASH_\ze.', '.', ''), '-', '_')
endfunction
function! timl#var#demunge(var) abort
let var = type(a:var) == type('') ? a:var : a:var[0]
return tr(substitute(var, '_\(\u\+\)_', '\=get(s:demunge, submatch(0), submatch(0))', 'g'), '_', '-')
endfunction
================================================
FILE: autoload/timl/vector.vim
================================================
" Maintainer: Tim Pope
if exists('g:autoloaded_timl_vector')
finish
endif
let g:autoloaded_timl_vector = 1
function! timl#vector#test(obj) abort
return timl#type#canp(a:obj, g:timl#core.nth)
endfunction
let s:type = timl#type#core_create('Vector')
function! timl#vector#claim(array) abort
lockvar 1 a:array
let vector = timl#type#bless(s:type, {'array': a:array})
lockvar 1 vector
return vector
endfunction
function! timl#vector#coerce(seq) abort
if a:seq is# g:timl#nil
return s:empty
elseif type(a:seq) ==# type([])
return timl#vector#claim(copy(a:seq))
elseif timl#type#string(a:seq) ==# s:type.str
return a:seq
endif
let array = []
let _ = {'seq': timl#coll#seq(a:seq)}
while _.seq isnot# g:timl#nil
call add(array, timl#coll#first(_.seq))
let _.seq = timl#coll#next(_.seq)
endwhile
return timl#vector#claim(array)
endfunction
function! timl#vector#seq(this) abort
return timl#array#seq(a:this.array)
endfunction
function! timl#vector#length(this) abort
return len(a:this.array)
endfunction
function! timl#vector#car(this) abort
return get(a:this.array, 0, g:timl#nil)
endfunction
function! timl#vector#cdr(this) abort
return len(a:this.array) <= 1 ? g:timl#empty_list : timl#array_seq#create(a:this.array, 1)
endfunction
function! timl#vector#lookup(this, idx, ...) abort
if type(a:idx) == type(0) && a:idx >= 0
return get(a:this.array, a:idx, a:0 ? a:1 : g:timl#nil)
endif
return a:0 ? a:1 : g:timl#nil
endfunction
function! timl#vector#nth(this, idx, ...) abort
let idx = timl#number#int(a:idx)
if a:0
return get(a:this.array, idx, a:1)
else
return a:this.array[idx]
endif
endfunction
function! timl#vector#conj(this, ...) abort
return timl#vector#claim(a:this.array + a:000)
endfunction
let s:empty = timl#vector#claim([])
function! timl#vector#empty(this) abort
return s:empty
endfunction
function! timl#vector#transient(this) abort
return copy(a:this.array)
endfunction
function! timl#vector#sub(this, start, ...) abort
let array = timl#vector#coerce(a:this).array
if a:0 && a:1 == 0
return s:empty
elseif a:0
return timl#vector#claim(array[a:start : (a:1 < 0 ? a:1 : a:1-1)])
else
return timl#vector#claim(array[a:start :])
endif
endfunction
function! timl#vector#call(this, _) abort
return call('timl#vector#lookup', [a:this] + a:_)
endfunction
================================================
FILE: autoload/timl.vim
================================================
" Maintainer: Tim Pope
if exists("g:autoloaded_timl")
finish
endif
let g:autoloaded_timl = 1
" Section: Util {{{1
function! timl#truth(val) abort
return a:val isnot# g:timl#nil && a:val isnot# g:timl#false
endfunction
function! timl#keyword(str) abort
return timl#keyword#intern(a:str)
endfunction
function! timl#symbol(str) abort
return timl#symbol#intern(a:str)
endfunction
" }}}1
" Section: Lists {{{1
function! timl#seq(coll) abort
return timl#coll#seq(a:coll)
endfunction
function! timl#first(coll) abort
return timl#coll#first(a:coll)
endfunction
function! timl#rest(coll) abort
return timl#coll#rest(a:coll)
endfunction
function! timl#next(coll) abort
return timl#coll#seq(timl#coll#rest(rest))
endfunction
function! timl#list(...) abort
return timl#list#create(a:000)
endfunction
" }}}1
" Section: Invocation {{{1
function! timl#call(Func, args, ...) abort
if type(a:Func) == type(function('tr'))
return call(a:Func, a:args, a:0 ? a:1 : {})
else
return a:Func.__call__(a:args)
endif
endfunction
function! timl#invoke(Func, ...) abort
if type(a:Func) == type(function('tr'))
return call(a:Func, a:000, {})
else
return a:Func.__call__(a:000)
endif
endfunction
" }}}1
" Section: Evaluation {{{1
function! timl#eval(x) abort
return timl#loader#eval(a:x)
endfunction
function! timl#re(str) abort
return timl#eval(timl#reader#read_string(a:str))
endfunction
function! timl#rep(str) abort
return timl#printer#string(timl#re(a:str))
endfunction
" }}}1
runtime! autoload/timl/bootstrap.vim
" vim:set et sw=2:
================================================
FILE: doc/timl.txt
================================================
*timl.txt* TimL
Author: Tim Pope
Repo: https://github.com/tpope/timl
License: EPL (http://opensource.org/licenses/eclipse-1.0.php)
USAGE *timl*
TimL files have an extension of ".tim" and a |filetype| of "timl". If they
are placed in "autoload/" in 'runtimepath', Vim's |autoload| will load them
just the same as ".vim" files.
*:TLrepl*
:TLrepl [ns] Start a REPL.
:source {file} Load a TimL file.
:Wepl In a TimL file, write, source, and start a REPL in
that namespace.
SYNTAX *timl-syntax*
It's Lisp. TimL files are just sequences of forms. Evaluation essentially
entails replacing symbols with their values and lists with the result of
calling the first element as function with the remaining elements as
arguments. An informal summary of the various forms follows:
Notation Description ~
; linewise comment
#! linewise comment (for shebangs)
#_ skip next form
nil |timl-nil|
false |timl-boolean|
true |timl-boolean|
\d... |timl-number| (see |expr-number|)
\k... |timl-symbol|
:... |timl-keyword|
"..." |timl-string| (see double quoted strings under |expr-string|)
#"..." |timl-regexp|
(...) |timl-list|
[...] |timl-vector|
{...} |timl-map|
#{...} |timl-set|
#(...) |timl-fn|
#*symbol |timl-funcref|
#*[...] |timl-array|
#*{...} |timl-dictionary|
^... |timl-metadata|
' |timl-quote|
` |timl-syntax-quote|
~ |timl-unquote|
~@ |timl-unquote-splicing|
@ |g:timl#core.deref|
TYPES *timl-types*
*timl-number*
Numbers ~
Same as Vim. See |expr-number|.
*timl-strings*
Strings ~
Same as strings in Vim. The literal syntax is the same as the double quoted
strings under |expr-string|.
*timl-regexps*
Regular Expressions ~
There's not a proper regexp type, but #"..." compiles down to a string of a
very magic |/\v| case sensitive |\/C| regexp string. Unlike with regular
string literals, you don't need to double your backslashes.
*timl-arrays*
Arrays ~
TimL arrays are actually Vim |Lists|. They have been rebranded arrays to
avoid confusion with the core Lisp data structure of a singly linked list.
Arrays participate in the expected collection abstractions, but be aware they
mutate, and thus are best avoided except when dealing with interop.
Arrays are shown as #*[...] when printed. The reader respects this syntax,
but it is preferrable to use |g:timl#core.array| to create a array.
*timl-dictionary* *timl-dictionaries*
Dictionaries ~
TimL dictionaries are Vim |Dictionaries|. TimL uses dictionaries in the
implementation of its type system, so "TimL dictionary" refers to a dictionary
that has not been blessed as any particular type. Dictionaries can be treated
as maps with forced string keys.
Dictionaries are shown as #*{...} when printed. The reader respects this
syntax, but it is preferrable to use |g:timl#core.dict| to create a
dictionary.
*timl-funcrefs*
Funcrefs ~
TimL provides a special #*symbol syntax for creating a Vim |Funcref|.
Funcrefs can be called like any other function: (#*bufnr "%"). Vim imposes
certain restrictions on assigning funcrefs to variables, so beware of using
them with |timl-set!| and |timl-def|.
*timl-nil*
Nil ~
VimL has no concept of nil, so this is actually just a special singleton
object. The literal form is "nil".
*timl-booleans*
Booleans ~
Booleans are the canonical truth values. There's a literal for each: "true"
and "false". Nil and false are the only false values in TimL. Note that in
VimL, zero is false, and built-in Vim functions return that as their false
value. Compose with |g:timl#core.nonzero_QMARK_| if you want to use the
result of a built-in Vim function in a conditional.
*timl-symbols*
Symbols ~
Any sequence of identifier characters that doesn't start with a number.
Identifier characters include alphanumerics and the special characters
"-_?!*+/<>". ":" and "#" are reserved for internal use and can be used to
refer to Vim variables (|b:var,| |w:var|, |t:var|, |g:var|, |v:var|).
Since symbols evaluate, you'll need to |timl-quote| one if you want it as a
value: 'symbol.
*timl-keywords*
Keywords ~
Keywords look like symbols preceded by a colon. Unlike symbols, they evaluate
to themselves, making them good |timl-map| keys. Calling a keyword as a
function tries to retrieve it from the given collection using
|g:timl#core.get|.
*timl-lists*
Lists ~
Lists are linked lists under the hood, and have a syntax literal of zero or more forms enclosed in parentheses (). Lists evaluate to a function
call of the first element with the remaining elements as args. To create a
list value, |timl-quote| it (also prevents evaluation of elements) or use
|g:timl#core.list|.
*timl-vectors*
Vectors ~
An ordered, indexed collection intended for random access. Created literally
by enclosing zero or more forms in brackets. Evaluates to a new vector of the
evaluation of the contained elements.
*timl-maps*
Maps ~
Maps are associative, unordered collections. The syntax literal is {...}.
The definining method of a map is |g:timl#core.dissoc|.
*timl-sets*
Sets ~
A set is an unordered collection of values, and can be thought of as a map
where the keys and values are the same. The syntax literal is #{...}. The
defining method of a set is |g:timl#core.disj|.
EVALUATION *timl-evaluation*
It's Lisp.
Symbols evaluate to their value in lexical scope (from let or fn) or the
current namespace. Symbols evaluating to special forms are handled as
explained under |timl-special-forms|.
Lists evaluate to a function call. Dictionaries evaluate their
values. Everything else evaluates to itself.
SPECIAL FORMS *timl-special-forms*
*timl-if*
(if {cond} {then} {else}?) ~
If {cond} is true, evaluate {then}, else evaluate {else}.
*timl-do*
(do {form} ...) ~
Evaluate a series of forms and return the result of the last one.
*timl-let*
(let [{symbol} {value} ...] {body} ...) ~
Bind the given symbols lexically for the scope of the given body.
*timl-fn*
(fn {name}? [{param} ...] {body} ...) ~
#(... % %2 %3 ... %&) ~
Create an anonymous function.
*timl-recur*
In tail position, re-calls the current function or |timl#core#loop| construct
with the given parameters. See Clojure's documentation at
http://clojure.org/special_forms#recur .
*timl-def*
(def {var} {value}) ~
Define a variable or function.
*timl-set!*
(set! {var} {value}) ~
Set a Vim variable, in a manner similar to |:let|. |g:var|, |b:var|, |w:var|,
|t:var|, |v:var|, |expr-option|, and variables in the current namespace are
supported. >
(set! b:did_ftplugin 1)
(set! &shiftwidth 2)
(set! *ns* (the-ns 'user))
<
*timl-quote*
(quote {form}) ~
'{form} ~
Return {form} unevaluated.
*timl-function*
(function {form}) ~
#*{form} ~
Return a |Funcref| for a built-in or user defined Vim function. Can be called
like any other function.
*timl-try* *timl-catch* *timl-finally*
(try {body} ... (catch {pattern} {e} {body} ...) ... (finally {body} ...) ...) ~
Wrap a set of forms in a |:try| block. The {pattern} is a regexp to match
the string exception as explained under |:catch|, or can also be a Vim error
number. You can access |v:exception| and |v:throwpoint| for information about
the exception, or look in dictionary {e}.
*timl-throw*
(throw {string}) ~
Pass the given {string} to |:throw|.
*timl-execute*
(execute {string}) ~
Run the given string with |:execute|.
*timl-.* *timl-dot*
(. {dict} -{key}) ~
Retrieve the given key of the given dict.
NAMESPACES *timl-namespaces* *timl-ns*
Namespaces take the Clojure model and adapt it to fit the VimL |autoload|
feature.
>
(ns foo.bar)
(def baz 1)
(in-ns 'user)
foo.bar/baz ; evaluates to 1
(alias 'quux 'foo.bar)
quux/baz ; evaluates to 1
(refer 'foo.bar)
baz ; evaluates to 1
<
You can also use the ns macro from Clojure.
>
(ns my.ns
(:refer-timl :exclude [+])
(:use timl.repl)
(:require [timl.file :as file]))
<
TimL files placed in the |autoload| directory will automatically be loaded in
the correct namespace.
vim:tw=78:et:ft=help:norl:
================================================
FILE: doc/timl_core.txt
================================================
*g:timl#core.array*
(timl.core/array & elems) Create a |timl-array| containing elems.
*g:timl#core.dict*
(timl.core/dict map) Convert a map to a |timl-dictionary|.
(timl.core/dict keyvals) Create a |timl-dictionary| from keyvals.
(timl.core/dict & keyvals) Create a |timl-dictionary| from keyvals.
vim:tw=78:sw=8:et:ft=help:norl:
================================================
FILE: epl-v10.html
================================================
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
================================================
FILE: ftplugin/timl.tim
================================================
(ns ftplugin.timl)
(use 'timl.ftplugin)
(include-guard)
(setlocal comments=":; ,:;;; ,:;; " commentstring="; %s")
(setlocal define="^\\s*(def\\k*")
(setlocal formatoptions+=cql)
(setlocal omnifunc=timl#interactive#omnicomplete)
(execute "nnoremap cp :set opfunc=timl#interactive#eval_opfuncg@")
(execute "nnoremap cpp :call timl#interactive#eval_opfunc(v:count)")
(execute "nnoremap K :execute 'help' ftplugin#timl#cursor_keyword()")
(defn cursor-keyword []
(let [kw (#*expand "")
ns (the-ns (symbol (#*timl#interactive#ns_for_cursor)))]
(cond
(re-find "^#\\*" kw) (str (subs kw 2) "()")
(re-find "^&" kw) (str "'" (subs kw 1) "'")
(special-symbol? (symbol kw)) (str "timl-" kw)
(ns-resolve ns (symbol kw)) (. (ns-resolve ns (symbol kw)) munged)
:else kw)))
================================================
FILE: indent/timl.tim
================================================
(ns indent.timl)
(execute "runtime! indent/clojure.vim")
================================================
FILE: plugin/timl.vim
================================================
" timl.vim - TimL
" Maintainer: Tim Pope
if exists("g:loaded_timl") || v:version < 700 || &cp
finish
endif
let g:loaded_timl = 1
if &maxfuncdepth == 100
set maxfuncdepth=200
endif
augroup timl
autocmd!
autocmd BufNewFile,BufReadPost *.tim set filetype=timl
autocmd BufNewFile,BufReadPost *
\ if getline(1) =~# '^#!' && getline(2) =~# ';.*\'))
autocmd SourceCmd *.tim call timl#loader#source(expand(""))
autocmd FuncUndefined *#* call s:autoload(expand(''))
autocmd VimEnter * nested
\ if exists('s:source') |
\ redraw! |
\ execute 'TLsource '.s:source |
\ unlet! s:source |
\ endif
augroup END
command! -bar -nargs=? TLrepl :execute timl#interactive#repl()
command! -bar TLscratch :execute timl#interactive#scratch()
command! -nargs=1 -complete=expression TLinspect :echo timl#printer#string()
command! -nargs=1 -complete=customlist,timl#interactive#input_complete TLeval
\ try |
\ echo timl#rep() |
\ catch |
\ unlet! g:timl#core._STAR_e |
\ let g:timl#core._STAR_e = timl#exception#build(v:exception, v:throwpoint) |
\ echoerr v:exception |
\ endtry
command! -bar TLcopen :call timl#interactive#copen(get(g:, 'timl#core#_STAR_e', []))
command! -bang -nargs=? -complete=file TLsource
\ if has('vim_starting') |
\ let s:source = |
\ else |
\ call timl#loader#source(expand(empty() ? '%' : )) |
\ endif
function! s:load_filetype(ft) abort
if empty(a:ft)
return ''
endif
let ft = split(a:ft)[0]
for kind in ['ftplugin', 'indent']
for file in findfile(kind.'/'.ft.'.tim', &rtp, -1)
try
call timl#loader#source(file)
catch
unlet! g:timl#core._STAR_e
let g:timl#core._STAR_e = timl#exception#build(v:exception, v:throwpoint) |
echohl WarningMSG
echomsg v:exception
echohl NONE
endtry
endfor
endfor
endfunction
if !exists('g:timl_requires')
let g:timl_requires = {}
endif
function! s:file4ns(ns) abort
if !exists('s:tempdir')
let s:tempdir = tempname()
endif
let file = s:tempdir . '/' . a:ns . '.vim'
if !isdirectory(fnamemodify(file, ':h'))
call mkdir(fnamemodify(file, ':h'), 'p')
endif
return file
endfunction
function! s:autoload(function) abort
let var = matchstr(a:function, '.*\ze#')
let ns = tr(var, '#_', '.-')
let base = tr(ns, '.-', '/_')
if !has_key(g:timl_requires, ns)
if !empty(findfile('autoload/'.base.'.vim'))
let g:timl_requires[ns] = 1
else
for file in findfile('autoload/'.base.'.tim', &rtp, -1)
call timl#loader#source(file)
let g:timl_requires[ns] = 1
break
endfor
endif
endif
let key = matchstr(a:function, '.*#\zs.*')
if has_key(g:, var) && has_key(g:{var}, key) && timl#type#canp(g:{var}[key], g:timl#core.call)
let body = ["function ".a:function."(...)",
\ " return timl#call(g:".var.".".key.", a:000)",
\ "endfunction"]
let file = s:file4ns(base)
call writefile(body, file)
exe 'source '.file
endif
endfunction
================================================
FILE: syntax/timl.vim
================================================
" Vim syntax file
" Language: TimL
" Maintainer: Tim Pope
" Filenames: *.timl
if exists("b:current_syntax")
finish
endif
syntax sync minlines=100
if !exists('s:functions')
let s:file = readfile(findfile('syntax/vim.vim', &rtp))
let s:options = split(join(map(filter(copy(s:file), 'v:val =~# "^syn keyword vimOption contained\t[^in]"'), 'substitute(v:val, "^.*\t", "", "g")'), ' '), '\s\+')
let s:functions = split(join(map(filter(copy(s:file), 'v:val =~# "^syn keyword vimFuncName contained\t[^in]"'), 'substitute(v:val, "^.*\t", "", "g")'), ' '), ' ')
endif
setl iskeyword+=?,!,#,$,%,&,*,+,.,/,<,>,:,=,45
let b:syntax_ns_str = timl#interactive#ns_for_cursor(0)
let b:syntax_vars = keys(timl#namespace#map(timl#namespace#find(b:syntax_ns_str)))
let b:current_syntax = "timl"
function! s:syn_keyword(group, keywords) abort
if !empty(a:keywords)
exe 'syntax keyword '.a:group.' '.join(a:keywords, ' ')
endif
endfunction
call s:syn_keyword('timlSymbol', b:syntax_vars)
call s:syn_keyword('timlDefine', filter(copy(b:syntax_vars), 'v:val =~# "^def\\%(ault\\)\\@!"'))
syntax keyword timlSpecialParam & &form &env
syntax keyword timlConditional if
syntax keyword timlDefine def deftype* set! declare
syntax keyword timlRepeat loop recur
syntax keyword timlStatement do let fn . execute
syntax keyword timlSpecial let* fn* var function
syntax keyword timlException try catch finally throw
syntax keyword timlConstant nil
syntax keyword timlBoolean false true
syntax match timlKeyword ":\k\+"
syntax match timlCharacter "\\\%(space\|tab\|newline\|return\|formfeed\|backspace\|.\)"
syntax match timlNumber "\<[-+]\=0\o\+\>"
syntax match timlNumber "\<[-+]\=0x\x\+\>"
syntax match timlNumber "\<[-+]\=\%([1-9]\d*\|0\)\%(\.\d\+\)\=\%([Ee]\d\+\)\=\>"
syntax keyword timlNumber Infinity -Infinity +Infinity NaN
syntax region timlString start=/"/ skip=/\\\\\|\\"/ end=/"/ contains=timlStringEscape,@Spell
syntax match timlStringEscape "\v\\%([uU]\x{4}|[0-3]\o{2}|\o\{1,2}|[xX]\x{1,2}|[befnrt\\"]|\<[[:alnum:]-]+\>)" contained
syntax region timlRegexp start=/#"/ skip=/\\\\\|\\"/ end=/"/ contains=timlRegexpSpecial
syntax match timlFuncref "\<#\*" nextgroup=timlVimFunction
syntax match timlVarref "\<#'" nextgroup=timlSymbol
syntax match timlQuote "'"
syntax match timlSyntaxQuote "`"
syntax match timlUnquote "\~@\="
syntax match timlDeref "@"
syntax match timlMeta "\^"
syntax region timlList matchgroup=timlGroup start="(" end=")" contains=TOP,@Spell
syntax region timlVector matchgroup=timlGroup start="\[" end="]" contains=TOP,@Spell
syntax region timlMap matchgroup=timlGroup start="{" end="}" contains=TOP,@Spell
syntax region timlSet matchgroup=timlGroup start="#{" end="}" contains=TOP,@Spell
syntax region timlFn matchgroup=timlGroup start="#(" end=")" contains=TOP,@Spell
syntax match timlSymbol '\<%[1-9]\d*\>'
syntax match timlSymbol '\<%&\=\>'
syntax match timlComment "\<#_"
syntax match timlComment ";.*$"
syntax match timlComment ";= "
syntax match timlComment ";! " nextgroup=timlError
syntax match timlError ".*$" contained
syntax match timlComment "#!.*$"
syntax match timlComment ";;.*$" contains=@Spell
call s:syn_keyword('timlVimOption', map(copy(s:options), "'&'.v:val"))
call s:syn_keyword('timlVimOption', map(copy(s:options), "'&l:'.v:val"))
call s:syn_keyword('timlVimOption', map(copy(s:options), "'&g:'.v:val"))
exe 'syn match timlVimFunction contained "\%('.join(s:functions, '\|').'\)\>"'
syntax match timlVar '\<[glabwtv]:\k\+\>'
hi def link timlDefine Define
hi def link timlSymbol Identifier
hi def link timlSpecialParam Special
hi def link timlConditional Conditional
hi def link timlRepeat Repeat
hi def link timlStatement Statement
hi def link timlException Exception
hi def link timlBoolean Boolean
hi def link timlConstant Constant
hi def link timlKeyword Constant
hi def link timlCharacter Character
hi def link timlString String
hi def link timlRegexp String
hi def link timlStringEscape Special
hi def link timlRegexpSpecial Special
hi def link timlNumber Number
hi def link timlSpecial Special
hi def link timlFuncref Special
hi def link timlVarref Special
hi def link timlQuote Special
hi def link timlSyntaxQuote Special
hi def link timlUnquote Special
hi def link timlDeref Special
hi def link timlMeta Special
hi def link timlGroup Special
hi def link timlComment Comment
hi def link timlError WarningMsg
hi def link timlVimFunction Function
hi def link timlVimOption Type
" vim:set et sw=2:
================================================
FILE: test/timl/core_coll_test.tim
================================================
(ns timl.core-coll-test)
(use 'timl.test)
(assert (= 3 (count (list 1 2 3))))
(assert (= 1 (count (dict "a" "b"))))
(assert (= (list) (empty (list 1 2 3))))
(assert (= (dict) (empty (dict "a" "b"))))
(assert (= "" (empty "string")))
(assert (nil? (empty 'symbol)))
(assert (nil? (empty 0)))
(assert (= (list 2 3 4) (map (partial + 1) (list 1 2 3))))
(assert (= (list "a") (map first (dict "a" "b"))))
(assert (= 6 (reduce + (list 1 2 3))))
================================================
FILE: test/timl/core_test.tim
================================================
(ns timl.core-test)
(use 'timl.test)
(let [sentinel (dict)]
(assert (identical? sentinel ((constantly sentinel)))))
(assert (= "42\n" (with-out-str (println 42))))
================================================
FILE: test/timl/number_test.tim
================================================
(ns timl.number-test)
(use 'timl.test)
(assert (number? 3))
(assert (number? 3.0))
(assert (not (number? "")))
(assert (integer? 3))
(assert (not (integer? 3.0)))
(assert (not (integer? "")))
(assert (not (float? 3)))
(assert (float? 3.0))
(assert (not (integer? "")))
(assert (= 0 (+)))
(assert (= 1 (+ 1)))
(assert (= 3 (+ 1 2)))
(assert (= 6 (+ 1 2 3)))
(assert (= 4 (inc 3)))
(assert (= -1 (- 1)))
(assert (= 0 (- 3 1 2)))
(assert (= 2 (dec 3)))
(assert (= 1 (*)))
(assert (= 6 (* 1 2 3)))
(assert (= 0 (/ 2)))
(assert (= 0.5 (/ 2.0)))
(assert (= 0.5 (/ 1 2.0)))
(assert (= 0.25 (/ 1 2.0 2.0)))
(assert (= 1 (rem 4 3)))
(assert (= -1 (rem -4 3)))
(assert (= 1 (mod 4 3)))
(assert (= 2 (mod -4 3)))
(assert (= 0 (mod 0 3)))
(assert (= -2 (mod 4 -3)))
(assert (= 1.0 (quot 3.0 2)))
(assert (= 7 (max 3 7 2 4)))
(assert (= 2 (min 3 7 2 4)))
(assert (= -1 (bit-not 0)))
(assert (= 5 (bit-xor 7 3 1)))
(assert (= 4 (bit-and 7 6 5)))
(assert (= 7 (bit-or 1 2 4)))
(assert (= 6 (bit-and-not 7 1 8)))
(assert (= 8 (bit-shift-left 1 3)))
(assert (= 1 (bit-shift-right 8 3)))
(assert (= 3 (bit-flip 1 1)))
(assert (= 3 (bit-set 1 1)))
(assert (= 1 (bit-clear 3 1)))
(assert (bit-test 3 1))
(assert (not (bit-test 5 1)))
(assert (= nil (not-negative -1)))
(assert (= 0 (not-negative 0)))
(assert (zero? 0))
(assert (not (zero? 1)))
(assert (nonzero? 1))
(assert (not (nonzero? 0)))
(assert (even? 2))
(assert (not (even? 3)))
(assert (odd? 3))
(assert (not (odd? 2)))
(assert (> 3 2 1))
(assert (not (> 3 2 2)))
(assert (< 1 2 3))
(assert (not (< 1 2 2)))
(assert (>= 3 2 2))
(assert (not (>= 3 1 2)))
(assert (<= 1 2 2))
(assert (not (< 1 3 2)))
(assert (== 0 0.0 0))
(assert (not (== 0 0.0 1)))
(defn fact [x]
(loop [n x
f 1]
(if (<= n 1) f (recur (dec n) (* f n)))))
(defn fib [n]
(first
(loop [xs [1 0]]
(if (< (count xs) n)
(recur (cons (+ (first xs) (second xs)) xs))
xs))))
(assert (= 120 (fact 5)))