]> gitweb.factorcode.org Git - factor.git/blob - basis/ui/tools/listener/history/history.factor
stomp.cli: simplify
[factor.git] / basis / ui / tools / listener / history / history.factor
1 ! Copyright (C) 2009 Slava Pestov.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors continuations documents io io.encodings.utf8
4 io.files io.styles kernel math math.order namespaces
5 prettyprint.backend prettyprint.config sequences strings.parser ;
6 IN: ui.tools.listener.history
7
8 TUPLE: history document elements start index ;
9
10 CONSTANT: history-file "~/.factor-history"
11
12 : read-history ( -- elements )
13     history-file file-exists? [ history-file utf8 file-lines [ unescape-string <input> ] V{ } map-as ] [ V{ } clone ] if ;
14
15 : append-history ( history -- )
16     history-file file-exists?
17     [
18         [
19             history-file utf8 [
20                 f string-limit? [
21                     [ elements>> ] [ start>> ] bi [ string>> f f unparse-string print ] swap each-from
22                 ] with-variable
23             ] with-file-appender
24         ] [ [ index>> ] keep start<< ] bi
25     ] [ drop ] if ;
26
27 : <history> ( document -- history )
28     read-history dup length dup history boa ;
29
30 <PRIVATE
31
32 : push-if-not-last ( elt seq -- )
33     2dup ?last = [ 2drop ] [ push ] if ;
34
35 : current-input ( history -- input ? )
36     document>> doc-string [ <input> ] [ empty? ] bi ;
37
38 PRIVATE>
39
40 : history-add ( history -- input )
41     dup current-input [ nip ] [
42         [
43             over elements>>
44             [ push-if-not-last ]
45             [ length >>index drop ] bi
46         ] keep
47     ] if ;
48
49 <PRIVATE
50
51 : set-element ( elt history -- )
52     [ index>> ] [ elements>> ] bi set-nth ;
53
54 : get-element ( history -- elt )
55     [ index>> ] [ elements>> ] bi nth ;
56
57 : save-history ( history -- )
58     dup current-input [ 2drop ] [ swap set-element ] if ;
59
60 : update-document ( history -- )
61     [ get-element string>> ] [ document>> ] bi
62     [ set-doc-string ] [ clear-undo ] bi ;
63
64 : change-history-index ( history i -- )
65     over elements>> length 1 -
66     '[ _ + 0 _ clamp ] change-index drop ;
67
68 : history-recall ( history i -- )
69     over elements>> empty? [ 2drop ] [
70         [ drop save-history ]
71         [ change-history-index ]
72         [ drop update-document ]
73         2tri
74     ] if ;
75
76 PRIVATE>
77
78 : history-recall-previous ( history -- )
79     -1 history-recall ;
80
81 : history-recall-next ( history -- )
82     1 history-recall ;