id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
1,720
cl-ana.typed-table.asd
ghollisjr_cl-ana/typed-table/cl-ana.typed-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; typed-table.asd (asdf:defsystem #:cl-ana.typed-table :serial t :description "Table types which have typed columns. Provides automatic conversion between foreign and LISP objects." :author "Gary Hollis" :license "GPLv3" :depends-on (#:alexandria #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.table #:cl-ana.typespec) :components ((:file "package") (:file "typed-table")))
1,360
Common Lisp
.asd
35
35.342857
70
0.680514
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e567d001e85f98750450fa4cb4373e7d8b992c50cbe37d292051aa95291bd155
1,720
[ -1 ]
1,721
cl-ana.columnar-table.asd
ghollisjr_cl-ana/columnar-table/cl-ana.columnar-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2019 Katherine Cox-Buday ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. (asdf:defsystem #:cl-ana.columnar-table :serial t :license "GPLv3" :author "Gary Hollis" :description "Used to access tables which have been pivoted so that a rows values are stratified across all rows, and a column's values are accessible all from a single row." :depends-on (#:cl-ana.table #:cl-ana.reusable-table) :components ((:file "package") (:file "columnar-table")))
1,210
Common Lisp
.asd
28
40.535714
70
0.707875
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
95fa9d7b2e1d7274169d7133d6dd1ea5bf18c0b7230504a360ecc2b13b95b19f
1,721
[ -1 ]
1,722
cl-ana.ntuple-table.asd
ghollisjr_cl-ana/ntuple-table/cl-ana.ntuple-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; ntuple-table.asd (asdf:defsystem #:cl-ana.ntuple-table :serial t :description "Table subclass specializing on ntuples as implemented via GSLL & used by CERN's PAW" :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.list-utils #:cffi #:gsll #:cl-ana.gsl-cffi #:cl-ana.table #:cl-ana.typed-table #:cl-ana.typespec #:alexandria) :components ((:file "package") (:file "ntuple-table")))
1,355
Common Lisp
.asd
37
33.189189
70
0.675019
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6d4e6af763008b3859ccd29e6d55034ce1e7d6b71884e7562fa9413eb4731757
1,722
[ -1 ]
1,723
cl-ana.reusable-table.asd
ghollisjr_cl-ana/reusable-table/cl-ana.reusable-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; reusable-table.asd (asdf:defsystem #:cl-ana.reusable-table :serial t :description "Table wrapper for reading which automatically re-loads table for reading after fully reading the contents (not guarranteed by the raw table types)." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.table #:alexandria) :components ((:file "package") (:file "reusable-table")))
1,281
Common Lisp
.asd
32
37.875
70
0.710737
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
335e1dc34f311890d0edb7dbaca7ffcdb262e3b0244a3344267732d03977832c
1,723
[ -1 ]
1,724
cl-ana.makeres-graphviz.asd
ghollisjr_cl-ana/makeres-graphviz/cl-ana.makeres-graphviz.asd
;;;; makeres-graphviz provides graph visualization for makeres target ;;;; graphs. ;;;; ;;;; Copyright 2014-2015 Gary Hollis ;;;; ;;;; This file is part of makeres-graphviz. ;;;; ;;;; makeres-graphviz is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; makeres-graphviz is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with makeres-graphviz. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-graphviz :serial t :author "Gary Hollis" :description "makeres-graphviz provides graph visualization for makeres target graphs." :license "GPLv3" :depends-on (#:cl-ana.makeres #:external-program) :components ((:file "package") (:file "dot")))
1,258
Common Lisp
.asd
32
36.90625
80
0.714286
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
497fc254b4397435bf1eab44acc6d1da059f0912ff5786ff23ce4294d4550699
1,724
[ -1 ]
1,725
cl-ana.array-utils.asd
ghollisjr_cl-ana/array-utils/cl-ana.array-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2021 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; list-utils.asd (asdf:defsystem #:cl-ana.array-utils :serial t :author "Gary Hollis" :description "Utilities for working with arrays" :license "GPLv3" :depends-on (#:alexandria) :components ((:file "package") (:file "array-utils")))
1,124
Common Lisp
.asd
29
36.896552
70
0.703839
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ba3bcb5cd3fbb9b8e4c66296c92261dc952a494c9cc668a22cdb11cff9dfe563
1,725
[ -1 ]
1,726
cl-ana.hdf-utils.asd
ghollisjr_cl-ana/hdf-utils/cl-ana.hdf-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; hdf-utils.asd (asdf:defsystem #:cl-ana.hdf-utils :serial t :description "Utilities for a more lispy interface to HDF5" :author "Gary Hollis" :license "GPLv3" :depends-on (#:cffi #:alexandria #:cl-ana.hdf-cffi #:cl-ana.pathname-utils #:cl-ana.memoization #:cl-ana.typespec #:cl-ana.hdf-typespec #:cl-ana.string-utils #:cl-ana.macro-utils) :components ((:file "package") (:file "hdf-utils")))
1,409
Common Lisp
.asd
37
33.162162
70
0.646973
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
24f9049ca5333993b6d36ff1e47168bf3f45c7d94eaaf6fc8964a8e95952102c
1,726
[ -1 ]
1,727
cl-ana.histogram.asd
ghollisjr_cl-ana/histogram/cl-ana.histogram.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; histogram.asd (asdf:defsystem #:cl-ana.histogram :serial t :author "Gary Hollis" :description "Support for binned data analysis via contiguous and sparse histograms; integrated into the generic-math framework." :license "GPLv3" :depends-on (#:iterate #:alexandria #:cl-ana.clos-utils #:cl-ana.symbol-utils #:cl-ana.list-utils #:cl-ana.hash-table-utils #:cl-ana.macro-utils #:cl-ana.functional-utils #:cl-ana.generic-math #:cl-ana.binary-tree #:cl-ana.map #:cl-ana.tensor #:cl-ana.fitting) :components ((:file "package") (:file "histogram") (:file "rectangular-histogram") (:file "contiguous-histogram") (:file "sparse-histogram") (:file "variable-binning-histogram") (:file "categorical-histogram") (:file "conversion")))
1,843
Common Lisp
.asd
48
32.229167
70
0.634894
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fc61d3a4a5caa083c8c91c704b1275e175f5984c0fb7ee14b2b4781d07775e89
1,727
[ -1 ]
1,728
cl-ana.memoization.asd
ghollisjr_cl-ana/memoization/cl-ana.memoization.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; memoization.asd (asdf:defsystem #:cl-ana.memoization :serial t :description "Provides memoized functions (only compute for new arguments, otherwise lookup in a hash table)" :author "Gary Hollis" :license "GPLv3" :depends-on (#:alexandria) :components ((:file "package") (:file "memoization")))
1,194
Common Lisp
.asd
30
37.9
70
0.711092
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c984fa8db88a90516f0400bd7320111f4fcac8ec3ee0780ff1f8c248c8534316
1,728
[ -1 ]
1,729
cl-ana.quantity.asd
ghollisjr_cl-ana/quantity/cl-ana.quantity.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.quantity :serial t :description "Provides basic physics functions such as dimensional analysis, units, and some common definitions." :author "Gary Hollis" :license "" :depends-on (#:alexandria #:cl-ana.list-utils #:cl-ana.macro-utils #:cl-ana.symbol-utils #:cl-ana.generic-math #:cl-ana.error-propogation #:cl-ana.math-functions) :components ((:file "package") (:file "unit") (:file "macros") (:file "quantity") (:file "binary") (:file "si") (:file "metric-non-si") (:file "us") (:file "constants") (:file "temperature") (:file "post-constants") (:file "convert-units")))
1,738
Common Lisp
.asd
45
31.555556
70
0.604253
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c00fbd68565a0399ea938a8d07aa228e4a6252054c3cc94a03f41910e0a5cc44
1,729
[ -1 ]
1,730
cl-ana.statistical-learning.asd
ghollisjr_cl-ana/statistical-learning/cl-ana.statistical-learning.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2019 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; statistics.asd (asdf:defsystem #:cl-ana.statistical-learning :serial t :description "Various statistical functions integrated into the generic-math framework." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.generic-math #:cl-ana.macro-utils #:cl-ana.map #:cl-ana.list-utils #:cl-ana.functional-utils #:cl-ana.histogram #:cl-ana.statistics #:cl-ana.math-functions #:cl-ana.linear-algebra) :components ((:file "package") (:file "statistical-learning")))
1,517
Common Lisp
.asd
38
34.078947
70
0.644114
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
be535058fa0cbd2faf02b8e2c1d2fad4e1ad4ee58e99cb636de0f040bbda77c9
1,730
[ -1 ]
1,731
cl-ana.lorentz.asd
ghollisjr_cl-ana/lorentz/cl-ana.lorentz.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; lorentz.asd (asdf:defsystem #:cl-ana.lorentz :serial t :description "Implements lorentz vectors, lorentz transformations, etc." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.generic-math #:cl-ana.linear-algebra #:cl-ana.tensor #:iterate) :components ((:file "package") (:file "lorentz")))
1,228
Common Lisp
.asd
33
34.666667
70
0.693467
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
927d820c05eb2f12c01e27fa94d01573b650ab5c75a2e82bd3b9b5e1a014243d
1,731
[ -1 ]
1,732
cl-ana.map.asd
ghollisjr_cl-ana/map/cl-ana.map.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.map :serial t :author "Gary Hollis" :description "Defines generic functions for working with/converting things which behave like maps (in the mathematical sense), e.g. hash tables, alists, etc." :license "GPLv3" :depends-on (#:cl-ana.hash-table-utils) :components ((:file "package") (:file "map")))
1,221
Common Lisp
.asd
30
38.733333
70
0.708403
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bec91e21e37b33d9fa074275f18f76aa8c1901376caa64e856e46676b40f6025
1,732
[ -1 ]
1,733
cl-ana.makeres-utils.asd
ghollisjr_cl-ana/makeres-utils/cl-ana.makeres-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2016 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with makeres. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-utils :serial t :author "Gary Hollis" :description "Utilities for using makeres effectively." :license "GPLv3" :depends-on (#:alexandria #:cl-ana.makeres #:cl-ana.fitting #:cl-ana.generic-math #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.symbol-utils #:cl-ana.map #:cl-ana.plotting #:cl-ana.string-utils #:cl-ana.functional-utils #:cl-ana.file-utils #:cl-ana.histogram #:cl-ana.pathname-utils #:cl-ana.table #:cl-ana.reusable-table) :components ((:file "package") (:file "makeres-utils")))
1,638
Common Lisp
.asd
43
31.209302
70
0.617315
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6c2f9ac1de91e1b6ecb405cc896280f026a39dfd0f1dae9c74a210dab166eb67
1,733
[ -1 ]
1,734
cl-ana.math-functions.asd
ghollisjr_cl-ana/math-functions/cl-ana.math-functions.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem :cl-ana.math-functions :serial t :author "Gary Hollis" :description "Auxiliary math functions provided within the generic-math framework." :license "GPLv3" :depends-on (#:cl-ana.generic-math #:gsll) :components ((:file "package") (:file "utils") (:file "distributions") (:file "combinatorics") (:file "misc")))
1,288
Common Lisp
.asd
33
35.212121
70
0.670916
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
24a59a5f2d3dd9228906716ce9bff715dbda5942c77a5d1504b8cb28a9c6e726
1,734
[ -1 ]
1,735
cl-ana.list-utils.asd
ghollisjr_cl-ana/list-utils/cl-ana.list-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; list-utils.asd (asdf:defsystem #:cl-ana.list-utils :serial t :author "Gary Hollis" :description "Utilities for working with lists not already provided by Alexandria." :license "GPLv3" :depends-on (#:alexandria #:cl-ana.functional-utils #:cl-ana.string-utils) :components ((:file "package") (:file "list-utils")))
1,243
Common Lisp
.asd
32
36.0625
70
0.691736
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
02656404a7d32c2756ea31a85ecdc1e7582dbf2b1066519f2e991e5c57d5875d
1,735
[ -1 ]
1,736
cl-ana.tensor.asd
ghollisjr_cl-ana/tensor/cl-ana.tensor.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; tensor.asd (asdf:defsystem #:cl-ana.tensor :serial t :author "Gary Hollis" :description "tensor provides utilities for treating nested sequences as multidimensional arrays; integration into the generic math framework yields MATLAB/GNU Octave-style functionality with arrays, lists, etc." :license "GPLv3" :depends-on (#:alexandria #:cl-ana.generic-math #:cl-ana.symbol-utils #:cl-ana.list-utils ;;debug #:cl-ana.macro-utils) :components ((:file "package") (:file "tensor")))
1,447
Common Lisp
.asd
37
35.432432
70
0.687012
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5582da6612f9ada159efc9173d517f135481b4ac22200a6289c371eef6dbf0a6
1,736
[ -1 ]
1,737
cl-ana.typespec.asd
ghollisjr_cl-ana/typespec/cl-ana.typespec.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; typespec.asd (asdf:defsystem #:cl-ana.typespec :serial t :description "typespec provides a mechanism for referring to foreign or LISP datatypes as well as utilities for conversion between the two." :author "Gary Hollis" :license "GPLv3" :depends-on (#:alexandria #:cffi #:cl-ana.int-char #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.tensor #:cl-ana.memoization) :components ((:file "package") (:file "typespec")))
1,435
Common Lisp
.asd
38
33.605263
70
0.669054
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8f2e2c59d5811f38c9dda78d924688f45c5614a170e77f74f09c2096ba44cd84
1,737
[ -1 ]
1,738
cl-ana.hdf-cffi.asd
ghollisjr_cl-ana/hdf-cffi/cl-ana.hdf-cffi.asd
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;;; ;;;; Copyright by The HDF Group. ;;;; All rights reserved. ;;;; ;;;; This file is part of hdf5-cffi. ;;;; The full hdf5-cffi copyright notice, including terms governing ;;;; use, modification, and redistribution, is contained in the file COPYING, ;;;; which can be found at the root of the source code distribution tree. ;;;; If you do not have access to this file, you may request a copy from ;;;; [email protected]. ;;;; ;;;; Note: This project has been modified and included as part of ;;;; cl-ana until bug fixes can be added upstream. (defsystem cl-ana.hdf-cffi ; used to be hdf5-cffi :serial t :description "hdf5-cffi is a CFFI wrapper for the HDF5 library." :version "1.8.18" :author "Gerd Heber <[email protected]>" :license "BSD" :defsystem-depends-on (:cffi-grovel) :depends-on (:cffi) :pathname "src/" :components ((:file "package") (:file "library") (:cffi-grovel-file "grovel") (:cffi-grovel-file "h5-grovel") (:file "h5") (:cffi-grovel-file "h5i-grovel") (:file "h5i") (:cffi-grovel-file "h5f-grovel") (:file "h5f") (:cffi-grovel-file "h5t-grovel") (:file "h5t") (:cffi-grovel-file "h5l-grovel") (:file "h5l") (:cffi-grovel-file "h5o-grovel") (:file "h5o") (:cffi-grovel-file "h5s-grovel") (:file "h5s") (:cffi-grovel-file "h5d-grovel") (:file "h5d") (:cffi-grovel-file "h5g-grovel") (:file "h5g") (:cffi-grovel-file "h5a-grovel") (:file "h5a") ;; (:cffi-grovel-file "h5pl-grovel") ;; (:file "h5pl") (:cffi-grovel-file "h5r-grovel") (:file "h5r") (:cffi-grovel-file "h5z-grovel") (:file "h5z") (:cffi-grovel-file "h5p-grovel") (:file "h5p")) :in-order-to ((test-op (test-op :hdf5-cffi.test))))
1,775
Common Lisp
.asd
56
28.678571
77
0.646682
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
46564c8ec6a09c63f3315220b829e951107edda4e5ca9e54981105c6908c513f
1,738
[ -1 ]
1,739
cl-ana.macro-utils.asd
ghollisjr_cl-ana/macro-utils/cl-ana.macro-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; macro-utils.lisp (asdf:defsystem #:cl-ana.macro-utils :serial t :description "Basic macro utilities" :author "Gary Hollis" :license "GPLv3" :depends-on (#:split-sequence #:alexandria #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.symbol-utils) :components ((:file "package") (:file "macro-utils")))
1,260
Common Lisp
.asd
33
34.636364
70
0.672372
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d0ab363dd3a45f6b1541514fbc662b23b89b461907baa58f3aebc894777c4aa7
1,739
[ -1 ]
1,740
cl-ana.clos-utils.asd
ghollisjr_cl-ana/clos-utils/cl-ana.clos-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.clos-utils :serial t :description "clos-utils provides various lacking utilities for working with structures and CLOS class instances as well as utilities for transforming them into clists which can be written/read with standard stream objects portably." :author "Gary Hollis" :license "GPLv3" :depends-on (#:closer-mop #:cl-ana.list-utils #:cl-ana.symbol-utils #:cl-ana.tensor) :components ((:file "package") (:file "clos-utils")))
1,408
Common Lisp
.asd
34
38
70
0.695779
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1b86a7b061c7388fbd2d4a15ce84c398481a91d904b7fc42e877c393f79dcb6f
1,740
[ -1 ]
1,741
cl-ana.hash-table-utils.asd
ghollisjr_cl-ana/hash-table-utils/cl-ana.hash-table-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.hash-table-utils :serial t :author "Gary Hollis" :description "Utilities for working with hash tables" :license "GPLv3" :depends-on () :components ((:file "package") (:file "hash-table-utils")))
1,113
Common Lisp
.asd
28
37.857143
70
0.704797
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cd9740e9d5ead2166873d3ef0e64f0fc4191eb84fb0c2889503e9f83343b120d
1,741
[ -1 ]
1,742
cl-ana.table-utils.asd
ghollisjr_cl-ana/table-utils/cl-ana.table-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.table-utils :serial t :license "GPLv3" :author "Gary Hollis" :description "Utilities for working with tables" :depends-on (#:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.table #:cl-ana.statistics #:cl-ana.generic-math #:cl-ana.symbol-utils #:cl-ana.string-utils #:cl-ana.hash-table-utils) :components ((:file "package") (:file "table-utils")))
1,380
Common Lisp
.asd
35
34.514286
70
0.651786
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
348f47dd5097fb2bf2c7e1550f0377b4437d9e22ca3e7e0d59d2a8f4e21a1ab2
1,742
[ -1 ]
1,743
cl-ana.pathname-utils.asd
ghollisjr_cl-ana/pathname-utils/cl-ana.pathname-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.pathname-utils :serial t :author "Gary Hollis" :license "GPLv3" :description "Utilities for working with pathnames" :depends-on () :components ((:file "package") (:file "pathname-utils")))
1,114
Common Lisp
.asd
28
37.642857
70
0.701382
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3e902ad1493166e27ed3aa6e78c0465ff29e4f166cf3e2d3aee90e3fc81fc701
1,743
[ -1 ]
1,744
cl-ana.plotting.asd
ghollisjr_cl-ana/plotting/cl-ana.plotting.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; plotting.asd (asdf:defsystem #:cl-ana.plotting :serial t :description "Extensible plotting library for Common Lisp using gnuplot as the backend." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.pathname-utils #:cl-ana.generic-math #:cl-ana.math-functions #:cl-ana.functional-utils #:cl-ana.error-propogation #:cl-ana.gnuplot-interface #:cl-ana.map #:cl-ana.string-utils #:cl-ana.list-utils #:cl-ana.macro-utils #:cl-ana.histogram #:cl-ana.tensor #:external-program #:split-sequence #:uiop #:alexandria #+sbcl #:sb-posix) :components ((:file "package") (:file "plotting")))
1,741
Common Lisp
.asd
47
30.042553
70
0.612522
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9151a03f12f85d43ee8c5c4011b1b52e0811f1a6949a9d05954a0f0757a69be9
1,744
[ -1 ]
1,745
cl-ana.symbol-utils.asd
ghollisjr_cl-ana/symbol-utils/cl-ana.symbol-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.symbol-utils :serial t :description "Basic utilities for working with symbols" :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.list-utils) :components ((:file "package") (:file "symbol-utils")))
1,125
Common Lisp
.asd
28
38.321429
70
0.705561
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
256585b7d0d19142607af3225e434af1faabc5597e9f8af75083e222acb0ef4c
1,745
[ -1 ]
1,746
cl-ana.spline.asd
ghollisjr_cl-ana/spline/cl-ana.spline.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2021 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.spline :serial t :author "Gary Hollis" :description "Provides natural splines to arbitrary order using GSL." :license "GPLv3" :depends-on (#:gsll #:cffi #:cl-ana.generic-math #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.tensor #:cl-ana.math-functions #:cl-ana.fitting ;; #:alexandria ;; #:cl-fad ;; #:cl-ana.memoization ;; #:cl-ana.generic-math ;; #:cl-ana.error-propogation ;; #:cl-ana.macro-utils ;; #:cl-ana.list-utils ;; #:cl-ana.symbol-utils ;; #:cl-ana.map ;; #:cl-ana.hash-table-utils ;; #:cl-ana.plotting ) :components ((:file "package") (:file "spline")))
1,774
Common Lisp
.asd
47
30
71
0.581692
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c8953c43d8dc13c7ec979fb765b0937bdba08f863863dd7442f88db94ed2daa6
1,746
[ -1 ]
1,747
cl-ana.makeres-block.asd
ghollisjr_cl-ana/makeres-block/cl-ana.makeres-block.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-block :serial t :author "Gary Hollis" :description "makeres-block is a makeres graph transformation which allows multiple results to be defined by a single block of code." :license "GPLv3" :depends-on (#:alexandria #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.makeres ;; #:cl-ana.symbol-utils ;; #:cl-ana.map ;; #:cl-ana.hash-table-utils ) :components ((:file "package") (:file "makeres-block")))
1,441
Common Lisp
.asd
36
35.166667
70
0.654558
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
32a6a85fed435dd383cf3103cab89fc15cf57055da7dc25f538503a3f6604a19
1,747
[ -1 ]
1,748
cl-ana.makeres.asd
ghollisjr_cl-ana/makeres/cl-ana.makeres.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with makeres. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres :serial t :author "Gary Hollis" :description "makeres is a make-like tool for building analysis results in Common Lisp" :license "GPLv3" :depends-on (#:uiop #:alexandria #:cl-fad #:cl-ana.memoization #:cl-ana.generic-math #:cl-ana.error-propogation #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.symbol-utils #:cl-ana.map #:cl-ana.hash-table-utils #:cl-ana.plotting ;; logres: #:external-program #:cl-ana.hdf-utils #:cl-ana.serialization #:cl-ana.string-utils #:cl-ana.functional-utils #:cl-ana.file-utils #:cl-ana.histogram #:cl-ana.pathname-utils #:cl-ana.table #:cl-ana.reusable-table) :components ((:file "package") (:file "makeres") (:file "lrestrans") ;; logres: (:file "logres") (:file "histogram") (:file "function") (:file "hash-table") (:file "cons") (:file "array") (:file "string") (:file "err-num")))
2,222
Common Lisp
.asd
61
27.065574
70
0.555556
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a026b5aa43fd5e768e488254c9f4faf4336c9230ee47d1dcbace5e36012e00dd
1,748
[ -1 ]
1,749
cl-ana.statistics.asd
ghollisjr_cl-ana/statistics/cl-ana.statistics.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; statistics.asd (asdf:defsystem #:cl-ana.statistics :serial t :description "Various statistical functions integrated into the generic-math framework." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.generic-math #:cl-ana.macro-utils #:cl-ana.map #:cl-ana.list-utils #:cl-ana.histogram #:cl-ana.math-functions #:cl-ana.math-functions) :components ((:file "package") (:file "statistics")))
1,390
Common Lisp
.asd
36
34.361111
70
0.667406
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
308cd8622820262456fbba3f2f9f9e9df022c856fba780099c9c4d283360cde6
1,749
[ -1 ]
1,750
cl-ana.int-char.asd
ghollisjr_cl-ana/int-char/cl-ana.int-char.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.int-char :serial t :description "For some reason my SBCL doesn't support int-char anymore, so here it is." :author "Gary Hollis" :license "GPLv3" :depends-on () :components ((:file "package") (:file "int-char")))
1,139
Common Lisp
.asd
29
37.137931
70
0.696396
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ace793cf28fc2d05029fce0d5b82fc542982d89942bb056c608f42a892f6ef37
1,750
[ -1 ]
1,751
cl-ana.hdf-typespec.asd
ghollisjr_cl-ana/hdf-typespec/cl-ana.hdf-typespec.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; hdf-typespec.asd (asdf:defsystem #:cl-ana.hdf-typespec :serial t :description "Utilities for creating/reading HDF5 types from/into typespecs." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cffi #:alexandria #:cl-ana.hdf-cffi #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.memoization #:cl-ana.typespec) :components ((:file "package") (:file "hdf-typespec")))
1,377
Common Lisp
.asd
37
33.216216
70
0.666916
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c2175e131354c076c615612f3c256e1dbb62891b14164c2e481a8abfa6537807
1,751
[ -1 ]
1,752
cl-ana.package-utils.asd
ghollisjr_cl-ana/package-utils/cl-ana.package-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.package-utils :serial t :author "Gary Hollis" :license "GPLv3" :description "Provides various utilities for using packages as well as the abstraction of a package group" :depends-on (#:alexandria) :components ((:file "package") (:file "package-utils")))
1,180
Common Lisp
.asd
29
38.551724
70
0.707211
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9252d28009c2c4a6780ef4a3967f1bd9cead0df5ac6f9874620d231208237d2f
1,752
[ -1 ]
1,753
cl-ana.makeres-macro.asd
ghollisjr_cl-ana/makeres-macro/cl-ana.makeres-macro.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-macro :serial t :author "Gary Hollis" :description "makeres-macro is a graph transformation for use with makeres" :license "GPLv3" :depends-on (#:cl-ana.list-utils #:cl-ana.makeres) :components ((:file "package") (:file "makeres-macro")))
1,184
Common Lisp
.asd
30
36.966667
70
0.697311
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
c4cc61cf653332ee5c3d14ed9773c8ab6fd7f67fad1dc6b382911bd9a329e8c1
1,753
[ -1 ]
1,754
cl-ana.table.asd
ghollisjr_cl-ana/table/cl-ana.table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; table.asd (asdf:defsystem #:cl-ana.table :serial t :description "Table class; provides basic necessary interface for working with sets of data." :author "Gary Hollis" :license "GPLv3" :depends-on (#:alexandria #:cl-ana.macro-utils #:cl-ana.list-utils #:cl-ana.string-utils #:cl-ana.symbol-utils #:cl-ana.functional-utils) :components ((:file "package") (:file "table") (:file "table-chain") (:file "plist-table")))
1,385
Common Lisp
.asd
37
33.810811
70
0.671863
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
5fb1613884e085b6d7c804d4dab0648d22432c9f80a847fdf76d631d35a8e495
1,754
[ -1 ]
1,755
cl-ana.makeres-branch.asd
ghollisjr_cl-ana/makeres-branch/cl-ana.makeres-branch.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with makeres. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-branch :serial t :author "Gary Hollis" :description "makeres-branch is a graph transformation for use with cl-ana.makeres" :license "GPLv3" :depends-on (#:alexandria #:cl-ana.generic-math #:cl-ana.makeres #:cl-ana.list-utils #:cl-ana.map #:cl-ana.hash-table-utils) :components ((:file "package") (:file "makeres-branch")))
1,323
Common Lisp
.asd
34
34.823529
70
0.671584
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6d68d41587e9f6cfe14e2f2aa4ba752dae42945fe3785bfb90612926796b78da
1,755
[ -1 ]
1,756
cl-ana.gsl-cffi.asd
ghollisjr_cl-ana/gsl-cffi/cl-ana.gsl-cffi.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; gsl-cffi.asd (asdf:defsystem #:cl-ana.gsl-cffi :serial t :description "Functions for interfacing with GSL which don't seem to work/aren't currently provided through GSLL." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cffi) :components ((:file "package") (:file "gsl-cffi")))
1,184
Common Lisp
.asd
30
37.566667
70
0.705117
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a42cebd8e2c295d0b1340329454923778a74bc06b309ca43e9610a3f6ba1fbfe
1,756
[ -1 ]
1,757
cl-ana.binary-tree.asd
ghollisjr_cl-ana/binary-tree/cl-ana.binary-tree.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.binary-tree :serial t :author "Gary Hollis" :license "GPLv3" :description "Simple binary-tree implementation, not meant for high-performance code." :depends-on (#:cl-ana.list-utils #:cl-ana.macro-utils #:cl-ana.functional-utils) :components ((:file "package") (:file "binary-tree")))
1,234
Common Lisp
.asd
31
36.967742
70
0.69218
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2f4830c4aa98f4e6f77315df0fbde0737b16d16413304edfc59c93f503c0d30b
1,757
[ -1 ]
1,758
cl-ana.gnuplot-interface.asd
ghollisjr_cl-ana/gnuplot-interface/cl-ana.gnuplot-interface.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2015 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.gnuplot-interface :serial t :author "Gary Hollis" :description "Interface for spawning & communicating with gnuplot sessions from LISP." :license "GPLv3" :depends-on (#:external-program) :components ((:file "package") (:file "gnuplot-interface")))
1,170
Common Lisp
.asd
29
38.310345
70
0.710526
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1d2bf292ea5a60713036487a65dc309e2628182387c4dcc1f23873fb1c12d3b4
1,758
[ -1 ]
1,759
cl-ana.fitting.asd
ghollisjr_cl-ana/fitting/cl-ana.fitting.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; fitting.asd (asdf:defsystem #:cl-ana.fitting :serial t :description "Library for non-linear least squares fitting (works for linear functions as well though); makes use of GSLL's fit functions." :author "Gary Hollis" :license "GPLv3" :depends-on (#:gsll #:alexandria #:cl-ana.generic-math #:cl-ana.math-functions #:cl-ana.error-propogation #:cl-ana.map) :components ((:file "package") (:file "fitting") (:file "functions")))
1,389
Common Lisp
.asd
37
34.081081
70
0.678756
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3fc011b9ae536cca38bf6fbf33804b4bacb587d465f945965f412062b8e7fa8f
1,759
[ -1 ]
1,760
cl-ana.makeres-table.asd
ghollisjr_cl-ana/makeres-table/cl-ana.makeres-table.asd
;;;; makeres-table is a graph transformation for makeres ;;;; Copyright 2014 Gary Hollis ;;;; ;;;; This file is part of makeres-table. ;;;; ;;;; makeres-table is free software: you can redistribute it ;;;; and/or modify it under the terms of the GNU General Public ;;;; License as published by the Free Software Foundation, either ;;;; version 3 of the License, or (at your option) any later version. ;;;; ;;;; makeres-table is distributed in the hope that it will be ;;;; useful, but WITHOUT ANY WARRANTY; without even the implied ;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;;;; See the GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with makeres-table. If not, see ;;;; <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.makeres-table :serial t :author "Gary Hollis" :description "makeres-table is a graph transformation for makeres" :license "GPLv3" :depends-on (#:cl-ana.memoization #:cl-ana.makeres #:cl-ana.makeres-macro #:cl-ana.macro-utils #:cl-ana.table #:cl-ana.reusable-table #:cl-ana.hdf-utils #:cl-ana.csv-table #:cl-ana.ntuple-table #:cl-ana.hdf-table #:cl-ana.hash-table-utils #:cl-ana.string-utils #:cl-ana.list-utils) :components ((:file "package") (:file "smart-gensym") (:file "table-operators") (:file "tabletrans") (:file "openers") (:file "logging")))
1,741
Common Lisp
.asd
45
31.644444
70
0.616519
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d802df6664cc6eccb5826898fcc48e6ab867bfb2cae3b27f988309d9d3ee7ce8
1,760
[ -1 ]
1,761
cl-ana.generic-math.asd
ghollisjr_cl-ana/generic-math/cl-ana.generic-math.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; generic-math.asd (asdf:defsystem #:cl-ana.generic-math :serial t :description "Provides generic versions of (most ATM) the standard Common Lisp math functions; this allows easy extension to new mathematical objects." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.package-utils #:cl-ana.list-utils) :components ((:file "package") (:file "generic-math") (:file "number")))
1,311
Common Lisp
.asd
33
37.151515
70
0.699295
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
def98245156c6d7925418dbb412f6f0554bbdf38d81e8145daa779490d509c1e
1,761
[ -1 ]
1,762
cl-ana.linear-algebra.asd
ghollisjr_cl-ana/linear-algebra/cl-ana.linear-algebra.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; linear-algebra.asd (asdf:defsystem #:cl-ana.linear-algebra :serial t :description "(minimal) Linear algebra library which is integrated into the generic math framework." :author "Gary Hollis" :license "GPLv3" :depends-on (#:cl-ana.generic-math #:cl-ana.tensor #:cl-ana.list-utils #:cl-ana.math-functions #:gsll) :components ((:file "package") (:file "linear-algebra")))
1,316
Common Lisp
.asd
34
35.558824
70
0.686183
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fc09d68a3b6d952472986407596a5e82a9c2c93e7d10b5cfc471e2fcdea95b75
1,762
[ -1 ]
1,763
cl-ana.calculus.asd
ghollisjr_cl-ana/calculus/cl-ana.calculus.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.calculus :serial t :license "GPLv3" :description "A few numerical and/or symbolic calculus functions." :depends-on (#:cl-ana.generic-math #:cl-ana.linear-algebra) :components ((:file "package") (:file "differentiation") (:file "newton") (:file "rk4")))
1,221
Common Lisp
.asd
30
37.2
70
0.67563
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e377219122839da0d51a08e6f87e86b65c331cf158283d1609cf979edd1af50b
1,763
[ -1 ]
1,764
cl-ana.table-viewing.asd
ghollisjr_cl-ana/table-viewing/cl-ana.table-viewing.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] ;;;; table.asd (asdf:defsystem #:cl-ana.table-viewing :serial t :description "Library for easily viewing the contents of a table (preferably a reusable table)" :author "Gary Hollis" :license "GPLv3" :depends-on (#:alexandria #:cl-ana.string-utils #:cl-ana.macro-utils #:cl-ana.table #:cl-ana.histogram #:cl-ana.plotting #:cl-ana.generic-math) :components ((:file "package") (:file "table-viewing")))
1,385
Common Lisp
.asd
36
34.222222
70
0.663947
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8fa523617c8772a81211d4e5f2e29c71c5b10688d782dc3e4c12ef334df8ff65
1,764
[ -1 ]
1,765
cl-ana.error-propogation.asd
ghollisjr_cl-ana/error-propogation/cl-ana.error-propogation.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.error-propogation :serial t :author "Gary Hollis" :description "Implements error propogation inside the generic-math framework." :license "GPLv3" :depends-on (#:cl-ana.generic-math #:cl-ana.math-functions) :components ((:file "package") (:file "error-propogation")))
1,202
Common Lisp
.asd
30
37.666667
70
0.703672
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f74a48cae32a74824347e6f08cd5d124ee14df77af7271da410215fd8cb893ae
1,765
[ -1 ]
1,766
cl-ana.file-utils.asd
ghollisjr_cl-ana/file-utils/cl-ana.file-utils.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.file-utils :serial t :description "Various utilities for working with files" :author "Gary Hollis" :license "GPLv3" :depends-on (#:external-program #:split-sequence) :components ((:file "package") (:file "read-utils") (:file "write-utils") (:file "stat-utils") (:file "sha")))
1,254
Common Lisp
.asd
32
35.5625
70
0.669394
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1031af4c1801f6d8bfa99ea12e638b941b79db9f25557d262585cff531a6a830
1,766
[ -1 ]
1,767
cl-ana.csv-table.asd
ghollisjr_cl-ana/csv-table/cl-ana.csv-table.asd
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013, 2014 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected] (asdf:defsystem #:cl-ana.csv-table :serial t :description "Table subclass specializing on CSV files; allows for whatever lisp types are understood by the reader." :author "Gary Hollis" :license "GPLv3" :depends-on (#:antik #:iterate #:alexandria #:cl-csv #:cl-ana.list-utils #:cl-ana.table) :components ((:file "package") (:file "csv-table")))
1,307
Common Lisp
.asd
34
34.647059
70
0.67217
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0f20bcc3ad3fec133ff59adc9b8df6238089eacc0670979cad50383637ddeb84
1,767
[ -1 ]
1,769
load-cl-ana.sh
ghollisjr_cl-ana/testing/load-cl-ana.sh
#!/bin/bash # This script loads all the systems in cl-ana individually and reports # errors. if [[ $# -ne 1 ]] ; then echo "Usage: load-cl-ana.sh <path_to_cl-ana>" echo "" echo "This script loads all cl-ana systems and reports errors" exit 1 fi clana_path=$1 system_files="$clana_path/*/*.asd" systems=$(for sf in $system_files; do basename $sf .asd done) # systems="cl-ana.pathname-util" i=0 declare -a retval for s in $systems; do echo "Loading $s" sbcl --noinform --eval "(handler-case (require '$s) (error (err) (print err) (progn (exit :code 1))))" --eval '(exit :code 0)' retval[$i]=$? i=$((i+1)) done i=0 no_errors=0; for s in $systems; do if [[ ${retval[$i]} -ne 0 ]]; then echo "Error loading $s" no_errors=1; fi done if [[ $no_errors -eq 0 ]] ; then echo "SUCCESS" else echo "FAILURE" fi
888
Common Lisp
.cl
36
21.166667
130
0.618824
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3f5a80a3bfd7ba20dbc79c50510ee1ca7ffe0c3ea78e62665d4eb65507ff6181
1,769
[ -1 ]
1,772
gpl_comment.txt
ghollisjr_cl-ana/gpl_comment.txt
;;;; cl-ana is a Common Lisp data analysis library. ;;;; Copyright 2013-2016 Gary Hollis ;;;; ;;;; This file is part of cl-ana. ;;;; ;;;; cl-ana is free software: you can redistribute it and/or modify it ;;;; under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; cl-ana is distributed in the hope that it will be useful, but ;;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with cl-ana. If not, see <http://www.gnu.org/licenses/>. ;;;; ;;;; You may contact Gary Hollis (me!) via email at ;;;; [email protected]
871
Common Lisp
.l
20
42.35
70
0.710928
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1936dc3f43557420ce833ee07727127a9ae3957259a883ca9cf0828054e81de3
1,772
[ -1 ]
1,817
makeres.el
ghollisjr_cl-ana/emacs-lisp/makeres.el
(defun makeres (&rest args) "Executes makeres-propagate! and makeres with arguments in current slime buffer." (interactive) (slime-command "(makeres-propagate!) (makeres)")) (add-hook 'lisp-mode-hook '(lambda () (local-set-key [f5] 'makeres))) (add-hook 'slime-repl-mode-hook '(lambda () (local-set-key [f5] 'makeres))) (defun load-project (&rest args) (interactive) (slime-command "(load-project) (makeres)")) (add-hook 'lisp-mode-hook '(lambda () (local-set-key [f8] 'load-project))) (add-hook 'slime-repl-mode-hook '(lambda () (local-set-key [f8] 'load-project))) (defun save-snapshot (&rest args) (interactive "sSave snapshot as (no quotes): ") (let ((path (car args))) (slime-command (format "(save-snapshot %S)" path)))) (add-hook 'lisp-mode-hook '(lambda () (local-set-key [f7] 'save-snapshot))) (add-hook 'slime-repl-mode-hook '(lambda () (local-set-key [f7] 'save-snapshot))) ;; Target look-up function: (defun target-lookup (&rest args) (interactive) (switch-to-buffer (slime-repl)) (slime-command "(target-ids)") ;; Simulate keyboard input: (setq unread-command-events (listify-key-sequence "\C-\M-r"))) (add-hook 'lisp-mode-hook '(lambda () (local-set-key [f12] 'target-lookup))) (add-hook 'slime-repl-mode-hook '(lambda () (local-set-key [f12] 'target-lookup)))
1,730
Common Lisp
.l
52
23.519231
60
0.528494
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3804d40609bdd1e95c2d9f1cc2e02498735cc45f02b8cd245ca5f936e0bf4cbf
1,817
[ -1 ]
1,818
general.el
ghollisjr_cl-ana/emacs-lisp/general.el
(defun slime-require-cmd (&rest args) "Executes (require 'system) (in-package system)" (interactive "sLoad system: ") (let ((system (car args))) (slime-command (format "(require '%s) (in-package :%s)" system system)))) (add-hook 'lisp-mode-hook '(lambda () (local-set-key [f6] 'slime-require-cmd))) (add-hook 'slime-repl-mode-hook '(lambda () (local-set-key [f6] 'slime-require-cmd)))
535
Common Lisp
.l
15
24.666667
59
0.503861
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3df9812d32a0c9897dbb92a269ab928c88a00b796a4021076d0f3114bb3e06df
1,818
[ -1 ]
1,819
utils.el
ghollisjr_cl-ana/emacs-lisp/utils.el
(defmacro in-slime-buffer (&rest body) (let ((win (gensym)) (result (gensym))) `(let ((,win (get-buffer-window))) (switch-to-buffer (slime-repl)) (end-of-buffer) (let ((,result (progn ,@body))) (other-window (find-window-index ,win)) ,result)))) (defun slime-command (&rest args) (in-slime-buffer (end-of-buffer) (apply #'insert args) (slime-repl-return))) (defun find-window-index (win) (let ((count 0) (result nil)) (walk-windows (lambda (w) (when (equal w win) (setf result count)) (setf count (+ 1 count)))) result))
691
Common Lisp
.l
24
20.708333
46
0.523308
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7dc8aed0a372eb19fc7219335194209e42a8fa7a5c0e58f6dff7ca253e716124
1,819
[ -1 ]
1,820
autocomplete.el
ghollisjr_cl-ana/emacs-lisp/autocomplete.el
;; This isn't working at the moment ;; ;; Was trying to follow this tutorial: ;; ;; http://auto-complete.org/doc/manual.html#extend (defun target-id-strings () (rest (slime-eval `(swank:eval-and-grab-output "(let ((*print-pretty* nil)) (mapcar (lambda (id) (format nil \"(res ~s)\" id)) (target-ids)))")))) (ac-define-source cl-ana-target-table-source '((candidates . target-id-strings) (prefix . "(res .*"))) (setq ac-sources '(ac-source-cl-ana-target-table-source))
534
Common Lisp
.l
17
26.529412
57
0.614786
ghollisjr/cl-ana
196
18
8
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b9c8370e1efd1c6627c20f84689ac379a24630c4bec98925d23e903c6cb2b3d1
1,820
[ -1 ]
2,125
mine.lisp
nibbula_lish/mine.lisp
;; ;; mine.lisp - Dig for command data ;; ;; This whole thing is an horrible hack. ;; ;; One could postulate a world in which it could be eliminated by having every ;; developer that makes a command, also making a defexternal or some other ;; agreed upon format which all shells could read. Either that or we would ;; submit patches to every debian/ubuntu/macports/bsdports/cygwin etc. package ;; which provides commands, to include a defexternal or similar. Oh, and then ;; every maintainer would keep them up to date. I think it's safe to say, ;; that's not going to happen. ;; ;; Another only slightly more feasible possibility would be that we would ;; maintain a massive accurately hand-crafted database of definitions for ;; every command. And then somehow keep it up to date. This also seems quite ;; unlikely, mostly for the “up to date” part. This is what other shells seem ;; to do. ;; ;; I suppose if I could muster the enormous motivation for such a project, I ;; could devise a format which would be a superset of the capabilities of ;; bash, zsh, fish, (others?) and lish, and develop a combined database that ;; would encompass all the combined knowledge, and then develop modules for ;; each shell to read it, and then submit patches, then the ‘universal’ ;; command database might a hope of being maintained. But of course the ;; maintenance of it should really lie with the individual command ;; implementors. This also seems very far-fetched. ;; ;; So instead this. ;; The general idea is we shamelessly try dig up the command line arguments from ;; where ever they may reside. In order of authority/accuracy that would seem ;; to be: ;; 1. The command executable ;; 2. The man page ;; 3. Some other shell's definition. ;; ;; Generating the data on demand has the meager advantages of: ;; - Only having to store data for commands you have used. ;; - Hopefully being as up to date as the source that's stolen from. ;; ;; This approach has the disadvantages of: ;; - Likely to fail ;; - Slow ;; - Hackish and complex ;; - Incomplete (in-package :lish) (defvar *command-sections* '("man1" "man6" "man8") "Normal sections where commands live.") (defvar *compression-suffixes* '(("gz" chipz:gzip) ("bz2" chipz:bzip2) ("bz" chipz:bzip2) ("zip" chipz:zlib))) (defmacro with-possibly-compressed-file ((stream-var filename) &body body) "Evaluate the ‘body’ with ‘stream-var’ open on ‘filename’. If ‘filename’ has a known compression suffix, then the stream is appropriately decompressed." (with-names (in-stream method) `(let ((,method (cadr (find-if #'(lambda (s) (and (glob:fnmatch (s+ "*." s) ,filename) t)) *compression-suffixes* :key #'car)))) (if ,method (progn (format t "Uncompressing~%") (with-input-from-string (,stream-var (map 'string #'code-char (with-open-file (,in-stream ,filename :direction :input :element-type '(unsigned-byte 8)) (chipz:decompress nil ,method ,in-stream)))) ,@body)) (progn (format t "Plain~%") (with-open-file (,stream-var ,filename) ,@body)))))) (defstruct mined-arg name description short-arg long-arg type default) (defstruct mined-cmd name short-description long-description args) (defun get-request (line) (let (req args) (multiple-value-setq (req args) (scan-to-strings "\\.([^ ]*)\\s+(.*)$" line)) (when req args))) (defun mine-page (stream) (let ((cmd (make-mined-cmd)) line next match strings) (declare (ignorable match)) (loop :while (setf line (read-line stream nil nil)) :do (cond ((eq next 'name) (dbugf 'mine-man "blurg ~s~%" line) (cond ((begins-with ".Nm" line :test #'equalp) (setf (mined-cmd-name cmd) (subseq line 4) next 'short-description)) ((multiple-value-setq (match strings) (scan-to-strings "^\\s*(\\w+)\\s+\\\\-\\s+(.*)$" line)) (dbugf 'mine-man "got name~%") (setf (mined-cmd-name cmd) (aref strings 0) (mined-cmd-short-description cmd) (aref strings 1)))) (setf next nil)) ((eq next 'synopsis) (setf next nil)) ((eq next 'short-description) (setf (mined-cmd-short-description cmd) (subseq line 4)) (setf next nil)) ((eq next 'long-description) (cond ((begins-with ".\\\"" line) #| ignore comment |# ) ((begins-with ".B" line) (push (subseq line 3) (mined-cmd-long-description cmd)))) (setf next nil)) ((begins-with ".\\\"" line) ;; ignore comments ) ((begins-with ".sh" line :test #'equalp) (cond ((equalp (subseq line 4) "NAME") (dbugf 'mine-man "Name~%") (setf next 'name)) ((equalp (subseq line 4) "DESCRIPTION") (dbugf 'mine-man "Description~%") (setf next 'long-description)) ((equalp (subseq line 4) "OPTIONS") (dbugf 'mine-man "Options~%") (setf next 'options)) ((equalp (subseq line 4) "SYNOPSIS") (dbugf 'mine-man "Synopsis~%") (setf next 'long-description)))) ((begins-with ".Nd" line :test #'equalp) (setf (mined-cmd-short-description cmd) (subseq line 4))))) cmd)) (defun mine-file (file) (with-possibly-compressed-file (f file) (mine-page f))) (defun manpath () "Return the manual path." (or (nos:environment-variable "MANPATH") (and (nos:command-pathname "manpath") (!$ "manpath")) #-windows (warn "Can't figure out the where the manuals are.") )) (defun find-manual-file (name) "Return the manual page file for something named NAME." (let ((manpath (manpath))) (when manpath (loop :for dir :in (split-sequence #\: manpath) :do ;;(format t "~a:~%" dir) (loop :for sec :in *command-sections* :do ;;(format t " ~a:~%" sec) (loop :for f :in (glob (s+ dir "/" sec "/*")) ;;:do ;; (format t " ~a~%" (path-snip-ext ;; (path-snip-ext (path-file-name f)))) :when (equal name (path-snip-ext (path-snip-ext (path-file-name f)))) :do (return-from find-manual-file f))))))) (defun mine-manual (command-name) (let ((file (find-manual-file command-name))) (and file (mine-file file)))) (defun mine-manual-pages () (loop :for dir :in (split-sequence #\: (manpath)) :do (format t "~a:~%" dir) (loop :for sec :in *command-sections* :do (format t " ~a:~%" sec) (loop :for f :in (glob (s+ dir "/" sec "/*")) :do (format t " ~a~%" (basename f)) (mine-file f))))) (defparameter *newline-fudge* 5 "How many strings without newlines to prospectively tolerate.") ;; This is the equivalent of screen scaping. (defun get-binary-usage-strings (file) "Slyly try to extract the usage from strings in a binary executable." (let ((type (magic:guess-file-type file)) contents start end usage str (no-nl-count 0) c cc len style arg-count) (when (and (or (equal "x-executable" (magic:content-type-name type)) (equal "x-pie-executable" (magic:content-type-name type)) (equal "x-sharedlib" (magic:content-type-name type))) (equal "application" (magic:content-type-category type))) (with-open-file (stream file :element-type '(unsigned-byte 8)) (setf contents (slurp stream :element-type '(unsigned-byte 8)) len (length contents))) (labels ((string-it (s) (map 'string #'code-char s)) (read-null-terminated-string () (setf end (position 0 contents :start start)) (when end (prog1 (string-it (subseq contents start end)) (setf start end)))) (skip-zeros () (loop :while (and (< start len) (zerop (aref contents start))) :do (incf start))) (check-newline () (or (and (eql #\newline (aref str (1- (length str)))) (setf no-nl-count 0)) (and (< no-nl-count *newline-fudge*) (incf no-nl-count)))) (valid-byte (c) (and (not (zerop c)) (eq (type-of (setf cc (code-char c))) 'standard-char) (or (alpha-char-p cc) (other-char cc)))) (other-char (cc) (or (digit-char-p cc) (position cc "-+_")))) ;; usage tagged (when (setf start (search "usage" contents :test (lambda (a b) (char-equal a (code-char b))))) (dbugf 'mine-bin "got usage start ~s~%" start) (loop :with i = 0 :while (and (setf str (read-null-terminated-string)) (< i 200) ;; @@@ some limit? ;;(eql #\newline (aref str (1- (length str)))) (check-newline) ) :do (push str usage) (skip-zeros) (incf i)) (setf style :gnu)) (setf arg-count (loop :for u :in usage :if (scan "^\\s*-" u) :count u)) ;;(format t "arg-count = ~s~%" arg-count) (when (or (not usage) (< arg-count 2)) ;; Any strings starting with - (setf start 0 usage nil) (loop :with i = 1 :and digit-count :and arg-count = 0 :while (and (setf start (position (char-code #\-) contents :start start)) (< arg-count 150)) :do ;;(format t "start ~a~%" start) (when (and start (not (zerop start)) (not (valid-byte (aref contents (1- start))))) (setf i 1 digit-count 0) (loop :while (and (setf c (aref contents (+ start i))) (valid-byte c)) :do (incf i) ;; don't do too many digits (when (other-char cc) (incf digit-count)) :while (and (< i 50) ; Arbitrary length limits (< digit-count 5))) (when (and (not (zerop i)) (>= i 5) (< digit-count 5) (> (- i 2) digit-count)) (setf str (string-it (subseq contents start (+ start i)))) (pushnew str usage :test #'string-equal) (incf arg-count) ;;(format t "~a~%" str) )) (incf start i) (skip-zeros)) (setf style :whatever)) (values (nreverse usage) style))))) (defun get-binary-usage-gnu (file strings) (let (usage-line doc args arg b e) (declare (ignorable b e)) (setf strings (flatten (mapcar (_ (split-sequence #\newline _)) strings))) (macrolet ((match (string) `(multiple-value-setq (b e starts ends) (scan ,string line))) (slarg (&rest props) `(progn (when arg (push arg args)) (setf arg (list ,@props))))) (dbugf 'mine-bin "not very ~s~%" (length strings)) (loop :with s = strings :and (line starts ends) :while s :do (setf line (car s)) (dbugf 'mine-bin "line = ~s~%" line) (cond ;; initial usage line ((and (not usage-line) (all-matches "^[Uu]sage:" line)) (setf usage-line line)) ;; lines of documentation before main arguments ((and (not args) (not (scan "^\\s*-" line))) (if (zerop (length line)) (when (stringp (car doc)) (rplaca doc (s+ (car doc) #\newline))) (push line doc))) ;; -e --example Blah blah blah. ((match "^\\s*-([A-Za-z0-9?])[,]?\\s*--([-A-Za-z0-9_/:]+)(\\s+(.*)|\\s*)$") (slarg :name (subseq line (aref starts 1) (aref ends 1)) :type 'arg-boolean :short-arg (char line (aref starts 0)) :long-arg (subseq line (aref starts 1) (aref ends 1)) :help (trim (subseq line (aref starts 2) (aref ends 2))))) ;; -e --example=foo Blah blah blah. ((match "^\\s*-([A-Za-z0-9?])[,]?\\s*--([-A-Za-z0-9_/:]+)[[]*=([A-Za-z]+)[]]*(\\s+(.*)|\\s*)$") (slarg :name (subseq line (aref starts 1) (aref ends 1)) :type 'arg-string :short-arg (char line (aref starts 0)) :long-arg (subseq line (aref starts 1) (aref ends 1)) :help (trim (subseq line (aref starts 3) (aref ends 3))))) ;; -e Blah blah blah. ((match "^\\s*-([A-Za-z0-9?])\\s+(.*)$") (slarg :name (s+ "dash-" (char line (aref starts 0))) :type 'arg-boolean :short-arg (char line (aref starts 0)) :help (subseq line (aref starts 1) (aref ends 1)))) ;; --example Blah blah blah. ((match "^\\s*--([-A-Za-z0-9_/:]+)(\\s+(.*)|\\s*)$") (slarg :name (subseq line (aref starts 0) (aref ends 0)) :type 'arg-boolean :long-arg (subseq line (aref starts 0) (aref ends 0)) :help (trim (subseq line (aref starts 1) (aref ends 1))))) ;; --example=foo Blah blah blah. ((match "^\\s*--([-A-Za-z0-9_/:]+)[[]*=([A-Za-z]+)[]]*(\\s+(.*)|\\s*)$") (slarg :name (subseq line (aref starts 0) (aref ends 0)) :type 'arg-string :long-arg (subseq line (aref starts 0) (aref ends 0)) :help (trim (subseq line (aref starts 2) (aref ends 2))))) ;; lines starting with spaces after args ((and arg (scan "^\\s+" line)) (setf (getf arg :help) (s+ (getf arg :help) (if (not (zerop (length (getf arg :help)))) " " "") (trim line)))) ;; start a new arg after blank lines ((zerop (length line)) (when arg (push arg args)) (setf arg nil))) (setf s (cdr s))) (when arg (push arg args)) (when doc (dbugf 'mine-bin "what up doc ~s~%" (car doc)) (if args ;; Get rid of up to *newline-fudge* doc strings with no newlines. (loop :with i = 0 :while (and doc (< i *newline-fudge*) (char/= #\newline (char (car doc) (1- (length (car doc)))))) :do (setf doc (cdr doc)) (incf i)) ;; If we didn't find any command line args, chances are good ;; the doc is junk. (setf doc (if (char= #\newline (char (car doc) (1- (length (car doc))))) (list (car doc)) nil)))) (when usage-line (make-mined-cmd :name (path-file-name file) :short-description (replace-subseq "%s" (path-file-name file) usage-line) :long-description (join-by-string (nreverse doc) #\newline) :args (nreverse args)))))) (defun get-binary-usage-whatever (file strings) (make-mined-cmd :name (path-file-name file) :short-description (princ-to-string (path-file-name file)) :long-description "" :args (loop :for s :in strings :collect `(:name ,(subseq s 1) :type arg-boolean ,@(if (char= (aref s 1) #\-) (list :long-arg (subseq s 2)) (list :old-long-arg (subseq s 1))))))) (defun get-binary-usage (file) (multiple-value-bind (strings style) (get-binary-usage-strings file) (case style (:gnu (get-binary-usage-gnu file strings)) (otherwise (get-binary-usage-whatever file strings))))) (defun convert-arglist (arglist) (loop :with type :for a :in arglist :do (setf type (getf a :type)) ;;(remf a :type) :collect (apply #'make-instance type a))) ;; @@@ Implement checksums (defun mine-command (command-name &key quietly) (let* ((cmd (get-command command-name)) (path (command-pathname command-name)) (mined (or (and path (get-binary-usage path)) (if quietly (without-warning (mine-manual command-name)) (mine-manual command-name))))) (when mined (cond ((not cmd) ;; make a new external command (make-external-command command-name path (convert-arglist (mined-cmd-args mined)) (join-by-string (flatten (append (list (mined-cmd-short-description mined)) (list (mined-cmd-long-description mined)))) #\newline))) ((typep cmd 'external-command) (cond ((external-command-manual cmd) (error "Won't override a manual command.")) (t (setf (command-arglist cmd) (convert-arglist (mined-cmd-args mined)) (documentation (command-function-name command-name) 'function) (join-by-string (flatten (append (list (mined-cmd-short-description mined)) (list (mined-cmd-long-description mined)))) #\newline))))) (t (error "Command must be external or undefined to mine it.")))))) (defun mine-command-help () ;; This is probably a bad idea. If we ever implement it, it should be an ;; option which is off by default. ) (defun mine () (mine-manual-pages) (mine-command-help) ;; what else? other shells? ) ;; EOF
15,837
Common Lisp
.lisp
446
30.737668
97
0.6171
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
fb2b1d241aebb2021ca937a7a14f3b3b41e0fafd214ad5594e90167d49937555
2,125
[ -1 ]
2,126
package.lisp
nibbula_lish/package.lisp
;;; ;;; package.lisp - Package definition for Lish ;;; (defpackage :lish (:documentation "Lish is both a command shell and a Lisp REPL. Lish is designed to make typing both operating system commands and Common Lisp expressions convienient. It combines the features of a traditional operating system shell with a Lisp REPL. It's designed to hopefully have little annoyance to people familair with a POSIX shell. But it does not have exact compatibility with POSIX shells. The motivation for writing Lish came from the annoyance of having to swtich between a Lisp REPL and a Unix shell. Lish may be used as a command shell, without any particular knowledge of it's Lisp programming features.") (:use :cl :dlib :opsys :dlib-misc :stretchy :char-util :glob :table :table-print :reader-ext :completion :keymap :terminal :terminal-ansi :rl :fatchar :fatchar-io :collections :ostring :ochar :grout :dtime :string-expand #+use-regex :regex #-use-regex :cl-ppcre) ;; #+sbcl (:import-from :sb-ext #:retry) (:export ;; Main entry point(s) #:lish #:shell-toplevel ;; variables #:*lish-level* #:*lish-user-package* #:*shell-name* #:*shell* #:*old-pwd* #:*dir-list* #:*accepts* #:*output* #:output #:*o* #:*input* #:input #:*i* #:with-output #:with-input #:*lishrc* #:*use-bracketed-paste* #:*version* #:*major-version* #:*minor-version* #:*build-version* ;; hooks @@@ maybe should be made into options? #:*pre-command-hook* #:*post-command-hook* #:*unknown-command-hook* #:*enter-shell-hook* #:*exit-shell-hook* ;; installation #:make-standalone #:make-standalone-command ;; shell options #:option ;; @@@ maybe we don't really need to export all this junk #:lish-prompt #:set-lish-prompt #:lish-prompt-function #:set-lish-prompt-function #:lish-right-prompt #:set-lish-right-prompt #:lish-sub-prompt #:set-lish-sub-prompt #:lish-ignore-eof #:set-lish-ignore-eof #:lish-debug #:set-lish-debug #:lish-collect-stats #:set-lish-collect-stats #:lish-autoload-from-asdf #:set-lish-autoload-from-asdf #:lish-autoload-quietly #:set-lish-autoload-quietly #:lish-history-expansion #:set-lish-history-expansion #:lish-expand-braces #:set-lish-expand-braces #:lish-colorize #:set-lish-colorize #:lish-auto-cd #:set-lish-auto-cd #:lish-history-style #:set-lish-history-style #:lish-history-format #:set-lish-history-format ;; #:lish-history-save-values #:set-lish-history-save-values #:lish-auto-suggest #:set-lish-auto-suggest #:lish-partial-line-indicator #:set-lish-partial-line-indicator #:lish-export-pipe-results #:set-lish-export-pipe-results #:make-prompt ;; shell object #:shell #:shell-interactive-p #:shell-aliases #:lish-editor #:lish-keymap #:lish-old-pwd #:lish-dir-list #:lish-suspended-jobs #:lish-last-background-job #:lish-start-time #:shell-help-table #:lish-options ;; arguments #:argument #:arg-name #:arg-type #:arg-value #:arg-default #:arg-repeating #:arg-rest #:arg-optional #:arg-hidden #:arg-prompt #:arg-help #:arg-short-arg #:arg-long-arg ;; argument types #:arg-boolean #:arg-number #:arg-integer #:arg-float #:arg-character #:arg-string #:arg-symbol #:arg-keyword #:arg-object #:arg-case-preserving-object #:arg-sequence #:arg-list #:arg-function #:arg-package #:arg-date #:arg-pathname #:arg-directory #:arg-choice #:arg-choices #:arg-choice-labels #:arg-choice-test #:arg-choice-compare-ignore-case #:arg-choice-compare #:arg-lenient-choice #:arg-option #:arg-input-stream-or-filename ;; argument types for builtins #:arg-job-descriptor #:arg-help-subject #:arg-boolean-toggle #:arg-signal #:arg-pid-or-job #:arg-function #:arg-key-sequence #:arg-command #:arg-system-designator #:arg-quicklisp-system-designator #:arg-autoload-place ;; argument generics #:convert-arg #:argument-choices #:defargtype ;; commands #:command #:command-name #:command-function #:command-arglist #:command-built-in-p #:command-loaded-from #:command-accepts #:internal-command #:shell-command #:builtin-command #:external-command #:command-list #:defcommand #:defexternal #:!cd #:!pwd #:!pushd #:!popd #:!dirs #:!suspend #:!fg #:!bg #:!jobs #:!history #:!echo #:!help #:!alias #:!unalias #:!exit #:!quit #:!source #:!debug #:!export #:!env #:!kill #:!time #:!times #:!umask #:!ulimit #:!wait #:!exec #:!bind #:!undefcommand #:!hash #:!type #:!opt #:!l #:!load #:!ldirs #:!ql #:!autoload #:!doc #:!var #:print-command-help ;; help #:defhelp #:help-table #:help-function #:help-subjects #:help-subjects-description #:help-on ;; convenience / scripting #:alias #:set-alias #:unset-alias #:get-alias #:command-paths #:pipe #:in-bg #:in-pipe-p #:out-pipe-p #:append-file #:append-files #:run-with-output-to #:run-with-input-from #:input-line-words #:input-line-list #:map-output-lines #:command-output-words #:command-output-list #:with-streamlike-input #:with-files-or-input #:with-shell #:run-with-env ;; magic punctuation #:! #:!? #:!! #:!$ #:!$$ #:!@ #:!_ #:!- #:!= #:!?= #:!!= #:!$= #:!$$= #:!@= #:!_= #:!-= #:!and #:!or #:!bg #:!> #:!>> #:!>! #:!>>! #:!< #:!!< #:!q #:!h #:!hh #:!v ;; internal-ish things that might want to be used #:get-command #:command-to-lisp-args #:posix-to-lisp-args #:expr-from-args #:enable-sharp-dollar-reader #:disable-sharp-dollar-reader #:file-enable-sharp-dollar-reader #:shell-read #:shell-eval #:shell-expand #:shell-expand-to-list #:fill-middle #:gradientize #:format-prompt #:symbolic-prompt-to-string #:load-file #:expand-single-file-name #:suspend-job #:find-job #:job #:job-id #:job-name #:job-command-line #:job-status #:job-pid #:continue-job-in-foreground #:continue-job-in-background #:kill-job #:list-all-jobs #:accepts #:get-accepts #:twiddlify #:unix-truthy #:shell-error #:shell-error-format #:shell-error-arguments #:file-expansion #:file-expansion-files )) ;; End
6,404
Common Lisp
.lisp
180
31.838889
79
0.644373
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
6437a4bee786d3ed50e2678ac0ecff92564e13794c1a04a719adf2abf670afda
2,126
[ -1 ]
2,127
run_lisp.sh
nibbula_lish/run_lisp.sh
#!/usr/bin/env sh # This is just to find and start a Lisp, to run a Lisp based script. fail() { echo "$0: $*" exit 1 } script_name="$1" if [ ! -n "$script_name" ]; then fail "Script name argument is missing." fi if [ ! -e "$script_name" ]; then fail "Script file doesn't exist." fi if [ ! -n "$LISP" ] ; then LISPS="sbcl ccl lisp clisp ecl" for l in $LISPS ; do if [ x"`command -v $l`" != x ] ; then LISP=$l break; fi done fi if [ ! -n "$LISP" -o ! -n "`command -v $LISP`" ] ; then echo "I can't find a Lisp to run. Please set the environment variable LISP to" echo "the name of an installed Common Lisp, and re-run this script." echo "For example: " echo echo "LISP=/usr/bin/sbcl sh ./build.sh" echo exit 1 fi try_to_figure_flags() { LOAD_ARGS="" BATCH_ARGS="" case "$LISP" in *sbcl*) OUR_PLAIN_LISP_FLAGS="--no-userinit" ; BATCH_ARGS="--noinform --noprint --disable-debugger --no-sysinit" ;; *ccl*) OUR_PLAIN_LISP_FLAGS="--no-init" #BATCH_ARGS="--batch" BATCH_ARGS="--quiet" ;; *clisp*) OUR_PLAIN_LISP_FLAGS="-norc" ;; *abcl*) OUR_PLAIN_LISP_FLAGS="--noinit" ;; *ecl*) OUR_PLAIN_LISP_FLAGS="--norc" BATCH_ARGS="-q" ;; *) echo "I'm not sure how to set flags for $LISP." ;; esac } try_to_figure_flags export LISH_PLAIN_FLAGS="${LISH_PLAIN_FLAGS:=$OUR_PLAIN_LISP_FLAGS}" export LISH_FLAGS="${BATCH_ARGS}" echo "[Using ${LISP} ${LISH_FLAGS} ${LISH_PLAIN_FLAGS}]" echo "[Running $script_name]" echo $LISP $LISH_FLAGS $LISH_PLAIN_FLAGS echo '(load "'"$script_name"'")' | $LISP $LISH_FLAGS $LISH_PLAIN_FLAGS || fail "somehow failed" exit 0
1,722
Common Lisp
.lisp
70
20.928571
80
0.60986
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
01b09eb57116ba2c9cdd81ea1ff9c03fbf4b7154d10334d2fab666cd3d48c9c4
2,127
[ -1 ]
2,128
expand.lisp
nibbula_lish/expand.lisp
;;; ;;; expand.lisp - Shell expansions. ;;; (in-package :lish) (defstruct fake-var "A compatibility variable." name value cacheable cached-value description) ;; Please don't add to these. These are just for superficial compatibility with ;; POSIX shells. (defparameter *fake-vars* `(("HOSTNAME" nil "Name of the host." *host*) ("HOSTTYPE" t "Type of the host." ,#'machine-type) ("MACHTYPE" nil "Fully specific platform" *arch*) ("OLDPWD" nil "Last working directory" ,#'(lambda () (lish-old-pwd *shell*))) #+unix ("PPID" t "Parent process ID" ,#'os-unix:getppid) ("PWD" nil "Current working directory" ,#'current-directory) ("SHLVL" nil "Shell level" *lish-level*) ("COLUMNS" nil "Terminal character columns" ,#'(lambda () (terminal-window-columns (rl:line-editor-terminal (lish-editor *shell*))))) ("ROWS" nil "Terminal character rows" ,#'(lambda () (terminal-window-rows (rl:line-editor-terminal (lish-editor *shell*))))) ("LINES" nil "Terminal character rows" ,#'(lambda () (terminal-window-rows (rl:line-editor-terminal (lish-editor *shell*))))) ;; These are readonly unlike the POSIX ones. But you can, as you may know: ;; (setf (lish-start-time *shell*) (get-universal-time)) ;; and of course: ;; (setf *random-state* (make-random-state)) ;; to get similar (or better) functionality. ("SECONDS" nil "Seconds elapsed since some time" ,#'(lambda () (- (get-universal-time) (lish-start-time *shell*)))) ("RANDOM" nil "A random 16 bit number." ,#'(lambda () (random (1- (ash 1 15))))) #+unix ("$" nil "Current process ID" ,#'os-unix:getpid) ("!" nil "Process ID of the previous command" nil) ;; @@@ ("?" nil "Result of the last command." nil)) ;; @@@ "List of: Name Cacheable-p Description Value") (defparameter *fake-var-table* nil "The fake var table.") (defparameter *fake-var-single-chars* nil "Sequence of single characters that are fake vars.") (defun fake-var-list () "Return a list of the fake variable names." (make-fake-var-table) (loop :for name :being :the :hash-keys :of *fake-var-table* :collect name)) (defun make-fake-var-table () ;;(format t "Making the fake var table.") (when (not *fake-var-table*) (setf *fake-var-table* (make-hash-table :test #'equal)) (loop :for (name cacheable desc value) :in *fake-vars* :do (setf (gethash name *fake-var-table*) (make-fake-var :name name :value value :cacheable cacheable :description desc)) ;; Note single char vars (when (= (length name) 1) (pushnew (char name 0) *fake-var-single-chars*))) (setf *fake-vars* nil)) ; maybe it could be gc'd *fake-var-table*) (defun fake-var (name) "Return the value of fake var named ‘name’." (make-fake-var-table) (flet ((evaluate (x) (cond ((functionp x) (funcall x)) ((symbolp x) (symbol-value x)) (t nil)))) (let ((var (gethash name *fake-var-table*))) ;;(format t "fake-var ~s = ~s~%" name var) (when var (if (fake-var-cacheable var) (or (fake-var-cached-value var) (setf (fake-var-cached-value var) (evaluate (fake-var-value var)))) (evaluate (fake-var-value var))))))) (defun remove-backslashes (s) "Remove quoting backslashes from the string S, except don't remove doubled backslashes." (with-output-to-string (str) (let ((start 0) (last-start 0) (len (length s))) (loop :while (and (< start len) (setf start (position #\\ s :start start))) :do ;;(format t "start = ~s last-start = ~s~%" start last-start) (when (> (- start last-start) 0) (princ (subseq s last-start start) str)) (when (and (< (1+ start) len) (char= #\\ (char s (1+ start)))) (write-char #\\ str) (incf start)) (incf start) (setf last-start start)) (when (< last-start len) (princ (subseq s last-start) str))))) ;; a.k.a. parameter expansion (defun shell-expand-variables (s) (make-fake-var-table) (expand-variables s :value-funcs `(,#'fake-var ,#'nos:env) :allowed (_ (or (alphanumericp _) (char= _ #\_) (position _ *fake-var-single-chars*))))) #+(or) (defun expand-variables (s) "Return a string based on the string ‘s’ with variables expanded." (let ((start 0) (last-start 0) (len (length s))) (with-output-to-string (str) (loop :while (and (< last-start len) (setf start (position-if (_ (or (char= #\$ _) (char= #\\ _))) s :start last-start))) :do (cond ;; backslash ((char= #\\ (char s start)) (incf start) ; skip over backslash (when (< start len) ; if there is one, (incf start)) ; skip over the next char ;; output the first part (when (not (zerop (- start last-start))) (princ (subseq s last-start start) str))) ;; dollar ((char= #\$ (char s start)) (when (not (zerop (- start last-start))) (princ (subseq s last-start start) str)) (make-fake-var-table) (if (and (< (1+ start) len) (position (char s (1+ start)) *fake-var-single-chars*)) (progn (princ (or (fake-var (subseq s (1+ start) (+ start 2))) "") str) (incf start 2)) (let ((end (or (position-if (_ (not (or (alphanumericp _) (char= #\_ _)))) s :start (1+ start)) (length s)))) (incf start) (if (not (zerop (- end start))) (progn ;;(format t "looking up |~s| start=~s end=~s~%" ;; (subseq s start end) start end) (princ (or (fake-var (subseq s start end)) (nos:environment-variable (subseq s start end)) "") str)) (princ "$" str)) (setf start end)))) (t (error "Variable parsing messed up somehow."))) ;;(format t "start = ~s last-start = ~s~%" start last-start) (setf last-start start) ) ;;(format t "end: start = ~s last-start = ~s~%" start last-start) (when (not (zerop (- (or start len) last-start))) (princ (subseq s last-start (or start len)) str))))) ;; @@@ Perhaps we could actually do the evaluation in here? (defun expand-bang (word) "Expand a shell word starting with !. If the history-expansion shell option is set, and the expression is an integer, do history expansion. Otherwise, return words which will evaluate a lisp expression." (or (and (lish-history-expansion *shell*) (and word (stringp word) (char= (char word 0) #\!)) (let (results expansion) (handler-case (multiple-value-bind (obj pos) (read-from-string (subseq word 1) nil) (declare (ignore pos)) ;; @@@ wrong, should complain (if (and obj (integerp obj) *shell* (get-option *shell* 'history-expansion)) ;;(setf expansion (shell-read (rl:history-nth obj)) (setf expansion (rl:history-entry-line (rl:history-nth obj)) results (typecase expansion (shell-expr (shell-expr-words expansion)) (t (list expansion)))) ;;(push (make-shell-word :word obj :eval t) results))) ;; (push obj results) (push word results) )) (end-of-file ()) (reader-error ())) results)) word)) (defun expr-from-args (args) "Return a shell expression made up of ‘args’ as the words." (let* (words (line (with-output-to-string (str) (loop :with pos = 0 :and as-string :for a :in args :do (when (not (zerop pos)) (princ #\space str) (incf pos)) (setf as-string (princ-to-string a)) (push (make-shell-word :word a :start pos :end (+ pos (length as-string))) words) (incf pos (length as-string)) (princ a str))))) (make-shell-expr :line line :words (reverse words)))) (defun OLD-lisp-exp-eval (expr) "Return the shell-expr ‘expr’ with Lisp expressions expanded." (make-shell-expr :words (loop :with results :and first-word = t :for w :in (shell-expr-words expr) :if (and (not first-word) (shell-word-p w) (or (consp (shell-word-word w)) (symbolp (shell-word-word w))) (shell-word-eval w)) :do (setf results (eval (shell-word-word w))) :and :if (and (listp results) (not (shell-word-quoted w))) ;; Spread list results into separate args :append (mapcar #'(lambda (x) (make-shell-word :word x)) results) :else :collect (make-shell-word :word results) :else :collect w :do (setf first-word nil)) ;; @@@ doesn't fix the line :line (shell-expr-line expr))) (defun lisp-exp-eval (expr) "Return the shell-expr ‘expr’ with Lisp expressions expanded." (let ((eval-results nil) (prev nil) (prev-join nil) (first-word t) (result nil)) (flet ((join (w value) "String append to previous and return nil (to omit this word)." (setf (shell-word-word (car prev)) (s+ (shell-word-word (car prev)) value) (shell-word-end (car prev)) (shell-word-end w)) nil)) (make-shell-expr :words (mapcan (lambda (w) (setf result (if (and (not first-word) (shell-word-p w) (or (consp (shell-word-word w)) (symbolp (shell-word-word w))) (shell-word-eval w)) (progn (setf eval-results (eval (shell-word-word w))) (cond ((and (listp eval-results) (not (shell-word-quoted w))) ;; Spread list results into separate args (mapcar #'(lambda (x) (make-shell-word :word x)) eval-results)) ((and prev (or (eq (shell-word-join w) :left) (eq (shell-word-join w) :both))) ;; string append to previous, and omit this word (join w eval-results)) ((and prev (or (eq prev-join :right) (eq prev-join :both))) (join w eval-results)) (t (list (make-shell-word :word eval-results))))) ;; not evaled (cond ((and prev (or (eq prev-join :right) (eq prev-join :both)) (shell-word-p w)) (join w (shell-word-word w))) (t (list w)))) first-word nil prev (or result prev) prev-join (and (shell-word-p w) (shell-word-join w))) result) (shell-expr-words expr)) ;; @@@ doesn't fix the line :line (shell-expr-line expr))))) ;; @@@ should probably rename lisp-exp-eval to this (defun expand-lisp-exp (exp) (lisp-exp-eval exp)) (defun number-padding (i) "Return how much padding we might need for an integer between zero and I." (if (zerop i) 0 (1+ (realpart (log i 10))))) (defun starts-with-superfluous-zero (s) "Return true if there's a pointless zero at the beginning of a string representing an integer." (or (and (> (length s) 1) (char= (char s 0) #\0)) (and (> (length s) 2) (char= (char s 0) #\-) (char= (char s 1) #\0)))) (defun range-padding (start start-int end end-int) "How much padding might we need for the range START .. END." (and (or (and start-int (starts-with-superfluous-zero start)) (and end-int (starts-with-superfluous-zero end))) (truncate (max (number-padding start-int) (length start) (number-padding end-int) (length end))))) (defun sequence-steps (start end step is-char prefix suffix) "Return a list of strings in the sequence from START to END, by counting STEP. If IS-CHAR is true, return characters in the range instead of numbers. If IS-CHAR is not true, and START or END are not integers, return NIL." (let* ((start-int (if is-char (char-code (char start 0)) ;; (parse-integer start :junk-allowed t))) (ignore-errors (parse-integer start)))) (end-int (if is-char (char-code (char end 0)) ;; (parse-integer end :junk-allowed t))) (ignore-errors (parse-integer end)))) test) (when (not (and start-int end-int)) (return-from sequence-steps nil)) (cond ((zerop step) (return-from sequence-steps nil)) ((and (> start-int end-int) (not (minusp step))) (setf step (- step))) ((and (< start-int end-int) (not (plusp step))) (setf step (- step)))) (setf test (if (< start-int end-int) (if (plusp step) #'<= #'>=) (if (minusp step) #'>= #'<=))) (if is-char (loop :with i = start-int :and limit = end-int :while (funcall test i limit) :collect (s+ prefix (code-char i) suffix) :do (incf i step)) (let ((zero-padding (range-padding start start-int end end-int))) (loop :with i = start-int :and limit = end-int :while (funcall test i limit) :if zero-padding :collect (format nil "~a~v,'0d~a" prefix zero-padding i suffix) :else :collect (s+ prefix i suffix) :end :do (incf i step)))))) ;; I don't think there's any formal specification of this. It isn't in POSIX. ;; I don't know who came up with it. Maybe it's from ksh? My implementation is ;; probably subtly different from others. I tend to agree with the way zsh ;; seems to do braces, so I think this code probably works more like zsh than ;; bash. It's just so convenient and useful, that I'm okay with sacrificing ;; curly braces to it. But I'm not really into adding character classes like ;; the zsh BRACE_CCL option, probably because it's so easy to generate arbitrary ;; sequences with just plain Lisp. ;; @@@ We should probably get rid of RECURSIVE keyword, by an flet or a ;; sub-function. ;; @@@ FIXME: "_{b{a,e}}_" expands to itself not "_{ba}_" "_{be}_" ;; It's a malformed expression, but the way that it fails doesn't make sense, ;; and isn't the same as other shells. I'm having trouble coming up with a fix ;; that doesn't involve totally re-writing the way that I do recursive ;; expressions. (defun expand-braces (string &key (do-sequences t) recursive) "Expand shell braces expressions in a string. Return a list of expanded words, which may be a list of just the STRING if no expansion was done. If DO-SEQUENCES is true (the default), expand shell sequence expressions. For internal purposes, we pass RECURSIVE true when we are inside a nested brace expression, and return a second value to update how much of the string we consumed. Alternatives: alt_exp : '{' brace_term ( ',' brace_term )+ '}' brace_term : [^{},]+ E.g.: {a,b,c} -> a b c x{a,b,c}y -> xay xby xcy {a,b{a,A},c} -> a ba bA c Sequences: seq_exp : '{' brace_char '..' brace_char [ '..' integer ] '}' | '{' integer '..' integer [ '..' integer ] '} brace_char : [^{},] E.g.: {1..5} -> 1 2 3 4 5 x{1..5}y -> x1y x2y x3y x4y x5y {-2..2} -> -2 -1 0 1 2 {a..g} -> a b c d e f g { " (when (not (lish-expand-braces *shell*)) (return-from expand-braces string)) (let ((len (length string)) (start 0) (i 0) prefix suffix alternatives output-words in-brace in-seq in-alts seq-start) (loop :while (< i len) :do (case (aref string i) (#\{ (if in-brace ;; Nested braces (multiple-value-bind (alts new-i) (expand-braces (subseq string start) :recursive t) (append (or alternatives '()) alts) (setf i (+ start new-i))) (setf prefix (subseq string start i) start (1+ i) seq-start (1+ i) in-brace t))) (#\, (when in-brace (when in-seq ;; Pretend the sequence was just an alternative. (setf start seq-start in-seq nil alternatives nil)) (push (subseq string start i) alternatives) (setf start (1+ i) seq-start (1+ i) in-seq nil in-alts t))) (#\. (when (and in-brace do-sequences (not in-alts) (< (1+ i) len) (char= #\. (aref string (1+ i)))) (push (subseq string start i) alternatives) (incf i) (setf start (1+ i) in-seq t))) (#\} (when in-brace (push (subseq string start i) alternatives) (setf suffix (if recursive (subseq string (1+ i) (position #\, string :start i)) (subseq string (1+ i))) in-brace nil start (1+ i)) (cond ((and in-seq alternatives) (setf alternatives (nreverse alternatives)) (let ((is-char (and (= 1 (length (first alternatives))) (= 1 (length (second alternatives)))))) ;; (format t "is-char = ~s~%alts = ~s~%" is-char alternatives) (case (length alternatives) (2 (setf output-words (append output-words (sequence-steps (first alternatives) (second alternatives) 1 is-char prefix suffix))) ;; (format t "output-words = ~s~%" output-words) ) (3 (let ((step (ignore-errors (parse-integer (third alternatives))))) (when step (setf output-words (append output-words (sequence-steps (first alternatives) (second alternatives) step is-char prefix suffix))))) ;; (format t "output-words = ~s~%" output-words) )))) ((and alternatives (> (length alternatives) 1)) (loop :for i :in alternatives :do (push (s+ prefix i suffix) output-words)))) ;; Expand possible remaining brace expressions in the suffix (if output-words (progn ;; (format t "derp ~s~%" output-words) (setf output-words (flatten (loop :for w :in output-words :collect (expand-braces w)))) (loop-finish)) (progn ;; Ignore malformed things? (setf start 0 in-brace nil alternatives nil ))))) (#\\ (incf i))) (incf i)) (values (or output-words (list string)) i))) (defun expand-filenames (string) "Expand filenames with glob in STRING. Return a list of filenames or just STRING if it's not a pattern or there's no matching files." (or (and (glob:pattern-p string nil t) (let ((expansion (glob:glob string :tilde t))) ;; If expansion fails we have to just return the pattern string. (if expansion (make-file-expansion :files expansion) string))) string)) #| (defun expand-word-once (word) "Try to exapnd the string WORD and return it's expansion. If no further expansion can be done, return WORD itself (i.e. eq)." (cond ((position #\$ w) ;; $ environment variable expansion (let ((expansion (expand-variables w))) (push (if (shell-word-p word) (make-shell-word :word expansion :start (shell-word-start word) ;; @@@ this could overlap a following word :end (+ (shell-word-start word) (length expansion)) :quoted t :eval (shell-word-eval word)) (make-shell-word :word expansion :quoted t)) new-words))) ((glob:pattern-p w nil t) ;; filename globbing, with ~ expansion on (let ((g (glob:glob w :tilde t))) (if g (dolist (x g) (push x new-words)) ;; @@@ fix to not dup ;; There's no existing file expansions, but try just ;; twiddle, and also keep the literal glob expression ;; if no matches. (push (glob:expand-tilde w) new-words)))) ((eql (char w 0) #\!) ;; !bang expansion (loop :for e :in (expand-bang w) :do ;; (format t "--> ~s~%" e) (push e new-words))) ((shell-word-p word) ;; quoted word without anything special to expand (setf (shell-word-word word) (remove-backslashes w)) (push word new-words)) ((stringp word) (push (remove-backslashes word) new-words)) (t (push word new-words)))) |# ;; (defun unquoted-string-p (w expr i) ;; "True if W in EXPR with index I is _not_ quoted." ;; (and (stringp w) (> (length w) 0) ;; (and (shell-expr-word-quoted expr) ;; (not (elt (shell-expr-word-quoted expr) i))))) (defun unquoted-string-p (word) "True if WORD is _not_ quoted." ;; @@@ ??? I'm not sure why I'm requiring it to be of non-zero length. (or (and (stringp word) (> (length word) 0)) (and (shell-word-p word) (stringp (shell-word-word word)) (> (length (shell-word-word word)) 0) (not (shell-word-quoted word))))) ;; (defun expand-alias-words (alias words) ;; "Take an alias and a shell-words array and return a shell-words array ;; with the alias expanded." ;; ;; (let* ((alias-words (expr-to-words (shell-read alias))) ;; (let* ((alias-words (shell-expr-words (shell-read alias))) ;; (new-words (append alias-words (subseq words 1)))) ;; new-words)) (defun possibly-expand-aliases (sh expr) "Return a shell-expr with aliases expanded. This does lisp expression expansion in the alias expansion." (if (zerop (length (shell-expr-words expr))) expr (let* ((cmd (nth-expr-word 0 expr)) (alias (gethash cmd (shell-aliases sh)))) (if alias (lisp-exp-eval (expand-alias alias expr)) expr)))) ;; XXX This can be problematic because in the back and forth to words things ;; in expr can get trashed or are not set, or faked like the shell-expr-line ;; below. (defun expand-alias (alias expr) "Take an alias and a shell-expr and return a shell-expr with the alias expanded." (let* ((expanded-expr (do-expansions (shell-read alias))) (expanded-line (shell-expr-line expanded-expr)) (expr-tail (cdr (shell-expr-words expr))) (new-words (append (shell-expr-words expanded-expr) expr-tail)) (new-line (s+ expanded-line #\space (shell-words-to-string expr-tail)))) (make-shell-expr :words new-words :line new-line))) ;; In POSIX shells the order of expansion is: ;; history * ;; brace * ;; tilde ;; variables (and parameters) ;; arithmetic ;; command substitution ;; word splitting * ;; filename expansion * ;; quote removal ;; Things with * can change the number of "words". ;; ;; Even though we have differnet expansions, and I'm not always fond of the way ;; other shells do it, we should probably try not to violate peoples' general ;; expectations much. (defparameter *expansions* ;; function until-stable? word / line `((expand-bang nil :word) (expand-braces nil :word) (expand-tilde nil :word) (shell-expand-variables t :word) ;;(expand-lisp-exp t :line) ;; lisp-exp-eval ;;(expand-lisp-exp t :expr) (expand-filenames nil :word) (remove-backslashes nil :word) )) (defparameter *recursive-expansion-limit* 100000 "Limit on how many recursive expansions to do.") (defun do-expansions (expr) "Perform shell syntax expansions / subsitutions on the expression. Remove backslash quotes." ;; (let ((words (map 'list #'word-word (shell-expr-words expr))) (let ((words (shell-expr-words expr)) new-words func until-stable unit) (labels ((push-word (w) (typecase w (string (push (make-shell-word :word w) new-words)) (t (push w new-words)) ;; (t (push (make-shell-word :word w) new-words)) )) (apply-func (func word until-stable unit) (let ((result word) (i 0)) (if until-stable (loop :with last-result :while (not (equal last-result (setf result (funcall func result)))) :do (setf last-result result) (incf i) (when (and *recursive-expansion-limit* (>= i *recursive-expansion-limit*)) (cerror "Keep expanding" "Shell expansion bailed out after ~s iterations. Set lish::*recursive-expansion-limit* higher (or to nil) and continue if you really want to keep expanding." i))) (setf result (funcall func word))) (case unit ((:line :expr) (setf new-words result)) (:word (if (listp result) (mapc (_ (push-word _)) result) (push-word result)))))) (expand-word (word) (cond ((not (unquoted-string-p word)) ;; Quoted, so just push it verbatim. (push-word word)) ((shell-word-p word) (expand-word (shell-word-word word))) ((stringp word) (apply-func func word until-stable unit)) ((consp word) ;; Assume it's one of the menagerie: (e.g. :pipe :redirect-*) (do-expansions (second word)) (push-word word)) (t ;; It's something else? like a pre-read or pre-evaled lisp obj? (push-word word))))) (loop :for e :in *expansions* :do (setf func (first e) until-stable (second e) unit (third e)) (ecase unit ;; (:expr ;; (format t "~s expand expr ~s~%" func expr) ;; (apply-func func until-stable unit) ;; ) (:line ;; (format t "~s expand line ~s~%" func words) (apply-func func words until-stable unit)) (:word (loop :for word :in words :do (expand-word word) ;; (format t "~s expand word ~s~%" func word) ) (setf words (nreverse new-words) new-words nil))) (setf (shell-expr-words expr) words)))) expr) ;; This is sort of equivalent to wordexp. (defun shell-expand (thing) "Expand THING and return a shell expression. If THING is a string it is turned into a shell-expr with shell-read." (possibly-expand-aliases *shell* (do-expansions (lisp-exp-eval (etypecase thing (string (shell-read thing)) (shell-expr thing)))))) ;; Maybe we should provide a shorthand for this? (defun shell-expand-to-list (thing) "Read and expand THING and return a list of words." (shell-words-to-list (shell-expr-words (shell-expand thing)))) (defun shell-expand-line (editor) "A command to expand the current line." ;;(format t "editor is a ~a = ~s~%" (type-of editor) editor) (let* ((buf (rl:get-buffer-string editor)) (words (shell-expr-words (possibly-expand-aliases *shell* (do-expansions (lisp-exp-eval (shell-read buf))))))) (rl::use-first-context (editor) (rl:replace-buffer editor (shell-words-to-fat-string words))))) #| (with-output-to-string (str) (labels ((write-thing (w) (typecase w (string (princ (quotify w) str)) (cons (write w :stream str :readably t :case :downcase)))) ;;(write w :stream str :readably t :case :downcase)) (write-it (w) (cond ((and (shell-word-p w) (word-quoted w)) (write-char #\" str) (write-thing (word-word w)) (write-char #\" str)) (t (write-thing (word-word w)))))) (when (first words) (write-it (first words))) (loop :for w :in (rest words) :do (write-char #\space str) (write-it w))))))) |# ;; End
26,269
Common Lisp
.lisp
742
30.493261
80
0.619683
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
9184653984ba93601e3924011fbeefb984632b6d6500349cf6618973d12ca5c7
2,128
[ -1 ]
2,129
args.lisp
nibbula_lish/args.lisp
;;; ;;; args.lisp - Command arguments. ;;; (in-package :lish) (defclass argument () ((name :documentation "Name" :initarg :name :accessor arg-name) (type :documentation "Declared type" :initarg :type :accessor arg-type) (value :documentation "Value" :initarg :value :accessor arg-value) (default :documentation "Default value, if optional." :initarg :default :initform nil :accessor arg-default) (repeating :type boolean :documentation "True if the value can repeat." :initarg :repeating :initform nil :accessor arg-repeating) (rest :type boolean :documentation "True if the argument is repeating and consumes the rest of the arguments, ignoring arguments that look like flags. Setting this will also make repeating be true." :initarg :rest :initform nil :accessor arg-rest) (optional :type boolean :documentation "True if a value is not required." :initarg :optional :initform t :accessor arg-optional) (hidden :type boolean :documentation "If true, don't show in help." :initarg :hidden :initform nil :accessor arg-hidden) (use-supplied-flag :type boolean :documentation "True to set the argument supplied flag when calling functions. The flag will be named <name>-SUPPLIED-P." :initarg :use-supplied-flag :initform nil :accessor arg-use-supplied-flag) (prompt :type string :documentation "Show when asking user for value." :initarg :propmt :accessor arg-propmt) (help :type string :documentation "Description for the user." :initarg :help :accessor arg-help) (completion-function :type function-designator :initarg :completion-function :accessor arg-completion-function :initform nil :documentation "A special completion function for the argument.") (short-arg :type (or character null) :documentation "Command line argument, short form." :initarg :short-arg ;;:initform nil :accessor arg-short-arg) (long-arg :type (or string null) :documentation "Command line argument, long form." :initarg :long-arg ;;:initform nil :accessor arg-long-arg) (old-long-arg :type (or string null) :documentation "Command line argument, old long form, with a single dash." :initarg :old-long-arg ;;:initform nil :accessor arg-old-long-arg) (pattern :type (or string null) :documentation "Pattern to match." :initarg :pattern :initform nil :accessor arg-pattern) (override ;; @@@ get rid of this after real parsing :initarg :override :accessor arg-override :initform nil :documentation "A boolen to process before other arguments, or a function that given the argument returns a boolean indicating whether to overrride.") (flattenable-p :initarg :flattenable-p :accessor arg-flattenable-p :type boolean :initform nil :documentation "True if we can flatten multiple arguments of this type.")) (:documentation "Generic command parameter.")) (defmethod initialize-instance :after ((o argument) &rest initargs &key &allow-other-keys) (declare (ignore initargs)) ;; Make the long-arg default to the name if the short-arg is set. (when (and (slot-boundp o 'short-arg) (slot-value o 'short-arg) (not (slot-boundp o 'long-arg))) (setf (slot-value o 'long-arg) (princ-to-string (slot-value o 'name)))) (when (not (slot-boundp o 'short-arg)) (setf (slot-value o 'short-arg) nil)) (when (not (slot-boundp o 'long-arg)) (setf (slot-value o 'long-arg) nil)) (when (not (slot-boundp o 'old-long-arg)) (setf (slot-value o 'old-long-arg) nil)) ;; Setting REST forces REPEATING to be true. (when (and (slot-boundp o 'rest) (slot-value o 'rest)) (setf (slot-value o 'repeating) t))) (defvar *arg-normal-flag-char* #\- "Normal argument flag character.") (defvar *arg-opposite-flag-char* #\+ "Opposite argument flag character.") (defvar *arg-flag-chars* (vector *arg-normal-flag-char* *arg-opposite-flag-char*) "Sequence of possible argument flag characters.") (defun is-flag-char (c) "Return true if C is a flag character." (position c *arg-flag-chars*)) (defun is-normal-flag-char (c) "Return true if C is a normal flag character." (char= c *arg-normal-flag-char*)) (defun is-opposite-flag-char (c) "Return true if C is an opposite flag character." (char= c *arg-opposite-flag-char*)) (defmethod print-object ((o argument) stream) "Print a lish command argument in an unreadable way." (let ((short-arg (and (slot-boundp o 'short-arg) (arg-short-arg o))) (long-arg (and (slot-boundp o 'long-arg) (arg-long-arg o)))) (print-unreadable-object (o stream :identity nil :type t) (format stream "~a~:[~; repeating~]~:[~; optional~]~:[~; hidden~]~:[~; rest~]~ ~:[~2*~; ~c~a~]~:[~3*~; ~c~c~a~]" (arg-name o) ;; (arg-type o) (arg-repeating o) (arg-optional o) (arg-hidden o) (arg-rest o) short-arg *arg-normal-flag-char* short-arg long-arg *arg-normal-flag-char* *arg-normal-flag-char* long-arg)))) (define-condition argument-error (shell-error cell-error) () (:report (lambda (c s) (when (shell-error-format c) (format s "~?" (shell-error-format c) (shell-error-arguments c))))) (:documentation "An error with command arguments.")) (defun arg-error (format &rest arguments) "Shorthand for an argument error." (restart-case (signal 'argument-error :format format :arguments arguments) (use-value (value) :report "Use a new value." :interactive (lambda () (multiple-value-list (eval (read-from-string (rl:rl :prompt "Enter a new value (evaluated): "))))) value))) (defgeneric convert-arg (arg value &optional quoted) (:documentation "Convert an argument value from one type to another.") (:method ((arg argument) value &optional quoted) "The base default conversion just returns the value." (declare (ignore quoted)) value)) (defgeneric argument-choices (arg) (:documentation "Return a list of possible argument values or nil if unknown.") (:method ((arg argument)) "The default choices are unknown." nil)) (defclass arg-boolean (argument) () (:documentation "A true or false value.")) (define-constant +true-strings+ '("T" "TRUE" "YES" "ON" "1")) (define-constant +false-strings+ '("NIL" "FALSE" "NO" "OFF" "0")) (defmethod convert-arg ((arg arg-boolean) (value string) &optional quoted) (declare (ignore quoted)) (cond ((position value +true-strings+ :test #'equalp) t) ((position value +false-strings+ :test #'equalp) nil) (t (arg-error "Can't convert ~w to a boolean." value)))) ;; (defmethod argument-choices ((arg arg-boolean)) ;; (concatenate 'list +true-strings+ +false-strings+)) (defclass arg-number (argument) () (:documentation "A number.")) (defmethod convert-arg ((arg arg-number) (value string) &optional quoted) (declare (ignore quoted)) (let* ((num (safe-read-from-string value nil nil))) (if (and num (numberp num)) num (arg-error "Can't convert ~w to a number." value)))) (defclass arg-integer (arg-number) () (:documentation "An integer.")) (defmethod convert-arg ((arg arg-integer) (value string) &optional quoted) (declare (ignore quoted)) (handler-case (let ((int (parse-integer-with-radix value))) (if (and int (integerp int)) int (arg-error "Can't convert ~w to an integer." value))) ;; Make the error be a little more descriptive. (error (c) (arg-error "Can't convert arg ~w to an integer: ~a" value c)))) (defclass arg-float (arg-number) () (:documentation "An floating point number.")) (defmethod convert-arg ((arg arg-float) (value string) &optional quoted) (declare (ignore quoted)) (let* ((num (safe-read-from-string value nil nil))) (if (and num (floatp num)) num (arg-error "Can't convert ~w to a float." value)))) (defclass arg-character (argument) () (:documentation "A character.")) (defmethod convert-arg ((arg arg-character) (value character) &optional quoted) (declare (ignore arg quoted)) value) (defmethod convert-arg ((arg arg-character) (value string) &optional quoted) (declare (ignore arg quoted)) (if (= (length value) 1) (char value 0) (or (name-char value) (arg-error "Can't convert character arg from string: ~s" value)))) (defclass arg-string (argument) () (:documentation "A string.")) (defmethod convert-arg ((arg arg-string) (value string) &optional quoted) (declare (ignore arg quoted)) value) (defmethod convert-arg ((arg arg-string) (value t) &optional quoted) (declare (ignore arg quoted)) (princ-to-string value)) (defclass arg-symbol (argument) () (:documentation "A symbol.")) (defmethod convert-arg ((arg arg-symbol) (value string) &optional quoted) (declare (ignore arg quoted)) value) (defmethod convert-arg ((arg arg-symbol) (value t) &optional quoted) (declare (ignore arg quoted)) (princ-to-string value)) (defclass arg-keyword (argument) () (:documentation "A Lisp keyword.")) (defmethod convert-arg ((arg arg-keyword) (value string) &optional quoted) (declare (ignore quoted)) (if (char/= (char arg 0) #\:) (intern (string-upcase (subseq value 1)) (find-package :keyword)) value)) (defclass arg-object (argument) () (:documentation "A Lisp object.")) (defmethod convert-arg ((arg arg-object) (value string) &optional quoted) (if quoted value (handler-case (multiple-value-bind (obj end) (safe-read-from-string value) ;; If the whole string wasn't an object, just treat as a string. (if (= end (length value)) obj value)) (error () ;; Just return the string value if we have problems reading it. (warn "Couldn't convert argument ~s into a Lisp object." value) value)))) (defclass arg-case-preserving-object (argument) () (:documentation "A Lisp object, read with case preserved.")) (defmethod convert-arg ((arg arg-case-preserving-object) (value string) &optional quoted) (if quoted value (handler-case (multiple-value-bind (obj end) (fancy-read-from-string value :safe t :case :preserve) ;; If the whole string wasn't an object, just treat as a string. (if (= end (length value)) obj value)) (error () ;; Just return the string value if we have problems reading it. (warn "Couldn't convert argument ~s into a Lisp object." value) value)))) (defclass arg-sequence (arg-object) () (:documentation "A sequence.")) (defmethod convert-arg ((arg arg-sequence) (value sequence) &optional quoted) (declare (ignore arg quoted)) value) (defclass arg-list (arg-object) () (:documentation "A list.")) (defmethod convert-arg ((arg arg-list) (value list) &optional quoted) (declare (ignore arg quoted)) ;; @@@ We could probably do better here. ;; Maybe?: (let (result) (omap (_ (push _ result)) value) result) (coerce value 'list)) (defclass arg-function (arg-symbol) () (:documentation "A function name.")) ;; (defmethod convert-arg ((arg arg-function) (value string) &optional quoted) ;; (declare (ignore arg quoted)) ;; (symbolify value)) (defmethod convert-arg ((arg arg-function) (value function) &optional quoted) (declare (ignore arg quoted)) value) (defclass arg-package (arg-keyword) () (:documentation "A package designator, either a keyword or a package.")) (defmethod convert-arg ((arg arg-package) value &optional quoted) (declare (ignore arg quoted)) (if (stringp value) (intern (string-upcase (if (char= (char value 0) #\:) (subseq value 1) value)) (find-package :keyword)) value)) (defmethod argument-choices ((arg arg-package)) (declare (ignore arg)) (sort-muffled (mapcar (_ (string-downcase (package-name _))) (list-all-packages)) #'string<)) (defclass arg-date (argument) () (:documentation "A date.")) (defmethod convert-arg ((arg arg-date) (value string) &optional quoted) (declare (ignore arg quoted)) ;; @@@ This could be better when we have a date parser. value) (defclass arg-pathname (arg-string) () (:default-initargs :completion-function #'shell-complete-filename :flattenable-p t) (:documentation "A file system path.")) (defmethod convert-arg ((arg arg-pathname) (value string) &optional quoted) (declare (ignore arg quoted)) value) (defmethod convert-arg ((arg arg-pathname) (value file-expansion) &optional quoted) (declare (ignore arg quoted)) (file-expansion-files value)) ;; (defmethod argument-choices ((arg arg-pathname)) ;; "Return the possible path names." ;; ;; @@@ Perhaps we should just use opsys:read-directory ? ;; (completion::filename-completion-list "")) (defclass arg-directory (arg-pathname) () (:default-initargs :completion-function #'shell-complete-directory) (:documentation "A file system directory.")) (defmethod convert-arg ((arg arg-directory) (value string) &optional quoted) (declare (ignore arg quoted)) value) ;; (defmethod argument-choices ((arg arg-directory)) ;; "Return the possible directory names." ;; ;; @@@ Perhaps we should just use opsys:read-directory ? ;; (completion::filename-completion-list "")) (defclass arg-stream (argument) () (:documentation "An stream of some sort.")) (defmethod convert-arg ((arg arg-stream) (value symbol) &optional quoted) (declare (ignore arg quoted)) (symbol-value value)) (defclass arg-input-stream (arg-stream) () (:documentation "An input stream.")) (defclass arg-output-stream (arg-stream) () (:documentation "An output stream.")) (defclass arg-io-stream (arg-stream) () (:documentation "An input/output stream.")) (defclass arg-stream-or-filename (arg-stream arg-pathname) () (:documentation "An stream or a filename.")) (defclass arg-input-stream-or-filename (arg-stream-or-filename) () (:documentation "An input stream or a filename.")) (defclass arg-output-stream-or-filename (arg-stream-or-filename) () (:documentation "An output stream or a filename.")) (defclass arg-io-stream-or-file (arg-stream-or-filename) () (:documentation "An I/O stream or a filename.")) (defun arg-choice-compare-ignore-case (choice value) "Return true if VALUE as a string is equalp to CHOICE." (equalp choice (princ-to-string value))) (defun arg-choice-compare (choice value) "Return true if VALUE as a string is equal to CHOICE." ;; (equal choice (princ-to-string value)) (string-equal choice (princ-to-string value)) ) (defclass arg-choice (argument) ((choices :type list :documentation "A list of choices for value." :initarg :choices :accessor arg-choices) (choice-labels :type list :documentation "A list of string names for choices." :initarg :choice-labels :accessor arg-choice-labels) (choice-func :type (or function symbol) :documentation "A function to call to get the list of choices." :initarg :choice-func :accessor arg-choice-func) (test :initarg :test :accessor arg-choice-test :type function :documentation "Function to compare values to choices.")) (:default-initargs :test #'arg-choice-compare-ignore-case) (:documentation "An argument whose value must be one of a list of choices.")) (defmethod convert-arg ((arg arg-choice) (value string) &optional quoted) (declare (ignore quoted)) (let (choice (choices (argument-choices arg))) (unless choices (error "Choice argument has no choices ~a." (arg-name arg))) (if (setf choice (find value choices :test (arg-choice-test arg))) choice (arg-error "~s is not one of the choices for the argument ~:@(~a~)." value (arg-name arg))))) (defmethod argument-choices ((arg arg-choice)) (cond ((slot-boundp arg 'choices) (arg-choices arg)) ((and (slot-boundp arg 'choice-func) (arg-choice-func arg)) (funcall (arg-choice-func arg))) (t nil))) (defmethod arg-help ((arg arg-choice)) (let ((help (if (slot-boundp arg 'help) (slot-value arg 'help) nil))) (cond ((and (slot-boundp arg 'choices) (slot-value arg 'choices)) (format nil "~@[~a ~]Choices: ~{~s~^ ~}" help (arg-choices arg))) ((and (slot-boundp arg 'choice-func) (slot-value arg 'choice-func)) (format nil "~@[~a ~]Choice function: ~a" help (arg-choice-func arg))) ((and (slot-boundp arg 'help) (slot-value arg 'help)) help) (t "")))) (defclass arg-lenient-choice (arg-choice) ((quiet :initarg :quiet :accessor arg-lenient-choice-quiet :initform nil :type boolean :documentation "True to not warn if the choice is not in the list.")) (:documentation "An argument with known choices, but accepting anything.")) (defmethod convert-arg ((arg arg-lenient-choice) (value string) &optional quoted) (declare (ignore quoted)) (let (choice (choices (argument-choices arg))) (if (not choices) (when (not (arg-lenient-choice-quiet arg)) (warn "Choice argument has no choices ~a." (arg-name arg))) (if (setf choice (find value choices :test (arg-choice-test arg))) choice (progn (when (not (arg-lenient-choice-quiet arg)) (warn "~s is not one of the choices for the argument ~:@(~a~)." value (arg-name arg))) value))))) ;; This is so if it's not provided, it can toggle. (defclass arg-boolean-toggle (arg-boolean) () (:default-initargs :default :toggle) (:documentation "A true or false value, that can be toggled.")) (defmethod initialize-instance :after ((o arg-boolean-toggle) &rest initargs &key &allow-other-keys) "Initialize a arg-boolean-toggle." (declare (ignore initargs)) (setf (arg-default o) :toggle)) ;; (defmethod convert-arg ((arg arg-boolean-toggle) (value string) &optional quoted) ;; (declare (ignore quoted)) ;; (cond ;; ((position value +true-strings+ :test #'equalp) t) ;; ((position value +false-strings+ :test #'equalp) nil) ;; (t (arg-error "Can't convert ~w to a boolean." value)))) (defun option-name-list () (loop :for o :in *options* :collect (arg-name o))) (defclass arg-option (arg-choice) () (:default-initargs :choice-func #'option-name-list) (:documentation "A shell option.")) (eval-when (:compile-toplevel :load-toplevel :execute) (defun argument-class-name (symbol) "Return a string representing the argument class for the SYMBOL." (s+ "ARG-" (string-upcase symbol)))) (defun argument-type-class (type) "Return the argument class for a given type. If the type is not a defined ARG-* class, it defaults to the generic ARGUMENT class." (flet ((try-sym (s pkg) (find-class (and (find-package pkg) (find-symbol (argument-class-name s) pkg)) nil))) (cond ((listp type) (if (not (eq (car type) 'or)) (error "Only (or ...) compound types are supported.") 'argument)) ((or (eq type t) (eq type 't) (and (stringp type) (equalp type "T"))) 'argument) ((symbolp type) (or (try-sym type :lish-user) (try-sym type :lish) (try-sym type (symbol-package type)) (progn (warn "Defaulting argument type ~s" type) 'argument))) ((stringp type) (or (try-sym type :lish-user) (try-sym type :lish) (try-sym type *package*)) (progn (warn "Defaulting argument type ~s" type) 'argument)) (t (error "Argument type is not a symbol, string or T."))))) (defun new-argument-type-class (type) (cond ((listp type) (if (not (eq (car type) 'or)) (error "Only (or ...) compound types are supported.") 'argument)) ((or (eq type t) (eq type 't) (and (stringp type) (equalp type "T"))) 'argument) ((or (symbolp type) (stringp type)) (symbolify (argument-class-name type) :package :lish-user)) (t (error "Argument type is not a symbol, string or T.")))) (defun arglist-value (arglist key) "Return a value from a DEFCOMMAND arglist argument." (let ((p (position key arglist))) (and p (elt arglist (1+ p))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun check-argument (a) (let (name type) (when (not (listp a)) (error "Argument list element must be a list.")) (setf name (first a) type (second a)) (when (not name) (error "Arguments must have a name.")) (when (not type) (error "Arguments must have a type.")))) (defun transform-arg (a) (let ((name (first a)) (type (second a))) (when (symbolp name) (setf name (string-downcase name))) (setf a (append `(:name ,name :type ',type) (cddr a))))) (defun make-argument (a &optional compile-time) (let (name type) (when (not (listp a)) (error "Argument list element must be a list.")) (setf name (first a) type (second a)) (when (not name) (error "Arguments must have a name.")) (when (not type) (error "Arguments must have a type.")) (when (symbolp name) (setf name (string-downcase name))) (setf a (append (list :name name :type type) (cddr a))) (apply #'make-instance (if compile-time 'argument (argument-type-class type)) a))) (defun make-argument-list (arglist &optional compile-time) "Take an ARGLIST from DEFCOMMAND and turn it into a list of argument objects, like in the command object." ;;; (declare (type list arglist)) (when (not (listp arglist)) (error "Command argument list must be a list.")) (loop :for a :in arglist :collect (make-argument a compile-time)))) ;; You can just do you own defclass, but the problem is what package ;; it gets defined in, because we do snipping off of the ARG- prefix. ;; It seems like we could either: ;; 1. Require the ARG- prefix everywhere, and require exporting, importing ;; and normal symbol management. ;; or ;; 2. Just define all ARG- classes in a lish package and look them up ;; there too. ;; I'm taking the second option for now, even though I may regret it. ;; Yet another defclass wrapper. (defmacro %defargtype (name package (&rest superclasses) &body body) "See the documentation for defargtype." (let* ((bod body) (class-name (intern (argument-class-name name) package)) (doc (when (stringp (first bod)) (pop bod))) (slots (if (listp (first bod)) (pop bod) (error "Missing slot list in defargtype."))) default-initargs (conversions '())) (loop :for form = bod :then (cdr form) :while (not (endp form)) :do (cond ((keywordp (car form)) (case (car form) (:convert (let ((val-type (cadr form)) (conv-body (copy-list (caddr form)))) ;; (format *trace-output* "before form = ~s~%" form) (finish-output *trace-output*) ;; Not cdddr because we have to leave one for the loop to eat. (setf form (cddr form)) ;; (format *trace-output* "after form = ~s~%" form) (finish-output *trace-output*) (push `(defmethod convert-arg ((arg ,class-name) (value ,val-type) &optional quoted) (declare (ignorable arg value quoted)) ,conv-body) conversions))) ;; @@@ What about :metaclass ? (otherwise (error "Unknown keyword in defargtype: ~s." (car form))))) ((listp (car form)) (case (caar form) (:default-initargs (setf default-initargs (car form)) ;;(pop form) ) (otherwise (error "Unknown clause in defargtype: ~s." (car form))))) (t (error "Unknown form in defargtype: ~s." (car form))))) `(progn (defclass ,class-name ,superclasses ,slots ,@(when default-initargs `(,default-initargs)) ,@(when doc `((:documentation ,doc)))) ,@conversions))) (defmacro defargtype (name (&rest superclasses) &body body) "Define a command argument type. The syntax is something like: (defargtype foo (superclasses...) \"doc\" ((slot :blah blah)) [ (:default-initargs ...) ] :convert zoo-type (and (arg-foo-ish arg) (bar-ize value)) :convert zib-type (progn (zabble arg) (zibble arg value))) This defines a class ARG-FOO with SUPERCLASSES, with slot definitions suitable for DEFCLASS. DOC is optional class documentation. The optional :CONVERT clauses define ARG-CONVERT methods for the new argument class and the given type, e.g.: (arg-convert ((arg arg-foo) (value zoo-type))) where ARG is the name of the argument and VALUE is the name of the value to be converted. See the documentation for ‘lish:argument’. " `(%defargtype ,name :lish-user (,@superclasses) ,@body)) (defmacro define-builtin-arg-type (name (&rest superclasses) &body body) `(%defargtype ,name :lish (,@superclasses) ,@body)) (defun arg-has-flag (arg) (or (and (slot-boundp arg 'short-arg) (arg-short-arg arg)) (and (slot-boundp arg 'long-arg) (arg-long-arg arg)))) ;; They must be keyworded if there are any flagged arguments. (defun args-keyworded (args) "Check if an argument must be keyworded." ;; (loop :for a :in args :do ;; (when (arg-has-flag a) ;; (return-from args-keyworded t))) ;; nil) (declare (ignore args)) ;; HOW ABOUT THIS: t) ;; Thankfully this is nowhere near as hairy as posix-to-lisp-args. (eval-when (:compile-toplevel :load-toplevel :execute) (defun command-to-lisp-args (command-args &key pass-keys-as) "Return a Lisp argument list for the given Lish argument list." (let ((mandatories (loop :for a :in command-args :if (not (arg-optional a)) :collect a)) (optionals (loop :for a :in command-args :if (arg-optional a) :collect a)) ;; (repeating ;; (loop :for a :in command-args ;; :if (arg-repeating a) ;; :collect a)) ;;(keyworded (or (args-keyworded command-args) pass-keys-as)) ;; (keyworded t) (new-list '())) ;; Mandatory arguments ;; (loop :for a :in mandatories :do ;; (push (symbolify (arg-name a)) new-list)) ;; This is augmented here to allow for (mostly theoretical) paralellism ;; in the let above. ;; HOW ABOUT NOT!!: ;; (setf keyworded (or keyworded ;; (and optionals repeating ;; (and (not (equal optionals repeating)) ;; (= (length optionals) 1))) ;; (> (length repeating) 1))) ;; (if keyworded (progn ;; Put in a rest argument to catch all the keys. (when pass-keys-as (push '&rest new-list) (push pass-keys-as new-list)) (push '&key new-list) ;; Mandatory arguments (loop :for a :in mandatories :do (push (symbolify (arg-name a)) new-list)) (loop :for a :in optionals :do (push (if (arg-default a) (if (arg-use-supplied-flag a) (list (symbolify (arg-name a)) (arg-default a) (symbolify (s+ (arg-name a) "-supplied-p"))) (list (symbolify (arg-name a)) (arg-default a))) (if (arg-use-supplied-flag a) ;; The default is NIL then. (list (symbolify (arg-name a)) 'NIL (symbolify (s+ (arg-name a) "-supplied-p"))) (symbolify (arg-name a)))) new-list))) #| (cond ;; If both optional and repeating, do repeating (i.e. &rest) (repeating (push '&rest new-list) ;; Must be only one repeating, else it would be keyworded. (push (symbolify (arg-name (first repeating))) new-list)) (optionals (push '&optional new-list) (loop :for a :in optionals :do (push (if (arg-default a) (if (arg-use-supplied-flag a) (list (symbolify (arg-name a)) (arg-default a) (symbolify (s+ (arg-name a) "-supplied-p"))) (list (symbolify (arg-name a)) (arg-default a))) (if (arg-use-supplied-flag a) ;; The default is NIL then. (list (symbolify (arg-name a)) NIL (symbolify (s+ (arg-name a) "-supplied-p"))) (symbolify (arg-name a)))) new-list))))) |# (nreverse new-list)))) ;; EOF
27,953
Common Lisp
.lisp
739
33.556157
91
0.669063
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
3534e4537a49859fd75c07eb81a3bc3a0f4bf6f11cd3f71ecd4d5c2bedebf82e
2,129
[ -1 ]
2,130
vars.lisp
nibbula_lish/vars.lisp
;;; ;;; vars.lisp - Variables for Lish ;;; (in-package :lish) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Versioning ;; Yet another version of versions where presumably the new "improved" build ;; script will increment it. (defparameter *version* #.(read-file-form (asdf:system-relative-pathname :lish "version.lisp"))) (let ((split-version (mapcar (_ (parse-integer _ :junk-allowed t)) (split-sequence #\. *version*)))) (defparameter *major-version* (first split-version) "Major version number. Releases with the same major version number should be compatible in the default configuration.") (defparameter *minor-version* (second split-version) "Minor version number. This should change at least for every release.") (defparameter *build-version* (third split-version) "Build version number. This should increase for every build, which probably means every dumped executable.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Misc (defparameter *shell-name* "Lish" "The somewhat superfluous name of the shell.") (defvar *shell* nil "The current shell instance.") ;; Pipeline input and output values (defvar %*input* nil "The output of the previous command in pipeline.") (defvar %*output* nil "The output of the current command.") (defun input () "The pipeline input object." %*input*) (defun output () "The pipeline output object." %*output*) (defun export-input () "Let external processes access *input*." (when (and (lish-export-pipe-results *shell*) %*input*) (setf (nos:env "LISH_INPUT") (princ-to-string %*input*)))) (defun export-output () "Let external processes access *output*." (when (and (lish-export-pipe-results *shell*) %*output*) (setf (nos:env "LISH_OUTPUT") (princ-to-string %*output*)))) (defun set-input (value) "Set the pipeline input object to VALUE." (setf %*input* value) (export-input) value) (defun set-output (value) "Set the pipeline output object to VALUE." (setf %*output* value) (export-output) value) ;; Possibly exporting *input* and *output* in the environment to sub-processes ;; when they're set is the reason for the symbol macro and functions nonsense. (defsetf input set-input) (defsetf output set-output) (define-symbol-macro *input* (input)) (define-symbol-macro *output* (output)) (define-symbol-macro *i* (input)) (define-symbol-macro *o* (output)) (defmacro with-input ((x) &body body) "Dynamicly rebind ‘*input*' to ‘x’." `(let ((%*input* ,x)) (export-input) ,@body)) (defmacro with-output ((x) &body body) "Dynamicly rebind ‘*output*' to ‘x’." `(let ((%*output* ,x)) (export-output) ,@body)) (defvar *accepts* nil "What the next command in the pipeline accepts.") (defvar *pipe-plus* nil "True to omap objects to a parenless function call.") (eval-when (:compile-toplevel :load-toplevel :execute) (defun make-user-package () (or (and (boundp '*lish-user-package*) (symbol-value '*lish-user-package*)) (find-package "LISH-USER") (make-package "LISH-USER" :use '(:cl :lish #+use-regex :regex #-use-regex :cl-ppcre :glob) :nicknames '("LU"))))) (defparameter *lish-user-package* (make-user-package) "Package for lish to hang out in. Auto-updates from :cl-user.") (defvar *junk-package* (progn (when (find-package :lish-junk) (delete-package :lish-junk)) (make-package :lish-junk)) "Package to put partial or unknown reader junk.") ;; @@@ Something else that should be in opsys? (defvar *buffer-size* (nos:memory-page-size) "General buffer size for file or stream operations.") (defparameter *options* nil "List of options defined.") (defun default-lishrc () (nos:path-append (nos:user-home) ".lishrc")) (defvar *default-lishrc* (default-lishrc) "Default value for the start up file.") (defvar *lishrc* nil "Pathname of the start up file.") (defvar *use-bracketed-paste* t "True to use safer pasting in terminals that support it.") (defvar *dont-deblarg* nil "True to not activate our debugger even if it's loaded.") ;; I really have some reservations about including this. It's somewhat ;; serendipitous that it works out this way, and it is highly efficient ;; keystroke-wise, but seems like an unorthogonal hackish trick. (defvar ! nil "The previous command, so you can say e.g.: sudo !!") ;; These are my magic cookies. I would GENSYM them, but I would like them to ;; be constant over loads or systems. (defparameter *real-eof-symbol* :Z-REAL-EOF-Z) (defparameter *continue-symbol* :Z-CONTINUE-Z) (defparameter *empty-symbol* :Z-EMPTY-Z) (defparameter *error-symbol* :Z-ERROR-Z) (defparameter *quit-symbol* :Z-QUIT-Z) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Types? (defstruct shell-expr "The result of the shell lexer. A sequence of words and their start and ~ end points in the original string." words ; sequence of objects line) ; the original string (defstruct shell-word "A word in a shell-expr." word ; an object start ; integer start position end ; integer end position quoted ; boolean, true if word quoted eval ; boolean, true to evaluate word join) ; nil :left :right or :both, to add to adjacent word ;; @@@ I'm not really sure if this is good idea yet. (defmethod print-object ((object shell-word) stream) "Print a shell-word to STREAM." (with-slots (word quoted) object (cond ((or *print-readably* *print-escape*) (call-next-method)) (quoted (format stream "\"~a\"" word)) (t (format stream "~a" word))))) (defstruct context "The context for a command. It's input and output streams and environment variables." ;; These are a stream or NIL for the default. in-pipe out-pipe ;; This is NIL for unspecified, :empty, or an alist environement. environment ;; True if we flipped *input* to *output* for a pipeline. flipped-io ;; True if we should run things in the background. background ;; True if we should map parenless function calls. pipe-plus ;; True if we should not pass the *output*. pipe-dot ;; True if we should pipe both output and error pipe-both ) (defvar *context* nil "The dynamic command context. If it is NIL it is equivalent to all the slots of the context being NIL, and so therefore equivalent to the default input, output and environment.") ;; We do a simple fake out for signals on OS's that don't really support them. (defparameter *siggy* #+windows '(("TERM" 15 terminate-process) ("STOP" 17 suspend-process) ("CONT" 19 resume-process)) #+unix (loop :for i :from 1 :below os-unix:*signal-count* :collect (list (os-unix:signal-name i) i)) "Fake windows signals.") (defparameter *signal-names* #+unix (make-array (list os-unix:*signal-count*) :initial-contents (cons "" (loop :for i :from 1 :below os-unix:*signal-count* :collect (os-unix:signal-name i)))) #+windows (mapcar #'car *siggy*) "Names of the signals.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Hooks (defvar *pre-command-hook* nil "Called before a command is run. Arguments are: COMMAND-NAME : string - The name of the command. COMMAND-TYPE : keyword - What kind of command it is.") (defvar *post-command-hook* nil "Called after a command is run. Arguments are: COMMAND-NAME : string - The name of the command. COMMAND-TYPE : keyword - What kind of command it is.") (defvar *unknown-command-hook* nil "Called when a command is not found. Arguments are the shell and the condition.") (defvar *enter-shell-hook* nil "Called when the shell starts, after loading the *lishrc*.") (defvar *exit-shell-hook* nil "Called when the shell exits.") ;; End
7,863
Common Lisp
.lisp
206
35.228155
80
0.68168
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
868a3d40602aa45090c2d452711dc112feccb945337f5fe28d06764cb625ccad
2,130
[ -1 ]
2,131
piping.lisp
nibbula_lish/piping.lisp
;;; ;;; piping.lisp - Piping for Lish ;;; ;; Piping, I/O redirection, and I/O functions that are useful for using in ;; a lish command line or script. (in-package :lish) (defun lisp-args-to-command (args &key (auto-space nil)) "Turn the arguments into a string of arguments for a system command. String arguments are concatenated together. Symbols are downcased and turned into strings. Keywords are like symbols but prefixed with '--'. Everything else is just turned into a string as printed with PRINC. If AUTO-SPACE is true, put spaces between every argument." (with-output-to-string (str) (loop :with first-time = t :for a :in args :do (when auto-space (if first-time (setf first-time nil) (princ " " str))) (typecase a (keyword ; this is sort of goofy (princ "--" str) (princ (string-downcase (symbol-name a)) str)) (symbol (princ (string-downcase (symbol-name a)) str)) (t (princ a str)))))) (defun possibly-read (expr) (typecase expr (string (shell-read expr)) (t expr))) #| ;; This needs so much work. (defun copy-stream (source destination) "Copy data from reading from SOURCE and writing to DESTINATION, until we get an EOF on SOURCE." (let ((buf (make-array *buffer-size* :element-type (stream-element-type source))) pos) (loop :do (setf pos (read-sequence buf source)) (when (> pos 0) (write-sequence buf destination :end pos)) :while (= pos *buffer-size*)))) |# (defun byte-copy-stream (source destination) "This seems like a slow thing that will only work on bivalent streams?" (loop :with b :while (setf b (read-byte source nil nil)) :do (write-byte b destination))) (defun append-files (input-files output-file &key callback) "Copy the data from ‘input-files’ appending it to ‘output-file’. Create ‘output-file’ if it doesn't exist." (with-open-file (out (quote-filename output-file) :direction :output :if-exists :append :if-does-not-exist :create :element-type '(unsigned-byte 8)) (loop :for file :in input-files :do (with-open-file (in (quote-filename file) :direction :input :element-type '(unsigned-byte 8)) (when callback (funcall callback file)) (copy-stream in out))))) ;; This is mostly for convenience from the command line (defun append-file (input-file output-file) "Copy the data from INPUT-FILE appending it to OUTPUT-FILE. Create OUTPUT-FILE if it doesn't exist." (append-files (list input-file) output-file)) (defun run-with-output-to (file-or-stream commands &key supersede append) "Run commands with output to a file or stream. COMMANDS can be a SHELL-EXPR, or a list of arguments." (when (and supersede append) (error "Can't both supersede and append to a file.")) (let ((result nil)) (multiple-value-bind (vals in-stream) (shell-eval (possibly-read commands) :context (modified-context *context* :out-pipe t)) (unwind-protect (when (and vals (> (length vals) 0)) (with-open-file-or-stream (out-stream file-or-stream :direction :output :if-exists (if supersede :supersede (if append :append :error)) :if-does-not-exist :create #+sbcl :element-type #+sbcl :default #-sbcl :element-type #-sbcl '(unsigned-byte 8) ) #+sbcl (if (and (or (eq (stream-element-type in-stream) :default) (eq (stream-element-type in-stream) 'unsigned-byte)) (or (eq (stream-element-type out-stream) :default) (eq (stream-element-type out-stream) 'unsigned-byte))) (byte-copy-stream in-stream out-stream) (copy-stream in-stream out-stream)) #-sbcl (copy-stream in-stream out-stream)) (setf result vals)) (when in-stream (close in-stream)))) result)) (defun run-with-input-from (file-or-stream commands) "Run commands with input from a file or stream. COMMANDS can be a SHELL-EXPR, or a list to be converted by LISP-ARGS-TO-COMMAND." (let ((result nil)) (with-open-file-or-stream (in-stream file-or-stream) (multiple-value-bind (vals) (shell-eval (possibly-read commands) :context (modified-context *context* :in-pipe in-stream)) (setf result vals))) result)) (defun input-line-words () "Return lines from *standard-input* as a string of words." (with-output-to-string (s) (loop :with l = nil :and first = t :while (setf l (read-line *standard-input* nil nil)) :do (if first (progn (format s "~a" l) (setf first nil)) (format s " ~a" l))))) (defun input-line-list (&optional (stream *standard-input*)) "Return lines from *standard-input* as list of strings." (loop :with l = nil :while (setf l (read-line (or stream *standard-input*) nil nil)) :collect l)) ;; @@@ trying to make it work with binary streams? ;; (defun map-output-lines (func command &key binary) ;; "Return a list of the results of calling the function FUNC with each output ;; line of COMMAND. COMMAND should probably be a string, and FUNC should take one ;; string as an argument." ;; (let (vals stream) ;; (unwind-protect ;; (progn ;; (multiple-value-setq (vals stream) ;; (shell-eval (possibly-read command) ;; :context (modified-context *context* :out-pipe t))) ;; (when (and vals (> (length vals) 0)) ;; (loop ;; :with l = nil ;; :and str = (if binary ;; (make-instance 'utf8b-stream:utf8b-input-stream ;; :input-stream stream) ;; stream) ;; :while (setf l (read-line str nil nil)) ;; :collect (funcall func l)))) ;; (when stream ;; (close stream))))) (defun map-output-lines (func command) "Return a list of the results of calling the function ‘func’ with each output line of ‘command’. ‘command’ should probably be a string, and ‘func’ should take one string as an argument." (let (vals stream) (unwind-protect (progn (multiple-value-setq (vals stream) (shell-eval (possibly-read command) :context (modified-context *context* :out-pipe t))) (when (and vals (> (length vals) 0)) (loop :with l = nil :while (setf l (read-line stream nil nil)) :collect (funcall func l)))) (when stream (close stream))))) ;; This is basically backticks #\` or $() in bash. (defun command-output-words (command &optional quoted) "Return lines output from command as a string of words." (labels ((convert-to-words (in-stream out-stream) (loop :with l = nil :and first-time = t :while (setf l (read-line in-stream nil nil)) :do (format out-stream (if quoted "~:[~; ~]\"~a\"" "~:[~; ~]~a") (not first-time) l) (setf first-time nil)))) (with-output-to-string (s) (let (vals stream) (unwind-protect (progn (multiple-value-setq (vals stream) (shell-eval (possibly-read command) :context (modified-context *context* :out-pipe t))) (when (and vals (> (length vals) 0)) (convert-to-words stream s))) (when stream (close stream))))))) (defun command-output-list (command) "Return lines output from command as a list." (map-output-lines #'identity command)) (defun pipe (&rest commands) "Send output from commands to subsequent commands." (labels ((sub (cmds &optional in-stream) (let (vals stream) (unwind-protect (progn (multiple-value-setq (vals stream) (shell-eval (possibly-read (car cmds)) :context (modified-context *context* :in-pipe in-stream :out-pipe (and (cadr cmds) t)))) (if (and vals (listp vals) (> (length vals) 0)) (if (cdr cmds) (apply #'pipe stream (cdr cmds)) (values-list vals)) nil)) (when (and stream (open-stream-p stream)) (finish-output stream) (close stream)))))) (if (streamp (car commands)) (sub (cdr commands) (car commands)) (sub commands)))) ;; @@@ This doesn't really work the way I'd like because backgrounding of ;; compound commands needs some redesign. Or more like a total re-write. (defun in-bg (expr) "Evaluate EXPR in the background. If it's a string, evaluate it as shell command in the background. If it's something else, evaluate it as a lisp expression in a separagte thread, if threads are supported." (typecase expr (string (shell-eval (shell-read expr) :context (modified-context *context* :background t))) (t (shell-eval `(progn ,expr) :context (modified-context *context* :background t))))) (defun in-pipe-p () "Return true if we have a pipeline as input." (when (and *shell* *context*) (and (context-in-pipe *context*) t))) (defun out-pipe-p () "Return true if we have a pipeline as output." (when (and *shell* *context*) (and (context-out-pipe *context*) t))) (defgeneric input-source-p (thing) (:documentation "Return true if ‘thing’ could be an input source.") (:method ((thing stream)) (input-stream-p thing)) (:method ((thing pathname)) (nos:file-exists thing)) (:method ((thing string)) (nos:file-exists thing)) (:method ((thing vector)) (equal (array-element-type thing) '(unsigned-byte 8)))) #| (defun input-source-p (thing) "Return true if ‘thing’ could be an input source." (or (and (streamp thing) (input-stream-p thing)) (and (or (pathnamep thing) (stringp thing)) (nos:file-exists thing)) ;; as string stream (stringp thing) ;; as byte array (and (vectorp thing) (equal (array-element-type thing) '(unsigned-byte 8))))) |# (defun as-input-stream (thing) "Make an input stream out of ‘thing’." (etypecase thing (stream thing) ;; assuming it's an input stream (pathname (open thing :direction :input)) (string (if (nos:file-exists thing) ;; (open thing :direction :input) (open (quote-filename thing) :direction :input) (make-string-input-stream thing))) #| @@@ finish bi-valent-streams or os-streams? (vector (make-bivalent-stream thing)) |# )) (defmacro with-streamlike-input ((arg &key use-stdin) &body body) "Allow a command to take stream-like input, getting the input from the argument ‘arg’, or from the the shell input ‘*input*’. Set ‘arg’ to be an input stream, or NIL if we can't." (with-names (arg-value used-stdin) `(let ((,arg-value ,arg) ,used-stdin) (unwind-protect (progn (setf ,arg (cond ((and (null ,arg-value) (and *input* (input-source-p *input*))) (as-input-stream *input*)) ((and ,arg-value (input-source-p ,arg-value)) (as-input-stream ,arg-value)) (,use-stdin (setf ,used-stdin t) *standard-input*))) ,@body) (when (and ,arg (streamp ,arg) (not ,used-stdin)) (close ,arg)))))) (defgeneric possible-file-name-p (thing) (:documentation "Return true if ‘thing’ could be a file name.") (:method (thing) (declare (ignore thing)) nil) (:method ((thing pathname)) t) (:method ((thing os-pathname)) t) (:method ((thing string)) t) (:method ((thing vector)) (equal (array-element-type thing) '(unsigned-byte 8)))) ;; This is useful for commands which want to take a list of files as an argument ;; or as *input*. (defmacro with-files-or-input ((arg &key on-unknown-input-type arg-list) &body body) "Evaluate ‘body’ adding ‘*input*’ to ‘arg’ if it could be a file or list of files. ‘arg’ should probably be the name of command argument that could be a list of files. If ‘arg-list’ is given, it is the name of the command argument plist, as provided to :args-as, and ‘arg’ is the keyword." (let ((place (if arg-list `(getf ,arg-list (keywordify ,arg)) arg))) `(block nil (cond ((possible-file-name-p lish:*input*) (push lish:*input* ,place)) ((consp lish:*input*) ;; We only check first item, but whatever. (when (possible-file-name-p (first lish:*input*)) (setf ,place (append lish:*input* ,place)))) (t ;; What to do for *input* that we can't determine is a file name. ;; By default, just ignore it. ,on-unknown-input-type)) ,@body))) ;; (defun spread (command &rest commands) ;; "Send output from a command to multiple commands in parallel." ;; ) ;; (defun gather (command &rest streams) ;; "Gather multiple streams and send them in order to a command." ;; ) ;; (defvar *files-to-delete* '() ;; "A list of files to delete at the end of a command.") ;; ;; ;; This has a lot of potential problems / security issues. ;; (defun != (&rest commands) ;; "Temporary file name output substitution." ;; (multiple-value-bind (vals stream) ;; (shell-eval (possibly-read commands) ;; :context (modified-context *context* :out-pipe t)) ;; (if (and vals (> (length vals) 0)) ;; (let ((fn (nos:mktemp "lish"))) ;; (push fn *files-to-delete*) ;; (with-posix-file (fd fn (logior O_WRONLY O_CREAT O_EXCL) #o600) ;; (let ((buf (make-string (buffer-size)))) ;; (loop :while (read-sequence buf stream) ;; (progn ;; (close stream) ;; nil)))) (defun run-with-env (env-alist args) "Run a shell command with environement variables as specified in ‘env-alist’." (with-shell () (shell-eval (possibly-read args) :context (modified-context *context* :environment env-alist)))) ;; Most of the ! functions are wrapped in with-shell so they should be able to ;; be used outside of an interactive shell. (defun ! (&rest args) "Evaluate the shell command." (with-shell () (shell-eval (shell-read (lisp-args-to-command args))))) (defun unix-truthy (value) "If the result is number, 0 is T and anything else is NIL. If the result isn't a number, only NIL is false, as usual." (cond ((numberp value) (zerop value)) (t (and value t)))) (defun !? (&rest args) "Evaluate the shell command, converting a Unix shell result code into boolean. This means that if the result is number, 0 is T and anything else is NIL. If the result isn't a number, only NIL is false, as usual." (with-shell () (let ((result (shell-eval (shell-read (lisp-args-to-command args))))) (cond ((numberp result) (zerop result)) (t (and result t)))))) (defun !$ (&rest command) "Return lines output from command as a string of words. This is basically like $(command) in bash." (with-shell () (command-output-words (lisp-args-to-command command)))) (defun !$$ (&rest command) "Return lines of output from command as a string of quoted words." (with-shell () (command-output-words (lisp-args-to-command command) t))) (defun !@ (&rest command) "Return the output from command, broken into words by the shell reader." (with-shell () (shell-words-to-list (lish::shell-expr-words (shell-read (!- command)))))) ;; @@@ What about something like: ;; (defmacro !q (&rest args) ;; `(!@ ,@(loop :for a :in args :collect ;; (typecase a ;; (symbol (string-downcase a)) ;; (string (s+ #\" a #\")) ;; (t a))))) ;; ;; @@@ or even ;; (defmacro !qq (&rest args) ;; `(!@ ,@(loop :for a :in args :collect ;; (typecase a ;; (symbol (if (boundp a) ;; (symbol-value a) ;; (string-downcase a))) ;; (string (s+ #\" a #\")) ;; (t a))))) ;; @@@ How about this? ;; Consider how something like this could be integrated into all the other ;; normal macros? This doesn't have all the return value options. (defmacro !q (&rest args) "Simpler shell quotation. Make a shell command out of the separate words of the downcased symbols. If a symbol starts with a ‘@’ character, than it will probably be evaluated. Lists or anything else, get passed as is. For example, you can say: (loop for f in (glob \"*.cl\") do (!q mv -i @f (s+ (remove-suffix f \".cl\") \".lisp\"))) instead of having to deal with string quoting, like: (loop for f in (glob \"*.cl\") do (! \"mv -i \\\"\" f \"\\\" \" (s+ (remove-suffix f \".cl\") \".lisp\"))) " `(!= ,@(loop :for a :in args :collect (typecase a (symbol (if (and (> (length (symbol-name a)) 1) (char= #\@ (char (symbol-name a) 0))) (symbolify (subseq (symbol-name a) 1)) (string-downcase a))) (string (s+ #\" a #\")) (t a))))) (defun !_ (&rest command) "Return a list of the lines of output from the command." (with-shell () (command-output-list (lisp-args-to-command command)))) (defun !- (&rest command) "Return a string containing the output from the command." (with-shell () (with-output-to-string (str) (run-with-output-to str (lisp-args-to-command command))))) (defun !and (&rest commands) "Run commands until one fails. Return the last result." (let (result) (loop :for c :in commands :while (unix-truthy (setf result (shell-eval (shell-read c))))) result)) (defun !or (&rest commands) "Run commands until one succeeds. Return the last result." (let (result) (loop :for c :in commands :until (unix-truthy (setf result (shell-eval (shell-read c))))) result)) ;; (defun !bg (&rest commands) ;; "Run commands in the background." ;; (declare (ignore commands)) ;; ) (defun !! (&rest commands) "Pipe output of commands. Return a stream of the output." (with-shell () (multiple-value-bind (vals stream) (shell-eval (shell-read (lisp-args-to-command commands)) :context (modified-context *context* :out-pipe t)) (if (and vals (> (length vals) 0)) stream (progn (close stream) nil))))) (defun !> (file-or-stream &rest commands) "Run commands with output to a file or stream." (with-shell () (run-with-output-to file-or-stream (lisp-args-to-command commands)))) (defun !>> (file-or-stream &rest commands) "Run commands with output appending to a file or stream." (declare (ignore file-or-stream commands)) ) (defun !<> (file-or-stream &rest commands) "Run commands with input and output to a file or stream." (declare (ignore file-or-stream commands)) ) (defun !>! (file-or-stream &rest commands) "Run commands with output to a file or stream, superseding it." (run-with-output-to file-or-stream commands :supersede t)) (defun !>>! (file-or-stream &rest commands) "Run commands with output appending to a file or stream, overwritting it." (declare (ignore file-or-stream commands)) ) (defun !< (file-or-stream &rest commands) "Run commands with input from a file or stream." (with-shell () (run-with-input-from file-or-stream (lisp-args-to-command commands)))) (defun !!< (file-or-stream &rest commands) "Run commands with input from a file or stream and return a stream of output." (with-shell () (with-open-file-or-stream (in-stream file-or-stream) (multiple-value-bind (vals stream) (shell-eval (shell-read (lisp-args-to-command commands)) :context (modified-context *context* :out-pipe t :in-pipe in-stream)) (if (and vals (> (length vals) 0)) stream (progn (close stream) nil)))))) (defun !h (n) "Return the N-th history item as a string. If N is positive it counts from the beginning of history. If N is negative it counts backward from the most recent." (rl:history-entry-line (rl:history-nth n))) (defun !hh (n) "Return the N-th history item, as a history entry object. If N is positive it counts from the beginning of history. If N is negative it counts backward from the most recent." (rl:history-nth n)) (defun !v (n) "Return the N-th history result values list. If N is positive it counts from the beginning of history. If N is negative it counts backward from the most recent." (getf (rl:history-entry-extra (rl:history-nth n)) :values)) (defsetf !v (n) (new-values) `(setf (getf (rl:history-entry-extra (rl:history-nth ,n)) :values) ,new-values)) ;; @@@ What about !h as a complex executed command object? ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; literal arg comands (= suffix) (defun != (&rest args) "Run a command with the separate verbatim arguments, without shell syntax." (with-shell () (shell-eval (expr-from-args args)))) (defun !?= (&rest args) "Evaluate the shell command, converting the system result code into boolean. This means the 0 is T and anything else is NIL." (with-shell () (let ((result (shell-eval (expr-from-args args)))) (and (numberp result) (zerop result))))) (defun !$= (&rest command) "Return lines output from command as a string of words. This is basically like $(command) in bash." (with-shell () (command-output-words (expr-from-args command)))) (defun !$$= (&rest command) "Return lines of output from command as a string of quoted words." (with-shell () (command-output-words (expr-from-args command) t))) (defun !@= (&rest command) "Return the output from command, broken into words by the shell reader." (with-shell () (shell-words-to-list (lish::shell-expr-words (shell-read (with-output-to-string (str) (run-with-output-to str (expr-from-args command)))))))) (defun !_= (&rest args) "Return a list of the lines of output from the command." (with-shell () (command-output-list (expr-from-args args)))) (defun !-= (&rest command) "Return a string containing the output from the command." (with-shell () (with-output-to-string (str) (run-with-output-to str (expr-from-args command))))) (defun !!= (&rest commands) "Pipe output of commands. Return a stream of the output." (with-shell () (multiple-value-bind (vals stream) (shell-eval (expr-from-args commands) :context (modified-context *context* :out-pipe t)) (if (and vals (> (length vals) 0)) stream (progn (close stream) nil))))) ;; EOF
21,874
Common Lisp
.lisp
574
34.120209
81
0.658815
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
c481758b09a28a60fb5f6265a148c11fa3729dce072bf4fed716bf5d3de04ce6
2,131
[ -1 ]
2,132
complete.lisp
nibbula_lish/complete.lisp
;;; ;;; complete.lisp - Completion for Lish ;;; (in-package :lish) ;; (defun quoted-start (str pos) ;; "Check if we are inside a shell quoted string and return it's starting ;; position." ;; ( (defun complete-env-var (str all) ;; (complete-string-sequence ;; str all (mapcar #'(lambda (x) (string (car x))) (nos:environment)))) (complete-list str (length str) all (append (fake-var-list) (mapcar #'(lambda (x) (string (car x))) (nos:environment))))) (defun complete-user-name (str all) (let ((result (complete-list str (length str) all (mapcar (_ (nos:user-info-name _)) (nos:user-list))))) ;; Put a trailing directory separator on it, it it exists. (when (and (completion-result-unique result) (file-exists (expand-tilde (s+ #\~ (completion-result-completion result))))) (setf (completion-result-completion result) (s+ (completion-result-completion result) nos:*directory-separator*))) result)) (defvar *verb-list* nil "List of current lish commands. Includes aliases, built-in commands, and ~ exectuables in the path. Use the \"rehash\" command to update after new ~ commands are added.") #+nil (progn ;; Unused code for better verb list caching (defun probe-file-or-dir (p) (or (probe-directory p) (probe-file p))) (defvar *last-update* nil "An alist of (:<facility> . <time-code>) for storing last time we updated the *VERB-LIST* for various facilites. The structure of <time-code> depends on the facility. Usually it's a universal-time, or an alist of (<thing> . <time>).") (defun verb-list-needs-upadating-p () (with-spin () (loop :for dir :in (split-sequence nos:*path-separator* (nos:environment-variable *path-variable*)) :do (spin) :if (probe-directory dir) :append (loop :for f :in (nos:read-directory :dir dir :full t :omit-hidden t) :if (without-access-errors (is-executable (s+ dir *directory-separator* (nos:dir-entry-name f)))) :collect (nos:dir-entry-name f))))) (defun update-verb-thing (thing) (ecase thing (:aliases) (:commands) (:path)) ) ) (defun verb-list (shell) "Return the command list for the current shell: *shell*." (if (not *verb-list*) (setf *verb-list* (with-spin () (locally #+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note)) (sort (remove-duplicates (append (loop :for k :being :the :hash-keys :of (shell-aliases shell) :collect k) (loop :for k :being :the :hash-keys :of (lish-commands) :do (spin) :collect k) (loop :for dir :in (split-sequence nos:*path-separator* (nos:environment-variable *path-variable*)) :do (spin) :if (probe-directory dir) :append (loop :for f :in (nos:read-directory :dir dir :full t :omit-hidden t) :if (without-access-errors (is-executable (s+ dir *directory-separator* (nos:dir-entry-name f)))) :collect (nos:dir-entry-name f)))) :test #'equal) #'string<)))) *verb-list*)) (defun complete-command (str all) ; (complete-string-sequence str all (verb-list *shell*) (complete-list str (length str) all (verb-list *shell*))) ;; This is mostly like complete-symbol but it handles the ! at the beginning. ;; XXX Uses completion internals. (defun complete-bang-symbol (context pos all) "Completion function for symbols (preceded by ! in the shell)." (let* ((word-start (scan-over-string context pos :backward :not-in completion::*lisp-non-word-chars*)) (word (subseq context word-start pos)) (pack nil) (external nil)) (dbugf 'completion "bang completion: word-start ~s word ~s~%" word-start word) (when (and (plusp (length word)) (eql #\! (aref word 0))) (setf word (subseq word 1) word-start (1+ word-start))) (multiple-value-setq (pack external) (completion::find-back-pack context word-start)) (if all (completion::symbol-completion-list word :package pack :external external) (let ((result (completion::symbol-completion word :package pack :external external))) (setf (completion-result-insert-position result) word-start) result)))) (defun shell-complete-symbol (context pos all &optional bang-p) "Complete symbols in the *lish-user-package*, optionally with a preceding exclamation point '!' ." (with-package *lish-user-package* (if bang-p (complete-bang-symbol context pos all) (complete-symbol context pos all)))) ;; Things in here: ;; quote char: \ ;; word separation: #\space ;; history / variable expansion: ! ;; lisp expression expansion: , ;; environment variable expansion: $ ;; piping: | (maybe should also '&' and '^' ?) ;; comment char: ; ;; glob chars: []*? ;; parens (evaluation): () ;; Note that backslash '\' must be first in this list, since otherwise you will ;; get doubled backslashes. (defparameter *quote-needing-chars* "\\ !,$|;[]*?()" "Characters that may need quoting in shell syntax, like if they are in a file name, so they don't get interpreted by the shell.") (defun quotify (string &key exceptions) "Put a backslash in front of any character in ‘string’ that might not be intrepreted literally in shell syntax. ‘exceptions’ is a sequence of character position not to quote." (let ((result string)) (labels ((char-loop (str) (let ((i 0)) (omapn (_ (when (and (oposition _ *quote-needing-chars*) (or (not exceptions) (not (position i exceptions)))) (princ #\\ str)) (princ _ str) (incf i)) result)))) (typecase string (string (with-output-to-string (str) (char-loop str))) (fat-string (with-output-to-fat-string (str) (char-loop str))))))) ;; perhaps would be faster with position and subseq? (defun de-quotify (string) "Convert double backslashes into a single backslash." (with-output-to-string (str) (let* ((len (length string)) (i 0)) (loop :while (< i (1- len)) :do (when (and (char= (char string i) #\\) (char= (char string (1+ i)) #\\)) (incf i)) (write-char (char string i) str) ;;(setf (char output o) (char string i)) (incf i)) (when (< i len) (write-char (char string i) str) )))) ;; (defun words-past (expr pos) ;; "Return how many words the position POS is past in EXPR." ;; (let ((past 0)) ;; (loop ;; :for i = 0 :then (1+ i) ;; :for w :in (shell-expr-words expr) ;; :do (when (> pos (shell-word-end w)) ;; (setf past (1+ i)))) ;; past)) (defun words-past (expr pos) (multiple-value-bind (word num) (find-shell-word expr pos) (declare (ignore word)) (or num -1))) ;; (let ((num (shell-word-num expr ;; ;; (min pos ;; ;; (length (shell-expr-line expr))) ;; pos))) ;; (or (and num (1- num)) 0))) (defun first-word-in-expr (expr pos) "Find the first word of pipeline where POS is in a shell expr." (let ((w (first (shell-expr-words expr))) (w2 (second (shell-expr-words expr)))) (cond ((stringp w) w) ((shell-word-p w) (if (>= pos (shell-word-start w)) w nil)) ; We couldn't find it? ((and (consp w) (member (car w) '(:pipe :pipe-plus :pipe-dot))) (if (and w2 (shell-word-p w2) (>= pos (shell-word-start w2))) w2 (first-word-in-expr (second w) pos)))))) (defun term-cols () "Return the terminal columns." (terminal-window-columns (rl:line-editor-terminal (lish-editor *shell*)))) (defun list-arg-choices (command doc choices) (let* (;; (cols (term-cols)) (prefix-str (s+ (if (>= *completion-count* 1) (s+ (documentation command 'function) #\newline) (s+ (posix-synopsis command) #\newline)) (or doc "") #\newline)) (comp-list (or choices (list "")))) ;; (with-output-to-string (str) ;; (print-columns choices ;; :stream str ;; :columns cols))) ;; "")))) ;; Trim possible trailing newline? ;; (when (eql (char out-str (1- (length out-str))) #\newline) ;; (setf out-str (subseq out-str 0 (1- (length out-str))))) ;;(make-completion-result :completion (list out-str) :count 1))) (make-completion-result :completion comp-list :count (length comp-list) :prefix prefix-str))) (defun show-dash-arglist (arglist) (let ((result (make-stretchy-string 200))) (with-output-to-string (str result) (output-table (make-table-from (loop :for a :in arglist :when (and (arg-short-arg a) (not (arg-hidden a))) :collect (list (s+ " -" (arg-short-arg a)) (s+ (or (and (slot-boundp a 'help) (substitute #\space #\newline (arg-help a))) (arg-name a)) (if (arg-default a) (s+ " [" (arg-default a) "]") ""))) :when (and (arg-old-long-arg a) (not (arg-hidden a))) :collect (list (s+ " -" (arg-old-long-arg a)) (s+ (or (and (slot-boundp a 'help) (substitute #\space #\newline (arg-help a))) (arg-name a)) (if (arg-default a) (s+ " [" (arg-default a) "]") "")))) :columns '((:name "Arg") (:name "desc" :align :wrap))) (make-instance 'text-table-renderer) str :trailing-spaces nil :print-titles nil :max-width (term-cols))) (setf result (rtrim result)) ;; Get rid of the final newline (when (and (> (length result) 0) (char= #\newline (aref result (- (length result) 1)))) ;; (setf (fill-pointer result) (- (length result) 2)) (setf (fill-pointer result) (- (length result) 1))) (make-completion-result :completion (list result) :count 1))) (defvar *long-double-dash-help* nil "True to show longer help for double dash arguments.") (defun show-double-dash-arglist (arglist) (let ((result (make-stretchy-string 200))) (with-output-to-string (str result) (output-table (make-table-from (loop :for a :in arglist :when (and (arg-long-arg a) (not (arg-hidden a))) :collect (if *long-double-dash-help* (list (s+ "--" (arg-long-arg a)) (arg-default a) (string-downcase (arg-type a)) (or (and (slot-boundp a 'help) (arg-help a)) (arg-name a))) (list (s+ "--" (arg-long-arg a)) (or (and (slot-boundp a 'help) (substitute #\space #\newline (arg-help a))) (format nil "~s ~(~a~)" (arg-default a) (arg-type a)))))) :columns '((:name "Arg" :align :overflow) (:name "desc" :align :wrap))) (make-instance 'text-table-renderer) str :trailing-spaces nil :print-titles nil :max-width (term-cols))) (setf result (trim result)) ;; Get rid of the final newline (when (and (> (length result) 0) (char= #\newline (aref result (- (length result) 1)))) (setf (fill-pointer result) (- (length result) 2))) (make-completion-result :completion (list result) :count 1))) (defun complete-double-dash-arglist (word pos arglist) (dbugf 'completion "word = ~s pos = ~s~%" word pos) (complete-list ;; (subseq word 2) (- pos 2) nil word pos nil (loop :for a :in arglist :if (arg-long-arg a) :collect (s+ "--" (arg-long-arg a))))) (defun complete-dash-arglist (word pos arglist) (dbugf 'completion "word = ~s pos = ~s~%" word pos) (complete-list ;; (subseq word 2) (- pos 2) nil word pos nil (loop :for a :in arglist :if (arg-old-long-arg a) :collect (s+ "-" (arg-old-long-arg a))))) (defun first-mandatory-or-non-flag-arg (past arglist) (or (loop :with i = 0 :for a :in arglist :do ;;(format t "~a ~a ~s~%" i (>= i (1- past)) a) (when (and (>= i (1- past)) (not (arg-optional a))) (return-from first-mandatory-or-non-flag-arg a)) (incf i)) ;; @@@ Unfortunately this makes the wrong choice for non-boolean ;; args. It should only pick a non-boolean arg which has a flag if we ;; are past the flag, but the simple numeric PAST count can't indicate ;; that. I'm not really sure what a workable way to patch this is. This ;; really shows how I need to totally redesign the argument code to do ;; proper parsing. Then we can reliably show what are the choices from a ;; given parse state. (loop :with i = 0 :for a :in arglist :do ;;(format t "~a ~a ~s~%" i (>= i (1- past)) a) (when (and (>= i (1- past)) (not (and (or (arg-short-arg a) (arg-long-arg a) (arg-old-long-arg a)) (eq (arg-type a) 'boolean)))) (return-from first-mandatory-or-non-flag-arg a)) (incf i)) (nth (max 0 (1- past)) arglist))) (defun flag-arg-p (arg) (and (or (arg-short-arg arg) (arg-long-arg arg) (arg-old-long-arg arg)) (not (eq (arg-type arg) 'boolean)))) #| (defun what-next (command expr pos) (let ((unused (copy-seq (command-arglist command))) used previous-flaged-arg) (loop :for word :in (cdr (mapcar #'word-word (shell-expr-words expr))) :do (loop :for a :in (command-arglist command) :do (cond ((and (flag-arg-p a) (or (string-equal word (s+ "-" (arg-short-arg a))) (string-equal word (s+ "--" (arg-long-arg a))))) (setf previous-flaged-arg a) (return)) ((and (arg-optional |# (defun shell-complete-quoted (func word position all &key parsed-exp) "Complete a thing that needs quoting, using the completion function FUNC." (declare (ignore parsed-exp)) (make-fake-var-table) ;; Include our fake-vars in with real env vars. (let* ((*filename-completion-value-funcs* `(,#'fake-var ,#'nos:env)) ;; Make some stupid chars be allowed variable names. (*filename-completion-value-allowed* (_ (or (alphanumericp _) (char= _ #\_) (position _ *fake-var-single-chars*)))) ;; Try not to quote the $ in vars, but do quote them in file names. (exceptions (with-collecting () (let ((i 0)) (omapn (_ (when (oposition _ *quote-needing-chars*) (collect i)) (incf i)) word)))) (result (funcall func (de-quotify word) position all))) (when (and result (completion-result-completion result) (ostringp (completion-result-completion result))) (setf (completion-result-completion result) (quotify (completion-result-completion result) :exceptions exceptions))) result)) (defun shell-complete-filename (word position all &key parsed-exp) "A version of complete-filename which does the right thing for the shell." (declare (ignore parsed-exp)) (shell-complete-quoted #'complete-filename word position all)) (defun shell-complete-directory (word position all &key parsed-exp) "A version of complete-directory which does the right thing for the shell." (declare (ignore parsed-exp)) (shell-complete-quoted #'complete-directory word position all)) ;; Note that this takes different args than a normal completion function. (defun complete-command-arg (context command expr pos all &optional word-num shell-word word-pos) "Complete a command argument." (let* ((past (words-past expr pos)) ;; (past (or (shell-word-num expr ;; ;; (min pos ;; ;; (length (shell-expr-line expr))) ;; pos) 0)) (word (word-word shell-word)) (fake-word (or word "")) ;;; (arg (nth (1- past) (command-arglist command))) (arg (first-mandatory-or-non-flag-arg past (command-arglist command))) (func (and arg (arg-completion-function arg)))) (dbugf 'completion "command arg : context = ~s pos = ~s fake-word = ~s~%~ shell-word = ~s word-num = ~s word-pos = ~s arg = ~s ~ func = ~s~%" context pos fake-word shell-word word-num word-pos arg func) (cond ((and shell-word (> word-pos 1) ;;; (char= (char word (1- word-pos)) #\-) ;;; (char= (char word (- word-pos 2)) #\-)) (is-flag-char (char word 0)) (is-flag-char (char word 1))) ;; double dash args (if all (show-double-dash-arglist (command-arglist command)) (progn (complete-double-dash-arglist word word-pos (command-arglist command))))) ((and all word-pos (> word-pos 0) ;;(is-flag-char (char word (1- (min word-pos (length word))))) (is-flag-char (char word 0))) ;; dash arg enumeration (show-dash-arglist (command-arglist command))) ((and (not all) word-pos (> word-pos 0) (is-flag-char (char word 0))) (complete-dash-arglist word word-pos (command-arglist command))) (func (dbugf 'completion "---> (~a ~s ~s ~s )~%" func fake-word (length fake-word) all) ;; I don't want to make all the arg completion functions have to use ;; completion-result, but will this suffice? Or will it lose something? ;; @@@ (let ((result (funcall func fake-word (length fake-word) all :parsed-exp expr))) (if (completion-result-p result) result (make-completion-result :completion result :count (length result) ;; @@@ redundant? )))) (t (let ((doc (and arg (documentation (type-of arg) 'type))) (choices (and arg (argument-choices arg)))) (let ((*print-lines* 10)) (dbugf 'completion "not dash or func : wazzup?~%~ fake-word = ~s choices = ~w ~%" fake-word choices)) (if all (progn #| (print-values* (command expr pos all word-num word)) |# (dbugf 'completion "show all : ummm... past = ~a~%" past) (if (and (= past 1) (not word-num)) (progn (dbugf 'completion "snoo ~a? words-past ~a~%" command past) (list-arg-choices command doc choices)) (progn (if (and fake-word choices) (complete-list fake-word (length fake-word) all choices) (shell-complete-filename fake-word pos all))))) (progn (dbugf 'completion "not all : fake-word ~s" fake-word) (if choices (complete-list fake-word (length fake-word) all choices) (shell-complete-filename fake-word pos all))))))))) (defun start-of-a-compound-p (expr pos) "Return true if we are at the start of the last compound command." (and (= (length (shell-expr-words expr)) 1) (consp (first (shell-expr-words expr))) (keywordp (first (first (shell-expr-words expr)))) (>= pos (length (shell-expr-line expr))))) (defun in-command-position-p (expr word-num pos) (or ;; first word in a line (= word-num 0) ;; first word after a compound command (and (= (length (shell-expr-words expr)) 2) (consp (first (shell-expr-words expr))) (keywordp (first (first (shell-expr-words expr)))) (= word-num 1) (or (in-word (elt (shell-expr-words expr) 1) pos) (> pos (length (shell-expr-line expr))))))) (defun try-command (command-name) "See if we can dig up the dirt on a command named COMMAND. Uses the first available of: - an already loaded command - a command which we load by the normal command path mechanism - a pre-defined external command, from an external command cache - a mined external command" (assert command-name) ; Don't be calling this with NIL. (assert (stringp command-name)) ; or some crap (let ((command (get-command command-name))) (typecase command (autoloaded-command (load-lisp-command-from command-name (command-load-from command) :silent (lish-autoload-quietly *shell*)) (get-command command-name)) (command command) (null (or (and (or (not *shell*) (lish-autoload-from-asdf *shell*)) (in-lisp-path command-name) (load-lisp-command command-name :silent (lish-autoload-quietly *shell*)) (get-command command-name)) ;;(and (load-external-command command) (get-command command)) (and (option "command-mining") (mine-command command-name :quietly t) (get-command command-name))))))) (defun first-command-of (word) (cond ((and (consp word) (member (car word) '(:redirect-from :redirect-to))) (first-command-of (cadr word))) ((typep word 'shell-word) (first-command-of (shell-word-word word))) ((typep word 'shell-expr) (first-command-of (first (shell-expr-words word)))) ;; ((stringp word) ;; word) (t ;; some other thing?? word))) (defun get-backward-word-symbol (type string position &key bang-p) "Get a symbol prior to POSITION in STRING. If BANG-P is true, ignore a leading exclamation point '!'. Return the TYPE given, the symbol as a string, the package, and boolean indicating if the package was with the external notation." (let* ((word-start (scan-over-string string position :backward :not-in completion::*lisp-non-word-chars*)) (word (subseq string word-start position)) (package nil) (external nil)) (when (and bang-p (plusp (length word)) (eql #\! (aref word 0))) (setf word (subseq word 1) word-start (1+ word-start))) (multiple-value-setq (package external) (completion::find-back-pack string word-start)) (values type word package external))) ;; @@@ consider consolidation of this and what's in colorize-expr ;; @@@ or just wait until parse (defun guess-word-before (string position) "Try to guess what the word before POSTION in STRING is. First value is a keyword indicating the type, which is one of: :symbol :bang-symbol :string :command :filename :command-or-symbol :unknown :environment-variable :user-name Second value is the word as a string. Third and fourth values depend on the type. Sorry you'll have to figure it out yourself." (let (exp explanation) (multiple-value-setq (exp explanation) (ignore-errors (shell-read (subseq string 0 position) :partial t :package *junk-package*))) (etypecase exp (keyword (cond ;; Couldn't read a whole expression. ((eq exp *continue-symbol*) ;; If it's not something we know about, it's probably a bug. (ecase (car explanation) (lisp-expr ; an incomplete lisp expression ;; (cdr explanation) should be the expr? (get-backward-word-symbol :symbol string position)) (bang-expr ; an incomplete !lisp expression ;; (cdr explanation) should be the expr? (get-backward-word-symbol :bang-symbol string position :bang-p t)) (string ; an unclosed string (let ((word (de-quotify (second explanation))) (position (third explanation))) (values :string word position))) (compound ; a compound connector with nothing after it (case (cadr explanation) ((:pipe :and :or :sequence) (values :command "")) ((:redirect-to :redirect-from :append-to) (values :filename "")))))) (t ;; This is probably a bug. (error "Unknown keyword returned from shell-read.")))) (cons (get-backward-word-symbol :symbol string position)) (shell-expr (let* ((shell-word (shell-word-at exp position)) (word (and shell-word (word-word shell-word))) (word-num (word-word (shell-word-num exp position))) (first-word (word-word (first-word-in-expr exp position))) #| word-pos |#) ;; word is the text of the word ;; word-pos is the relative position in the word ;; (when shell-word ;; (setf word-pos (- position (shell-word-start shell-word)))) (cond ((or (and (not word) (zerop position)) (start-of-a-compound-p exp position)) ;; no words (values :command "")) ((not word) (if (= 0 (length (shell-expr-words exp))) ;; probably () (progn (dbugf 'completion "not in a word, empty list : bogo~%") (get-backward-word-symbol :symbol string position)) ;; a blank spot somewhere in the line (values :command-or-symbol first-word ;; (shell-word-start shell-word) position ))) ((symbolp word) (dbugf 'completion "symbol word : janky~%") (get-backward-word-symbol :symbol string position)) ((consp word) ; (foo) (dbugf 'completion "junky~%") (get-backward-word-symbol :symbol string position)) ((not (stringp word)) ;; We don't know how to complete it. ;; Of course we could implement completion for random typed ;; objects, like with a method, but what would that be like? ;; We could error here, that's probably just annoying. (dbugf 'completion "word of weird type ~s ~s~%" word (type-of word)) (values :unknown (type-of word) word)) ((zerop (length word)) (dbugf 'completion "empty word~%") ;; It's probably !() or something so just list the symbols. (get-backward-word-symbol :symbol string position)) ((eql (aref word 0) #\() ; (foo (dbugf 'completion "half baka~%") (get-backward-word-symbol :symbol string position)) ((eql (aref word 0) #\!) ; !foo (get-backward-word-symbol :symbol string position :bang-p t)) ((eql (aref word 0) #\$) ; $foo (values :environment-variable (subseq word 1) (1+ (shell-word-start shell-word)))) ((and (eql (aref word 0) #\~) ; ~foo (valid-user-name (subseq word 1))) (values :user-name (subseq word 1) (1+ (shell-word-start shell-word)))) ;; first word, when not starting with directory chars ((and (in-command-position-p exp word-num position) (not (position (aref word 0) "/.~"))) (dbugf 'completion "first word, non path : jinky~%") ;; (get-backward-word-symbol :symbol string position)) ;; try commands (values :command-or-symbol first-word (shell-word-start shell-word))) (t (values :command-or-symbol first-word position)))))))) (defun shell-complete (context pos all) (declare (type string context)) "Analyze the context and try figure out what kind of thing we want to ~ complete, and call the appropriate completion function." (dbugf 'completion "shell-complete ~s ~s ~s~%" context pos all) (let (exp explanation cmd) (multiple-value-setq (exp explanation) (ignore-errors (shell-read context :partial t :package *junk-package*))) (dbugf 'completion "exp ~s is a ~a~%" exp (type-of exp)) (flet ((simple-complete (func word wpos) (let ((result (funcall func word all))) (if all (setf (completion-result-count result) (length (completion-result-completion result))) (setf (completion-result-insert-position result) wpos)) result))) (typecase exp (keyword (cond ;; Couldn't read a whole expression. ((eq exp *continue-symbol*) ;; If it's not something we know about, it's probably a bug. (ecase (car explanation) (lisp-expr ; an incomplete lisp expression ;; (cdr explanation) should be the expr? (dbugf 'completion "partial lisp-expr ~s ~s~%" context pos) (shell-complete-symbol context pos all)) (bang-expr ; an incomplete !lisp expression ;; (cdr explanation) should be the expr? (dbugf 'completion "partial bang-expr ~s ~s~%" context pos) (shell-complete-symbol context pos all)) (string ; an unclosed string ;; This is lame. Anything could be in a string. (dbugf 'completion "partial string ~s ~s~%" (second explanation) (third explanation)) (simple-complete #'shell-complete-filename (second explanation) (third explanation))) (compound ; a compound connector with nothing after it (dbugf 'completion "partial compound ~s~%" (cdr explanation)) (case (cadr explanation) ((:pipe :and :or :sequence) (dbugf 'completion "whut?~%") (prog1 (simple-complete #'complete-command "" pos) (dbugf 'completion "why?~%"))) ((:redirect-to :redirect-from :append-to) (shell-complete-filename "" 0 all)))))) (t ;; This is probably a bug. (error "Unknown keyword returned from shell-read.")))) (cons (dbugf 'completion "Hellow I am janky! : symbol completion~%") (shell-complete-symbol context pos all)) (shell-expr (let* ((shell-word (shell-word-at exp pos)) (word (and shell-word (word-word shell-word))) (word-num (word-word (shell-word-num exp pos))) (first-word (word-word (first-word-in-expr exp pos))) word-pos) ;; word is the text of the word ;; word-pos is the relative position in the word (when shell-word (setf word-pos (- pos (shell-word-start shell-word)))) (dbugf 'completion "~%expr completion~%word = ~w word-pos = ~w shell-word ~w~%" word word-pos shell-word) (cond ((or (and (not word) (zerop pos)) (start-of-a-compound-p exp pos)) ;; no words (dbugf 'completion "no words~%") (simple-complete #'complete-command "" 0)) ((not word) (if (= 0 (length (shell-expr-words exp))) ;; probably () (progn (dbugf 'completion "not in a word, empty list : bogo~%") (shell-complete-symbol context pos all)) ;; a blank spot somewhere in the line (let ((from-end (- (length context) pos))) (dbugf 'completion "blank spot : heyba ~a~%" first-word) (let ((result (if (and first-word (setf cmd (try-command (first-command-of first-word)))) (progn (dbugf 'completion "in a command : Baaa~%") (complete-command-arg context cmd exp pos all)) (shell-complete-filename word (- (length word) from-end) all)))) (setf (completion-result-insert-position result) (or (and shell-word (shell-word-start shell-word)) pos)) result)))) ((symbolp word) (dbugf 'completion "symbol word : janky~%") (shell-complete-symbol context pos all t)) ((consp word) ; (foo) (dbugf 'completion "junky~%") (shell-complete-symbol context pos all)) ((characterp word) (dbugf 'completion "real char~%") (simple-complete #'complete-char-name (char-name word) (+ (shell-word-start shell-word) 2))) ((not (stringp word)) ;; We don't know how to complete it. ;; Of course we could implement completion for random typed ;; objects, like with a method, but what would that be like? ;; We could error here, that's probably just annoying. (dbugf 'completion "word of weird type ~s ~s~%" word (type-of word)) (make-completion-result)) ((zerop (length word)) (dbugf 'completion "empty word~%") ;; It's probably !() or something so just list the symbols. (shell-complete-symbol context pos all)) ((eql (aref word 0) #\() ; (foo (dbugf 'completion "half baka~%") (shell-complete-symbol context pos all)) ((eql (aref word 0) #\!) ; !foo (shell-complete-symbol context pos all t)) ((eql (aref word 0) #\$) ; $foo (simple-complete #'complete-env-var (subseq word 1) (1+ (shell-word-start shell-word)))) ((and (eql (aref word 0) #\~) ; ~foo (valid-user-name (subseq word 1))) (simple-complete #'complete-user-name (subseq word 1) (1+ (shell-word-start shell-word)))) ((and (eql (aref word 0) #\#) ; #\ (> (length word) 1) (eql (aref word 1) #\\)) (dbugf 'completion "bogo char~%") (simple-complete #'complete-char-name (subseq word 2) (+ (shell-word-start shell-word) 2))) ;; first word, when not starting with directory chars ((and (in-command-position-p exp word-num pos) (not (find (aref word 0) "/.~"))) (dbugf 'completion "first word, non path : jinky~%") ;; try commands (let ((result (simple-complete #'complete-command first-word ;; was: context (shell-word-start shell-word)))) ;; then symbols ;; XXX Symbols won't come up in the list. (when (not (completion-result-completion result)) (setf result (shell-complete-symbol context pos all))) result)) (t (dbugf 'completion "nothing special : hello ~a ~a~%" word first-word) (let* ((from-end (- (length context) pos)) (first-command (and first-word (first-command-of first-word))) (result (if (and first-word (stringp first-command) (setf cmd (try-command first-command))) (progn (dbugf 'completion "command : blurgg~%") (complete-command-arg context cmd exp pos #| (- (length word) from-end) |# all word-num word ;; @@@ band-aid : this code's days are numbered ;; bug shows up e.g. : foo "+<tab> (min word-pos (length word)) )) (progn (dbugf 'completion "default to filename : jorky~%") (shell-complete-filename word (- (length word) from-end) all))))) (dbugf 'completion "result = ~s~%" result) (if all (setf (completion-result-count result) (length (completion-result-completion result))) (setf (completion-result-insert-position result) (let ((ss (shell-word-start shell-word))) (if (shell-word-quoted shell-word) (1+ ss) ss)))) result))))))))) ;; End
33,256
Common Lisp
.lisp
860
33.152326
80
0.624486
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
15bf2b912944ef16e00e048c5d6d672d2506bca2b4dcafa376464fec23beb57f
2,132
[ -1 ]
2,133
lish.lisp
nibbula_lish/lish.lisp
;;; ;;; lish.lisp - A Lisp shell. ;;; ;; This file contains the basic REPL and dispatch, and some other odds and ends. (in-package :lish) ;; The "result" argument is not for the caller, but rather so we can detect ;; cycles in the package inheritance graph. (defun flattened-package-use-list (package &optional result) (loop :for p :in (package-use-list package) :do (when (not (position p result)) (push p result) (loop :for ip :in (flattened-package-use-list p result) :do (pushnew ip result)))) result) ;; This tries to keep :LISH-USER up to date with respect to :CL-USER, ;; because I just so love to push the package system beyond it's limits. ;; This would probably be better done with something like conduits. (defun update-user-package () ;; Update uses (loop :with isym :and isymbol-type :and esym :and esymbol-type :for p :in (package-use-list :cl-user) :do (when (not (position p (flattened-package-use-list *lish-user-package*))) ;; Things directly in lish-user are uninterned in favor of one ;; in cl-user. (unintern-conflicts *lish-user-package* p) ;; Conflicts in inherited symbols are resolved by having the ;; "explicitly" used package symbol (i.e. things used by :lish-user ;; such as :lish) interned and made shadowing. (do-symbols (sym p) (setf (values esym esymbol-type) (find-symbol (symbol-name sym) p) (values isym isymbol-type) (find-symbol (symbol-name sym) *lish-user-package*)) (when (not (equal esym isym)) (case isymbol-type ((:internal :external) (shadow isym *lish-user-package*)) (:inherited (when (not (eq (symbol-package esym) (symbol-package isym))) (shadowing-import isym *lish-user-package*)))))) (use-package p *lish-user-package*))) ;; Update all symbols (do-symbols (sym :cl-user) ;; @@@ deal with conflicts between imported symbols from different packages ;; @@@ keep symbols from packages used directly by :lish-user (when (not (find-symbol (symbol-name sym) *lish-user-package*)) (import sym *lish-user-package*))) ;; Export exported symbols (do-external-symbols (sym :cl-user) (export sym *lish-user-package*))) ;; Get rid of this is if it's unnecessary. (defun modified-context (context &key (in-pipe nil in-pipe-p) (out-pipe nil out-pipe-p) (environment nil environment-p) (flipped-io nil flipped-io-p) (pipe-plus nil pipe-plus-p) (pipe-dot nil pipe-dot-p) (pipe-both nil pipe-both-p) (background nil background-p)) "Return a new context based on ‘context’, with the given slots." (if (not context) (make-context :in-pipe in-pipe :out-pipe out-pipe :environment environment :flipped-io flipped-io :pipe-plus pipe-plus :pipe-dot pipe-dot :pipe-both pipe-both :background background) (let ((c (copy-structure context))) (when in-pipe-p (setf (context-in-pipe c) in-pipe)) (when out-pipe-p (setf (context-out-pipe c) out-pipe)) (when environment-p (setf (context-environment c) environment)) (when flipped-io-p (setf (context-flipped-io c) flipped-io)) (when pipe-plus-p (setf (context-pipe-plus c) pipe-plus)) (when pipe-dot-p (setf (context-pipe-dot c) pipe-dot)) (when pipe-both-p (setf (context-pipe-both c) pipe-both)) (when background-p (setf (context-background c) background)) c))) (defun %find-shell-word (expr position &optional (word-num 0)) (loop :for word :in (shell-expr-words expr) :do (typecase word (shell-word (when (<= position (shell-word-end word)) (throw 'found (list (if (>= position (shell-word-start word)) word nil) word-num)))) (cons (when (and (keywordp (first word)) (shell-expr-p (second word))) (%find-shell-word (second word) position word-num)))) (incf word-num)) (list nil nil)) (defun find-shell-word (expr position) (values-list (catch 'found (%find-shell-word expr position ;; (min position ;; ;; (1- (length (shell-expr-line expr))) ;; (length (shell-expr-line expr)) )))) (defun shell-word-num (expr pos) "Return the shell expression's word that position POS is in." (multiple-value-bind (word num) (find-shell-word expr pos) (if word num (and num (max 0 (1- num)))))) (defun shell-word-at (expr pos) "Return the shell expression's word that position POS is in." (first (multiple-value-list (find-shell-word expr pos)))) (defun word-word (word) "Word is bond." (typecase word (shell-word (shell-word-word word)) (t word))) (defun word-quoted (word) (typecase word (shell-word (shell-word-quoted word)) (t nil))) (defun in-word (word position) "Return true if ‘position’ is in shell-word ‘word’." (and (>= position (shell-word-start word)) (<= position (shell-word-end word)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Job control (cffi:defcallback sigtstp-handler :void ((signal-number :int)) (declare (ignore signal-number)) ;;(format t "[Terminal Stop]~%") (finish-output) #+unix (setf uos::*got-tstp* :dont-suspend) ;; I'm scared of this. ;; (invoke-restart (find-restart 'abort)) ;;(throw 'interactive-interrupt nil) ) (defun start-job-control () #+unix (setf (os-unix:signal-action os-unix:+SIGTSTP+) 'sigtstp-handler (os-unix:signal-action os-unix:+SIGTTIN+) :ignore (os-unix:signal-action os-unix:+SIGTTOU+) :ignore)) (defun stop-job-control (saved-sigs) #-unix (declare (ignore saved-sigs)) #+unix (let ((tstp (first saved-sigs)) (ttin (second saved-sigs)) (ttou (third saved-sigs))) (setf (os-unix:signal-action os-unix:+SIGTSTP+) (if (keywordp tstp) tstp :default) (os-unix:signal-action os-unix:+SIGTTIN+) (if (keywordp ttin) ttin :default) (os-unix:signal-action os-unix:+SIGTTOU+) (if (keywordp ttou) ttou :default)))) (defun job-control-signals () #+unix (list (os-unix:signal-action os-unix:+SIGTSTP+) (os-unix:signal-action os-unix:+SIGTTIN+) (os-unix:signal-action os-unix:+SIGTTOU+))) (defun set-default-job-sigs () #+unix (setf (os-unix:signal-action os-unix:+SIGTSTP+) :default (os-unix:signal-action os-unix:+SIGTTIN+) :default (os-unix:signal-action os-unix:+SIGTTOU+) :default)) ;(defun run (cmd args) ; block sigchld & sigint ; give terminal to child if not running in bg? ; fork ; in the child: ; unblock sigchld & sigint ; set default action tty signals (TSTP, TIN, TOU) ; or ignore them if not going to be in the foreground ; set the process group setpgid to it's own pid (or group of the pipeline) ; give terminal to child's process group ; exec ; in the parent: ; just to be sure: ; set the child's process group (setpgid) to it's own pid ; (or group of the pipeline) ; unblock sigchld & sigint ; wait for the child ; ) ; (defun set-terminal-group (tty group) ; "Make the terminal TTY be controled by process group GROUP." ; ;block TTOU TTIN TSTP & CHLD while we do this: ; (tcsetpgrp tty group)) ; (defun init-job-control (sh) ; (let ((our-process-group (getpgid 0)) ; (tty-process-group (tcgetpgrp tty)) ; (our-pid (getpid))) ; (loop :while (/= our-process-group tty-process-group) ; :do ; ;; If we're not the foreground process ; ;; Signal the process group that we want input, which will likely ; ;; stop us. Keep demanding the tty until we get it or die. ; (kill SIGTTIN) ; (setf tty-process-group (tcgetpgrp tty))) ; ;; If for some reason we're not the process group leader, ; ;; then become it, and take control of the terminal. ; (when (/= our-process-group our-pid) ; (setpgid 0 our-pid) ; (set-terminal-group our-pid)))) (defun handle-job-change (job result status &key foreground) "Take appropriate action when JOB changes status." (case status (:exited ;; Only announce normal exits when not running in the foreground. (when (not foreground) (format t ";; Exited ~a ~a~%" (job-name job) result)) (finish-output) (delete-job job) result) ((:signaled :coredump) (format t ";; Killed ~a ~a" (job-name job) (job-pid job)) #+unix (progn (when (and result (integerp result)) (format t " ~a" (os-unix:signal-description result))) (when (eq status :coredump) (format t " Core dump"))) (terpri) (finish-output) (delete-job job) nil) (:error (format t ";; Error ~a" result) #+unix (when (and result (integerp result)) (format t " ~a" (os-unix:error-message result))) (terpri) (finish-output) ;; (delete-job job) ;; ??? Should we? result) (:stopped (format t ";; Stopped ~a ~a~%" (job-name job) (job-pid job)) (finish-output) (setf (job-status job) :suspended) nil))) (defun wait-for-jobs (sh) "Wait for any jobs we started in a pipeline." #+unix (loop :with pid :and result :and status :and job ;; :while (shell-wait-for sh) ;; :do ;; (format t "WAIT: -------~%") ;; ;; (multiple-value-setq (pid result status) (uos:wait)) ;; (multiple-value-setq (pid result status) (uos:check-jobs t)) ;; (format t "WAIT: ~s ~s ~s~%" pid result status) ;; (cond ;; ((not pid) ;; (return nil)) ;; ((setf job (find pid (shell-wait-for sh) ;; :key #'job-pid)) ;; (handle-job-change job result status :foreground t) ;; (setf (shell-wait-for sh) ;; (delete job (shell-wait-for sh)))) ;; (t ;; (format t "WAIT: some other job?~%")))) :while (shell-wait-for sh) :do ;; (format t "WAIT: -------~%") ;; (multiple-value-setq (pid result status) (uos:wait)) (multiple-value-setq (pid result status) (uos:check-jobs)) ;; (format t "WAIT: ~s ~s ~s~%" pid result status) (cond ((not pid) (return nil)) ((setf job (find pid (shell-wait-for sh) :key #'job-pid)) (handle-job-change job result status :foreground t) (setf (shell-wait-for sh) (delete job (shell-wait-for sh)))) (t ;; (format t "WAIT: some other job?~%") ))) #-unix (declare (ignore sh))) (defparameter *compound-expr-strings* '(:and "&&" :or "||" :sequence "^" :redirect-to ">" :redirect-both-to ">&" :append-to ">>" :redirect-from "<" :pipe "|" :pipe-plus "|+" :pipe-dot "|.") "For reconstructing expression strings.") (defun compound-tag-string (keyword) "Return the string representation for the compound operator keyword THING." (getf *compound-expr-strings* keyword)) (defun %shell-words-to-string (words stream &key literal-line) "The internal part of shell-words-to-*-string." (declare (ignore literal-line)) (let (#| start end |# skip) (labels ((write-thing (w) (typecase w ((or string fat-string) (princ (quotify w) stream)) ((or character fatchar) (princ w stream)) (cons (let ((s (compound-tag-string (car w)))) (if (and s (shell-expr-p (second w))) (format stream "~a ~a~a" (shell-words-to-string (shell-expr-words (second w))) s (shell-words-to-string (rest w))) (write w :stream stream :readably t :case :downcase)))) (t ;; @@@ is this reasonable? (princ w stream)))) (write-it (w &optional space) (setf skip nil) ;; @@@ This whole literal-line thing is dubious because ;; the start and end positions in words can be totally messed ;; up, especially in regard to the line fragment we're passed. #| (when literal-line (cond ((and (shell-word-p w) (shell-word-start w) (shell-word-end w)) ;; A word with positions, just update start and end ;; and skip further processing. (when (not start) (setf start (shell-word-start w))) (setf end (shell-word-end w) skip t)) ((and (shell-word-p w) (or (not (shell-word-start w)) (not (shell-word-end w))) start end) ;; A word without positions, write out what we got, and ;; clear the start and end. (when space (write-char #\space stream)) (write-string (subseq literal-line start end) stream) (setf start nil end nil)))) |# (when (not skip) (when space (write-char #\space stream)) (cond ((and (shell-word-p w) (word-quoted w)) (write-char #\" stream) (write-thing (word-word w)) (write-char #\" stream)) (t (write-thing (word-word w))))))) (when (first words) (write-it (first words))) (loop :for w :in (rest words) :do (write-it w t)) #| (when (and literal-line start end) ;; Write out the last piece. (write-char #\space stream) (write-string (subseq literal-line start end) stream)) |# ))) (defun shell-words-to-string (words &key literal-line) "Put a list of shell words, properly quoted, into a string separated by spaces. This of course loses some data in the words. If LITERAL-LINE is given, try to take as much as we can from it as the original line." (with-output-to-string (stream) (%shell-words-to-string words stream :literal-line literal-line))) (defun shell-words-to-fat-string (words &key literal-line) "Put a list of shell words, properly quoted, into a fat string separated by spaces. This of course loses some data in the words. If LITERAL-LINE is given, try to take as much as we can from it as the original line." (with-output-to-fat-string (stream) (%shell-words-to-string words stream :literal-line literal-line))) (defun shell-words-to-list (words) "Return shell words as a list of strings." (mapcar #'word-word words)) ;; @@@ This is very WIP at moment. (rl:defsingle shell-help-key (editor) (handler-case (use-first-context (editor) (with-context () (multiple-value-bind (type word) (guess-word-before (rl:get-buffer-string editor) inator::point) (labels ((symbol-help () (let ((symbol (symbolify word :no-new t))) (if symbol (let* (result (doc (fatchar-io:with-output-to-fat-string (str) (setf result (%doc symbol :all t :stream str))))) (inator:message editor "~s ~s~%~/fatchar-io:print-string/" type symbol (or (and result doc) (and (fboundp symbol) (function-help symbol 0)))) (setf (rl::keep-message editor) t)) (inator:message editor "FAIL ~s ~s ~s~%" type symbol word)))) (command-help () (inator:message editor "~s ~s~%~/fatchar-io:print-string/" type word (fatchar-io:with-output-to-fat-string (stream) (%doc word :stream stream))) (setf (rl::keep-message editor) t))) (case type (:symbol (symbol-help)) (:command (command-help)) (:command-or-symbol (case (command-type *shell* word) ((:builtin-commandd :shell-command :command) (command-help)) (:external-command ;; @@@ if it has a man page show it ;; otherwise do our fake command help (command-help)) (:file ;; @@@ show a man page if it exists ) (:directory ;; @@@ like maybe ls -l or something, but that violates ;; dependencies :( ) (t (symbol-help)))) (otherwise ;; (inator:message editor "Sorry. No help for a ~s." type) (error "FUCKALL") )))))) (condition (x) (inator:message editor "Help got an error: ~s" x)))) (defun nth-expr-word (n expr) "Return the Nth, potentially unwrapped, word of the shell-expr." (let ((w (nth n (shell-expr-words expr)))) (typecase w (shell-word (shell-word-word w)) (t w)))) (defun resolve-command (command &optional seen) "Try to figure out what the command really is, for testing accepts." (let ((alias (gethash command (shell-aliases *shell*))) word) (if alias (progn (setf word (nth-expr-word 0 (shell-read alias))) (if (not (position command seen :test #'equal)) ; don't circle (progn (pushnew command seen :test #'equal) (resolve-command word seen)) word)) command))) (defun get-accepts (expr) (typecase expr (shell-expr (get-accepts (nth-expr-word 0 expr))) (list (get-accepts (if (keywordp (car expr)) (cdr expr) (car expr)))) (string (let* ((cmd-name (resolve-command expr)) (cmd (get-command cmd-name))) (and cmd (command-accepts cmd)))) (t :unspecified))) ;; *accepts* ;; accept-type ;; where ;; accept-type => ;; keyword ;; or ;; Fake types are keywords. ;; Fake types are for things that would be hard to specify with a type (defun accepts (first-type &rest other-types) "Return true if *ACCEPTS* matches or is a subtype of one of the given types. This should be used rather than directly testing *ACCEPTS*." ;; (let ((types (cons first-type other-types))) (let ((types (append (list first-type) other-types))) (labels ((is-like (x type) ;; (format t "is-like ~s ~s~%" x type) (or (equal x type) #+clisp (ignore-errors (subtypep x type)) ;; #-clisp (subtypep x type) #-clisp (ignore-errors (subtypep x type)) ))) (typecase *accepts* (cons (if (keywordp (car *accepts*)) (some (_ (position _ *accepts* :test #'is-like)) types) (some (_ (is-like *accepts* _)) types))) (keyword (some (_ (eq _ *accepts*)) types)) (t (some (_ (is-like _ *accepts*)) types)))))) (defun successful (obj) "Return true if the object represents a successful command result." (or ;; Zero return value from a system command? (and obj (and (numberp obj) (zerop obj))) (consp obj))) ;; Any other value from lisp code or commands. (defun read-parenless-args (string) "Read and shell-eval all the expressions possible from a string and return them as a list." ;;; @@@ I think I want to change this to do a shell-read ;;(format t "p-l line = ~s~%" string) (loop :with start = 0 :and expr :while (progn (setf (values expr start) (read-from-string string nil *real-eof-symbol* :start start)) (not (eq expr *real-eof-symbol*))) ;;:do ;;(format t "p-l before eval arg ~s of type ~a~%" expr (type-of expr)) :collect (eval expr))) (defmacro with-first-value-to-output (&body body) "Evaluuate BODY and set *OUTPUT* to first value." (with-names (vals) `(values-list (let ((,vals (multiple-value-list (progn ,@body)))) (setf (output) (first ,vals)) ,vals)))) (defun command-type (sh command &key already-known) "Return a keyword representing the command type of COMMAND, or NIL. If ALREADY-KNOWN is true, only check for already cached commands, don't bother consulting the file system." ;;(declare (ignore already-known)) ;; @@@ ;; The order here is important and should reflect what actually happens ;; in shell-eval. (let (cmd path) (cond ((setf cmd (gethash command (lish-commands))) (typecase cmd (external-command :external-command) (builtin-command :builtin-command) (shell-command :shell-command) (t :command))) ((gethash command (shell-aliases sh)) :alias) ((gethash command (lish-global-aliases sh)) :global-alias) ;; @@@ A loadable system isn't really a command, rather a potential ;; command, so maybe it shouldn't be in here? ((loadable-system-p command) :loadable-system) ((setf path (get-command-path command :already-known already-known)) (if (source-command-p path) :source-command :file)) ((and (lish-auto-cd sh) (directory-p (expand-tilde command))) :directory) ((and (fboundp (symbolify command))) :function) (t nil)))) ;; @@@ Maybe this would be better done by typep, but then we'd have to somehow ;; put aliaes, systems, and files, into the type system? (defun maybe-a-command-p (expr) "Return true if ‘expr’ has a first symbol which might be a command." (and expr (symbolp (car expr)) (not (member (command-type *shell* (string-downcase (car expr)) :already-known t) '(:directory :function))))) (defun call-parenless (func line context) "Apply the function to the line, and return the proper values. If there are not enough arguements supplied, and *INPUT* is set, i.e. it's a recipient of a non-I/O pipeline, supply *INPUT* as the missing tail argument." (let ((parenless-args (read-parenless-args line)) (function-args (argument-list (if (functionp func) (third (multiple-value-list (function-lambda-expression func))) func))) (*context* context)) (if (and (< (length parenless-args) (length function-args)) *input*) (progn (if parenless-args (progn (with-first-value-to-output (if (context-pipe-plus *context*) (let ((curried (_ (with-input (_) (apply func `(,@parenless-args ,_)))))) ;; @@@ maybe there's faster way to do this? (apply #'omap curried (list *input*))) (apply func `(,@parenless-args ,*input*))))) (progn (with-first-value-to-output (if (context-pipe-plus *context*) (let ((wrapper (_ (with-input (_) (funcall func _))))) (omap wrapper *input*)) (apply func (list *input*))))))) ;; no *input* stuffing (with-first-value-to-output (apply func parenless-args))))) (defmacro maybe-do-in-background ((bg-p name args) &body body) (with-names (thunk string-name args-val) `(flet ((,thunk () (progn ,@body))) (if (and ,bg-p nos:*supports-threads-p*) (progn (let ((,string-name (prin1-to-string ,name)) (,args-val ,args)) (setf (lish-last-background-job *shell*) (add-job ,string-name (or (and ,args-val (shell-words-to-string ,args-val)) "") (nos:make-thread #',thunk :name ,string-name))))) (progn (funcall #',thunk)))))) (defun eval-lisp-expr (expr) "A wrapper to eval that does the right thing for an invidual expression as an element in a pipeline." (let ((- expr)) (if (context-pipe-plus *context*) (let ((wrapper (_ (with-input (_) (eval expr))))) (omap wrapper *input*)) (eval expr)))) (defun post-command (name type) "Things to do after a command." (run-hooks *post-command-hook* name type) (finish-output)) (defun call-thing (thing args context &optional parenless) "Call a command or function with the given POSIX style arguments. THING is a COMMAND object or a function/callable symbol. ARGS is a list of POSIX style arguments, which are converted to Lisp arguments by POSIX-TO-LISP-ARGS and given to the COMMAND's function. If OUT-PIPE is true, return the values: a list of the values returned by COMMAND a input stream from which can be read the output of command and NIL. If IN-PIPE is true, it should be an input stream to which *STANDARD-INPUT* is bound during command. If PARENLESS is set, it's the text of rest of the line to be fed to CALL-PARENLESS." (with-slots (in-pipe out-pipe environement) context (let ((command-p (typep thing 'base-command)) (bg (context-background context))) (labels ((runky (thing args) (cond ((typep thing 'autoloaded-command) (let ((*context* context)) ;; The args can't be converted yet. (maybe-do-in-background (bg (command-name thing) args) (invoke-command thing args)))) (command-p (let ((lisp-args (posix-to-lisp-args thing args)) (*context* context)) (maybe-do-in-background (bg (command-name thing) args) (invoke-command thing lisp-args)))) (parenless (call-parenless thing parenless context)) (t (maybe-do-in-background (bg thing args) (let ((- thing)) (eval-lisp-expr thing))))))) (if out-pipe (let ((out-str (make-stretchy-string 20))) (values ;; @@@ This is totally stupid (list (with-output-to-string (*standard-output* out-str) (if in-pipe (let ((*standard-input* in-pipe)) (runky thing args)) (runky thing args)))) (let ((oo (make-string-input-stream out-str))) ;; (format t "out-str = ~w~%" out-str) ;; (format t "(slurp oo) = ~w~%" (slurp oo)) ;; (file-position oo 0) oo) nil)) (if in-pipe (let ((*standard-input* in-pipe)) (if command-p (runky thing args) (let ((vals (multiple-value-list (runky thing args)))) (values vals nil t)))) (if command-p (runky thing args) ;; (values (list (runky thing args)) nil t)))))))) (let ((vals (multiple-value-list (runky thing args)))) (values vals nil t))))))))) (defun expr-to-args (expr) "Convert the shell expression ‘expr’ to system command arguments, which must be a list of strings. Spread expression words that need it." (mapcan (_ (let ((x (spread (word-word _)))) (if (listp x) (mapcar #'princ-to-string x) (list (princ-to-string x))))) (shell-expr-words expr))) (defun do-system-command (expr context) "Run a system command. EXPR is a shell-expr. IN-PIPE is an input stream to read from, if non-nil. OUT-PIPE is T to return a input stream which the output of the command can be read from." (let* ((command-line ;; System command arguments must be strings ;; (mapcar (_ (or (and (stringp _) _) ;; (princ-to-string (shell-word-word _)))) ;; (shell-expr-words expr))) (expr-to-args expr)) (program (car command-line)) (args (cdr command-line)) (path #| (get-command-path program) |#) result result-stream pid status job) ;; Since run-program can't throw an error when the program is not found, ;; we try to do it here. (loop :while (not (with-simple-restart (continue "Try the command again.") (setf path (get-command-path program)) (when (not path) (signal 'unknown-command-error :name 'path :command-string program :format "not found.")) (setf path (get-command-path program))))) ;; This actually should be in the child process: ;;(set-default-job-sigs) (with-slots (in-pipe out-pipe environment background) context (if (or in-pipe out-pipe) (progn ;; (when in-pipe ;; (format t "thingy: ~s~%would have been: ~s~%" ;; in-pipe ;; (slurp in-pipe)) ;; (file-position in-pipe 0)) (setf (values result-stream pid) (apply #'nos:pipe-program `(,path ,args ,@(when in-pipe `(:in-stream ,in-pipe)) ,@(when (not out-pipe) '(:out-stream t)) ,@(when environment `(:environment ,environment))))) (when (not out-pipe) (setf result-stream nil))) ;; No pipes (let (#|(tail (last args)) background |#) ;;(format t "tail = ~s~%" tail) #| (when (equal (car tail) "&") (setf args (nbutlast args)) (setf background t) ;; (format t "background = ~a~%args = ~s~%" background args) ) |# (setf pid (apply ;; #+(or clisp ecl lispworks) #'fork-and-exec ;; #-(or clisp ecl lispworks) #'nos:run-program #+unix #'uos::forky #-unix #'nos:run-program `(,path ,args ,@(when environment `(:environment ,environment)) :background ,background)) job (add-job program (join-by-string command-line #\space) pid)) ;; &&& temporarily re-get the terminal so we can debug ;; (sleep .2) ;; (uos::syscall (uos:tcsetpgrp 0 (uos:getpid))) ;; (cerror "Keep going" "Your breakpoint, sir?") (if background (setf (job-status job) :running (lish-last-background-job *shell*) job) (progn ;; Wait for it... (multiple-value-setq (result status) (nos:wait-and-chill pid)) (handle-job-change job result status :foreground t)))))) (values (or result '(0)) result-stream))) ;; This ends up calling one of the following to do the actual work: ;; do-system-command , if it's an external command ;; call-parenless , if it's a function ;; call-thing , if it's a Lish command ;; eval , if it's a object ;; This also directs alias expansion, and lisp sub-expression evaluation. (defun shell-eval-command (sh expr context &key no-alias) "Evaluate a shell expression that is a command. If the first word is an alias, expand the alias and re-evaluate. If the first word is a system that can be loaded, load it and try to call it as a lish command. This is vaugely like autoload. If the first word is a lish command, call it. If the first word is an existing directory and the auto-cd option is set, try to change to it. If the first word is an executable file in the system path, try to execute it. If the first word is a symbol bound to a function, call it with the arguments, which are read like lisp code. This is like a ‘parenless’ function call. Otherwise just try to execute it with the system command executor, which will probably fail, but perhaps in similar way to other shells." (let* (;(words (shell-expr-words expr)) (cmd (word-word (nth-expr-word 0 expr))) (command (get-command cmd)) (alias (gethash cmd (shell-aliases sh))) (expanded-expr (lisp-exp-eval expr)) result result-stream path) ;; These are in order of precedence, so: ;; aliases, lisp path, commands, system path (flet ((sys-cmd () "Do a system command." (run-hooks *pre-command-hook* cmd :system-command) (setf (values result result-stream) (do-system-command expanded-expr context)) (post-command cmd :system-command) (when (not result) (format t "Command failed.~%")) ;; (finish-output) ; @@@ is this really a good place for this? (values result result-stream nil)) (rest-of-the-line (expr) "Return the rest of the line after the first word." (if (> (length (shell-expr-words expr)) 1) (shell-words-to-string (rest (shell-expr-words expr))) "")) (literal-rest-of-the-line (expr) (if (> (length (shell-expr-words expr)) 1) (shell-words-to-string (rest (shell-expr-words expr)) :literal-line (shell-expr-line expr)) "")) (run-fun (func line) "Apply the func to the line, and return the proper values." (run-hooks *pre-command-hook* cmd :function) (values-list (let ((vals (multiple-value-list (call-thing func '() context line)))) (post-command cmd :function) ;;(finish-output) ; @@@ is this really a good place for this? vals)))) (cond ;; Alias ((and alias (not no-alias)) ;; re-read and re-eval the line with the alias expanded (shell-eval (expand-alias alias expanded-expr) :context context :no-expansions t)) ;; Lish command ((typep command '(or internal-command autoloaded-command)) (call-thing command (subseq (shell-expr-words expanded-expr) 1) context)) ;; external command ((typep command 'external-command) (run-hooks *pre-command-hook* cmd :command) (sys-cmd)) ((functionp cmd) ;; (format t "CHOWZA ~s~%" (rest-of-the-line expr)) (run-fun cmd (rest-of-the-line expr))) ((and (symbolp cmd) (fboundp cmd)) ;; (format t "FLEOOP ~s~%" (rest-of-the-line expr)) (run-fun (symbol-function cmd) (rest-of-the-line expr))) ;; Autoload ;; @@@ perhaps we should cache since it seems dumb to check each time ;; for things we already know are a system command? ((and (lish-autoload-from-asdf sh) (in-lisp-path cmd) (setf command (load-lisp-command cmd :silent (lish-autoload-quietly sh)))) (call-thing command (subseq (shell-expr-words expanded-expr) 1) context)) ;; Source a file ((and (not (listp cmd)) (setf path (get-command-path cmd)) (source-command-p path) (setf command (make-source-command path))) (call-thing command (subseq (shell-expr-words expanded-expr) 1) context)) ((stringp cmd) ;; If we can find a command in the path, try it first. (cond (path (sys-cmd)) ((and (lish-auto-cd sh) (directory-p cmd)) (when (> (length (shell-expr-words expr)) 1) (cerror "Ignore the rest of the line." "Arguments aren't allowed after the auto-cd directory.")) (change-directory cmd)) (t ;; Otherwise try a parenless Lisp line. (multiple-value-bind (symb pos) (read-from-string (shell-expr-line expr) nil nil) (declare (ignore pos)) (if (and (symbolp symb) (fboundp symb)) (if (macro-function symb) (progn (shell-eval (cons symb (read-parenless-args (rest-of-the-line expr))) :context context)) (progn (run-fun (symbol-function symb) ;;(subseq (shell-expr-line expr) pos) ;;(rest-of-the-line expr) (literal-rest-of-the-line expr) ))) ;; Just try a system command anyway, which will likely fail. (sys-cmd)))))) (t ;; Some other type, just return it, like it's self evaluating. ;;(values (multiple-value-list (eval cmd)) nil t)))))) ;; (values (multiple-value-list ;; ;;(with-first-value-to-output ;; (call-thing (car cmd) (cdr cmd) context)) ;; nil t) ;; The first word was probably a Lisp expression, evaluating or not. ;; Just treat the rest of the words as potentially Lisp expressions. (let ((first-word (elt (shell-expr-words expr) 0))) (if (and (shell-word-p first-word) (shell-word-eval first-word)) (call-thing cmd nil context) (values (list (eval-lisp-expr cmd) nil t)))) ;; @@@ How can we evaluate the words after the first and return all ;; their possibly multiple values? ;; (loop :for w :in (shell-expr-words expr) ;; (when (shell-word-eval w) ;; (call-thing (word-word w) nil context) ;; ;; @@@@@ ))))) ;; This does normal expansions, sets up piping and redirections and ;; eventually calls shell-eval-command. (defun shell-eval (expr &key no-expansions (shell *shell*) (context *context*)) "Evaluate the shell expression EXPR. If NO-EXPANSIONS is true, don't expand aliases. Return a list of the result values, a stream or NIL, and a boolean which is true to show the values. Generally SHELL-EVAL takes the result of SHELL-READ. EXPR is either a SHELL-EXPR structure or some other Lisp type. If it's not a SHELL-EXPR then just eval it. If it is a SHELL-EXPR then do the shell expansions on it, as done by DO-EXPANSIONS. If the first word of EXPR is a list, then it is a compound command, which is a :PIPE, :AND, :OR, :SEQUENCE. :PIPE takes the output from the piped command, and feeds it as input to the subcommand. :AND evaluates each subcommand until one of them is false. :OR evaluates each subcommand until one of them is true. :SEQUENCE evaluates each subcommand in sequence, ignoring return values. " (let ((*context* (or context (make-context))) first-word vals out-stream show-vals) (with-slots (in-pipe out-pipe environment flipped-io pipe-plus pipe-dot background) *context* (setf flipped-io nil) (macrolet ((eval-compound (test new-pipe) "Do a compound command. TEST determines whether the next~ part of the command gets done. NEW-PIPE is true to make a~ new pipe." `(multiple-value-bind (vals out-stream show-vals) (let ((*accepts* (get-accepts (nth-expr-word 1 expr)))) (shell-eval (second first-word) :context (make-context :in-pipe in-pipe :out-pipe ,new-pipe :environment environment :flipped-io flipped-io :pipe-plus pipe-plus :pipe-dot pipe-dot))) ;;:flipped-io (not flipped-io)))) (declare (ignore show-vals) (ignorable vals)) (when ,test (with-package *lish-user-package* (shell-eval (make-shell-expr :words (cdr (shell-expr-words expr)) ;; @@@ perhaps we should retain original, ;; since indexes not adjusted? :line (format nil "~{~a ~}" (cdr (shell-expr-words expr)))) ;; @@@ is this right with out-stream? :context (if out-stream (modified-context *context* :in-pipe out-stream) *context*) :no-expansions no-expansions)))))) ;; unpack an eval-able lisp expr (when (and (shell-expr-p expr) (= (length (shell-expr-words expr)) 1) (shell-word-eval (first (shell-expr-words expr)))) (setf expr (shell-word-word (first (shell-expr-words expr))))) ;; @@@ But what if there's multiple eval-able lisp exprs? (cond ((not (shell-expr-p expr)) ;; A full Lisp expression all by itself (cond ((and (consp expr) expr (and (symbolp (car expr)) (fboundp (car expr)))) ;; Give precedence to functions ;; (with-package *lish-user-package* ;; (values (multiple-value-list (eval expr)) nil t))) (with-package *lish-user-package* (when (not flipped-io) (setf *input* (if pipe-dot nil *output*) *output* nil flipped-io t)) (multiple-value-bind (result-values output show-p) (call-thing expr nil *context*) (post-command expr :expression) (setf (output) (car result-values)) (values result-values output show-p)))) ((consp expr) (if (maybe-a-command-p expr) ;; Try to do a system command in s-exp syntax (shell-eval (shell-read (join-by-string (cons (string-downcase (car expr)) (with-package *lish-user-package* (let ((*print-case* :downcase) (*print-escape* nil)) (mapcar (_ (if (consp _) (s+ #\" (prin1-to-string _) #\") (prin1-to-string _))) (cdr expr))))) #\space)) :context context) (with-package *lish-user-package* (values (multiple-value-list (eval-lisp-expr expr)) nil t)))) ((stringp expr) (shell-eval (shell-read expr) :context context)) (t (with-package *lish-user-package* (values (multiple-value-list (eval-lisp-expr expr)) nil t))))) ((zerop (length (shell-expr-words expr))) ;; Quick return when no words (return-from shell-eval (values nil nil nil))) ((and (listp (setf first-word (nth-expr-word 0 expr))) (keywordp (first first-word))) ;; First word is a list with a keyword, so it's a compound command. (unless no-expansions (do-expansions expr)) (case (first first-word) ((:pipe :pipe-plus :pipe-dot) (when (not flipped-io) (setf *input* (if pipe-dot nil *output*) *output* nil *pipe-plus* (eq (first first-word) :pipe-plus) (context-pipe-plus *context*) (eq (first first-word) :pipe-plus) (context-pipe-dot *context*) (eq (first first-word) :pipe-dot) flipped-io t)) (setf (values vals out-stream show-vals) (eval-compound (successful vals) t)) (values vals out-stream show-vals)) (:and (eval-compound (successful vals) nil)) (:or (eval-compound (not (successful vals)) nil)) (:sequence (setf pipe-dot t) ;; don't pass *output* for sequences (eval-compound t nil)) (:redirect-to (run-with-output-to (word-word (elt (shell-expr-words expr) 1)) (elt first-word 1))) (:append-to (run-with-output-to (word-word (elt (shell-expr-words expr) 1)) (elt first-word 1) :append t)) (:redirect-from (run-with-input-from (word-word (elt (shell-expr-words expr) 1)) (elt first-word 1))) (t (error "Unknown compound command type.")))) (t ;; The first word is not a list, so it's a ‘simple’ command. (unless no-expansions (do-expansions expr)) ;; A stupid way to do backgrounding: (when (equal (word-word (car (last (shell-expr-words expr)))) "&") (setf background t (shell-expr-words expr) (nbutlast (shell-expr-words expr)))) (with-package *lish-user-package* ;; accepts is :unspecified because we're last in the ;; pipeline. (when (not flipped-io) (setf *input* (if pipe-dot nil (output)) *output* nil flipped-io t)) (setf (values vals out-stream show-vals) (shell-eval-command shell expr *context* :no-alias no-expansions)) (values vals out-stream show-vals)))))))) (defun read-file (file &key (action #'shell-eval)) "Load a lish syntax file." (let ((*load-pathname* (pathname file)) (line-number 1) expression-start-line expr) (with-open-file (stream file :direction :input) (with-package *lish-user-package* (labels ((read-a-line () (prog1 (read-line stream nil) (incf line-number)))) (loop :with line = nil :and new-line = t :while (and (setf line (read-a-line)) new-line) :do (loop :while (and (eql (setf expr (shell-read line)) *continue-symbol*) (setf new-line (read-a-line))) :do ;; Keep track of the start line of a continued expression. (when (and expr (eql expr *continue-symbol*) (not expression-start-line)) (setf expression-start-line line-number)) (setf line (s+ line +newline-string+ new-line))) (when (and expr (not (eql expr *continue-symbol*))) (setf expression-start-line nil)) (with-input (nil) (with-output (nil) ;; (shell-eval expr) (funcall action expr) ))) (when (eql expr *continue-symbol*) (error "End of file in expression. Probably starting at line ~a." expression-start-line))))))) (defun load-file (file) "Load a lish syntax file." (read-file file)) (defun expand-single-file-name (file-name) (expand-tilde (shell-expand-variables file-name))) (defun pick-an-rc-file () (loop :for file :in (list *lishrc* (path-append (config-dir "lish") "lishrc") *default-lishrc*) :do (when file (let ((expanded-file (expand-single-file-name file))) (when (and expanded-file (probe-file expanded-file)) (return expanded-file)))))) (defun load-rc-file (init-file) "Load the users start up (a.k.a. run commands) file, if it exists." (when init-file (let ((file-name (expand-single-file-name init-file))) (when (nos:file-exists file-name) (let ((*lish-user-package* (find-package :lish-user))) (load-file file-name)))))) (defun find-id (shell) "Return the lowest ID that isn't in use." (loop :for i = 1 :then (1+ i) :if (not (position i (lish-jobs shell) :key #'job-id)) :return i :if (> i 100000) :do (error "Something probably went wrong with finding a job ID."))) (defun add-job (name command-line thing &key (status :running)) "Add a job with the given NAME and COMMAND-LINE. THING is either an integer process ID or a resume function designator. STATUS defaults to :RUNNING." (let (job) (typecase thing (integer (setf job (make-instance 'system-job :id (find-id *shell*) :name name :command-line command-line :status status :pid thing :process-group thing))) (process-handle (setf job (make-instance 'system-job :id (find-id *shell*) :name name :command-line command-line :status status ;; @@@ bullcrap workaround :pid (process-handle-value thing) :process-group (process-handle-value thing)))) ((or symbol function) (setf job (make-instance 'lisp-job :id (find-id *shell*) :name name :command-line command-line :status status :resume-function thing))) (t (if (and (refer-to :bt '*supports-threads-p*) (symbol-call :bt :threadp thing)) (setf job (make-instance 'thread-job :id (find-id *shell*) :name name :command-line command-line :status status :thread thing)) (error "Tried to a job of an unknown type ~s" (type-of thing))))) (push job (lish-jobs *shell*)) job)) (defun suspend-job (name command-line resume-function) "Suspend a job. This should be called by the program that wants to suspend itself." (add-job name command-line resume-function)) (defun delete-job (job) "Delete the job. JOB is either a JOB struct or a JOB-ID." (when (not (or (job-p job) (integerp job))) (error "JOB must be a JOB or an integer JOB-ID.")) (setf (lish-jobs *shell*) (typecase job (integer (delete job (lish-jobs *shell*) :test #'= :key #'job-id)) (job (delete job (lish-jobs *shell*) :test #'eq))))) (defun check-all-job-status (sh) "Check the status of all jobs and perform appropriate actions." (mapc (_ (check-job-status sh _)) *job-types*)) (defvar *shell-non-word-chars* #(#\space #\tab #\newline #\linefeed #\page #\return #\( #\) #\[ #\] #\: #\; #\/ #\" #\' #\\ #\# #\, #\` #\| #\. #\- #\$ #\~ #\! #\&) "Characters that are not considered to be part of a word in the shell.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Main ;; ;; This is conceptually like the traditional REPL: ;; ;; (lish (loop (lish-print (lish-eval (lish-read))))) ;; ;; These functions pass arount a READ-STATE to keep track of continued lines. ;; LISH-READ calls SHELL-READ to get SHELL-EXPRs. ;; LISH-EVAL calls SHELL-EVAL which is the top of everything else. ;; Just the state of the REPL-y area to make it easy to pass around. (defstruct read-state "The line we've read and the previous line." string prefix-string this-command last-command (error-count 0)) (cffi:defcallback sigint-handler :void ((signal-number :int)) (declare (ignore signal-number)) (format t "[Interrupt]~%") (finish-output) ;; I'm scared of this. ;; (invoke-restart (find-restart 'abort)) (throw 'interactive-interrupt t) ) (defun set-signals () "Make sure signal handlers are set up for shell reading. Return a list of (signal . action) to be reset later." #+unix (let (result) (progn ;; Ignore quit (push (cons uos:+SIGQUIT+ (uos:signal-action uos:+SIGQUIT+)) result) (uos:set-signal-action uos:+SIGQUIT+ :ignore) ;; Ignore suspend (push (cons uos:+SIGTSTP+ (uos:signal-action uos:+SIGTSTP+)) result) ;; (uos:set-signal-action uos:+SIGTSTP+ :ignore) (uos:set-signal-action uos:+SIGTSTP+ 'sigtstp-handler) ;; Handle interrupt ;; #-sbcl ;; (progn ;; (push (cons uos:+SIGINT+ (uos:signal-action uos:+SIGINT+)) result) ;; (uos:set-signal-action uos:+SIGINT+ 'sigint-handler)) ) result) #-unix t) (defun restore-signals (actions) "Restore (or really just set) the signal actions in ACTIONS." #-unix (declare (ignore actions)) #+unix (loop :for (sig . act) :in actions :do (uos:set-signal-action sig act))) (defun lish-read (sh state) "Read a string with the line editor and convert it shell expressions." (with-slots ((str string) (pre-str prefix-string) this-command last-command) state (finish-output) (tt-finish-output) (setf str (rl :eof-value *real-eof-symbol* :quit-value *quit-symbol* :history-context :lish :editor (lish-editor sh) :accept-does-newline nil :re-edit (when pre-str (setf pre-str nil) t) :prompt ;; (if pre-str ;; (lish-sub-prompt sh) (safety-prompt sh) :right-prompt (safety-prompt sh :right))) (cond ((and (stringp str) (equal 0 (length str))) *empty-symbol*) ((equal str *real-eof-symbol*) *real-eof-symbol*) ((equal str *quit-symbol*) *quit-symbol*) (t (setf ! last-command last-command (copy-seq this-command)) ;; This is the read of the REPL. (shell-read (setf this-command (if pre-str (s+ pre-str +newline-string+ str) str))))))) #+(or) (defun maybe-save-values (vals show-vals) "Save result values in the history if the option is on." (when (get-option *shell* 'history-save-values) (if (and show-vals vals (olength-at-least-p 1 vals)) (setf (getf (rl:history-entry-extra (dl-list:dl-content (rl::history-current-get))) :values) (copy-list vals)) (when *output* (setf (getf (rl:history-entry-extra (dl-list:dl-content (rl::history-current-get))) :values) (list *output*)))))) (defun lish-print (values) "Print the results of an evaluation. VALUES are a list of values to print." (with-package *lish-user-package* (loop :with len = (length values) :and i = 0 :for v :in values :do ;; (format t "~s" v) (format t "~w" v) (if (and (> len 1) (< i (- len 1))) (format t " ;~%")) (incf i) :finally (format t "~&")))) (defparameter *fuxor* nil) (defun lish-eval (sh expr state) "Evaluate the shell expressions in EXPR." (declare (ignore sh)) (with-slots ((str string) (pre-str prefix-string)) state (cond ((eq expr *continue-symbol*) (if (stringp pre-str) (setf pre-str (format nil "~a~%~a" pre-str str)) (setf pre-str (format nil "~a" str)))) ((eq expr *empty-symbol*) ;; do nothing (format t "~%")) ; <<<< ((eq expr *error-symbol*) ;; do nothing ;; (break) (cerror "Go on." "lish-eval got an ~s~%" *error-symbol*) ) (t (setf pre-str nil *input* nil *output* nil) ;; @@@ This one is the trouble (when (shell-interactive-p *shell*) (format t "~%")) ; <<<< (force-output) (when (catch 'interactive-interrupt (multiple-value-bind (vals stream show-vals) #| @@@ This really fails. #+(and unix (not sbcl)) ;; (uos:with-signal-handlers ((uos:+sigint+ . sigint-handler)) ;; (format t "Howdy pardner.~%") ;; (shell-eval expr :context nil)) (progn (uos:set-signal-action uos:+sigint+ 'sigint-handler) (shell-eval expr :context nil) (uos:set-signal-action uos:+sigint+ :default)) #-(and unix (not sbcl)) |# (shell-eval expr :context nil) (declare (ignore stream)) (let ((vals-list (if (listp vals) vals (list vals)))) (setf /// // // / / vals-list *** ** ** * * (car vals-list)) ;; (maybe-save-values vals show-vals) (when show-vals ;; Maybe save expression values in history. (lish-print vals))) nil)) ;; Got an intterrupt, so stop reading this multi-line expression. (format t ">>>> Control-C <<<<~%") ;; does this ever happen? (set pre-str nil)))))) (defun confirm-quit () (if (lish-jobs *shell*) (progn (format t "There are stopped jobs. ") (confirm "quit the shell")) t)) (defun ensure-theme () "Make sure a theme is set." (when (not theme:*theme*) (setf theme:*theme* (theme-default:default-theme)))) (defun save-history (sh &key update) "Save the history." (handler-bind ((serious-condition #'(lambda (c) (if (lish-debug *shell*) (invoke-debugger c) (progn (format t "Saving history failed. ~ Turn on debug if you want.~%~a~%" c) (abort)))))) (history-store-save (lish-history-store sh) (history-style sh) :update update))) (defun load-history (sh &key update) (with-simple-restart (continue "Keep going even though history failed to load.") (handler-bind ((serious-condition #'(lambda (c) (if (lish-debug *shell*) (invoke-debugger c) (progn (format t "Loading history failed. Turn on debug if you ~ want.~%~a~%" c) (continue)))))) (history-store-load (lish-history-store sh) (history-style sh) :update update)))) (defun init-history (sh) "Create the history store and load the history from it." (rl::history-init) (setf (lish-history-store sh) (make-instance (ecase (history-format sh) (:text-file 'text-history-store) (:database 'db-history-store)))) (history-store-start (lish-history-store sh) (history-style sh))) ;; @@@ Since there's a shared history for all shells in the same image, there ;; should be a shared history store for the image too, which probably should ;; be saved at least when a shell exits, but for sure when the last shell ;; exits. ;; ;; For now we don't do any saving for shells other than the first. (defun start-history (sh) (when (not (get-history)) ;; @@@ (init-history sh) (load-history sh))) (defun finish-history (sh) "Save the history finish using the history store." (when (lish-history-store sh) ;; @@@ (with-simple-restart (abort "Abort finishing lish history.") (save-history sh) (history-store-done (lish-history-store sh) (history-style sh))))) (defmacro with-error-handling ((state) &body body) (with-names (results just-print-the-error condition) `(let* (,condition (,results ;; We have to be careful to preserve the values (multiple-value-list (catch ',just-print-the-error (handler-bind (#+sbcl (sb-ext::step-condition 'repple-stepper) #+sbcl ;; So we can do something on ^C (sb-sys:interactive-interrupt #'(lambda (c) ;; Stop reading this multi-line expression (setf (read-state-prefix-string ,state) nil) (if (lish-debug *shell*) (invoke-debugger c) (progn (format t "~%") (finish-output) (invoke-restart (find-restart 'abort)))))) (unknown-command-error #'(lambda (c) (cond ((lish-debug *shell*) (if *unknown-command-hook* (progn (with-simple-restart (continue "~a" (or (documentation *unknown-command-hook* 'function) "Continue the *unknown-command-hook*")) (invoke-debugger c)) (funcall *unknown-command-hook* *shell* c)) (invoke-debugger c))) (*unknown-command-hook* (if (funcall *unknown-command-hook* *shell* c) (continue) (signal c))) (t (setf ,condition c) (throw ',just-print-the-error ',just-print-the-error))))) ;; Normal error handling (serious-condition #'(lambda (c) (if (lish-debug *shell*) (invoke-debugger c) ;; We can't just print the error here because the ;; terminal could be screwed up, in a way which ;; can make the conditional newline fail, so we ;; throw out, so that hopefully the terminal will ;; be reset by unwind code and then print and ;; abort. (progn (setf ,condition c) (throw ',just-print-the-error ',just-print-the-error)))))) ,@body))))) (if (eq (car ,results) ',just-print-the-error) (progn ;; We can't leave this error counting to the debugger, since ;; we never get into it when debugging is off. (incf (read-state-error-count ,state)) (when (> (read-state-error-count ,state) 10) (format t "Too many errors!~%") ;; This will mostly happen if we get an error in the shell or ;; line editor code. Errors from commands probably won't recur. (break)) (format t "~&~a~&" ,condition) (finish-output) ; semi-dubious (invoke-restart 'abort)) (values-list ,results))))) ;; These with-* macros break shell initialization up into pieces so we can ;; do non-interactive commands, especially the various ! functions, without ;; repeating ourselves, and so we can call the ! functions when not already in ;; an interactive shell. (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro with-job-signals (() &body body) `(unwind-protect (progn (start-job-control) ,@body) (stop-job-control (shell-saved-signals *shell*)))) (defmacro with-shell-signals (() &body body) "Evaluate the BODY with the system signal handlers set the way they should be for normal interactive execution in the shell. This usually means ignoring suspend ^Z and quit ^\, and setting sub-process jobs control signals." (with-names (saved-signals) `(let (,saved-signals) (unwind-protect (progn (setf ,saved-signals (set-signals)) (with-job-signals () ,@body)) (when ,saved-signals (restore-signals ,saved-signals)))))) (defmacro with-new-shell ((&rest args) &body body) "Evaluate the BODY with *SHELL* bound to anew shell instance." `(let* ((*shell* (make-instance 'shell ,@args)) (*history-context* :lish) (*lish-level* (if *lish-level* (funcall #'1+ (symbol-value '*lish-level*)) 0))) ,@body)) (defmacro with-shell-command (() &body body) "Evaluate the BODY as a non-interactive shell command." (with-names (result) `(let (,result) (catch 'interactive-interrupt (ensure-theme) (unwind-protect (with-job-signals () (run-hooks *enter-shell-hook*) (setf ,result (progn ,@body))) (run-hooks *exit-shell-hook*))) (if (shell-exit-values *shell*) (values-list (shell-exit-values *shell*)) ,result)))) (defmacro with-shell (() &body body) "Evaluate the body as a non-interactive shell command, making a new shell if we aren't already inside one." `(if *shell* ;; @@@ How can we avoid the code duplication? I don't think the thunk ;; trick will work here? (with-input (nil) (with-output (nil) (progn ,@body))) (with-new-shell () (with-shell-command () ,@body))))) (defun lish (&key debug terminal-name terminal-type (terminal *terminal*) ;;(init-file (or *lishrc* *default-lishrc*)) (init-file (pick-an-rc-file)) prompt command) "Lish is a LIsp SHell. Type the “help” command for more documentation. Arguments: debug - True to turn on entering the debugger on errors. terminal-name - Device name of the terminal. terminal-type - Type of terminal to read from. Defaults from pick-a-terminal-type and so *default-terminal-type*. terminal - A terminal to use. Ignores terminal-name and terminal-type. init-file - File to load on startup or *default-lishrc* if not given. command - A command to evaluate and exit." ;; (let* ((*shell* (make-instance 'shell :debug debug)) ;; (sh *shell*) ; shorthand ;; (state (make-read-state)) ;; (*history-context* :lish) ;; (*lish-level* (if *lish-level* ;; (funcall #'1+ (symbol-value '*lish-level*)) ;; 0)) ;; (*lishrc* init-file) ;; So it's inherited by sub-shells. ;; ! ;-) ! ;; (saved-sigs (job-control-signals)) ;; ;; (old-terminal *terminal*) ;; ) (with-new-shell (:debug debug) (let* ((sh *shell*) ; shorthand (state (make-read-state)) (*lishrc* init-file) ;; So it's inherited by sub-shells. (*terminal* (or terminal *terminal*)) !) (setf (lish-debug *shell*) debug) ; @@@ the arg to make-instance doesn't ;; Make the user package if it doesn't exist. (when (not (find-package :lish-user)) (setf *lish-user-package* (make-user-package))) ;; Don't do the wacky package updating in other packages. (when (eq *lish-user-package* (find-package :lish-user)) (update-user-package)) ;; Set the recursion level for system processes. (setf (nos:environment-variable "LISH_LEVEL") (format nil "~d" lish::*lish-level*)) ;; Perhaps do a single command and exit. (when command ;; (let (result) ;; (catch 'interactive-interrupt ;; (ensure-theme) ;; (start-job-control) ;; (run-hooks *enter-shell-hook*) ;; (setf result (lish-eval sh ;; (typecase command ;; (list command) ;; (t (shell-read command))) ;; (make-read-state))) ;; (stop-job-control saved-sigs) ;; (run-hooks *exit-shell-hook*)) ;; (return-from lish (if (shell-exit-values sh) ;; (values-list (shell-exit-values sh)) ;; result)))) ;; Load the startup file. (load-rc-file init-file) (when prompt (setf (lish-prompt sh) prompt)) (setf (shell-interactive-p sh) nil) (return-from lish (with-shell-command () (lish-eval sh (typecase command ((or list shell-expr) command) (t (shell-read command))) (make-read-state))))) ;; Use our debugger unless we're told not to or it's not loaded. (when (and (not *dont-deblarg*) (find-package :deblarg)) (symbol-call :deblarg :activate :quietly t)) ;; Figure out the terminal type. (setf terminal-type (if terminal (type-of terminal) (or terminal-type (and *terminal* (find-terminal-type-for-class (type-of *terminal*))) (pick-a-terminal-type)))) (with-terminal (terminal-type *terminal* :device-name terminal-name :start-at-current-line t) ;; We can't just use a terminal-crunch as *standard-output* because ;; it won't know about output from other programs or other streams, ;; but since the lower level terminals are are something like ;; "immediate mode" maybe they should work? The point is to get ;; color output for fat-strings. (let ((*standard-output* ;; We can't use typecase because the terminal types don't ;; have to be loaded. (case (keywordify (type-of *terminal*)) (:terminal-crunch (terminal-wrapped-terminal *terminal*)) (:null *standard-output*) (t *terminal*)))) (setf (tt-input-mode) :line) (ensure-theme) ;; Load the startup file. (load-rc-file init-file) (when prompt (setf (lish-prompt sh) prompt)) (when *use-bracketed-paste* (dlib-i:setup-bracketed-paste)) ;; Make a customized line editor (setf (lish-editor sh) (make-instance 'lish-line-editor ;; 'rl:line-editor :non-word-chars *shell-non-word-chars* :completion-func #'shell-complete :history-context *history-context* :terminal-device-name terminal-name :auto-suggest-p (lish-auto-suggest sh) :prompt-func nil :filter-hook `(colorize) :partial-line-indicator (lish-partial-line-indicator *shell*) :gutter-char (lish-gutter-char *shell*))) (start-history sh) (with-shell-signals () (run-hooks *enter-shell-hook*) (when (not (eq :lish-quick-exit (catch :lish-quick-exit (loop :named pippy :with expr = nil :and lvl = *lish-level* :and eof-count = 0 :and retry = nil :if (shell-exit-flag sh) :if (confirm-quit) :return (values-list (shell-exit-values sh)) :else :do (setf (shell-exit-flag sh) nil) :end :end :do (restart-case (with-error-handling (state) (check-all-job-status sh) (if retry (setf retry nil) (setf expr (lish-read sh state))) (when (and (eq expr *real-eof-symbol*) (confirm-quit)) (return-from pippy expr)) (if (eq expr *quit-symbol*) (if (and (not (lish-ignore-eof sh)) (confirm-quit)) (return-from pippy expr) (progn (when (numberp (lish-ignore-eof sh)) (if (< eof-count (lish-ignore-eof sh)) (incf eof-count) (if (confirm-quit) (return-from pippy expr) (setf eof-count 0)))) (let ((remain (1+ (- (lish-ignore-eof sh) eof-count)))) (format t "Type 'exit'~:[ or ~a ~d more time~p~ ~;~^~] to exit the shell.~%" (zerop eof-count) (char-util:nice-char (rl::last-event (lish-editor sh)) :caret t) remain remain)))) (progn (setf eof-count 0) (prog1 (lish-eval sh expr state) (incf (shell-command-count sh))))) (setf (read-state-error-count state) 0)) (abort () :report (lambda (stream) (format stream "Return to Lish ~:[~;TOP ~]level~:[~; ~d~]." (= lvl 0) (/= lvl 0) lvl)) nil) (retry () :report (lambda (stream) (format stream "Retry Lish command ~:[~;TOP ~]level~:[~; ~d~]." (= lvl 0) (/= lvl 0) lvl)) (setf retry t) nil))))))) ;; (stop-job-control saved-sigs) ) ;;(save-command-stats) (run-hooks *exit-shell-hook*))) (finish-history sh) (when (shell-exit-flag sh) (return-from lish (when (shell-exit-values sh) (values-list (shell-exit-values sh))))) (format t "*EOF*~%") ;; Well, let's hope that this will clear the EOF on *standard-input* (clear-input *standard-input*)))) (defvar *standalone* nil "True if we are nearly just a shell.") ; [sic] (defun flash-msg (msg) "Temporarity flash a message, nearly subliminally." (format t msg) (finish-output) (sleep .2) (format t "~v,,,va" (length msg) #\backspace #\backspace) (finish-output) (sleep .1) (format t "~v,,,va" (length msg) #\space #\space) (format t "~v,,,va" (length msg) #\backspace #\backspace)) (defun lishity-split () "Get out real quick." (if *standalone* (flash-msg "You the man now dog.") (throw :lish-quick-exit :lish-quick-exit))) (defcommand lish ((command string :short-arg #\c :help "Command to execute.") (init-file pathname :short-arg #\i :default *default-lishrc* :use-supplied-flag t :help "File to execute on startup.") (no-init-file boolean :short-arg #\n :help "Don't load any startup file.") (greeting boolean :short-arg #\g :default t :help "True to print a greeting.") (terminal-type choice :short-arg #\t :choice-func (lambda () (mapcar #'string-downcase (terminal-types))) :help "Terminal type.") (debug boolean :short-arg #\d :help "True to turn on debugging.") ;; We have to do non-auto-help because so it works from shell-toplevel. (version boolean :long-arg "version" :help "Print the version and exit.") (help boolean :long-arg "help" :help "Show the help.")) :args-as args "Lisp Shell" (cond (help (print-command-help (get-command "lish")) (return-from !lish 0)) (version (format t "~a~%" *version*) (return-from !lish 0))) (remf args :help) (remf args :version) (when (and greeting (not command)) (format t "Welcome to ~a ~a~%" *shell-name* *version*)) (remf args :greeting) (when (not init-file-supplied-p) (setf init-file (when (not no-init-file) (pick-an-rc-file)))) (remf args :no-init-file) (when no-init-file (setf (getf args :init-file) nil)) (apply #'lish args)) (defun wordify-list (word-list) "Return a list of shell words that is like the strings in word-list separated by spaces." (loop :with pos = 0 :for w :in word-list :collect (make-shell-word :word w :start pos :end (+ pos (length w))) :do (incf pos (1+ (length w))))) (defun is-this-shell (command &optional (name *shell-name*)) "Return true if ‘command’ probably names this shell." (let ((start 0)) ;; Called as a login shell on unix, with starting dash. #+unix (when (char= (char command 0) #\-) (incf start)) (and command (stringp command) (command-test (lambda (cmd path) (string-equal path cmd :start1 start)) name command)))) (defvar *saved-default-external-format* nil) ;; If you want to invoke lish commands from another shell or another program, ;; you can make a "link farm", which is a directory in your path which has ;; links to the shell as the command names you want to invoke. Since lish/los ;; commands are intentionally not very compatible with POSIX, it's advisable ;; that unless you're in a setup that won't be using any POSIX shell scripts, ;; to link commands that are also POSIX commands, as "lish-<command>", and then ;; make aliases in the other shell to invoke them. (defun shell-toplevel () "Invoked the standalone shell. If we're not invoked as our known shell name, try to run the command that we're invoked as, or the command we're invoked as with a (s+ *shell-name* “-”) stripped off." (setf *standalone* t *default-lishrc* (default-lishrc)) ;; No, this doesn't work: ;; (asdf:initialize-output-translations) (uiop:restore-image) (let* ((level-string (nos:environment-variable "LISH_LEVEL")) ;;(args-expr (when (cdr (nos:lisp-args)) ;; (shell-read (join-by-string (cdr (nos:lisp-args)) #\space ;;(args-expr (wordify-list (nos:lisp-args))) ) (when level-string (setf *lish-level* (parse-integer level-string))) ;; @@@ Of course this is wrong. We really get it from LANG or LC_CYTPE, or ;; whatever it is on Windows or whatever O/S. #+sbcl (setf sb-impl::*default-external-format* (or *saved-default-external-format* :utf-8)) (let* ((args (nos:lisp-args)) (command (remove-prefix (nos:basename (car args)) (s+ (string-downcase *shell-name*) #\-)))) (cond ;; When not invoked as *shell-name*, try to run it as a command. ;; So you can do the link farm thing. ((and args (not (is-this-shell command))) (cond ;; @@@ This seems expensive, but we have to check that we won't ;; invoke it as an external command to prevent unwanted recursion. ((ignore-errors (with-new-shell () ;; (not (member (command-type *shell* (first args)) (not (member (command-type *shell* command) '(:external-command :file))))) (if (and *lish-level* (> *lish-level* 7)) (format t "We're ~s levels deep. Something probably went ~ wrong, so I'm giving up.~%~ The command was ~s.~%" *lish-level* args) (with-new-shell (:debug nil) (setf (shell-interactive-p *shell*) nil) (let ((state (make-read-state))) (with-simple-restart (abort "Abort the command.") (with-error-handling (state) (with-shell-command () (lish-eval *shell* (expr-from-args (cons command (cdr args))) state)))))))) (t (format t "Sorry, this ~a doesn't have a ~s command in it.~%" *shell-name* command)))) ((cdr args) ;; Some args ;; Invoke as if we were invoking the lish command from in the shell. (apply #'!lish `(,@(posix-to-lisp-args (get-command "lish") (wordify-list (cdr args))) :greeting t ;; :terminal-type :crunch ))) (t ;; No args ;; Interactive (!lish :greeting t ;; :terminal-type :crunch )))) (nos:exit-lisp))) ;;; @@@ refactor with shell-toplevel (defun command-toplevel (command) "Invoked a standalone commaned." (setf *standalone* t *default-lishrc* (default-lishrc)) ;; No, this doesn't work: ;; (asdf:initialize-output-translations) (uiop:restore-image) (let ((level-string (nos:environment-variable "LISH_LEVEL")) (args (nos:lisp-args))) (when level-string (setf *lish-level* (parse-integer level-string))) ;; @@@ Of course this is wrong. We really get it from LANG or LC_CYTPE, or ;; whatever it is on Windows or whatever O/S. #+sbcl (setf sb-impl::*default-external-format* (or *saved-default-external-format* :utf-8)) (if (and *lish-level* (> *lish-level* 7)) (format t "We're ~s levels deep. Something probably went ~ wrong, so I'm giving up.~%~ The command was ~s.~%" *lish-level* (command-name command)) ;; @@@ Maybe refactor this terminal thing from the main lish function. (with-terminal (nil *terminal* :start-at-current-line t) ;; We can't just use a terminal-crunch as *standard-output* because ;; it won't know about output from other programs or other streams, ;; but since the lower level terminals are are something like ;; "immediate mode" maybe they should work? The point is to get ;; color output for fat-strings. (let ((*standard-output* ;; We can't use typecase because the terminal types don't ;; have to be loaded. (case (keywordify (type-of *terminal*)) (:terminal-crunch (terminal-wrapped-terminal *terminal*)) (:null *standard-output*) (t *terminal*)))) (setf (tt-input-mode) :line) (with-new-shell (:debug nil) (setf (shell-interactive-p *shell*) nil) (let ((state (make-read-state))) (with-simple-restart (abort "Abort the command.") (with-error-handling (state) (with-shell-command () (invoke-command command (posix-to-lisp-args command (wordify-list (cdr args)))))))))))) (nos:exit-lisp))) (defun make-standalone-executable (name function &key (smaller t)) "Save an executable shell command in ‘name’, which calls ‘function’." #-sbcl (declare (ignore smaller)) ;; (update-version) (let (options) #+sbcl (progn ;; So that the saved image can start with a fresh external format. (setf *saved-default-external-format* sb-impl::*default-external-format*) ;; In case we were built with the debugger turned off. ;; @@@ Maybe this should be in the top level function?? (sb-ext:enable-debugger) ;; Turn on core compression if it's available (when (and smaller (has-feature :sb-core-compression)) (setf options (nconc options (list :compression t)))) ;; So toplevel doesn't get any interference with the command line. ;; Unfortuneately that means we can't change the damn "dynamic" space size. (setf options (nconc options (list :save-runtime-options t)))) ;; Clear the user packages (delete-package *lish-user-package*) (delete-package *junk-package*) (setf *lish-user-package* nil *lish-user-package* (make-user-package) *junk-package* (make-package :lish-junk)) ;; So the invoking user doesn't get the saving user's. (setf *lishrc* nil *default-lishrc* nil) ;; Save the build locale data in the image so we don't need it around at ;; runtime. @@@ Later it should be a option in build system, which locale ;; if any, or all, should be saved in the image. (locale:ensure-locale) ;; Make sure ASDF is cleared. (asdf:clear-configuration) (setf asdf:*central-registry* nil) ;; Make all the current systems register as pre-loaded. ;; This should make it so we can load new things in the image. (loop :for system :in (asdf:registered-systems) :do (asdf:register-preloaded-system system) (asdf:clear-system system)) (apply #'save-image-and-exit name :initial-function function options))) (defun make-standalone (&key (name #-windows "lish" #+windows "lish.exe") (smaller t)) "Make a lish executable." (make-standalone-executable name #'lish:shell-toplevel :smaller smaller)) ;; @@@ figure out how to appease asdf to do this from an already dumped lish (defun make-standalone-command (command &key (smaller t)) "Make a lish executable." (typecase command (command) (string (when (null (setf command (get-command command))) (error "Command ‘~a’ isn't defined." command))) (t (error "I don't know how to make a ~s ~s into a command." (type-of command) command))) ;; (let ((type (command-type *shell* command))) ;; (when (member type '(:external-command :file)) ;; (error "The command shouldn't be a ~s." type))) (when (not (typep command 'shell-command)) (error "The command should be a ‘shell-command’, not ~s." (type-of command))) (make-standalone-executable (command-name command) (lambda () (command-toplevel command)) :smaller smaller)) ;; So we can conditionalize adding of lish commands in other packages. (d-add-feature :lish) ;; EOF
75,533
Common Lisp
.lisp
2,022
32.12908
81
0.633954
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
3a6337b76204e9cb9bb801a593d317a7defbe6e6824ecfb54ed8776c578dc6e5
2,133
[ -1 ]
2,134
reader.lisp
nibbula_lish/reader.lisp
;;; ;;; reader.lisp - Lish reader ;;; (in-package :lish) (defun read-string (s) "Read a lish string. It has similar syntax to a lisp string. ~ Assumes the opening double quote has already been read. ~ Read until a double quote. Backslash escapes the special meaning of ~ the following character. Return the string and how long it is. If we got to ~ the end and didn't get a close quote, the third value is true.~ " (let ((v (make-stretchy-string 10)) (i 0) (end-quote nil) (quote-next nil)) (loop :for c :across s :do (setf end-quote (and (eql c #\") (not quote-next))) :while (not end-quote) :do (if (and (eql c #\\) (not quote-next)) (setf quote-next t) (progn (setf quote-next nil) (vector-push-extend c v))) (incf i)) (values v i (not end-quote)))) (defmacro define-reader-macro (char name (&optional (stream-arg 'stream) (char-arg 'subchar) (param-arg 'arg)) &body body) "Define a “dispatch” level reader macro function for sharpsign #\# and ‘char’, named ‘name’. The function will have arguments called ‘stream’, ‘subchar’ and ‘arg’, which are the reader stream, the dispatch sub-character, and the infix parameter, as in the CL standard. Defines functions to enable and disable it in the current readtable, and enable it for the rest of file. Defines a variable to save the current function, if any." (let ((func-name (symbolify (format nil "~@:(~a~)-READER" name))) (save-var-name (symbolify (s+ "*SAVED-" name "-FUNC*")))) `(progn (defvar ,save-var-name nil) (defun ,func-name (,stream-arg ,char-arg ,param-arg) ,@body) (defun ,(symbolify (s+ "ENABLE-" func-name)) () (when (not ,save-var-name) (setf ,save-var-name (get-dispatch-macro-character #\# ,char))) (set-dispatch-macro-character #\# ,char #',func-name)) (defun ,(symbolify (s+ "DISABLE-" func-name)) () (when ,save-var-name (set-dispatch-macro-character #\# ,char ,save-var-name))) (defmacro ,(symbolify (s+ "FILE-ENABLE-" func-name)) () '(eval-when (:compile-toplevel :load-toplevel :execute) ;; It works to just set it because when a file is finished loading ;; the *readtable* is restored. (setf *readtable* (copy-readtable)) (set-dispatch-macro-character #\# ,char #',func-name)))))) ;; XXX This is horribly wrong, since it doesn't actually respect the syntax. ;; To do it right, we probably have to modify shell-read to not actually read ;; but just accumulate characters. Also, to be balanced, we give up the ability ;; to have a shell varibale ‘$#’, but that's okay since we don't want such a ;; thing. Also, we don't get lexical scope, but with full parsing we could by ;; doing something like: #$ foo ,var bar $# => (! "foo " var " bar") (define-reader-macro #\$ sharp-dollar (stream subchar arg) "Read a command in Lish syntax." (declare (ignore subchar arg)) (when (not *read-suppress*) (list '! (with-output-to-string (s) (loop :with c = (read-char stream) ;; :and done :while (not (and (char= c #\$) (char= (peek-char nil stream) #\#))) :do (write-char c s) (setf c (read-char stream))) (read-char stream))))) ;; read the final # ;; I'm not sure if I would ever use this. (define-reader-macro #\h sharp-h (stream subchar arg) "Read a “here” document until a line starting with the given token. The token should probably be a string." (declare (ignore subchar arg)) (when (not *read-suppress*) (let ((token (princ-to-string (read-from-string (read-line stream t nil t))))) (with-output-to-string (s) (loop :with line = (read-line stream t nil t) :while (not (begins-with token line)) :do (write-line line s) (setf line (read-line stream t nil t))))))) (defparameter *shell-whitespace* #(#\space #\tab #\newline #\return #\page) "Word separators for lish.") (defun contains-whitespace-p (s) (position-if #'(lambda (x) (position x *shell-whitespace*)) s)) (defparameter *reader-quote-char* ;; I don't think #\\ should be in here. #(#\" #\( #\) #\! #\space #\; #\| #\< #\> #\& #\^) "Characters which the reader interprets specially if not quoted.") (defun shell-read (line &key partial (package *lish-user-package*)) "Read objects in shell syntax and return them. It returns a ‘shell-expr’ or a normal lisp object. The syntax is vaguely like: ; comment command [arg...] command \"string\" ,*lisp-object* (lisp-code) command word\ with\ spaces \"string \\\" with a double quote\" command | command | ... command < file-name command > file-name ([lisp expressions...]) If ‘partial’ is true, don't signal an error if we can't read a full expression. Instead we return ‘*continue-symbol*’ as the first value, and as the second value, an explaination which consists of (tag-symbol datum...)." ; (setf line (expand-global-aliases line)) (let (words word-start (c nil) ; current char (i 0) ; index in line (len (length line)) (args '()) (sub-expr '()) (w (make-stretchy-string 12)) ; temp word (in-word nil) ; t if in word (in-first-word t) ; t if in the first word on the line (join-left t) ; t if we should maybe join left (join-right t) ; t if we should maybe join right (string-quote nil) (lisp-quote nil) (in-compound nil) (did-quote nil) (brace-depth 0) ; count braces and brakets (bracket-depth 0)) ; so we don't expand ! or , in them (labels ((reset-word () "Reset the word to be empty." (setf (fill-pointer w) 0 in-word nil in-first-word nil did-quote nil)) (add-finished-word () (push (make-shell-word :word (if sub-expr sub-expr (copy-seq w)) :eval (and sub-expr t) :start word-start :end i :quoted did-quote) args)) (try-char () ;; As a special hack for reading lisp characters for ;; parenless lisp evaluation, convert words starting with ;; #\ to the actual character. (let ((char (ignore-errors (read-from-string (copy-seq w) nil *continue-symbol*)))) (cond ((characterp char) (push (make-shell-word :word char :eval nil :start word-start :end i :quoted nil) args)) (t (add-finished-word))))) (finish-word () "Finish the current word." ;; (dbugf 'reader "finish-word ~s ~s~%" w in-word) (when in-word (if (and (not sub-expr) (>= (length w) 2) (char= (aref w 0) #\#) (char= (aref w 1) #\\)) (try-char) (add-finished-word))) (reset-word)) ;; (ignore-word () ;; "Ignore the current word." ;; (when in-word ;; (reset-word))) (add-to-word () "Add the character to the current word or start a new one." (when (not in-word) (setf word-start i) (when (and join-right (car args) (shell-word-eval (car args))) (setf (shell-word-join (car args)) (if (eq (shell-word-join (car args)) :left) :both :right))) (setf join-right nil)) (setf in-word t join-left t) (vector-push-extend c w) (incf i)) (read-lisp-expr () (when lisp-quote (decf i)) (handler-bind ((end-of-file (_ (declare (ignore _)) (do-continue 'lisp-expr (copy-seq w)))) ;; The spec is a bit vauge about what type of error should ;; be signaled if a symbol with a package marker doesn't ;; exist. In section 2.3.5 it says it should be correctable ;; and the effect should be the same as reading the symbol ;; with *package* set to the package prefix, but there's no ;; symbol existence error that can happen when it's not ;; prefixed. ;; ;; For example SBCL signals a reader-error, while CCL ;; signals a simple-error. I guess we should catch either? ;; This really only matters when partial is set. (reader-error (_ (do-reader-error _))) (simple-error (_ (do-reader-error _)))) ;; read a form as a separate word (multiple-value-bind (obj pos) (with-package package (if partial (clean-read-from-string line *junk-package* nil *continue-symbol* :start i) (read-from-string line nil *continue-symbol* :start i))) (setf word-start i i pos) ;; The CL reader reads one whitespace character past the end ;; of the expression. We need to see that whitespace, so ;; back it up. (when (and (/= i len) (plusp i) (position (aref line (1- i)) *shell-whitespace*)) (decf i)) (push (make-shell-word :word obj :eval t :quoted lisp-quote :start word-start :end i :join (if join-left :left nil)) args) ))) (return-partial () (setf word-start i) (push (make-shell-word :word (subseq line i) :start word-start :end (length line) :quoted nil :eval nil) args) (return-from shell-read (make-shell-expr :line line :words (nreverse args)))) (do-continue (reason &optional data) "Handle when the expression is incomplete." (if partial (return-partial) (return-from shell-read (values *continue-symbol* `(,reason ,@data))))) (do-reader-error (c) "Handle when the expression has an error." ;; (format t "lish-read error ~a~%" c) (if partial (return-partial) (signal c))) (next-char () "Return the next character or NIL." (when (< (+ i 1) len) (aref line (1+ i)))) (reverse-things () "Reverse the things we've been consing, so they're in order." (setf words (nreverse args))) (make-the-expr () "Make an expression, with it's own copy of the lists." (setf in-compound nil) (make-shell-expr :line line :words (copy-seq words))) (make-compound (key &optional (inc 2)) "Make a compound expression with type KEY." ;; (ignore-word) (finish-word) (reverse-things) (let ((e (list key (make-the-expr)))) (setf args (list e))) (incf i inc) (setf word-start 0 ;; word-end (list 0) ;; word-quoted (list nil) ;; word-eval (list nil) in-compound key join-left nil))) (loop :named tralfaz :while (< i len) :do (setf c (aref line i)) (cond ;; quoted char (string-quote ;; @@@ Actually I think we should leave some quote chars in until ;; after expansion. That way we can expand part of word, while ;; having some chars protected from expansion, e.g. glob chars ;; can be quoted. (when (not (position c *reader-quote-char*)) (vector-push-extend #\\ w)) (vector-push-extend c w) (when (not in-word) (setf word-start (1- i))) (setf in-word t) (setf string-quote nil) (incf i)) ;; a string ((eql c #\") (finish-word) ;; read a string as a separate word (multiple-value-bind (str ink cont) (read-string (subseq line (1+ i))) (when (and cont (not partial)) (return-from shell-read (values *continue-symbol* `(string ,str ,i)))) (setf word-start i) (incf i (+ (if cont 1 2) ink)) (push (make-shell-word :word str :start word-start :end i :quoted t :eval nil) args))) ;; a lisp function application ((eql c #\() (finish-word) (read-lisp-expr) (setf lisp-quote nil join-right t)) ((and (or (eql c #\') (eql c #\`)) (eql (next-char) #\()) (finish-word) (setf lisp-quote t) (incf i)) ((eql c #\#) ;; This is so we can use the Lisp reader interpretation of # at ;; the beginning of a shell line, but otherwise, in the rest of ;; the line ‘#’ is treated as a normal character. ;; This means we can do #+foo etc. before an expressin in scripts ;; and but still have command arguments, like filenames, that ;; begin with ‘#’. Of course ‘#’ in Lisp sub-expressions still ;; should work. (cond (in-word ;; # doesn't break words, like ( (add-to-word)) (in-first-word (read-lisp-expr)) (t (add-to-word)))) ;; Hack to not expand , in braces ((eql c #\{) (incf brace-depth) (add-to-word)) ((eql c #\}) (when (plusp brace-depth) (decf brace-depth)) (add-to-word)) ;; Hack to not expand ! in brackets ((eql c #\[) (incf bracket-depth) (add-to-word)) ((eql c #\]) (when (plusp bracket-depth) (decf bracket-depth)) (add-to-word)) ;; a lisp expr ((or #|(and (eql c #\!) (zerop bracket-depth)) |# (and (eql c #\,) (zerop brace-depth))) (setf sub-expr nil) (finish-word) (when (not in-word) (setf word-start i)) ;; read a form as a separate word (handler-bind ((end-of-file (_ (declare (ignore _)) (do-continue 'bang-expr (copy-seq w)))) (reader-error (_ (do-reader-error _)))) (multiple-value-bind (obj pos) (with-package package (if partial (clean-read-from-string line *junk-package* nil *continue-symbol* :start (+ i 1)) (read-from-string line nil *continue-symbol* :start (+ i 1)))) (setf i pos) (setf in-word t) ; so it gets output ;; (dbugf 'reader " ~s~%" obj) (if (and obj (integerp obj) *shell* (get-option *shell* 'history-expansion)) (map-into w #'identity (subseq line word-start i)) (setf sub-expr obj)) (finish-word) (setf sub-expr nil) ))) ;; quote char ((eql c #\\) (setf string-quote t) (incf i)) ;; whitespace ((position c *shell-whitespace*) (finish-word) (setf join-left nil join-right nil) (incf i)) ;; comment ((eql c #\;) (finish-word) ;; (loop :for j :from i :below len ;; :while (not (eql (aref line j) #\newline)) ;; :do (incf i)) (setf i (or (position #\newline line :start i) len))) ;; pipe plus ((and (eql c #\|) (eql (next-char) #\+)) (make-compound :pipe-plus)) ;; pipe dot ((and (eql c #\|) (eql (next-char) #\.)) (make-compound :pipe-dot)) ;; pipe ((and (eql c #\|) (not (eql (next-char) #\|))) (make-compound :pipe 1)) ;; redirect ((or (eql c #\<) (eql c #\>)) (finish-word) (reverse-things) ;; @@@ need to get the file name as a word (let ((e (list (if (eql c #\>) (cond ((eql (next-char) #\>) (progn (incf i) :append-to)) ((eql (next-char) #\&) (progn (incf i) :redirect-both-to)) (t :redirect-to)) :redirect-from) (make-the-expr)))) (setf word-start i) (setf args (list (make-shell-word :start word-start ;; :word (list e) ;; ??? :word e :end i :quoted nil :eval t)))) (incf i)) ;; and ((and (eql c #\&) (eql (next-char) #\&)) (make-compound :and)) ;; or ((and (eql c #\|) (eql (next-char) #\|)) (make-compound :or)) ;; sequence ((eql c #\^) (make-compound :sequence 1)) ;; any other character: add to word (t (add-to-word))) :finally (progn (finish-word) (reverse-things) )) (if (and (= (length words) 1) (consp (first words)) (not in-compound)) ;; just a lisp expression to be evaluated (first words) ;; a normal shell expression (if (and in-compound (< (length words) 2)) (return-from shell-read (values *continue-symbol* `(compound ,in-compound))) (make-the-expr)))))) ;; End
15,877
Common Lisp
.lisp
471
27.690021
80
0.592643
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
6fc9eebf503ecb35be4a9074c7b52ab21276d07e4dc7ab572e78a283e78fdb2e
2,134
[ -1 ]
2,135
prompt.lisp
nibbula_lish/prompt.lisp
;;; ;;; prompt.lisp - Things to make the prompt ;;; (in-package :lish) (defvar *lish-level* nil "Number indicating the depth of lish recursion. Corresponds to the ~ LISH_LEVEL environment variable.") ;; This is mostly so we can override some editor commands. (defclass lish-line-editor (line-editor) () (:default-initargs :default-keymap *lish-default-keymap*) (:documentation "A line editor for lish.")) (defsingle-method inator:redraw ((e lish-line-editor)) (setf (rl::prompt-string e) (safety-prompt *shell*)) (redraw-command e)) (defun fixed-homedir () "(user-homedir-pathname) with a trailing slash removed if there was one." (let ((h (safe-namestring (truename (user-homedir-pathname))))) (if (equal #\/ (aref h (1- (length h)))) (subseq h 0 (1- (length h))) h))) (defun twiddlify (name) "Turn (user-homedir-pathname) occuring in name into a tilde." (replace-subseq (safe-namestring (fixed-homedir)) "~" (safe-namestring name) :count 1)) (defun last-dot-segment (string) "Return the part of string after the last #\." (let ((pos (oposition #\. string :from-end t))) (if (and pos (< pos (olength string))) (osubseq string (1+ pos)) string))) ;; @@@ Should this be somewhere else? Do we need some kind of spacing DSL? (defun fill-middle (left middle-char right &key post-process) "Return a fat string exactly fitting the in the termimnal width, with ‘left’, the ‘middle-char’ repeated an appropriate amount, and then ‘right’. ‘post-process’ is function to apply to the middle string, the result of which is used as the middle string, if it's non-NIL." (let* ((l (char-util:display-length left)) (r (char-util:display-length right)) (m (max 0 (- (tt-width) l r))) (middle (fatchar:make-fat-string :length m :initial-element (etypecase middle-char (fatchar middle-char) (character (make-fatchar :c middle-char)))))) (if (zerop m) (fs+ left middle-char right) (fatchar-io:fs+ left (if post-process (or (funcall post-process middle) middle) middle) right)))) ;; This is mostly for bash compatibility. (defun format-prompt (sh prompt &optional (escape-char #\%)) "Return the prompt string with bash-like formatting character replacements. So far we support: %% A percent. %a #\\bell %e #\\escape %n #\\newline %r #\\return %NNN The character whose ASCII code is the octal value NNN. %s The name of the shell, which is usually “Lish”. %v Shell version. %V Even more shell version. %u User name. %h Host name truncated at the first dot. %H Host name. %w Working directory, tildified. %W The basename of `$PWD', tildified. %$ If the effective UID is 0, `#', otherwise `$'. %i The lisp implementation nickname. %p The shortest nickname of *lish-user-package*. %P The current value of *lish-user-package*. %d <3 char weekday> <3 char month name> <date>. %t 24 hour HH:MM:SS %T 12 hour HH:MM:SS %@ The time, in 12-hour am/pm format. %A The time, in 24-hour HH:MM format. %D{FORMAT} Some date formated by mini-strftime. Without the FORMAT just put some locale-specific date. %j The number of jobs currently managed by the shell. %! The history number of this command. %# The command number of this command. %l The approximate name of the shell's terminal device. " ;; These are not implemented yet, but I don't think it's a good idea anyway ;; since we can do colors and effects a better way and it would assume ;; something inappropriate about the terminal. ;; ;; %[ Start of non-printing characters. ;; %] End of non-printing characters. (declare (ignore sh)) (flet ((output-loop (str) (loop :with c :for i :from 0 :below (olength prompt) :do (setf c (oelt prompt i)) (if (equal c escape-char) (progn (incf i) (when (< i (olength prompt)) (setf c (simplify-char (oelt prompt i))) (case c (#\% (write-char escape-char str)) (#\a (write-char #\bell str)) (#\e (write-char #\escape str)) (#\n (write-char #\newline str)) (#\r (write-char #\return str)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (write-char (code-char (parse-integer (osubseq prompt i (+ i 3)) :radix 8)) str)) (#\s (write-string (princ-to-string *shell-name*) str)) (#\v (princ *major-version* str)) (#\V (write-string (princ-to-string *version*) str)) (#\u (write-string (nos:user-name) str)) (#\h (write-string (initial-span (os-machine-instance) ".") str)) (#\H (write-string (machine-instance) str)) (#\w (write-string (twiddlify (nos:current-directory)) str)) (#\W (write-string (twiddlify (basename (nos:current-directory))) str)) (#\$ (write-char (if (= (nos:user-id :effective t) 0) #\# #\$) str)) (#\i (write-string (princ-to-string *lisp-implementation-nickname*) str)) (#\p (write-string (s+ (and *lish-user-package* (last-dot-segment (shortest-package-nick *lish-user-package*)))) str)) (#\P (write-string (s+ (and *lish-user-package* (package-name *lish-user-package*))) str)) (#\d (write-string (format-date "~3a ~3a ~2d" (:day-abbrev :month-abbrev :date)) str)) (#\t (write-string (format-date "~2,'0d:~2,'0d:~2,'0d" (:hours :minutes :seconds)) str)) (#\T (write-string (format-date "~2,'0d:~2,'0d:~2,'0d" (:12-hours :minutes :seconds)) str)) (#\@ (write-string (format-date "~2,'0d:~2,'0d ~2a" (:12-hours :minutes :am)) str)) (#\A (write-string (format-date "~2,'0d:~2,'0d" (:hours :minutes)) str)) (#\D (multiple-value-bind (s e ss ee) (ppcre:scan "\\{(%[A-Za-z]{1,10})\\}" (subseq prompt i)) (cond ((and s ss) (write-string (dtime:mini-strftime (subseq prompt (+ i (aref ss 0)) (+ i (aref ee 0)))) str) (incf i (1- e))) (t (write-string (dtime:date-string) str))))) (#\j (format str "~d" (length (lish-jobs *shell*)))) (#\! ;; This is slow (format str "~d" (olength (rl::history-current-get)))) (#\# (format str "~d" (shell-command-count *shell*))) (#\l (write-string #+unix (remove-prefix (file-handle-terminal-name 0) "/dev/") #-unix (file-handle-terminal-name (stream-system-handle *terminal-io*)) ;whatever str)) ))) ;; (write-char c str) (princ c str) )))) (etypecase prompt (string (with-output-to-string (str) (output-loop str))) ((or fat-string fatchar-string) (with-output-to-fat-string (str) (output-loop str)))))) (defun symbolic-prompt-to-string (sh symbolic-prompt #| &optional ts-in |#) "Take a symbolic prompt and turn it into a fat-string. This uses span-to-fatchar-string with a filter of format-prompt and with the addition of evaluation, so see the documentation of those for more detail, Briefly, a symbolic prompt can be any printable lisp object, which is converted to a fat string. If it is a list, it translates sublists starting with certain keywords, to characters with text effects applied to the enclosed objects. Some of the keywords recognized are: :BOLD :UNDERLINE :INVERSE and the colors :BLACK :RED :GREEN :YELLOW :BLUE :CYAN :WHITE and :DEFAULT. The colors can be prefixed by :FG- or :BG- for the foreground or background. Complex colors are also supported, for example (:fg :color [color]), where [color] can be something supported the color package, e.g. #(:RGB 0.1 0.7 0.9). Evaluation is supported, so symbols will be replaced by their value and functions will be evaluated with the primary result printed as a string. Strings can have '%' directives which are expanded by format-prompt." ;; @@@ This docstring could use improvement? (fatchar:span-to-fat-string symbolic-prompt :filter (_ (format-prompt sh _)) :unknown-func (lambda (x) ; eval is magic (cond ((and (listp x) (symbolp (car x)) (fboundp (car x))) ;; Actually we need a full eval here. (values (eval x) t)) ((symbolp x) (when (boundp x) (values (symbol-value x) nil))) (t (values (princ-to-string x) nil)))))) #| (defun fill-prompt () (#\f (let ((len (length out)) out-char cols) (when (> len 1) (setf out-char (aref out (1- len)) cols (terminal-window-columns (rl:line-editor-terminal (lish-editor sh)))) (loop :repeat (- cols len) :do (write-char out-char str)))))) 1. Expand the %<things> in the symbolic version. 2. Convert to fatchar and expand the %fill which can now know the true size 3. Convert from fatchar to final device form |# (defvar *fallback-prompt* "Lish> " "Prompt to use as a last resort.") (defgeneric make-prompt (shell prompt) (:documentation "Return a string to prompt with.")) (defmethod make-prompt ((sh shell) prompt) "Return a string to prompt with." (or (and prompt ;; (format-prompt ;; sh (symbolic-prompt-to-string (lish-prompt sh)))) (symbolic-prompt-to-string sh prompt)) ;; (if (and (lish-prompt-char sh) ;; (characterp (lish-prompt-char sh))) ;; (format nil "~a " ;; (make-string (+ 1 *lish-level*) ;; :initial-element (lish-prompt-char sh))) *fallback-prompt*)) ;; This isn't even "safe". (defun safety-prompt (sh &optional side) "Return a prompt, in a manner unlikely to fail." (let (prompt-error) (macrolet ((handle-it (&body body) `(catch 'problems (handler-case (progn ,@body) (error (c) (setf prompt-error c) (throw 'problems nil)))))) (if (eq side :right) (or (and (lish-right-prompt sh) (or (handle-it (make-prompt sh (lish-right-prompt sh))) (progn (format t "Your right prompt is broken: ~s~%" prompt-error) ""))) "") (or (and (lish-prompt-function sh) (or (handle-it (funcall (lish-prompt-function sh) sh)) (format t "Your prompt function failed: ~s.~%" prompt-error))) (or (handle-it (make-prompt sh (lish-prompt sh))) (progn (format t "Your prompt is broken: ~s~%" prompt-error) *fallback-prompt*))))))) (defun is-lisp-expr-p (expr) "Return true if the the shell expr is likely just a wrapped Lisp expr." (and (= 1 (length (shell-expr-words expr))) (or (consp (elt (shell-expr-words expr) 0)) (consp (word-word (elt (shell-expr-words expr) 0)))))) (defun is-probably-a-lisp-expr-p (word) (let ((trimmed (ltrim word))) (and (not (zerop (length trimmed))) (eql #\( (aref trimmed 0))))) (defun colorize-function (form env) (declare (ignore env)) `(#\( (:fg-magenta ,(string-downcase (car form))) ,@(cdr form) #\))) (defun colorize-atom (form env) (declare (ignore env)) (s+ " " (string-downcase form))) (defun colorize-lisp (expr fat-string) "Colorize a lisp expression." (declare (ignore expr fat-string)) #| (dbugf :recolor "boglar-ize ~s~%" expr) (let* ((sexp (word-word (first (shell-expr-words expr)))) (colorized-span (agnostic-lizard:walk-form sexp nil :on-function-form #'colorize-function :on-every-atom #'colorize-atom)) ) (dbugf :recolor "smooty span ~s ~s ~s~%" sexp colorized-span (olength fat-string)) ;; (loop :with new = (span-to-fatchar-string colorized-span) ;; :for i :from 0 :below (olength new) ;; :do (setf (oelt fat-string i) (oelt new i))) (dbugf :recolor "smoot string ~s ~s~%" fat-string (olength fat-string))) |# ) (defun themify-shell-word-in-fat-string (word string theme-item) "Apply the THEME-ITEM, which should be a style, to the WORD in the fat string STRING. Don't do anything if theme-item isn't found or is nil." (when (theme:theme-value theme:*theme* theme-item) (let* ((fcs string #| (fat-string-string string) |#) (style (oelt (style:themed-string theme-item '("x")) 0))) ;; (dbugf :recolor "word ~s~%style ~s~%item ~s~%string ~s~%" ;; word style theme-item string) (when (not (zerop (length (word-word word)))) (loop :for i :from (shell-word-start word) :below (shell-word-end word) :do (copy-fatchar-effects style (aref fcs i))))))) (defun unthemify-shell-word-in-fat-string (word string) (loop :for i :from (shell-word-start word) :below (shell-word-end word) :do (remove-effects (aref string i)))) (defun colorize-expr (expr fat-str) "Colorize a shell expression." (let* ((first-word (and (shell-expr-p expr) (first (shell-expr-words expr)))) type) (flet ((theme-it (tt word) "Apply theme TT to WORD." (themify-shell-word-in-fat-string word fat-str tt))) (cond ((is-lisp-expr-p expr) (colorize-lisp expr fat-str)) ((and (listp first-word) (keywordp (first first-word))) ;; colorize the sub-expression of a compound expression (colorize-expr (second first-word) fat-str)) ((shell-expr-p expr) (when (and first-word (stringp (word-word first-word))) ;; @@@ stupid hack to not turn lisp red (if (is-probably-a-lisp-expr-p (word-word first-word)) (progn (dbugf :recolor "smellman ~s~%" (word-word first-word)) ;; (colorize-lisp (word-word first-word) fat-str) (colorize-lisp expr fat-str) ) (progn (setf type (command-type *shell* (word-word first-word) :already-known t)) ;; (dbugf :recolor "command-type ~s~%" type) (case type ((:external-command :source-command :builtin-command :shell-command :command :alias :global-alias :function :loadable-system) (dbugf :recolor "melgor ~s~%" first-word) (theme-it `(:command ,type :style) first-word)) (:file (theme-it '(:command :system-command :style) first-word)) (:directory (theme-it '(:command :directory :style) first-word)) (otherwise (dbugf :recolor "glorb ~s~%" first-word) (theme-it '(:command :not-found :style) first-word)))))) (loop :for w :in (rest (shell-expr-words expr)) :do (when (stringp (word-word w)) (cond ;; ((handler-case ;; (nos:file-exists (glob:expand-tilde (word-word w))) ;; (opsys-error (c) ;; (declare (ignore c)))) ((ignore-errors (nos:file-exists (shell-expand-variables (glob:expand-tilde (word-word w))))) (theme-it '(:command-arg :existing-path :style) w)) (t (unthemify-shell-word-in-fat-string w fat-str)))))))))) (defun colorize (e) "Colorize the editor buffer." (when (lish-colorize *shell*) ;;(format t "buf = ~s ~s~%" (type-of (rl::buf e)) (rl::buf e)) (catch 'whatever (handler-case (progn (let ((expr (shell-read (char-util:simplify-string (rl::buf e)) :partial t))) (if (shell-expr-p expr) (progn (colorize-expr expr (rl::buf e))) (progn (dbugf :recolor "moomar ~s~%" expr)) ))) (error () ;; Errors are particularly useless and annoying here. (throw 'whatever nil)) )))) (defun gradientize (string start-color end-color &key (start 0) end (which :bg)) "Make the color of string be a gradient from ‘start-color’ to ‘end-color’. Only effect characters from ‘start’ to ‘end’. ‘which’ is either :fg or :bg to indicate which color to affect, and defaults to :bg." (setf string (typecase string ((or fat-string fatchar-string) string) (string (string-to-fat-string string)) (t (error "Gradientize should be passes a string or a fat-string, ~ not a ~s." (type-of string))))) (when (not end) (setf end (olength string))) (setf start-color (dcolor:lookup-color start-color) end-color (dcolor:lookup-color end-color)) (let ((steps (- end start))) (when (> steps 1) (let* ((end-red (dcolor:color-component end-color :red)) (end-blue (dcolor:color-component end-color :blue)) (end-green (dcolor:color-component end-color :green)) (start-red (dcolor:color-component start-color :red)) (start-blue (dcolor:color-component start-color :blue)) (start-green (dcolor:color-component start-color :green)) (red-step (/ (abs (- end-red start-red)) (- steps 1))) (green-step (/ (abs (- end-green start-green)) (- steps 1))) (blue-step (/ (abs (- end-blue start-blue)) (- steps 1)))) (setf red-step (if (< (- end-red start-red) 0) (- red-step) red-step)) (setf green-step (if (< (- end-green start-green) 0) (- green-step) green-step)) (setf blue-step (if (< (- end-blue start-blue) 0) (- blue-step) blue-step)) (loop :for i :from start :below (+ start steps) :for r = start-red :then (+ r red-step) :for g = start-green :then (+ g green-step) :for b = start-blue :then (+ b blue-step) :do (case which (:fg (setf (fatchar-fg (oelt string i)) (vector :rgb r g b))) (:bg (setf (fatchar-bg (oelt string i)) (vector :rgb r g b)))))))) string) ;; End
17,074
Common Lisp
.lisp
438
34.385845
80
0.63531
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
f21d43482325e5b5955a0db6a4ee9133d0cd305150b58340b8a8f67eed0e11fd
2,135
[ -1 ]
2,136
builtin.lisp
nibbula_lish/builtin.lisp
;;; ;;; builtin.lisp - Lish built-in commands. ;;; ;; Here we define the commands that are built in to Lish. ;; Most of these are for familiarity and superficial compatability with a ;; POSIX shell. You could get rid of them, or use different names, since most ;; of their functionality is contained in Lisp functions. (in-package :lish) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Command definitions (defun home-directory () "Return a namestring of the user's home directory in a particular way." (or (nos:environment-variable "HOME") (nos:user-home) (namestring (user-homedir-pathname)))) (defun push-directory-ring (dir) "Push ‘dir’ on the directory ring." (with-slots (directory-ring directory-ring-size) *shell* (when (> (length directory-ring) directory-ring-size) (pop directory-ring)) (setf directory-ring (append directory-ring (list dir))))) (defun find-directory-in-ring (regexp) "Return a directory from the directory ring matching ‘regexp’. If not found just return the current directory." (let ((result (find regexp (lish-directory-ring *shell*) :test #'cl-ppcre:scan))) (or result (nos:current-directory)))) (defbuiltin cd ((directory directory :help "Directory to change to.")) "Change the current directory to DIRECTORY. If DIRECTORY isn't specified, use *input* if it's a directory or the shell's idea of the user's home directory." (when (equal directory "-") (setf directory (lish-old-pwd *shell*))) (when (begins-with "=" directory) (setf directory (find-directory-in-ring (subseq directory 1)))) (push-directory-ring (nos:current-directory)) (setf (lish-old-pwd *shell*) (nos:current-directory)) (nos:change-directory (or directory (and *input* (nos:directory-p *input*) *input*) (home-directory))) ;; Update $PWD like traditional Unix shells. ;; @@@ Maybe someday we can get rid of this. (setf (nos:environment-variable "PWD") (nos:current-directory))) (defbuiltin pwd () "Print the current working directory." (format t "~a~%" (setf *output* (nos:current-directory))) *output*) (defbuiltin pushd ((directory directory :help "Directory to push on the stack.")) "Change the current directory to DIRECTORY and push it on the the front of the directory stack." (when (not directory) (setf directory (pop (lish-dir-list *shell*)))) (push (nos:current-directory) (lish-dir-list *shell*)) (!cd :directory directory)) (defbuiltin popd ((number number :help "Number of item to pop.")) "Change the current directory to the top of the directory stack and remove it from stack." (declare (ignore number)) (let ((dir (pop (lish-dir-list *shell*)))) (!cd :directory dir) dir)) (defbuiltin dirs () "Show the directory stack." (format t "~{~a~%~}" (lish-dir-list *shell*)) (setf *output* (lish-dir-list *shell*))) (defbuiltin suspend () "Suspend the shell." (opsys:suspend-process)) (defun job-id-list () "Return a list of suspended job ids." (loop :for j :in (lish-jobs *shell*) :collect (job-id j))) (define-builtin-arg-type job-descriptor (arg-lenient-choice) "A job descriptor." () (:default-initargs :choice-func #'job-id-list)) ;; (defclass arg-job-descriptor (arg-lenient-choice) ;; () ;; (:default-initargs ;; :choice-func #'job-id-list) ;; (:documentation "A job descriptor.")) (defbuiltin fg ((job-descriptor job-descriptor :optional t :help "Job to resume.")) "Resume a suspended job." (let (job) (cond ((or (null (lish-jobs *shell*)) (= (length (lish-jobs *shell*)) 0)) (format t "No jobs to resume.~%") (return-from !fg (values))) ((= (length (lish-jobs *shell*)) 1) (setf job (first (lish-jobs *shell*)))) (t (setf job (find-job job-descriptor)))) (if (not job) (format t "Couldn't find a job matching ~a.~%" job-descriptor) (continue-job-in-foreground job)))) (defbuiltin bg ((job-descriptor job-descriptor :optional t :help "Job to backaground.")) "Put a job in the background." (let ((job (find-job job-descriptor))) ;; (format t "job-descriptor = ~s ~a job = ~s~%" ;; job-descriptor (type-of job-descriptor) job) (if job (continue-job-in-background job) (format t "Couldn't find a job matching ~a.~%" job-descriptor))) (values)) (defbuiltin jobs ((long boolean :short-arg #\l :help "Show the longer output.") (all boolean :short-arg #\a :help "Show all (or at least maybe more) jobs.")) "Lists spawned processes that are active." (flet ((job-row (j) (with-slots (id name command-line status) j (let ((result (list id (job-type-name j) name command-line)) (extra (when long (typecase j (lisp-job (job-resume-function j)) (system-job (s+ status " " (job-pid j))))))) (if extra (nconc result (list extra)) result))))) (let ((table (make-table-from (loop :for j :in (if all `(,@(lish-jobs *shell*) ,@(list-all-jobs 'lisp-job) ,@(list-all-jobs 'thread-job)) (lish-jobs *shell*)) :collect (job-row j)) :columns `((:name "ID" :type number) (:name "Type") (:name "Name") (:name "Command") ,(when long '(:name "Extra")))))) (with-grout () (grout-print-table table :print-titles nil)) (setf *output* table)))) (defbuiltin history ((clear boolean :short-arg #\c :help "Clear the history.") (write boolean :short-arg #\w :help "Write the history to the history file.") (read boolean :short-arg #\r :help "Read the history from the history file.") (append boolean :short-arg #\a :help "Append the history to the history file.") (read-not-read boolean :short-arg #\n :help "Read history items not already read from the history file.") ;; @@@ I think I'd lke it if it would only apply only for that command, ;; but that probably involves changes to the history-store protocol. (filename pathname :short-arg #\f :help "Use ‘pathname’ as the history file. If given with other commands, then the pathname is changed before the command.") (show-times boolean :short-arg #\t :help "Show history times.") (delete integer :short-arg #\d :help "Delete the numbered history entry.") (table boolean :short-arg #\T :help "True to return a table of the history.") (yes boolean :short-arg #\y :help "Don't warn for destructive operations.") (dedup boolean :short-arg #\D :help "Remove duplicates.")) "Show a list of the previously entered commands." ;; Check argument conflicts (cond ;; @@@ Could this kind of thing be done automatically? ;; Yes, it totally could with the grammer based argument parser. ((and clear (or write read append read-not-read filename show-times dedup delete)) (error "CLEAR should not be given with any other arguments.")) ((and delete (or write read append read-not-read filename show-times dedup clear)) (error "DELETE should not be given with any other arguments.")) ((and dedup (or write read append read-not-read filename show-times clear delete)) (error "DEDUP should not be given with any other arguments.")) ((> (count t `(,write ,read ,append ,read-not-read)) 1) (error "Only one of WRITE, READ, APPEND, or READ-NOT-READ should be given.")) ((and filename (not (or read write append read-not-read))) (error "FILENAME is only useful with READ, WRITE, APPEND, or READ-NOT-READ."))) ;; Set the file name before other commands. (when filename (setf (history-store-file-name (lish-history-store *shell*)) filename)) (cond (clear (when (or yes (yes-or-no-p "Are you sure you want to erase history?")) (rl:history-clear :lish))) (dedup (when (or yes (yes-or-no-p "Are you sure you want to remove duplicates from history?")) (rl:history-dedup :lish))) ;; @@@ It might be nice if we could say what happend, like how many ;; history items were saved or loaded. (write (save-history *shell*)) (read (load-history *shell*)) (append (save-history *shell* :update t)) (read-not-read (load-history *shell* :update t)) (delete (format t "Sorry, delete is not implemented yet.~%")) (table (setf *output* (rl:history-table :context :lish))) (t (rl:show-history :context :lish :show-time show-times ;; :show-extra (get-option *shell* 'history-save-values) )))) ;; This seems stupid and unnecessary. ;; (defbuiltin #:|:| (("args" t :repeating t)) ;; "Arguments are evaluated for side effects." ;; (declare (ignore args)) ;; (values)) (defbuiltin echo ((no-newline boolean :short-arg #\n :help "Don't output a newline.") (args t :rest t :help "Words to print.")) "Output the arguments. If -n is given, then don't output a newline a the end." (let ((echo-list (or args (if (consp *input*) *input* (list *input*))))) (format t "~{~a~#[~:; ~]~}" echo-list) (when (not no-newline) (terpri)) ;; pop the bubble (setf *output* (if (olength-at-least-p 2 echo-list) echo-list (oelt echo-list 0))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; help (defun print-columnar-help (rows) (with-grout () (let ((table (make-table-from rows :columns '((:name "Name") (:name "Description" :align :wrap))))) (grout-print-table table :print-titles nil) table))) (defun command-list (type) "Return a list of commands of TYPE." (sort (loop :for k :being :the :hash-values :of (lish-commands) :when (typep k type) :collect k) #'string-lessp :key #'command-name)) (defun print-multiple-command-help (commands) (let ((rows (loop :for k :in commands :collect (etypecase k ;; @@@ make generic? (autoloaded-command (list (command-name k) (string-downcase (command-load-from k)) ;; (documentation ;; (command-function-name (command-name k)) 'function) )) (command (let* ((doc (documentation (command-function k) 'function)) (pos (position #\. doc))) (list (command-name k) ;; Only the first sentance, i.e. up to the first period, ;; without newlines. (substitute #\space #\newline (if pos (subseq doc 0 (1+ pos)) doc))))))))) (print-columnar-help rows))) ;; This has to make sure to be able to operate without a current shell or even, ;; current terminal, since it's called by the documentation method. (defun print-command-help (cmd &key (stream ;; (or *terminal* *standard-output*) *standard-output*) indent) "Print documentation for a command. Return a table." (declare (ignore indent)) (with-grout (*grout* stream) (grout-format "~a~%" (documentation cmd 'function)) (let (table) (when (and (command-arglist cmd) (not (zerop (length (command-arglist cmd))))) (grout-format "Arguments:~%") (grout-print-table (setf table (make-table-from (loop :for a :in (command-arglist cmd) :when (not (arg-hidden a)) :collect (list (if (arg-short-arg a) (s+ " -" (arg-short-arg a)) " ") (if (arg-long-arg a) (s+ "--" (arg-long-arg a)) (if (arg-short-arg a) "" (arg-name a))) #| (or (arg-default a) "") |# (string-downcase (arg-type a)) (or (and (slot-boundp a 'help) (substitute #\space #\newline (arg-help a))) (arg-name a)))) :columns '((:name "Short") (:name "Long") (:name "Type") (:name "Help" :align :wrap)))) :long-titles nil :print-titles nil #|:max-width (get-cols)|# :trailing-spaces nil)) (when (and (command-accepts cmd) (not (eq (command-accepts cmd) :unspecified))) (grout-format "~&Accepts: ~a~%" (command-accepts cmd))) (typecase cmd (command (when (and (not (command-built-in-p cmd)) (command-loaded-from cmd)) (grout-format "Loaded from: ~a~%" (command-loaded-from cmd)))) ;; (autoloaded-command ;; (grout-format "Load from: ~a~%" (command-load-from cmd))) ) table))) ;; For use by other things. Like my "doc" command. ;; This used to be (eql :command), but that was taken by lispworks, so fuck it. (defmethod documentation ((symbol symbol) (type (eql 'command))) (let ((cmd (get-command (string-downcase (symbol-name symbol))))) (when cmd (with-output-to-string (str) (print-command-help cmd :stream str))))) (defmethod documentation ((command command) (type (eql 'command))) (with-output-to-string (str) (print-command-help command :stream str))) (defmethod describe-object ((object command) stream) (format stream "~s [~s]~%" (command-name object) (type-of object)) (print-command-help object :stream stream) (call-next-method)) (defvar *help-table* nil "Hash table of help functions.") (eval-when (:compile-toplevel :load-toplevel :execute) (defun help-function-name (subject) "Return the help function for ‘subject’." (symbolify (s+ "help-" subject))) (defun help-table () ;; Allow shells to have a customized help table. (or (and *shell* (shell-help-table *shell*)) *help-table* (setf *help-table* (make-hash-table :size 16 :test 'equalp)))) (defmacro defhelp (subject () &body body) "Define a help subject for ‘subject-name’, which can be invoked by the ‘help’ command. You should provide a docstring in the body which will be the subject description. The body should probably output the help to *standard-output*, but could do whatever you think is helpful, such as invoking a more sophisticated help viewer." (let ((func-name (help-function-name subject))) `(progn (defun ,func-name () ,@body) (setf (gethash (string ',subject) (help-table)) (function ,func-name)))))) (defparameter *basic-help* "~ Lish version ~a help: This is Lish, a command line shell with Lisp. A brief summary of what to type: command [arg*...] Run a program in your path with the given ARGs. ([expressions]...) Evaluate Lisp expressions. help [subject] Show help on the subject. exit Exit the shell. Further help is available on these subjects: ") (defhelp "" () "Basic help." (format t *basic-help* *version*) (let ((table (make-table-from (loop :for s :in (remove "" (help-subjects) :test #'equal) :collect (list s (help-subject-description s))) :columns '((:name "Subject" :format " ~va") (:name "Description" :format " ~va"))))) (with-grout () (grout-print-table table :print-titles nil)) (setf *output* table))) (defhelp builtins () "Built-in commands." (format t "Built-in commands:~%") (setf *output* (print-multiple-command-help (command-list 'builtin-command)))) (defhelp commands () "Defined commands." (format t "Defined commands:~%") (setf *output* (print-multiple-command-help (command-list 'shell-command)))) (defhelp external () "Defined external commands." (format t "Defined external commands:~%") (setf *output* (print-multiple-command-help (command-list 'external-command)))) (defparameter *editor-help* "You can use some Emacs-like commands to edit the command line. Some notable keys are: <Tab> Try to complete the word in front of the cursor. Twice for more. ? Show what input is expected. List possibilities. <Control-D> Quit, when on an empty line, or delete the following character. <Control-P> Previous history line. Also the <Up Arrow> key. <Control-N> Next history line. Also the <Down Arrow> key. <Control-B> Move the cursor back one character. Also the <Left Arrow> key. <Control-F> Move the cursor forward one character. Also the <Right Arrow> key. <Control-Q> Quote next character, like if you want to really type '?'. ") ;; This doesn't really work unless you start lish from inside a tiny-repl, so we ;; probably shouldn't advertise it. It's relatively pointless anyway. ;; <F9> Switch back and forth between LISH and the lisp REPL. (defhelp editor () "The line editor." (format t *editor-help*)) ;; @@@ I want this to be markdown or something. At least fit the paragraphs to ;; the width of the terminal. (defparameter *syntax-help* "The syntax is a combination of POSIX shell and Lisp, hopefully in a way that is familiar and not too surprising to those who know either. It is vaguely like: ; comment command [arg...] command \"string\" ,*lisp-object* (lisp-code) $ENV_VAR command *.glob ?ooba[rz] command word\\ with\\ spaces \"string \\\" with a double quote\" command | command | ... command < file-name command > file-name ([lisp expressions...]) Basically, inside parentheses you get Lisp reader syntax. Outside parentheses, you get a very simplified shell syntax with Lisp strings and comments. Some typical shell expansions are done in command arguments, such as shell globbing with *,?,and [], environment variable expansions with $VAR, and home directory expansions with ~~user. Pipeline and redirections should work nearly as expected. Commands can be: - System executables in your standard PATH - Built-in or later defined commands, defined with DEFCOMMAND - Names of systems in your ASDF \"path\" which are expected to define a command with the same name as the system, which is then invoked. - Lisp functions or methods ") (defhelp syntax () "Shell syntax." (format t *syntax-help*)) (defparameter *differences-help* "Lish is different from a POSIX shell. The most notable differences are: - Parentheses switch to Lisp syntax, and don't mean run in sub-shell. Lisp inside parentheses is evaluated and substituted in the current line. - String quoting is done only with double quote \". Single quote ' and back quote `, are not special to avoid confusion with Lisp syntax. - The prefix VAR=value isn't supported. Use the ‘env’ command instead. - Redirection syntax is different, e.g \"2>&1\" doesn't work. - Commands can be Lish commands and Lisp functions, as well as executables in your PATH. Lish commands can be searched for and automatically loaded from ASDF places, manipulated by the ‘ldirs’ command. - Most scripting related shell commands are missing, e.g. if, test, case. Scripting parameter expansion like $1 $* ${} are missing. Use Lisp instead. - Shell expansions are different. Many expansions can be done by Lish functions starting with ! , such as (!_ \"ss\") expands to a list of strings of the lines of output, (!? \"grep fuse /proc/filesystems\") returns a boolean status. Comma can be used to substitute a Lisp value, e.g. \"echo ,*package*\". - Comments start with ; not # For more detail see the section ‘Differences from POSIX shells’ in docs/doc.org ") (defhelp differences () "Differences from other ehells." (format t *differences-help*)) (defhelp options () "Shell options." (format t "~ Options can be examined and changed with the ‘opt’ command.~%~ Shell options:~%") (setf *output* (print-columnar-help (loop :for o :in (lish-options *shell*) :collect `(,(arg-name o) ,(substitute #\space #\newline (arg-help o))))))) (defhelp keys () "Key bindings." (format t "Here are the keys active in the editor:~%") (!bind :print-bindings t)) (defparameter *startup-help* "Here's what the shell does when starting: - Increment the *lish-level* and LISH_LEVEL. - Update the LISH-USER package with symbols from CL-USER. - Load the startup commands file, which comes from one of: - The value passed to the shell with the :init-file keyword - The value of *lishrc* - The standard place for configuration files: (opsys:path-append (opsys:config-dir \"lish\") \"lishrc\") which is: ~s - The value of *default-lishrc*, which is: ~s The current value is: ~s - Make sure *theme* is set, using the (default-theme) if necessary. - Make a new line editor, which might make a new *terminal*. See the documentation for RL for details. - Evaluate the *enter-shell-hook* functions. The current value is: ~a.~%~%") (defhelp startup () "What happens when the shell starts." (format t *startup-help* (opsys:path-append (opsys:config-dir "lish") "lishrc") *default-lishrc* *lishrc* *enter-shell-hook*)) (defun help-subjects () "Return a list of help subjects." (sort (omap-as 'list (_ (string-downcase (oelt _ 0))) (help-table)) #'string<)) (defun help-function (subject) "Return the help function for for ‘subject’, or NIL if it isn't defined." (gethash (string subject) (help-table))) (defun help-subject-description (subject) "Return the description of help subject ‘subject’." ;; (documentation (help-function-name subject) 'function)) (documentation (help-function subject) 'function)) (defun help-on (subject) "Print help on ‘subject’." (let ((func (help-function subject))) (if func (funcall func) (format t "I don't know about the subject \"~a\"~%" subject)))) (defun help-choices () "Return a list of choices for a help subject." (concatenate 'list (remove "" (help-subjects) :test #'equal) (mapcar #'(lambda (x) (or (and (symbolp x) (string-downcase (symbol-name x))) (and (stringp x) x) x)) *command-list*))) (define-builtin-arg-type help-subject (arg-choice) "Something which we can get help on." () (:default-initargs :choice-func #+clisp 'help-choices ; I'm not sure why. #-clisp #'help-choices)) (defbuiltin help ((subject help-subject :help "Subject to get help on.")) "Show help on the subject. Without a subject show some subjects that are available." (when (null subject) (setf subject "")) (let (cmd) (cond ((help-function subject) (help-on subject)) ((setf cmd (get-command subject)) ;; Try a specific command (let* ((symb (intern (string-upcase subject) :lish)) (doc (when cmd (documentation cmd 'function))) (fdoc (when (fboundp symb) (documentation (symbol-function symb) 'function)))) (cond (doc (setf *output* (print-command-help cmd))) (fdoc (format t "Lisp function:~%~a~%" fdoc)) (cmd (format t "Sorry, there's no help for \"~a\".~%" subject))))) (t (format t "I don't know about the subject \"~a\"~%" subject))))) (defmethod documentation ((b command) (doctype (eql 'function))) "Return the documentation string for the given shell command." (with-output-to-string (str) (format str "~a" (posix-synopsis b)) (let ((doc (documentation (command-function b) 'function))) (when doc (format str "~%~a" doc))))) ;; (when (command-loaded-from b) ;; (format str "~%Loaded from ~a" (command-loaded-from b))) (defun set-alias (name expansion &key global (shell *shell*)) "Define NAME to be an alias for EXPANSION. NAME is replaced by EXPANSION before any other evaluation." (setf (gethash name (if global (lish-global-aliases shell) (shell-aliases shell))) expansion)) (defun unset-alias (name &key global (shell *shell*)) "Remove the definition of NAME as an alias." (remhash name (if global (lish-global-aliases shell) (shell-aliases shell)))) (defun get-alias (name &key global (shell *shell*)) "Return the alias definition of ‘NAME’, or NIL if there isn't one. - SHELL The shell instance to look in, which defaults to *SHELL*. - GLOBAL Return the 'global' alias." (if global (gethash name (lish-global-aliases shell)) (gethash name (shell-aliases shell)))) (defun alias (name) "Return the alias definition of NAME, or NIL if there isn't one." (gethash name (shell-aliases *shell*))) (defsetf alias set-alias "Set the alias definition.") (defun edit-alias (name &key global) (rl :prompt (s+ "alias " name " ") :string (or (get-alias name :global global :shell *shell*) ""))) (defbuiltin alias ((global boolean :short-arg #\g :help "True to define a global alias.") (edit boolean :short-arg #\e :help "True to edit the alias's value.") (name string :help "Name of the alias.") (expansion string :rest t :help "Text to expand to.")) "Define NAME to expand to EXPANSION when starting a line." (if (not name) (let ((table (make-table-from (loop :for a :being :the :hash-keys :of (if global (lish-global-aliases *shell*) (shell-aliases *shell*)) :collect (list a (get-alias a :global global :shell *shell*))) :columns '((:name "Alias") (:name "Expansion"))))) (omapn (_ (format t "alias ~a ~:[is not defined~;~:*~w~]~%" (oelt _ 0) (oelt _ 1))) table) (setf *output* table)) (if (not expansion) (if edit (set-alias name (edit-alias name) :global global) (format t "alias ~a ~:[is not defined~;~:*~w~]~%" name (get-alias name :global global :shell *shell*))) (set-alias name (join-by-string expansion " ") :global global :shell *shell*)))) (defbuiltin unalias ((global boolean :short-arg #\g :help "True to define a global alias.") (name string :optional nil :help "Name of the alias to forget.")) "Remove the definition of NAME as an alias." (unset-alias name :global global :shell *shell*)) (defbuiltin exit ((values string :repeating t :help "Values to return.")) "Exit from the shell. Optionally return values." (when values (setf (shell-exit-values *shell*) (loop :for v :in values :collect v))) (setf (shell-exit-flag *shell*) t)) ;; Override an implementations quit function, so that we only exit one level ;; of the shell, not the whole Lisp system. (defbuiltin quit ((values string :repeating t :help "Values to return.")) :keys-as args "Exit from the shell. Optionally return values." (apply #'!exit args)) (defbuiltin source ((filename pathname :optional nil :help "Filename to read.")) "Evalute lish commands in the given file." (without-warning (load-file filename))) ;; XXX I wish this would work without using the :use-supplied-flag, just using ;; the default value of :toggle in boolean-toggle, but there is some kind of ;; bug or something about class default args at compile time that I don't ;; understand. (defbuiltin debug ((state boolean-toggle :help "State of debugging." :use-supplied-flag t)) "Toggle shell debugging." (setf (lish-debug *shell*) (if (or (not state-supplied-p) (eql state :toggle)) (not (lish-debug *shell*)) state)) (format t "Debugging is ~:[OFF~;ON~].~%" (lish-debug *shell*))) (defbuiltin export ((remove boolean :short-arg #\n :help "True to stop the NAME from being exported.") (edit boolean :short-arg #\e :help "True to edit the value of the variable.") (name string :help "Name of the variable to export.") (value string :help "Value of the variable to export.")) "Set environment variable NAME to be VALUE. Omitting VALUE, just makes sure the current value of NAME is exported. Omitting both, prints all the exported environment variables. If NAME and VALUE are converted to strings if necessary. If NAME has an equal sign ‘=’ in it, do the POSIX shell style of NAME=value." (when (not name) (setf name *input*)) (when (and name (not (stringp name))) (setf name (princ-to-string name))) (when (and value (not (stringp value))) (setf value (princ-to-string value))) (setf *output* (if name (let (pos) (cond ((setf pos (position #\= name)) ; POSIX style (let ((n (subseq name 0 pos)) (v (subseq name (1+ pos)))) (setf (nos:environment-variable n) v))) (remove (prog1 (nos:environment-variable name) (setf (nos:environment-variable name) nil))) (edit (setf (nos:environment-variable name) (rl :prompt (s+ "export " name #\=) :string (or value (nos:environment-variable name))))) (value (setf (nos:environment-variable name) value)) (t (nos:environment-variable name)))) ; Actually does nothing (progn (dlib-interactive:printenv) (nos:environment))))) #|-+ |\| So we have (from a man page): |\| |\| env [-i] [name=value ...] [utility [argument ...]] |\| |\| as a lambda list: |\| |\| (&key ignore-environment variable-assignments shell-command) |\| |\| but that doesn't have enough information. So |\| |\| (:or "-i" "var=value" (:and "cmd") |\|@@@@@@@@@@@@@@@ |\| |\| (("ignore-environment" boolean :short-arg #\i |\| :help "Ignore the environment.") |\| :positional |\| ("variable-assignment" string :repeating t :matches "\\S+=\\S+" |\| :help "Assingment to make in the environment.") |\| ("shell-command" shell-command |\| :help "Command to execute with the possibly modified environment.") |\| ("arguments" string :repeating t |\| :help "Variable assignments, commands and command arguments.")) |\| Vauguely like how I would like: (defbuiltin env ((ignore-environment boolean :short-arg #\i :help "Ignore the environment.") (variable-assignment string :repeating t :help "Assingment to make in the environment.") (shell-command shell-command :help "Command to execute with the possibly modified environment.") (arguments string :repeating t :help "Variable assignments, commands and command arguments.")) "Modify the command environment. If ignore-environment" (if (and (not shell-command) (not arguments)) ;; Just print variables (loop :for v :in variable-assignment :do (let ((var (if (position #\= v) (first (split-sequence #\= v)) v))) (when var (format t "~a=~a~%" var (nos:environment-variable var))))) ;; Set variables and execute command (progn (loop :for v :in variable-assignment :do (let ((pos (position #\= v)) var val seq) (if pos (setf seq (split-sequence #\= v) var (first seq) val (third seq)) (setf var v)) (when (and var val) (setf (nos:environment-variable var) val)))) (apply #'do-system-command `(,`(,shell-command ,@arguments) ,(if ignore-environment (modified-context *context* :environment nil) *context*)))))) But instead we have to to a kludgey version: |# ;; Another problem is, it's rather counter-intuitive to POSIX shell users ;; (including me), that, say, ;; ;; env "CFLAGS=-g -Wall -O2" ./configure --enable-impossible-color ... ;; ;; works, but ;; ;; env CFLAGS="-g -Wall -O2" ./configure --enable-impossible-color ... ;; ;; doesn't work. ;; It doesn't work because the shell reader splits words at double quotes, ;; so it becomes "env" "CFLAGS" "=-g -Wall -O2". The reader splits words like ;; that for what I think is good reason, so I'm not sure I want to change it. (defbuiltin env ((ignore-environment boolean :short-arg #\i :help "Ignore the environment.") (arguments string :rest t :help "Variable assignments, command and command arguments. Any number of leading words with equal signs '=' are taken to be environment variable assignments. The rest of the arguments are taken to be a command with and it's arguments. The environment variable assignments are only in effect for the command.")) "Modify the command environment. If ignore-environment is true, only variables explicitly set in arguments are passed to the command." (if arguments ;; Set variables and execute command (let (env new-env cmd (a arguments) args) ;; Accumulate environment modifications in env (loop :while (and a (position #\= (car a))) :do (let* ((seq (split-sequence #\= (car a))) (var (first seq)) (val (second seq))) (when var ;; (format t "push env var=~s val=~s~%" var val) (push (cons var val) env))) (setf a (cdr a))) ;; Set the command and arguments (setf cmd (car a) args (cdr a)) (when (not ignore-environment) (setf new-env (or (context-environment *context*) (environment)))) ;; Set the variables ;; (format t "cmd = ~s~%args = ~s~%env = ~s~%" cmd args env) ;; (finish-output) (loop :with e :for (var . val) :in env :do (setf e (assoc (intern var :keyword) new-env)) (if e (rplacd e val) (setf new-env (acons (intern var :keyword) val new-env)))) ;; Unixify the new-env ;;(setf new-env ;; (mapcar (_ (format nil "~a=~a" (car _) (cdr _))) new-env)) ;; Run the command ;; @@@ This should respect piping!!! (when cmd ;; (funcall #'do-system-command ;; (make-shell-expr :words `(,cmd ,@args)) ;; (modified-context *context* :environment new-env)))) (funcall #'shell-eval ;; (make-shell-expr :words `(,cmd ,@args)) (shell-read (join-by-string (append (list cmd) args) " ")) :context (modified-context *context* :environment new-env)))) ;; Just print the variables (loop :for e :in (environment) :do (format t "~a=~a~%" (car e) (cdr e))))) (defun get-cols () ;; (let ((tty (rl:line-editor-terminal (lish-editor *shell*)))) ;; (terminal-get-size tty) ;; (terminal-window-columns tty)) (or (and *terminal* (tt-width)) 80)) (define-builtin-arg-type signal (arg-integer) "A system signal." () :convert string (or #+unix (position value *signal-names* :test #'equalp) #+windows (cadr (assoc value *siggy* :test #'equalp)) (ignore-errors (parse-integer value)) value)) (defun pseudo-kill (sig job-or-pid) "Kill a job or an OS process ID." (labels ((kill-pid (p) #+unix (os-unix:kill p (or sig uos:+SIGTERM+)) #+windows (funcall (caddr (find sig *siggy* :key #'second)) p))) (cond ((stringp job-or-pid) (let ((job (find-job job-or-pid)) pid-int) (cond ((job-p job) (kill-job job :signal sig)) (t (when (setf pid-int (ignore-errors (parse-integer job-or-pid))) (kill-pid pid-int)))))) ((job-p job-or-pid) (kill-job job-or-pid :signal sig)) ((integerp job-or-pid) (kill-pid job-or-pid))))) (defun pid-or-job-list () "Return a list of jobs and process IDs." `(,@(job-id-list) ,@(mapcar #'nos:os-process-id (nos:process-list)))) ;; (defclass arg-pid-or-job (arg-lenient-choice) ;; () ;; (:default-initargs ;; :choice-func #'pid-or-job-list) ;; (:documentation "A job descriptor or process ID.")) (define-builtin-arg-type pid-or-job (arg-lenient-choice) "A process ID or a job." () (:default-initargs :choice-func #'pid-or-job-list)) (defun rl-yes-or-no-p (&optional (format "") &rest args) "Like yes-or-no-p but using RL." (loop :with line :do (tt-finish-output) (finish-output) (setf line (rl:rl :prompt (s+ (apply #'format nil format args) " (yes or no) "))) (cond ((equal (trim line) "yes") (return t)) ((equal (trim line) "no") (return nil)) (t (tt-write-line "Please type \"yes\" for yes or \"no\" for no.") (tt-finish-output))))) (defbuiltin kill ((list-signals boolean :short-arg #\l :help "List available signals.") (interactive boolean :short-arg #\i :help "Kill jobs interactively.") (signal signal :default "TERM" :help "Signal number to send.") (pids pid-or-job :repeating t :help "Process IDs to signal.")) "Sends SIGNAL to PID." (let (job) (cond (list-signals (format t (s+ "~{~<~%~1," (get-cols) ":;~a~> ~}~%") ; bogus, but v fails ;; (loop :for i :from 1 :below nos:*signal-count* ;; :collect (format nil "~2d) ~:@(~8a~)" i (nos:signal-name i)))) (loop :for s :in *siggy* :collect (format nil "~2d) ~:@(~8a~)" (second s) (first s))))) (interactive ;; I think maybe it's too dangerous to take pids from *input* when ;; not interactive. (when (and (not pids) *input*) (setf pids (if (consp *input*) *input* (list *input*)))) (if (not pids) (error "But what processes to kill?") (loop :for p :in pids :when (rl-yes-or-no-p "Kill process ~s" p) :do (pseudo-kill signal p)))) (t (cond (pids (mapcar #'(lambda (x) (pseudo-kill signal x)) pids)) (signal (typecase signal (string (if (setf job (find-job signal)) (pseudo-kill nil job) (error "No such job ~s" signal))) (integer (pseudo-kill nil signal))))))))) ;; Actually I think that "format" and "read" are a bad idea / useless, because ;; they're for shell scripting which you should do in Lisp. #| ;;; make printf an alias (defbuiltin format ((format-string string :optional nil :help "Format control string.") (args object :repeating t :help "Format arguments.")) "Formatted output." (apply #'format t format-string args)) ;; Since this is for scripting in other shells, I think we don't need to worry ;; about it, since the user can just call READ-LINE-like functions directly. (defbuiltin read ((name string :help "Variable to read.") (prompt string :short-arg #\p :help "Prompt to print.") (timeout integer :short-arg #\t :help "Seconds before read times out.") (editing boolean :short-arg #\e :help "True to use line editing.")) "Read a line of input." ;; @@@ totally faked & not working (declare (ignore timeout name)) (if editing (rl:rl :prompt prompt) (read-line nil nil))) |# ;; @@@ Maybe this should get the times of subprocesses too, but I think that ;; would necessitate forking and waiting, which I'm not sure is a good idea. (defbuiltin time ((command string :repeating t :help "Command to time.")) "Shows some time statistics resulting from the execution of COMMNAD." (prog1 (time (shell-eval (expr-from-args command))) (force-output *trace-output*))) (defun print-time (seconds micro-seconds &optional (stream t)) (let* ((secs (+ seconds (/ micro-seconds 1000000))) days hours mins) (setf days (/ secs (* 60 60 24)) secs (mod secs (* 60 60 24)) hours (/ secs (* 60 60)) secs (mod secs (* 60 60)) mins (/ secs 60) secs (mod secs 60)) ;; (format t "days ~a hours ~a min ~a sec ~a~%" ;; (floor days) (floor hours) (floor mins) secs) (format stream "~@[~dd ~]~@[~dh ~]~@[~dm ~]~5,3,,,'0fs" (when (>= days 1) (floor days)) (when (>= hours 1) (floor hours)) (when (>= mins 1) (floor mins)) secs))) (defbuiltin times () "Show accumulated times for the shell." (let (self-u-sec self-u-ms self-s-sec self-s-ms children-u-sec children-u-ms children-s-sec children-s-ms) (setf (values self-u-sec self-u-ms self-s-sec self-s-ms) (process-times :self) (values children-u-sec children-u-ms children-s-sec children-s-ms) (process-times :children)) (labels ((label (s) (grout-write (style:themed-string '(:program :label :style) s) :escape nil :readably nil)) (data (s) (grout-write (style:themed-string '(:program :data :style) s) :escape nil :readably nil))) (with-grout () (label " Self User: ") (data (princ-to-string (print-time self-u-sec self-u-ms nil))) (grout-format "~32t") (label "System: ") (data (princ-to-string (print-time self-s-sec self-s-ms nil))) (grout-write #\newline :escape nil) (label "Children User: ") (data (princ-to-string (print-time children-u-sec children-u-ms nil))) (grout-format "~32t") (label "System: ") (data (princ-to-string (print-time children-s-sec children-s-ms nil))) (grout-write #\newline :escape nil))) (setf *output* (list self-u-sec self-u-ms self-s-sec self-s-ms children-u-sec children-u-ms children-s-sec children-s-ms)))) (defbuiltin umask ((print-command boolean :short-arg #\p :help "Print a command which sets the umask.") (symbolic boolean :short-arg #\S :help "Output in symbolic mode.") (mask string :help "Mask to set.")) "Set or print the default file creation mode mask (a.k.a. permission mask). If mode is not given, print the current mode. If PRINT-COMMAND is true, print the mode as a command that can be executed. If SYMBOLIC is true, output in symbolic format, otherwise output in octal." #+windows (declare (ignore print-command symbolic mask)) #+windows (error "umask is not a thing on windows.") #+unix (declare (ignore symbolic)) ;; @@@ #+unix (if (not mask) ;; printing (let ((current-mask (os-unix:umask 0))) (os-unix:umask current-mask) (when print-command (format t "umask ")) ;; (if symbolic ;; (format t "~a~%" (symbolic-mode-offset current-mask)) ;; (format t "~o~%" current-mode))) (format t "~o~%" current-mask)) ;; setting (progn (multiple-value-bind (real-mask err) (ignore-errors (parse-integer mask :radix 8)) (when (typep err 'error) (error err)) (os-unix:umask real-mask))))) (defparameter *limits* #+unix (loop :for l :in '(:SBSIZE :CORE :DATA :NICE :FSIZE :SIGPENDING :KQUEUE :MEMLOCK :RSS :NOFILE :MSGQUEUE :RTPRIO :STACK :CPU :NPROC :AS ; or maybe _VIRTMEM or _VMEM :SWAP ; or maybe we need a getter? :LOCKS :NTHR ; _PTHREAD or _NTHR ;; :PIPE not settable? uos:get-pipe-size ;; :PTYS not settable? pseudo terminals? ) :when (uos:rlimit-number l nil) :collect l) #-unix '() "List of limits for ulimit command.") #+unix (defun format-limit (cell width) "Format a numeric resource limit." (if (and (numberp cell) (= cell uos:+RLIMIT-INFINITY+)) (format nil "~v@a" width "unlimited") (format nil "~vd" width cell))) (defbuiltin ulimit ((print-all boolean :short-arg #\a :help "True to print all limits.") (soft-limit boolean :short-arg #\S :help "True to operate on the soft limit.") (hard-limit boolean :short-arg #\H :help "True to operate on the hard limit.") (limit choice :choices *limits* :choice-test (lambda (x y) (or (eql x y) (eq (keywordify x) (keywordify y)))) :help "Limit to print or set.") (value object :help "New value for the limit.")) "Examine or set process resource limits." #-unix (declare (ignore print-all soft-limit hard-limit limit value)) #-unix (values) #| #+unix (declare (ignore soft-limit)) |# #+unix (flet ((value->string (value) (if (equal value uos:+RLIMIT-INFINITY+) "unlimited" value)) (string->value (value) (if (and (or (stringp value) (symbolp value)) (equalp (string value) "unlimited")) uos:+RLIMIT-INFINITY+ value)) (result->value (result) (if hard-limit (uos:rlimit-maximum result) (uos:rlimit-current result)))) (cond (print-all (let ((table (make-table-from (loop :with val :for l :in *limits* :when (uos:rlimit-number l nil) :do (setf val (uos:getrlimit l)) :and :collect (list (string-downcase l) (uos:rlimit-current val) (uos:rlimit-maximum val) (documentation (symbolify (s+ "+RLIMIT-" l "+") :package :uos) 'variable))) :columns `((:name "Name") (:name "Soft Value" :type number :format ,#'format-limit) (:name "Hard Value" :type number :format ,#'format-limit) (:name "Description" :align :wrap))))) ;; (print-table table :max-width (get-cols)) ;; (terpri) (with-grout () (grout-print-table table)) (setf *output* table))) (limit (let ((limit-number (uos:rlimit-number limit nil)) lim) (if limit-number (progn (setf lim (uos:getrlimit limit-number)) (if value (progn (cond ((and hard-limit soft-limit) (setf (uos:rlimit-maximum lim) (string->value value)) (uos:rlimit-current lim) (string->value value)) (hard-limit (setf (uos:rlimit-maximum lim) (string->value value))) (t (setf (uos:rlimit-current lim) (string->value value)))) (uos:setrlimit limit-number lim)) (progn (setf *output* (result->value lim)) (format t "~a~%" (value->string *output*))))) (error "Unknown limit ~s" limit)))) (t (format t "~a~%" (value->string (result->value (uos:getrlimit :fsize)))))))) (defbuiltin wait () "Wait for commands to terminate." #+unix (let (job) ;; @@@ should we wait for threads or what? (multiple-value-bind (pid result status) (uos::wait) (when pid (if (setf job (find-if (_ (and (typep _ 'system-job) (eql (job-pid _) pid))) (lish-jobs *shell*))) (handle-job-change job result status) (format t "Unknown job changed ~a~%" pid))))) #-unix (values)) (defbuiltin exec ((command-words t :rest t :help "Words of the command to execute.")) "Replace the whole Lisp system with another program. This seems like a rather drastic thing to do to a running Lisp system." #+windows (declare (ignore command-words)) #+windows (error "Wouldn't you prefer a nice game of chess?") #+unix (when command-words (let ((path (command-pathname (first command-words)))) ;; (format t "path = ~w~%command-words = ~w~%" path command-words) (os-unix:exec path command-words)))) ;; (define-builtin-arg-type function (arg-symbol) ;; "A function name." ;; () ;; :convert string ;; (find-symbol (string-upcase value))) (define-builtin-arg-type key-sequence (arg-string) "A key sequence." ()) (defmethod convert-arg ((arg arg-key-sequence) (value vector) &optional quoted) (declare (ignore arg quoted)) value) (defmethod convert-arg ((arg arg-key-sequence) (value list) &optional quoted) (declare (ignore arg quoted)) value) ;; @@@@ need to update for new inator keymaps (defbuiltin bind ((print-bindings boolean :short-arg #\p :help "Print key bindings.") (print-readable-bindings boolean :short-arg #\P :help "Print key bindings in a machine readable way.") (query function :short-arg #\q :help "Ask what key invokes a function.") (remove-function-bindings function :short-arg #\u :help "Remove the binding for ‘function’.") (remove-key-binding key-sequence :short-arg #\r :help "Remove the binding for a ‘key-sequence’.") (key-sequence key-sequence :help "The key sequence to bind.") (function-name function :help "The function to bind the key sequence to.")) "Manipulate key bindings." (when (> (count t (list print-bindings print-readable-bindings query remove-function-bindings remove-key-binding)) 1) (error "Mutually exclusive arguments provided.")) (cond (print-bindings (loop :for keymap :in (inator:inator-keymap (lish:lish-editor *shell*)) :do (format t "~s:~%" (keymap:keymap-name keymap)) (keymap:describe-keymap keymap))) (print-readable-bindings (loop :for keymap :in (inator:inator-keymap (lish:lish-editor *shell*)) :do (format t ";; ~s:~%" (keymap:keymap-name keymap)) (keymap:map-keymap #'(lambda (key val) (format t "(keymap:define-key ~(~s~) ~w '~a)~%" (keymap-name keymap) key (key-definition-action val))) keymap))) ;; @@@ todo: remove-function-bindings remove-key-binding ((and key-sequence (not function-name)) (format t "~a: ~(~a~)~%" (typecase key-sequence (character (nice-char key-sequence)) (sequence (with-output-to-string (str) (when (plusp (length key-sequence)) (princ (nice-char (oelt key-sequence 0)) str)) (omapn (_ (write-char #\space str) (princ (nice-char _) str)) (osubseq key-sequence 1))))) (keymap:key-sequence-binding key-sequence (inator:inator-keymap (lish:lish-editor *shell*))))) (query (flet ((print-it (key action) (format t "~a: ~(~a~)~%" (char-util:nice-char key) action))) (loop :for keymap :in (inator:inator-keymap (lish-editor *shell*)) :do (keymap:map-keymap #'(lambda (key val) (let ((a (key-definition-action val))) (typecase a (function (when (and (functionp query) (eq query a)) (print-it key a))) (symbol (typecase query (function (when (eq query (ignore-errors (fdefinition a))) (print-it key a))) ((or symbol string) (when (equalp (string query) (string a)) (print-it key a)))))))) keymap)))) ((and key-sequence function-name) (keymap:set-key key-sequence function-name (rl::local-keymap (lish-editor *shell*)))))) #| This is really just for simple things. You should probably use the Lisp version instead. This is what I might like to be able to say: @ defcommand tf ((file filename :optional nil)) (! "file" ($$ "type -p" file)) Actually I think this whole thing is ill advised becuase of syntax mixing problems. As a command the stuff in parens doesn't parse right, so it's better just to use Lisp syntax. |# #| (defbuiltin defcommand (("name" string :optional nil) ("function" string :optional nil)) "Defines a command which calls a function." (let (;(func-name (command-function-name name)) (cmd-name (string-downcase name)) (func-symbol (let ((*read-eval* nil)) (read-from-string (string-upcase function)))) (cmd-symbol (intern (string name)))) (if (fboundp func-symbol) (progn (push cmd-symbol *command-list*) (set-command cmd-name (make-instance 'command :name cmd-name :function func-symbol :arglist '()))) (format t "~a is not a function" func-symbol)))) |# #| (defclass arg-command (arg-choice) () (:default-initargs :choice-func #'verb-list) (:documentation "The name of a lish command.")) (defmethod convert-arg ((arg arg-command) (value string) &optional quoted) "Convert a string to a command." (get-command value)) |# ;; @@@ should it be here or in commands.lisp??? ;; (define-builtin-arg-type command (arg-choice) ;; "The name of a lish command." ;; () ;; (:default-initargs ;; :choice-func #'verb-list) ;; :convert string (get-command value)) ;; (defmethod convert-arg ((arg arg-command) (value string) &optional quoted) ;; "Convert a string to a command." ;; (get-command value)) (defbuiltin undefcommand ((command command :optional t :help "The command to forget.") (all-external boolean :short-arg #\e :help "True to undefine all external commands.")) "Undefine a command." (cond (all-external (loop :for c :in *command-list* :do (when (typep (get-command c) 'external-command) (undefine-command c)))) (command (typecase command ((or string symbol) (undefine-command (string-downcase command))) (command (undefine-command (command-name command))) (t (error "I don't know how to undefine a command of type ~a." (type-of command))))))) ;; @@@ resolve vs. nos:command-pathname (defun command-paths (cmd) "Return all possible command paths. Don't cache the results." (loop :with r = nil :for dir :in (command-path-list) ;; (split-sequence *path-separator* ;; (nos:environment-variable "PATH")) :do (setf r (when (probe-directory dir) (loop :with full = nil :for f :in (read-directory :dir dir) :when (and (command-test #'equal cmd f) (is-executable ;; (setf full ;; (s+ dir *directory-separator* cmd)) (setf full (s+ dir *directory-separator* f)) :regular t)) :return full))) :if r :collect r)) #| (defparameter *command-cache* nil "A hashtable which caches the of full names of commands.") (defun get-command-path (cmd &key already-known) "Return the possibly cached command path. If ALREADY-KNOWN is true, only check for already cached commands, don't bother consulting the file system." (when (not *command-cache*) (setf *command-cache* (make-hash-table :test #'equal))) (let ((result (gethash cmd *command-cache*))) (when (and (not result) (not already-known)) (let ((path (command-pathname cmd))) (when path (setf (gethash cmd *command-cache*) path result path)))) result)) |# (defun get-command-path (cmd &key already-known) "Return the possibly cached command path. If ALREADY-KNOWN is true, only check for already cached commands, don't bother consulting the file system." (command-pathname cmd :cached (if already-known :only :default))) ;; Maybe this should be called "cache", and leave a posix compatible hash. (defbuiltin hash ((rehash boolean :short-arg #\r :help "Forget about command locations.") (packages boolean :short-arg #\p :help "Forget about cached loadable packages.") (commands t :repeating t :help "Command to operate on.")) "Show or forget remembered full pathnames of commands." (labels ((pr-cmd (dir cmd) (format t "~a~%" (path-append dir cmd)))) (when rehash (if commands (loop :for c :in commands :do (opsys:command-pathname-cache-remove c)) (progn (opsys:command-pathname-cache-clear) (setf *verb-list* nil)))) ; @@@ from complete.lisp (when packages (clear-loadable-system-cache)) (let ((table (and opsys:*command-pathname-cache* (opsys::command-cache-table opsys:*command-pathname-cache*)))) (when (and table (not (or rehash packages))) (if commands (loop :with path ;; :and multi = (> (length commands) 1) :for c :in commands :do (setf path (gethash c table)) (if path (pr-cmd path c) (if (setf path (command-pathname c)) ;; (format t "~:[~;~a ~]~a~%" multi c path) (format t "~a~%" path) (format t "~a was not found~%" c)))) (maphash #'(lambda (c p) (pr-cmd p c)) table)))))) ;; Since this is based on phonetics, we would need phonetic dictionaries to do ;; this right. Also, it's specific to language, so it should be in a language ;; package. (defun indefinite (str) (declare (type string str)) "Return an approximately appropriate indefinite article for the given ~ string. Sometimes gets it wrong for words startings with 'U', 'O', or 'H'." (when (> (length str) 0) (let ((c (aref str 0))) (if (position c "aeiouAEIOU") "an" "a")))) (defun describe-command (cmd) (let (x) (cond ((setf x (gethash cmd (shell-aliases *shell*))) (when x (format t "~a is aliased to ~a~%" cmd x))) ((setf x (gethash cmd (lish-global-aliases *shell*))) (when x (format t "~a is a global alias for ~a~%" cmd x))) ((setf x (gethash cmd (lish-commands))) (when x (format t "~a is the command ~a~%" cmd x))) ((setf x (get-command-path cmd)) (when x (format t "~a is ~a~%" cmd x))) ((setf x (read-from-string cmd)) (when (and (symbolp x) (fboundp x)) (format t "~a is the function ~s~%" cmd (symbol-function x))))))) (defbuiltin type ((type-only boolean :short-arg #\t :help "Show only the type of the name.") (path-only boolean :short-arg #\p :help "Show only the path of the name.") (all boolean :short-arg #\a :help "Show all definitions of the name.") (names string :repeating t :help "Names to describe.")) "Describe what kind of command the name is." (when names (loop :with args = names :and n = nil :and did-one :while args :do (setf n (car args) did-one nil) (cond (path-only (let ((paths (command-paths n))) (when paths (format t "~a~%" (setf *output* (first paths)))))) (all (let ((x (gethash n (shell-aliases *shell*)))) (when x (format t "~a is aliased to ~a~%" n x) (push x *output*) (setf did-one t))) (let ((x (gethash n (lish-global-aliases *shell*)))) (when x (format t "~a is globally aliased to ~s~%" n x) (push x *output*) (setf did-one t))) (let ((x (gethash n (lish-commands)))) (when x (format t "~a is the ~:[~;builtin ~]command ~a~%" n (command-built-in-p x) x) (push x *output*) (setf did-one t))) (let ((paths (command-paths n))) (when paths (format t (format nil "~~{~a is ~~a~~%~~}" n) paths) (setf *output* (append *output* paths)) (setf did-one t))) (let* ((obj (read-from-string n))) (when (and (symbolp obj) (fboundp obj)) (format t "~a is the function ~s~%" n (symbol-function obj)) (push (symbol-function obj) *output*) (setf did-one t))) (when (not did-one) (format t "~a is unknown~%" n))) (t (let* ((type (command-type *shell* n)) (tt (string-downcase type))) (if type (progn (if type-only (format t "~a~%" tt) (describe-command n)) (setf *output* type)) (format t "~a is unknown~%" n))))) (setf args (cdr args)))) *output*) ;; Which which is which? ;; (set-alias "which" "type -p") or maybe just "type" (defbuiltin which ((all boolean :short-arg #\a :help "Show all definitions of the name.") (names string :repeating t :help "Names to describe.")) "Describe which command is invoked." (!type :all all :names names)) (defun edit-opt (name &optional (value nil value-supplied-p)) (read-from-string (rl :prompt (s+ name " := ") :string (prin1-to-string (if value-supplied-p value (get-option *shell* name)))) nil nil)) (defbuiltin opt ((readable boolean :short-arg #\r :help "True to output options that are re-readable by the shell.") (edit boolean :short-arg #\e :help "True to edit the option's value.") (help boolean :short-arg #\h :help "True to show help for the option.") (name option :help "Option to set.") (value object :help "Value to set option to." :use-supplied-flag t)) :no-help t "Examine or set shell options. Type 'help options' for descriptions." (when (and help edit) (error "Please supply only one of --help or --edit.")) (if name (if value-supplied-p (set-option *shell* name (if edit (edit-opt name value) value)) (cond (help (let ((o (find-option *shell* name))) (print-columnar-help `((,name ,(substitute #\space #\newline (arg-help o))))))) (edit (set-option *shell* name (edit-opt name))) (t (format t "~w~%" (get-option *shell* name))))) (cond (edit (format t "I don't know how to edit all the options at once yet.~%")) (help (setf *output* (print-columnar-help (loop :for o :in (lish-options *shell*) :collect `(,(arg-name o) ,(substitute #\space #\newline (arg-help o))))))) (readable (loop :for o :in (lish-options *shell*) :do (format t "opt ~a ~w~%" (arg-name o) (arg-value o)))) (t (with-grout () (let ((table (make-table-from (loop :for o :in (lish-options *shell*) :collect (cons (arg-name o) (format nil "~s" (arg-value o)))) :columns '((:name "Name" :align :right) (:name "Value" :align :wrap))))) (grout-print-table table :print-titles nil) (setf *output* table))))))) #| (defbuiltin lpath ((command sub-command :default :list :help "What to do with the lpath." :commands ((show () "Show the Lisp path." (format t "~s) (append ((directory directory :help "The directory to append.")) "Append an element to the end of path." (setf asdf:*central-registry* (append asdf:*central-registry* (list directory)))) (prepend ((directory directory :help "The directory to prepend.")) "Prepend and element to the front of the path." (setf asdf:*central-registry* (cons directory asdf:*central-registry*))) (set ((value list :help "The value to set the Lisp path to.")) "Set the Lisp path to VALUE, which should be a list of directories." (setf asdf:*central-registry* value)))) (command-args object :repeating t :help "Arguments to sub-commands.")) "Manipulate the Lisp path." (setf *output* (call-command command command-args))) |# (defun loadable-system-list () (dlib-misc:loadable-systems :as-strings t)) (define-builtin-arg-type system-designator (arg-keyword) "A system designator, either a keyword or an ASDF/SYSTEM:SYSTEM" () :convert string (if (and (stringp value) (char= (char value 0) #\:)) (intern (string-upcase (subseq value 1)) (find-package :keyword)) value)) (defmethod argument-choices ((arg arg-system-designator)) (declare (ignore arg)) (dlib-misc:loadable-systems :as-strings t)) (defun asdf-load (system &key verbose force) "Load a system with ASDF." (let ((symbol (if (or (stringp system) (keywordp system)) system (intern (string-upcase (princ-to-string system)) :keyword)))) (asdf:oos 'asdf:load-op symbol :verbose verbose :force force))) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *default-quality-number* 1 "The default optimization quality number.")) (defparameter *debug-profile* `((speed ,*default-quality-number*) (safety 3) (debug 3) (space ,*default-quality-number*) (compilation-speed ,*default-quality-number*)) "Optimization settings for debugging.") (defparameter *speed-profile* `((speed 3) (safety 2) (debug 0) (space 2) (compilation-speed 0)) "Optimization settings for execution speed.") (defparameter *speed-debug-profile* `((speed 3) (safety 0) (debug 3) (space 1) (compilation-speed 0)) "Optimization settings for execution speed and debugging.") (defbuiltin l ((system system-designator :optional nil :help "System designator to load.") (no-notes boolean :short-arg #\n :help "Suppress compiler notes on some implementations.") (no-warn boolean :short-arg #\w :help "Suppress compiler warnings on some implementations.") (verbose boolean :short-arg #\v :default *compile-verbose* :help "Show more compiler output than normal. Defaults to *compile-verbose*.") (print boolean :short-arg #\p :default *compile-print* :help "Print what's being compiled. Defaults to *compile-print*.") (force boolean :short-arg #\f :help "Force reloading systems.") (force-all boolean :short-arg #\F :help "Force reloading all systems, even dependencies.") ;; (no-verbose boolean :short-arg #\v ;; :help "Turn off verbosity on some implementations.") (debug boolean :short-arg #\d :help "Use the debugging optimzation profile.") (speed boolean :short-arg #\s :help "Use the speed optimzation profile.") (optimization list :short-arg #\O :help "A list of optimize declaration qualities, e.g. '((speed 3) (safety 2)) Note that this option overrides the -d and -s options.")) "Load a system." ;; We could theoretically use asdf:*compile-file-warnings-behaviour* ;; but it doesn't look like it applies to notes. (labels ((load-that () (let ((*compile-verbose* verbose) (*compile-print* print)) (asdf-load system #| :verbose verbose |# :force (or force (and force-all :all))))) (with-opt (qualities-list) (with-optimization (qualities-list) (load-that))) ;; (with-opt (qualities-list) ;; (do-opt qualities-list system (or force (and force-all :all)))) ;; (do-opt (qualities-list system force) ;; ;; @@@ I don't know how else to do it? ;; (print `(locally (declare (optimize ,@qualities-list)) ;; (asdf-load ,system :force ,force))) ;; (eval `(locally (declare (optimize ,@qualities-list)) ;; (asdf-load ,system :force ,force)))) (load-it () (cond (optimization (with-opt optimization)) ((and speed debug) (with-opt *speed-debug-profile*)) (speed (with-opt *speed-profile*)) (debug (with-opt *debug-profile*)) (t (load-that))))) (if (or no-notes no-warn) (handler-bind ((condition (lambda (c) #-sbcl (declare (ignore c)) #+sbcl (cond ((and no-notes (typep c 'sb-ext::compiler-note)) (muffle-warning)) ((and no-warn (typep c 'warning)) (muffle-warning)) (t (signal c)))))) (load-it)) (load-it)))) (defbuiltin load ((file pathname :default '(pick-file) :help "A file name to load.")) "Load a file." (load file)) ;; This is not very close to being correct. (defun load-dirs () "Directories where things may get loaded from." (remove-if #'keywordp (flatten (concatenate 'list asdf:*central-registry* asdf:*source-registry-parameter*)))) (defun fix-load-dir (d dont-warn) "Make a directory be appropriate for the ldirs command." (let ((result (nos:safe-namestring d))) (when (not (nos:absolute-path-p result)) (setf result (nos:path-to-absolute result))) (when (and (plusp (length result)) (not (equal (char result (1- (length result))) nos:*directory-separator*))) (setf result (s+ result nos:*directory-separator*))) (when (and (not (nos:file-exists result)) (not dont-warn)) (warn "Adding a non-existent directory to the Lisp path: ~a" result)) result)) (defbuiltin ldirs ((push boolean :short-arg #\p :help "Push directories on the load path.") (add boolean :short-arg #\a :help "Append directories to the load path.") (remove boolean :short-arg #\r :help "Remove directories from the load path.") (clear boolean :short-arg #\C :help "Empty the whole load path.") (dir pathname :optional t :repeating t :help "Directories to operate on.")) "Manipulate the ASDF load path. Without arguments list some directories where things are maybe loaded from. Missing directories are printed in red on some terminals. If a directory is given without an action option, it is as if --push was given." (labels ((pr (d) (grout-format "~a~%" d)) ;; This should probably be some system specific thing in opsys. (do-push () (map nil (_ (let ((fixed-dir (fix-load-dir _ remove))) (pushnew fixed-dir asdf:*central-registry* :test #'equal) (add-asdf-directory fixed-dir))) dir))) (with-grout () (when (> (count t `(,push ,add ,remove)) 1) (error "Please specidify only one of push, add, or remove.")) (when (and (or push add remove) (not dir)) (error "~:(~a~) requires a directory." (or push add remove))) (cond (push (do-push)) (add (let ((dirs (map 'list (_ (fix-load-dir _ remove)) dir))) (map nil #'add-asdf-directory dirs) (nconc asdf:*central-registry* dirs))) (remove (map nil (_ (setf asdf:*central-registry* (delete (fix-load-dir _ remove) asdf:*central-registry* :key #'safe-namestring :test #'equal))) dir)) (clear (when (y-or-n-p "Really clear the load path?") (setf asdf:*central-registry* nil))) (dir (do-push)) (t ;; No args (typecase *input* (null ;; No input, so list it. (loop :for d :in (load-dirs) :do (if (not (nos:file-exists d)) (progn (grout-set-color :red :black) (pr d) (grout-set-normal)) (pr d)))) ((or string pathname) (setf dir (list *input*)) (do-push)) (sequence (setf dir *input*) (do-push))) (setf *output* asdf:*central-registry*)))))) #+quicklisp (progn (defun quicklisp-system-list () (dlib-misc:quickloadable-systems :as-strings t)) (define-builtin-arg-type quicklisp-system-designator (arg-keyword) "A system designator for QUICKLOAD, either a keyword or a string." () :convert ql-dist:system (values value) :convert string (if (and (stringp value) (char= (char value 0) #\:)) (intern (string-upcase (subseq value 1)) (find-package :keyword)) value)) (defmethod argument-choices ((arg arg-quicklisp-system-designator)) (declare (ignore arg)) (dlib-misc:quickloadable-systems :as-strings t)) (defbuiltin ql ((system quicklisp-system-designator :optional nil :help "System designator to load.")) "QuickLoad a system." (ql:quickload system))) (defmethod documentation ((b autoloaded-command) (doctype (eql 'function))) "Return the documentation string for the given shell command." (with-output-to-string (str) (format str "Auto-loaded from ~a" (command-load-from b)) (when (documentation (command-function-name (command-name b)) 'function) (format str "~%~a" (documentation (command-function-name (command-name b)) 'function))))) (define-builtin-arg-type autoload-place (arg-keyword) ;(argument) "Where to load a command from either a keyword, a string, or a pathname." () ;; :convert ql-dist:system (values value) ;; :convert symbol (values value) ;; :convert pathname (values value) :convert string (if quoted value (if (char= (char value 0) #\:) (intern (string-upcase (subseq value 1)) (find-package :keyword)) value))) (defbuiltin autoload ((force boolean :short-arg #\f :help "Replace an existing command.") (list boolean :short-arg #\l :help "List autoloaded commands.") (command-name string #| :optional nil |# :help "The name of the command to load.") (where autoload-place #| :optional nil |# :help "Where to load a command from. A keyword for an ASDF system, or a string or pathname designating a file.") (docstring string :help "A documentation string.")) "Set a command to be automatically loaded." (cond (list (with-grout () (let ((table (make-table-from (loop :for k :in (command-list 'autoloaded-command) :collect (list (command-name k) (string-downcase (command-load-from k)) (or (documentation (command-function-name (command-name k)) 'function) ""))) :columns '((:name "Name") (:name "Loaded from") (:name "Description" :align :wrap))))) (grout-print-table table :long-titles t) (setf *output* table)))) (t (let ((old-command (get-command command-name))) ;; If there's already a non-autoloaded command, don't overwrite it. (when (or (not old-command) (typep old-command 'autoloaded-command) force) (let ((cmd (make-instance 'autoloaded-command :name command-name :load-from where))) (pushnew command-name *command-list* :test #'equal) (setf (documentation (command-function-name command-name) 'function) docstring) (set-command command-name cmd))))))) (defparameter *doc-types* '(compiler-macro function method-combination setf structure type variable) "Types of documentation to try for the DOC function.") (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *doc-doc* "DOC tries to find documentation for something. It knows how to find documentation for a Lisp symbol or object, regardless of what package it's in, if it has one of the standard documentation types of: FUNCTION VARIABLE STRUCTURE TYPE SETF COMPILER-MACRO METHOD-COMBINATION It also can find the documenation for shell commands." "This is the *doc-doc* doc.") (defparameter *%doc-doc* (s+ *doc-doc* #\newline "%doc is useful directly if you want to find documentation for a value, or direct the output to somewhere other than *STANDARD-OUTPUT*.")) (defparameter *doc-doc-doc* (s+ *doc-doc* #\newline "The DOC macro is convenient from a REPL so you don't have to quote things.") "This is the *doc-doc-doc* doc.") (defparameter *doc-doc-command-doc* (s+ "Show documentation for something named by ‘thing’." #\newline *doc-doc* #\newline "The \"doc\" command also just calls ‘describe’ if it can't find anything else.") "Be serious now!")) (defun output-text (s &optional stream) (syntax:format-comment-text (make-instance 'syntax-lisp:lisp-token :object s) (or stream (grout-stream *grout*)))) (defun output-class (symbol) "Print out documentation for ‘class’." (let ((class (find-class symbol))) (output-text (or (documentation class t) (documentation class 'type))) (when (not (mop:class-finalized-p class)) (ignore-errors (mop:finalize-inheritance class))) (grout-print-table (make-table-from (loop :for s :in (mop:class-slots class) :collect `(,(span-to-fat-string `(:fg-cyan ,(string-downcase (mop:slot-definition-name s)))) ,(ostring-trim *whitespace* (with-output-to-fat-string (str) (let ((doc (documentation s t))) (or (and doc (output-text doc str)) "")))))) :columns '((:name "Slot") (:name "Documentation" :align :wrap)))))) (defun %doc (thing &key (stream *standard-output*) (all t)) #.*%doc-doc* (let* ((did '()) (x (if (stringp thing) (make-symbol thing) thing)) (p (ignore-conditions (type-error) (find-package x))) (cols (or (and *terminal* (or (ignore-errors (terminal-get-size *terminal*) (terminal-window-columns *terminal*)) 80)) 80))) (with-grout (*grout* stream) (labels ((maybe-doc (obj type) (without-warning (documentation obj type))) (is-class (sym) (let ((c (ignore-errors (find-class sym)))) (and c (typep c 'standard-class)))) (print-doc (sym pkg doc-type &optional fake-type) (when (maybe-doc sym doc-type) (when did (grout-princ #\newline)) ;; Package and name (cond ;; Print function help for functions. ((and (eq doc-type 'function) (maybe-doc sym doc-type)) (when (and pkg (not (eq pkg (find-package :cl)))) (grout-color :green :default (format nil "~a " (package-name pkg))) (grout-color :green :default (format nil "~:(~a~):~%" (or fake-type doc-type)))) (grout-format "~a~%" (function-help sym 0 :width cols))) (t (grout-color :green :default (format nil "~:(~a~): " (if (is-class sym) "Class" (or fake-type doc-type)))) (when pkg (grout-color :green :default (format nil "~a:" (package-name pkg)))) (grout-color :green :default (format nil "~(~a~)~%" sym)))) ;; The actual documentation (cond ((eq doc-type 'command) (grout-color :white :default (maybe-doc sym doc-type)) (pushnew :command did)) ((is-class sym) (output-class sym) (pushnew :class did)) (t (output-text (maybe-doc sym doc-type)) ;;(grout-princ #\newline) (pushnew (keywordify doc-type) did))))) (do-docs (sym pkg) (loop :for d :in *doc-types* :do ;; Don't print duplicate type documentation for structures, (when (and (eq d 'structure) (maybe-doc sym d)) (pushnew :structure did)) (when (not (and (eq d 'type) (find :structure did))) (print-doc sym pkg d))))) ;;(do-docs x nil) (when (and (or (not did) all) #+sbcl (not (symbolp x)) ; sbcl warns about this (maybe-doc x t)) ;;(grout-color :white :default ;; (format nil "~a~%" (maybe-doc x t))) (when did (grout-princ #\newline)) (output-text (maybe-doc x t)) (push t did)) ;; We have to check packages separately (when (and p (maybe-doc p t)) (when did (grout-princ #\newline)) (grout-color :green :default "Package:") (grout-princ #\newline) ;;(grout-color :white :default ;; (format nil "~%~a~%" (maybe-doc p t))) (output-text (maybe-doc p t)) (push t did)) ;; Check for the symbol name in other packages (when (and (symbolp x) (or (not did) all)) (loop :for s :in (find-all-symbols (symbol-name x)) :do ;(when (not (eq (symbol-package s) (find-package :cl))) (do-docs s (symbol-package s)))) ;; Check for the command symbol in other packages ;; (when (or (not did-one) all) ;; (loop :for s :in (find-all-symbols (s+ "!" (symbol-name x))) ;; :do ;; ;;(do-docs s (symbol-package s)) ;; (print-doc s (symbol-package s) 'function 'command))) (when (or did all) (let ((c (get-command (or (and (stringp thing) thing) (string-downcase x))))) (when c ;; (print-doc c nil 'command) (print-doc thing nil 'command) ))) ;;(when (not did-one) ;; (grout-format "Nothing.~%")) )) did)) ;; This is a macro just so we don't have to quote the argument. (defmacro doc (x) #.*doc-doc-doc* (cond ((or (listp x) (stringp x)) `(%doc ,x)) ((symbolp x) ; Unbound symbol, so: `(%doc ',x)) ; quote it. (t `(progn (format t "Nothing.~%") nil)))) (defbuiltin doc ((thing object :required nil :help "What to get documentation for.")) #.*doc-doc-command-doc* (if (not thing) (format t "~ This shows documentation strings for something. Try typing \"doc doc\". ") (progn ;;(format t "Thing is a ~s with the value ~s.~%" (type-of thing) thing) (when (not (setf *output* (%doc thing #| :stream *terminal* |#))) (describe thing)) *output*))) ;; This is just a convenient wrapper around defparameter. I'm not really sure ;; this is a "good thing", but it can be useful for interactive programming. ;; Not having to declare variables, was probably first invented for interactive ;; programming in Lisp, but this can still have it's use. Of course ;; implementations vary on getting a warning. (defbuiltin var ((name string :optional nil :help "Name of the variable.") (value object :help "Initial value of the variable." ) (documentation string :use-supplied-flag t :help "Documentation string for the variable.")) "Define a variable, if you are so inclined." (eval `(defparameter ,(intern (string-upcase name)) ,(or value *input*) ,@(when documentation-supplied-p (list documentation))))) ;; EOF
77,713
Common Lisp
.lisp
2,035
33.592138
82
0.64755
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
a82f5d74863b7721196e9ab270ae94fecf9243dcabb01218e32279a5f985fa2a
2,136
[ -1 ]
2,137
lish-config.lisp
nibbula_lish/lish-config.lisp
;;; ;;; lish-config.lisp - Configuration for Lish ;;; (defpackage :lish-config (:documentation "Configuration for Lish") (:use :cl :config) (:export)) (in-package :lish-config) (defconfiguration ( ;; Actually I don't need this now. ;; (use-threads boolean-feature ;; "True if this implementation has usable threads." ;; (feature-expression '(or (and sbcl sb-thread) ;; (and ecl threads) ;; (and clisp mt) ;; mezzano ;; lispworks ;; (and allegro multiprocessing)))) (optimization-settings list "Default optimization settings for each file/compilation unit." ;; If we don't have at least debug 2, then most compilers won't save ;; the function arguments, which wrecks discoverability among other things. `((debug 2))))) (configure) ;; End
837
Common Lisp
.lisp
26
28.961538
79
0.659232
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
834be7a519877a5316c4f3da2351d8bcb617e19925e81ef6934bb6f7855debce
2,137
[ -1 ]
2,138
shell.lisp
nibbula_lish/shell.lisp
;;; ;;; shell.lisp - The shell object and it's options. ;;; (in-package :lish) (defkeymap *lish-default-keymap* () "Keymap for Lish." `((:f1 . shell-help-key) ;(,(ctrl #\v) . shell-expand-line) (,(meta-char #\o) . shell-expand-line) )) (define-key *lish-default-keymap* #\escape (build-escape-map *lish-default-keymap*)) ;; @@@ perhaps temporary for backwards compatibility (defun lish-keymap (fake) (declare (ignore fake)) *lish-default-keymap*) ;; @@@ I want to change all the lish-* accessors to shell-* (defclass shell () ((exit-flag :initarg :exit-flag :accessor shell-exit-flag :documentation "Set to true to exit the shell.") (exit-values :initarg :exit-values :accessor shell-exit-values :documentation "List of values to return to the caller.") (interactive-p :initarg :interactive :accessor shell-interactive-p :initform t :type boolean :documentation "True if the shell repeatedly prompts the user.") (aliases :accessor shell-aliases :documentation "Hash table of aliases.") (global-aliases :accessor lish-global-aliases :documentation "Hash table of global aliases.") (editor :accessor lish-editor :initform nil :documentation "Line editor instance.") (history-store :initarg :history-store :accessor lish-history-store :initform nil :documentation "Where to save history.") (old-pwd :accessor lish-old-pwd :initform nil :documentation "The last working directory.") (dir-list :accessor lish-dir-list :initform nil :documentation "Directory list for pushd and popd.") (directory-ring :initarg :directory-ring :accessor lish-directory-ring :initform '() :type list :documentation "A place to put the list of visited directories.") (directory-ring-size :initarg :directory-ring-size :accessor lish-directory-ring-size :initform 32 :type fixnum :documentation "Limit for the directory ring.") (jobs :accessor lish-jobs :initarg :jobs :initform nil :documentation "List of jobs.") (last-background-job :accessor lish-last-background-job :initform nil :documentation "The last job run in background, or NIL if there wasn't one.") (wait-for :initarg :wait-for :accessor shell-wait-for :initform nil :documentation "Jobs to wait for.") (saved-signals :initarg :saved-signals :accessor shell-saved-signals :initform nil :documentation "Saved O/S signal handlers that were active when the shell was invoked.") (start-time :initarg :start-time :accessor lish-start-time :type integer :documentation "Seconds elapsed since some time. Defaults to since shell was started.") (command-count :initarg :command-count :accessor shell-command-count :type integer :initform 0 :documentation "The count of commands entered in this shell.") (help-table :initarg :help-table :accessor shell-help-table :initform nil :documentation "A custom help table for this shell.") (options :initarg :options :accessor lish-options :initform nil :documentation "Operator configurable options.")) (:default-initargs :exit-flag nil :exit-values '() :start-time (get-universal-time)) (:documentation "A lispy system command shell.")) (defmethod initialize-instance :after ((sh shell) &rest initargs &key &allow-other-keys) (declare (ignore initargs)) ;; Save O/S signals (setf (slot-value sh 'saved-signals) (job-control-signals)) ;; Make alias tables (setf (slot-value sh 'aliases) (make-hash-table :test #'equal)) (setf (slot-value sh 'global-aliases) (make-hash-table :test #'equal)) ;; Copy the objecs from the defined option list, and set the default values. (loop :with o :for opt :in *options* :do (setf o (shallow-copy-object opt) (arg-value o) (arg-default o)) (push o (lish-options sh))) ;; Make command table (init-commands)) ;; Most things that are designed to be settable by the user should likely ;; be made into an option. Options defined by DEFOPTION are accessible like a ;; typical class slot acessor method on the shell object, as well as being an ;; easily accesible using the 'opt' command. ;; ;; We think of options like they are arguments for the shell, and use ;; the argument class to store them. That way we can use the same completion ;; and conversion. (defun find-option (sh name) "Find the option of the shell SH, named NAME. Error if there is none." (or (find (string name) (lish-options sh) :key #'arg-name :test #'equalp) (error 'shell-error :format "No such option ~w" :arguments (list name)))) (defparameter *option-accessor-prefix* "LISH-") (defun set-option (sh name value) "Set the option named NAME, for shell SH, to VALUE." (funcall (symbolify (s+ "SET-" *option-accessor-prefix* name) :package :lish) value sh)) (defun get-option (sh name) "Get the option named NAME, for shell SH." (arg-value (find-option sh name))) ;; @@@ The whole option setting interface is stupid, and we should probably ;; convert to just using (option name) and (setf (option name)) (defun option (name) "Accessor for the value of the option named ‘name’, for the current ‘*shell*’." (arg-value (find-option *shell* name))) (defun %set-option (name value) (set-option *shell* name value) value) (defsetf option %set-option "Set a shell option for the current ‘*shell*’.") (defmacro defoption (name (&key omit-setter) &rest arg) "Define a shell option named NAME, with the properties in arg. The syntax is like Lish arguments, e.g.: (defoption \"foo\" type :help \"Make sure to foo.\" :short-arg #\\f)" (let* ((sym (symbolify (s+ "LISH-" name))) (setter (symbolify (s+ "SET-" sym))) (name-string (string-downcase name)) (setter-def (when (not omit-setter) `((defmethod ,setter (value (sh shell)) (setf (arg-value (find-option sh ',name)) value)))))) `(progn ;; Access options as if they were in the shell object. (defgeneric ,sym (shell) (:documentation ,(s+ "Return the value of " name-string "."))) (defmethod ,sym ((sh shell)) (get-option sh ,name-string)) (defgeneric ,setter (value shell) (:documentation ,(s+ "Set the value of " name-string "."))) ,@setter-def ;; Make a separate setter so it can be easily overridden. (defgeneric (setf ,sym) (value shell) (:documentation ,(s+ "Set the value of " name-string "."))) (defmethod (setf ,sym) (value (sh shell)) (,setter value sh)) (push (make-argument (list ',name ',(first arg) ,@(rest arg))) *options*)))) (setf *options* nil) (defoption prompt () object :help "Normal prompt. Output if there is no prompt function. Output with SYMBOLIC-PROMPT-TO-STRING and FORMAT-PROMPT. See the documentation for those functions for more detail about prompt formatting." ;; :default nil :default '((:magenta "%u") (:green "@") (:cyan "%h") " " (:white "%w") (:red "%$") " ")) (defoption prompt-function () function :help "Function which takes a SHELL and returns a string to output as the prompt." ;; :default make-prompt ; N.B.: #'make-prompt doesn't work here ) (defoption right-prompt () object :help "Prompt for the right side of the input line. Output with SYMBOLIC-PROMPT-TO-STRING and FORMAT-PROMPT. See the documentation for those functions for more detail about prompt formatting." :default nil) (defoption sub-prompt () string :help "String to print when prompting for more input." :default "- ") ; @@@ maybe we need sub-prompt-char & sub-prompt-func? (defoption ignore-eof () integer :help "If true, prevent the EOF (^D) character from exiting the shell. If a number ignore it that many times before exiting." :default nil) (defoption debug () boolean :help "True to enter the debugger when there is an error." :default nil) (defoption collect-stats () boolean :help "True to collect statistics on commands." :default nil) (defoption autoload-from-asdf () boolean :help "True to try to load unknown commands from an ASDF system of the same name." :default t) (defoption autoload-quietly () boolean :help "True to suppress output from autoloading." :default t) (defoption history-expansion () boolean :help "True if !<integer> should expand to a history item." :default nil) (defoption expand-braces () boolean :help "True to expand braces in shell commands." :default t) (defoption colorize () boolean :help "True to colorize the command line." :default t) (defoption auto-cd () boolean :help "True to treat a directroy as a command to change to that directory." :default nil) (defoption history-style () choice :help "Style of history to use. Simple stores just text lines. Fancy stores more information, such as the date." :choices '("simple" "fancy") :default :fancy) (defmethod history-style ((sh shell)) (keywordify (get-option sh 'history-style))) ;; When changing the style, save and re-initialize the store. (defmethod (setf history-style) (value (sh shell)) (when (not (eq value (get-option sh 'history-style))) (finish-history sh) (set-option sh 'history-style value) (init-history sh))) (defoption history-format () choice :help "Style of history to use." :choices '("database" "text-file") ;; :default #.(if (getf rl-config::*config* :use-sqlite) ;; :database :text-file)) :default (if (getf rl-config::*config* :use-sqlite) :database :text-file)) (defmethod history-format ((sh shell)) (keywordify (get-option sh 'history-format))) ;; When changing the format, save and re-initialize the store. (defmethod (setf history-format) (value (sh shell)) (when (not (eq value (get-option sh 'history-format))) (finish-history sh) (set-option sh 'history-format value) (init-history sh))) ;; @@@ This is trouble. ;; (defoption history-save-values () boolean ;; :help "True to save the result values of expressions in the history." ;; :default nil) (defoption command-glob () boolean :help "Let Lish commands do their own globbing.") (defoption auto-suggest (:omit-setter t) boolean :help "True to make suggestions for the rest of the line." :default t) (defmethod set-lish-auto-suggest (value (sh shell)) (setf (arg-value (find-option sh 'auto-suggest)) value) (when (lish-editor sh) ;; There isn't always an editor. (setf (line-editor-auto-suggest-p (lish-editor sh)) value))) (defoption partial-line-indicator (:omit-setter t) object :help "A string to put at the end of partial lines before the prompt, or NIL not to indicate partial lines." :default (span-to-fat-string '(:standout "%"))) (defmethod set-lish-partial-line-indicator (value (sh shell)) (setf (arg-value (find-option sh 'partial-line-indicator)) value) (when (lish-editor sh) (setf (rl::partial-line-indicator (lish-editor sh)) value))) (defoption gutter-char (:omit-setter t) object :help "A character to use for the gutter, or NIL not use a gutter. The gutter is an unused area under the prompt. Having a gutter helps align the display of multiple lines." :default #\space) (defmethod set-lish-gutter-char (value (sh shell)) (setf (arg-value (find-option sh 'gutter-char)) value) (when (lish-editor sh) (setf (rl::gutter-char (lish-editor sh)) value))) (defoption export-pipe-results () boolean :help "True to export LISH_INPUT and LISH_OUTPUT to sub-processes.") (defoption auto-report-time () integer :help "If a job takes longer than this number of seconds, report timing statistics." :default -1) (defoption command-mining () boolean :help "True to dig through various places to find external command usage." :default t) ;; EOF
11,780
Common Lisp
.lisp
285
37.82807
81
0.708599
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
db89063b0ae55bb76d571948fadf0596411c8e4210a648732c4bfd71b7e21375
2,138
[ -1 ]
2,139
jobs.lisp
nibbula_lish/jobs.lisp
;; ;; jobs.lisp - Shell job objects ;; (in-package :lish) ;; If we someday jettison being tied to a text only world, we can get rid of ;; the *job-counter* and job-id, which only exists so you can type it in text. ;; In that world, we could have the job object *in* the command line. We would ;; of course have to have some, presumablely interactive, way of putting the ;; object in there. ;; So, of course, I would like a portable atomic operations library, pretty ;; much like the one in SBCL. Does such a thing exist? Probably. But how am I ;; supposed to find it??? So instead you get another page from the cookbook of ;; failure. (declaim (type fixnum *job-counter*)) #+sbcl (sb-ext:defglobal *job-counter* 0 "A counter for job identifier numbers.") (eval-when (:compile-toplevel :load-toplevel :execute) #+sbcl (defalias 'atomic-incf 'sb-ext:atomic-incf)) #-sbcl (defvar *job-counter* 0 "A counter for job identifier numbers.") (eval-when (:compile-toplevel :load-toplevel :execute) #-sbcl (defalias 'atomic-incf 'incf)) (deftype job-status () "A keyword indicating what's going on with a job." '(member :running :stopped :suspended :dead)) (defclass job () ((id :initarg :id :accessor job-id ;;:initform (atomic-incf *job-counter*) :type integer :documentation "Still stuck in the text world.") (name :initarg :name :accessor job-name :documentation "Some kind of name for the job.") (command-line :initarg :command-line :accessor job-command-line :documentation "The command line that started it.") (status :initarg :status :accessor job-status :initform :running :type job-status :documentation "Keyword indicating what's going on with the job.")) (:default-initargs :id (atomic-incf *job-counter*)) (:documentation "A generic shell job.")) (defmethod print-object ((object job) stream) "Print a job to STREAM." (with-slots (id name status command-line) object (print-unreadable-object (object stream :type t :identity t) (format stream "~s ~s ~s ~s" id name status command-line)))) (defgeneric continue-job-in-foreground (job) (:documentation "Continue a stopped job in the foreground.")) (defgeneric continue-job-in-background (job) (:documentation "Continue a stopped job in the background.")) (defgeneric kill-job (job &key signal) (:documentation "Destroy a job.")) (defgeneric list-all-jobs (type) (:documentation "List all jobs of a type.")) (defgeneric check-job-status (shell type) (:documentation "Check status of all jobs of a type.")) (defun job-p (object) "Return true if OBJECT is a JOB." (typep object 'job)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; System jobs (defclass system-job (job) ((pid :initarg :pid :accessor job-pid :documentation "System process identifier.") (process-group :initarg :process-group :accessor job-process-group :documentation "System process group.") ;; (process-handle-value ;; @@@ resolve this somehow ;; :initarg :process-handle-value :accessor job-process-handle-value ;; :documentation "Job process handle.") ) (:documentation "An operating system job.")) (defmethod job-pid ((job job)) "Pretend non-system jobs have a NIL PID." nil) (defmethod continue-job-in-foreground ((job system-job)) #+unix (multiple-value-bind (result status) (os-unix::resume-background-pid (job-pid job)) (handle-job-change job result status))) (defmethod continue-job-in-background ((job system-job)) #+unix (progn (uos::background-pid (job-pid job)) (setf (job-status job) :running))) (defmethod kill-job ((job system-job) &key signal) #+unix (os-unix:kill (job-pid job) (or signal uos:+SIGTERM+)) #+windows (funcall (caddr (find signal *siggy* :key #'second)) (job-pid job)) ) (defmethod list-all-jobs ((type (eql 'system-job))) ;; @@@ This is underwhelming. We probably should use the OS specific ;; system-procces-list, but of course that creates more problems. (mapcar (_ (make-instance 'system-job :id (os-process-id _) :name (os-process-name _) :command-line "" :pid (os-process-id _))) (nos:process-list))) (defmethod check-job-status (shell (type (eql 'system-job))) (let (job pid result status) (loop :do (multiple-value-setq (pid result status) (nos:check-jobs)) :while pid :do (if (setf job (find pid (lish-jobs shell) :test #'eql :key #'job-pid)) (handle-job-change job result status) (format t "Unknown job changed ~a~%" pid))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Lisp jobs (defclass lisp-job (job) ((resume-function :initarg :resume-function :accessor job-resume-function :documentation "A function that resumes the job.")) (:documentation "A job which is a Lisp closure.")) (defmethod continue-job-in-foreground ((job lisp-job)) (when (job-resume-function job) (setf (lish-jobs *shell*) (delete job (lish-jobs *shell*))) (funcall (job-resume-function job)))) (defmethod continue-job-in-background ((job lisp-job)) (error "I don't know how to background a Lisp job yet.")) (defmethod kill-job ((job lisp-job) &key signal) (declare (ignore signal)) (error "I don't know how to kill a Lisp job yet.")) (defmethod list-all-jobs ((type (eql 'lisp-job))) ;; @@@ To really do this we would have to somehow find all shell instances. ;; It would probably be cool to be able to resume a job from a diffent shell, ;; but we would probably have to add a terminal switching interface. (remove-if (_ (not (typep _ 'lisp-job))) (lish-jobs *shell*))) (defmethod check-job-status (shell (type (eql 'lisp-job))) (declare (ignore shell)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Thread jobs (defclass thread-job (job) ((thread :initarg :thread :accessor job-thread :documentation "A thread object.")) (:documentation "A job which is a thread.")) (defmethod continue-job-in-foreground ((job thread-job)) (nos:join-thread (job-thread job)) ) (defmethod continue-job-in-background ((job thread-job)) ;; @@@ If we created the the thread, we could have set up ;; a condition variable that in the interrupt handler we would ;; ask the thread to wait on, then we could use ;; condition-notify here to wake it up, effectively backgrounding it. (error "Threads can't be backgrounded yet.")) (defmethod kill-job ((job thread-job) &key signal) (declare (ignore signal)) (nos:destroy-thread (job-thread job))) (defmethod list-all-jobs ((type (eql 'thread-job))) ;; @@@ This still has the id specification problem. (when nos:*supports-threads-p* (mapcar (_ (make-instance 'thread-job :id nil :name (nos:thread-name _) :command-line "" :thread _)) (nos:all-threads)))) (defmethod check-job-status (shell (type (eql 'thread-job))) (loop :for j :in (lish-jobs shell) :when (typep j 'thread-job) :do (cond ((not (find (job-thread j) (nos:all-threads))) (format t ";; Thread done ~a~%" (job-name j)) (delete-job j)) ((not (nos:thread-alive-p (job-thread j))) ;; It's destroyed but it's still in all-threads ?? (setf (job-status j) :dead))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defparameter *job-types* '(system-job lisp-job thread-job) "All the different job types.") (defun job-type-name (job) "Return a personized string for the type of JOB." (if (not (typep job 'job)) "????" (string-capitalize (remove-suffix (string (type-of job)) "-JOB")))) (defun find-job (job-descriptor) "Return a job given a descriptor." (cond ;; Presumably this is a good guess. ((null job-descriptor) (first (lish-jobs *shell*))) ((stringp job-descriptor) ;; strip off a leading percent (when (and (not (zerop (length job-descriptor))) (char= (char job-descriptor 0) #\%)) (setf job-descriptor (subseq job-descriptor 1))) (or (find job-descriptor (lish-jobs *shell*) :test #'equalp :key #'job-name) (find job-descriptor (nos:all-threads) :test #'equalp :key #'nos:thread-name) (and (setf job-descriptor (ignore-errors (parse-integer job-descriptor))) (find job-descriptor (lish-jobs *shell*) :test #'eql :key #'job-id)))) ((numberp job-descriptor) (find job-descriptor (lish-jobs *shell*) :test #'= :key #'job-id)) ((symbolp job-descriptor) (or (find (string job-descriptor) (lish-jobs *shell*) :test #'equalp :key #'job-name) (when (find-package :bt) (find (string job-descriptor) (nos:all-threads) :test #'equalp :key #'nos:thread-name)))) (t (find job-descriptor (lish-jobs *shell*) :test #'equalp :key #'job-name)))) ;; EOF
8,872
Common Lisp
.lisp
210
38.466667
81
0.661833
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
ebe47a980f47b7354d0d5917c1e7aa07a0136b6aad7bdda72b1f00179c35fa09
2,139
[ -1 ]
2,140
commands.lisp
nibbula_lish/commands.lisp
;;; ;;; commands.lisp - How Lish does commands ;;; ;; Define command objects through which a command can be invoked. We store a ;; fair amount of command properties, such the arguments to commands, ;; documentation, and things useful for completion. ;; ;; We provide the ‘defcommand’ macro for defining commands. There are also a ;; few subtypes of command such and builtin and external. This file also ;; contains the code for converting from a unix style command invocation, to ;; lisp arguments for the command function. (in-package :lish) (define-condition unknown-command-error (shell-error cell-error) ((command-string :accessor unknown-command-error-command-string :initarg :command-string :type string :documentation "Name of the unknown command.")) (:report (lambda (c s) (if (shell-error-format c) (format s "~a ~?" (unknown-command-error-command-string c) (shell-error-format c) (shell-error-arguments c)) (format s "~a not found" (unknown-command-error-command-string c))))) (:documentation "Tried to execute an unknown command.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Commands (defclass base-command () ((name :accessor command-name :initarg :name :documentation "The string word that invokes the command.")) (:documentation "Minimum common base command.")) (defgeneric command-accepts (command) (:documentation "What types the commands accepts as input.") (:method ((command base-command)) nil)) (defgeneric command-arglist (command) (:documentation "The command's argument list.") (:method ((command base-command)) nil)) (defgeneric invoke-command (command args) (:documentation "Invoke the command.")) (defclass command (base-command) ((function :accessor command-function :initarg :function :documentation "The function that performs the command.") (arglist :accessor command-arglist :initarg :arglist :documentation "A list of arguments.") (handle-unrecognized :initarg :handle-unrecognized :accessor command-handle-unrecognized :initform nil :type boolean :documentation "True to pass unrecogized arguments to the command.") (pass-keys-as :initarg :pass-keys-as :accessor command-pass-keys-as :initform nil :type symbol :documentation "Argument name to pass all keyword arguments as. NIL if we don't need it.") (auto-help :initarg :auto-help :accessor command-auto-help :initform t :type boolean :documentation "Automatically handle help arguments.") (accepts :initarg :accepts :accessor command-accepts :initform :unspecified :documentation "Sequence of things the command accepts. Probably one of: :STREAM An output stream. :GROTTY-STREAM An output stream which can have terminal decorations. :SEQUENCE A sequnce of objects. :UNSPECIFIED We don't know. This is the default. <non-keyword> A lisp type. NIL Doesn't accept anything.") (loaded-from :accessor command-loaded-from :initarg :loaded-from :initform nil :documentation "Where the command was loaded from.")) (:documentation "A command defined internally in the shell.")) (defmethod initialize-instance :after ((b command) &rest initargs) (declare (ignore initargs)) ;; Make the default function binding from the name (if (not (slot-boundp b 'function)) (setf (slot-value b 'function) (command-function-name (slot-value b 'name))))) (defmethod print-object ((o command) stream) "Print a lish command in an unreadable way." (print-unreadable-object (o stream :identity nil :type t) ;; (if (slot-boundp o 'synopsis) ;; (format stream "~s" (command-synopsis o)) ;; (format stream "~s" (if (slot-boundp o 'name) ;; (command-name o) ;; (format stream "<unnamed>")))))) (format stream "~a" (posix-synopsis o)))) ;; Command class hierarchy: ;; ;; base-command ;; command ;; internal-command ;; shell-command ;; builtin-command ;; external-command ;; autoloaded-command (defclass internal-command (command) () (:documentation "An command implemented in the shell.")) (defmethod invoke-command ((command internal-command) args) "Invoke an internal command that has a command function." (run-hooks *pre-command-hook* command :command) ;; @@@ This idea could be expanded upon. We could probably move some the ;; functionality from lish.lisp to invoke-command methods. (multiple-value-bind (done new-args) (process-auto-args command args) (when done ;; If it was handled, return without actually calling the command. (return-from invoke-command (values))) (setf args new-args)) (multiple-value-prog1 (if args (apply (command-function command) args) (funcall (command-function command))) (post-command command :command))) (defclass shell-command (internal-command) () (:documentation "A shell command.")) ;; (defparameter *initial-commands* nil ;; "List of initial commands.") (defvar *command-list* nil "List of command names.") (defvar *lish-commands* nil "Hash table of commands. This means that commands are shared by all shell instances.") (defun lish-commands () (when (not *lish-commands*) (setf *lish-commands* (make-hash-table :test #'equal))) *lish-commands*) ;; @@@ {get,set,unset}-command should probably be deprecated for the ;; command method (defun set-command (name obj) (setf (gethash name (lish-commands)) obj)) (defun unset-command (name) (remhash name (lish-commands))) (defun get-command (name) (gethash name (lish-commands))) (defgeneric command (name) (:documentation "Return the command named NAME, or NIL if one isn't defined.")) (defmethod command ((name string)) (gethash name (lish-commands))) (defmethod (setf command) ((object command) (name string)) (setf (gethash name (lish-commands)) object)) (defmethod (setf command) ((object null) (name string)) (declare (ignore object)) (remhash name (lish-commands))) (defun init-commands () "This doesn't really do anything anymore, we're just keeping it in case we want to use it for something in the future." (values)) ;; "Set up the *LISH-COMMANDS* hash table, and load it with the commands from ;; *INITIAL-COMMANDS*, which is likely whatever commands were defined with ;; DEFBUILTIN." ;; (loop :for (k v) :in *initial-commands* ;; :do (set-command k v))) (eval-when (:compile-toplevel :load-toplevel) ; needed by defcommand macro (defun command-function-name (n) "Return the normal command function symbol for the given command name." (intern (concatenate 'string "!" (string-upcase n))))) #| (defmacro squirrel-def (package &body body) (let ((squirrel-package (s+ package "-DEFS")) (defs-sym (gensym "SQUIRREL-DEF"))) `(if (find-package ,package) (progn ,@body) (progn (when (not (find-package ,squirrel-package)) (make-package ,squirrel-package) (let ((,defs-sym (intern "*DEFS*" (find-package ,squirrel-package)))) (eval `(defvar ,,defs-sym '())))) (let ((,defs-sym (intern "*DEFS*" (find-package ,squirrel-package)))) (set ,defs-sym (cons ',body (symbol-value ,defs-sym)))))))) |# (defun ignorable-filter (args) "Given a lambda list return a list of variable names to ignore." (lambda-list-vars args :all-p t)) (defun process-auto-args (command args) "Process automatic arguments for ‘command’. Return the if we should return without invoking the normal command." (when (command-auto-help command) (let ((h (getf args :help 'zerpy))) (when (not (eq h 'zerpy)) ; If :help is in args, (setf args (remf args :help)) ; remove it, (when h ; and if it's true, (print-command-help command) ; print it. (return-from process-auto-args (values t args)))))) ;; Should we complain if an auto :help arg was removed? (values nil args)) (defun remove-auto-args (command args) "Remove any automatic arguments from ‘arg’ for ‘command’ and return them." (when (and (command-auto-help command) (not (null args))) (remf args :help))) ;; There should be little distinction between a user defined command and ;; "built-in" command, except perhaps for a warning if you redefine a ;; pre-defined command, and the fact that things defined in the shell are ;; considered "built-in" and listed in help that way. ;; ;; I would wish that defcommand could provide enough documentation to make a ;; man page, or an info page, or a CLHS like page. ;; ;; We should make it easy to indicate man page sections and info links. ;; We should accept some kind of markdown for doc strings. ;; We should automatically generate any sections possible. ;; ;; Man pages have: ;; NAME name - Less than one line summary ;; SYNOPSIS (should be automatically generated, as in help) ;; DESCRIPTION Pretty much the normal docstring. ;; OPTIONS List options and describe in detail. Generate from ;; option docstrings? ;; EXAMPLES very useful ;; FILES <perhaps not so useful / optional> ;; ENVIRONMENT <perhaps not so useful / optional> ;; DIAGNOSTICS populated by gleaning errors? ;; BUGS Of course we don't need this ;) ;; AUTHOR Gleaned from package author ;; SEE ALSO this is useful in CLHS, so... ;; ;; Info pages have: ;; Up, Prev, Next links ;; Menu sub links ;; ;; CLHS pages have: ;; Summary (type, name, args, and return values) ;; Arguments and Values ;; Description ;; Examples ;; Exceptional Situations ;; Side Effects ;; Affected By ;; See Also ;; Notes ;; @@@ :KEYS-AS is the deprecated name for :ARGS-AS. :ARGS-AS makes more sense ;; now that we don't have any non-keyword arguments. ;; Someday get rid of :KEYS-AS. ;; @@@@ add a :handlers tag to bind argument error handlers (defparameter *special-body-tags* #(:accepts :keys-as :args-as :no-help :handlers) ;; @@@@@@ "Keywords with special meanings appearing first in the command body.") ;; This defines a function with the appropriate Lisp argument list. ;; At eval time, which is usually load time, it makes an shell argument list, ;; a command instance with the argument list, and adds the command to the ;; command table. A temporary argument list is made at compile time to ;; figure out the Lisp args. (defmacro %defcommand (name type do-defun (&rest arglist) &body body) "See the documentation for DEFCOMMAND." (let ((func-name (command-function-name name)) (name-string (string-downcase name)) (accepts :unspecified) (my-fixed-body body) (fixed-arglist arglist) command-arglist pass-keys-as params ignorables default-keys rest-var defun-clause (auto-help t)) ;; Pull out special body tags: (loop :with tag :while (setf tag (find (car my-fixed-body) *special-body-tags*)) :do (case tag (:accepts (setf accepts (cadr my-fixed-body) my-fixed-body (cddr my-fixed-body))) ((:keys-as :args-as) (setf pass-keys-as (setf rest-var (cadr my-fixed-body)) my-fixed-body (cddr my-fixed-body))) (:no-help (setf auto-help nil my-fixed-body (cddr my-fixed-body))))) ;; If there's already a help arg, don't add one. (when (find 'help arglist :key #'car :test #'string=) (setf auto-help nil)) (when auto-help (setf fixed-arglist (append fixed-arglist (list '(help boolean :long-arg "help" :help "Show the help."))))) (setf params ;; We use arglist instead of fixed-arglist, becuase the auto command ;; args (like :help) should be removed before the function is called. (command-to-lisp-args (make-argument-list arglist t) :pass-keys-as pass-keys-as) ignorables (when (and params (or pass-keys-as auto-help)) `((declare (ignorable ,@(ignorable-filter params))))) ;; Set the &rest parameter from the defaulted args. default-keys (when (and params pass-keys-as) `(setf ,rest-var (list ,@(loop :for a :in (remove rest-var (lambda-list-vars params)) :collect (keywordify a) :collect a)))) defun-clause (with-decls-and-body (my-fixed-body) (if do-defun `((defun ,func-name ,params ,@ignorables ,@doc-and-decls ,default-keys ,@fixed-body)) `((defun ,func-name () ,@doc-and-decls ,@fixed-body))))) (setf command-arglist (loop :for a :in fixed-arglist :do (check-argument a) :collect `(make-instance ',(new-argument-type-class (second a)) ,@(transform-arg a)))) `(progn (when (find-package :lish) ;; Protect against loading without the shell. ,@defun-clause (pushnew ,name-string lish::*command-list* :test #'equal) (set-command ,name-string (make-instance ',type :name ,name-string :loaded-from *load-pathname* :accepts ',accepts :auto-help ,auto-help :pass-keys-as ,(and pass-keys-as `(quote ,pass-keys-as)) ;;:arglist (make-argument-list ',arglist) :arglist (list ,@command-arglist))))))) (defmacro defcommand (name (&rest arglist) &body body) "Define a command for the shell. NAME is the name it is invoked by. ARGLIST is a shell argument list, which has the form: ([(name type [initargs...])...]) where initargs are initializing keyword arguments for calling make-instance of ARG-<type>. BODY is the body of the function it calls. BODY recognizes some special keywords: :ACCEPTS followed by a single indicator or list of indicators that can be types or keywords to indicate what the command accepts from a shell pipeline. :ARGS-AS followed by a symbol which will be a list of the keywords and values given to the command function. :KEYS-AS is a deprecated synonym." `(%defcommand ,name shell-command t (,@arglist) ,@body)) (defclass builtin-command (internal-command) () (:documentation "A command that is considered parth of the shell.")) (defun command-built-in-p (command) "Return true if a command is a “builtin” command." (typep command 'builtin-command)) (defmacro defbuiltin (name (&rest arglist) &body body) "Just like DEFCOMMAND, except it sets BUILT-IN-P to T." `(%defcommand ,name builtin-command t (,@arglist) ,@body)) (defclass external-command (command) ((path :initarg :path :accessor external-command-path :documentation "File system path of the command.") (checksum :initarg :checksum :accessor external-command-checksum :documentation "Checksum for the data in the command file.") (checksum-type :initarg :checksum-type :accessor external-command-checksum-type :documentation "Keyword indicating the algorithm used to calculate the checksum.") (manual :initarg :manual :accessor external-command-manual :initform t :type boolean :documentation "True if the comannd was defined manually. False if it was defined by mining command data.")) (:documentation "A command that is an external program to the shell.")) ;; This was going to intialize program-name, but maybe it's not necessary. ;; (defmethod initialize-instance ;; :after ((o external-command) &rest initargs &key &allow-other-keys) ;; "Initialize a external-command." ;; (declare (ignore initargs)) ;; (setf (slot-value o 'program-name) ;; (slot-value o 'command-name)) ;; ) (defmacro defexternal (name (&rest arglist) &body body) "Define an external command for the shell. NAME is the name it is invoked by and the name of the external program. ARGLIST is a shell argument list." `(%defcommand ,name external-command nil (,@arglist) ,@body ;; This T is because we usually don't supply anything but a docstring, ;; which would otherwise be interpreted as a string to return as the ;; function's value. t)) (defun make-external-command (name path arglist doc) (pushnew name *command-list* :test #'equal) (set-command name (make-instance 'external-command :name name :arglist arglist :path path :manual nil)) (setf (documentation (command-function-name name) 'function) doc)) (defun undefine-command (name) (unset-command name) (setf *command-list* (delete name *command-list*))) (defun in-lisp-path (command) "Return true if a command can be found by ASDF." ;; (loop :with path ;; :for dir :in *lisp-path* :do ;; (when (setf path (probe-file (s+ dir command))) ;; (asdf::resolve-symlinks path)))) ; XXX I know, this is cheating. ;; Maybe we should make our own system search function? ;; i.e. push on asdf:*system-definition-search-functions* (typecase command ((or keyword symbol) (ignore-errors (asdf:find-component nil command))) (string (when (not (position #\/ command)) ; looks like a path itself (ignore-errors (asdf:find-component nil command)))) (t nil))) (defmacro stfu (&body body) (let ((nilly (gensym))) `(let (,nilly) (unwind-protect (progn (setf ,nilly (make-broadcast-stream)) (let ((*standard-output* ,nilly) (*error-output* ,nilly) ;; (*debug-io* ,nilly) (*trace-output* ,nilly) (*load-print* nil) (*load-verbose* nil) ;;(asdf::*verbose-out* nil) ) ,@body)) (when ,nilly (close ,nilly)))))) (defun load-lisp-command-from (command-name package &key silent) "Try to load a command in the Lisp path. Return the command on success or NIL on failure. The Lisp path is most likely the ASDF path." (let* (succeeded) (handler-case (let ((asdf:*compile-file-warnings-behaviour* :ignore) (asdf:*compile-file-failure-behaviour* :ignore)) ;; :error :warn :ignore (if silent (stfu (asdf:oos 'asdf:load-op package :verbose nil)) (asdf:oos 'asdf:load-op package :verbose nil)) ;; Presumable we succeeded if we didn't get an error. (setf succeeded t)) (asdf:system-definition-error (c) (declare (ignore c))) (asdf:operation-error (c) (declare (ignore c)))) (if succeeded (progn ;; (init-commands sh) (get-command command-name)) ;; failed nil))) (defun load-lisp-command (command &key silent) "Try to load a command in the Lisp path. Return the command on success or NIL on failure. The Lisp path is most likely the ASDF path." (load-lisp-command-from command (intern (string-upcase command) :keyword) :silent silent)) (defclass file-based-command (base-command) ;; @@@ In the case of source commands, "load" isn't exactly right, so ;; we should change it. ((load-from :initarg :load-from :accessor command-load-from :documentation "Where to load the command from.")) (:documentation "A command loaded from somewhere when invoked.")) (defmethod print-object ((o file-based-command) stream) "Print a lish command in an unreadable way." (print-unreadable-object (o stream :identity nil :type t) (format stream "from ~s" (command-load-from o)))) #|──────────────────────────────────────────────────────────────────────────┤# │ Autoloaded commands ╰|# (defclass autoloaded-command (file-based-command) () (:documentation "A command automatically loaded from somewhere when invoked.")) ;; (defmethod initialize-instance ;; :after ((o autoloaded-command) &rest initargs &key &allow-other-keys) ;; "Initialize a autoloaded-command." ;; (declare (ignore initargs)) ;; (when (not (slot-boundp o 'name)) ;; (error "autoloaded-command must have a name.")) ;; ) ;; (defmethod print-object ((o autoloaded-command) stream) ;; "Print a lish command in an unreadable way." ;; (print-unreadable-object (o stream :identity nil :type t) ;; ;; (if (slot-boundp o 'synopsis) ;; ;; (format stream "~s" (command-synopsis o)) ;; ;; (format stream "~s" (if (slot-boundp o 'name) ;; ;; (command-name o) ;; ;; (format stream "<unnamed>")))))) ;; (format stream "from ~s" (command-load-from o)))) (defmethod invoke-command ((command autoloaded-command) args) (let ((loaded-command (load-lisp-command-from (command-name command) (command-load-from command) :silent (lish-autoload-quietly *shell*)))) (typecase loaded-command (autoloaded-command (error "Autoloading ~a from ~a failed. Probably because the command ~ wasn't defined in the system." (command-name command) (command-load-from command))) (null (error "Autoloading ~a from ~a failed. Probably becuase the system is ~ missing." (command-name command) (command-load-from command))) (command ;; We can only convert the args AFTER we load the command. (let ((lisp-args (posix-to-lisp-args loaded-command args))) (invoke-command loaded-command lisp-args)))))) #|──────────────────────────────────────────────────────────────────────────┤# │ Sourced commands ╰|# (defclass sourced-command (file-based-command) () (:documentation "A command sourced from somewhere when invoked.")) (defun source-command-p (path) "Return true if the file in ‘path’ is a source command." (block nil (handler-case (with-open-file (f path :element-type '(unsigned-byte 8)) (and (= (read-byte f) (char-code #\;)) (= (read-byte f) (char-code #\!)))) (error () (return nil))))) (defun make-source-command (path) (let* ((command-name (path-file-name path)) (command (make-instance 'sourced-command :name command-name :load-from path))) (pushnew command-name *command-list* :test #'equal) ;; (setf (documentation (command-function-name command-name) 'function) ;; docstring) (set-command command-name command))) (defmethod invoke-command ((command sourced-command) args) (declare (ignore args)) ;; @@@ (load-file (command-load-from command))) ;; (defun load-external-command (command) ;; "Try to load an external command definition." ;; (let* ((path (command-pathname command)) ;; (path-list (split-path path))) ;; (when path ;; path-list ;; ))) #| (defclass arg-list () (arg-list-list) (:documentation "A list of arguments.")) (defgeneric get-args () (:documentation "Return a string to prompt with.")) (defmethod get-args (arg-list)) (defgeneric args-help () (:documentation "Return a string to prompt with.")) (defmethod args-help (arg-list)) |# #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||# #|| ||# #|| Let's try something different. ||# #|| ||# #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||# ;; [ ] optional ;; ( ) mandatory (not optional) ;; ... repeating ;; a | b or ;; foo literal string "foo", not optional ;; --foo option "foo" ;; <foo> type foo : arg-<foo> ;; -- start of positional only ;; We already have :optional and :repeating on individual items. ;; We don't have grouping, which we need for mandatory ( ), and "or". ;; We should implement "--". ;; (:or a b c) a | b | c ;; (:opt a b c) [ a b c ] ;; (:and a b c) ( a b c ) ;; (:repeat a b c) ( a b c )... ;; (:repeat a) a... ;; (:opt (:repeat a)) [a...] ;; --a :positional b c --a -- --a ;; (:or ("foo" (:opt x y z)) foo [x] [y] [z] ;; ("bar" (:opt a b c))) bar [a] [b] [c] ;; (:case <foo-cmd> So we can have type based completion. ;; (foo (x y z)) foo [x] [y] [z] ;; (bar (a b c))) bar [a] [b] [c] #|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||# #| We used to alllow non-keyword arguments for command functions, but this turns out to be much more complicated for the small benefit of a slightly nicer interface when calling the Lisp version of the command. We now only use keywords, so rest of this whole comment is only useful if we want to go back to that. XXX-- Start of obsolete comment --XXX The rules for converting POSIX arguments to lambda lists are fairly complicated. Here we try to examine some of the possiblities. We use a letter to denote the category of argument: m = manditory o = optional r = repeating f = flagged When only manditory and optional are present, we don't need keywords. The order of manditories vs optionals doesn't matter to lambda lists, but does to POSIX. Non-flagged optionals must come after manditories. m1 m2 (m1 m2) m1 m2 m1 m2 o1 o2 (m1 m2 &optional o1 o2) m1 m2 [o1] [o2] o1 o2 m1 m2 (m1 m2 &optional o1 o2) [o1] [o2] m1 m2 problematic??? o1 o2 (&optional o1 o1) [o1] [o2] We can't have more than one non-flagged repeating: ro1 (&rest r1) [ro1...] rm1 rm2 ERROR ro1 ro2 ERROR m1 m2 ro1 (m1 m2 &rest r1) m1 m2 [ro2...] m1 m2 r1 r2 ERROR o1 o2 r1 ERROR (o1 and o2 must be flagged) rm1 (&rest r1) r1[...] r1 r2 ERROR m1 m2 rm1 (m1 m2 &rest r1) m1 m2 rm1[...] m1 m2 ro1 (m1 m2 &rest r1) m1 m2 [ro1...] m1 m2 r1 r2 ERROR of1 of2 rm1 (&key of1 of2 r1) [-12] r1[...] of1 of2 ro1 (&key of1 of2 r1) [-12] [r1...] Flagged optional must be done as keywords: m1 m2 of1 o2 (m1 m2 &key of1 o2) [-1] m1 m2 [o2] m1 m2 o1 of2 (m1 m2 &key o1 of2) [-2] m1 m2 [o1] m1 m2 of1 of2 (m1 m2 &key o1 of2) [-2] m1 m2 [o1] of1 o2 m1 m2 (m1 m2 &key of1 o2) [-1] m1 m2 [o2] of1 of2 m1 m2 (m1 m2 &key of1 of2) [-12] m1 m2 of1 of2 (&key of1 of2) [-12] o1 of2 (&key of1 of2) [-2] [o1] of1 o2 (&key of1 of2) [-1] [o2] Flagged manditory must be done as keywords, which DOES'T make other manditories keywords. Manditory flagged treated as optional flagged, except error afterward if not present. mf1 m2 of1 o2 (m2 &key mf1 of1 o2) [-of1] [-mf1] [o2] m2 m1 mf2 o1 of2 (m1 &key mf2 o1 of2) [-mf2] [-of2] [o1] m1 mf1 mf2 of1 of2 (&key mf1 mf2 o1 of2) [-mf1] [-mf2] [-of2] [o1] of1 o2 mf1 m2 (m2 &key of1 o2 mf1) [-of1] [-mf1] [o2] m2 of1 of2 m1 mf2 (m1 &key of1 of2 mf2) [-of1] [-of2] [-mf2] m1 mf1 mf2 (&key mf1 mf2) [-mf1] [-mf2] Repeating flagged: can have more than one, but values can't start with dashes! Repeating flagged manditory and optional are treated the same. rf1 (&rest rf1) [-rf1 foo] [...] (*stupid but legal) rf1 rf2 (&key rf1 rf2) [-rf1 foo...] [-rf2 bar...] (*can be given in any order, e.g.: -rf2 foo bar -rf1 foo bar baz) Flagged arguments can appear in POSIX in multiple ways: (:short-arg x :type boolean) [-x] ((:short-arg x :type boolean) [-xy] (:short-arg y :type boolean)) (:short-arg x :type (not boolean)) [-x arg] ((:short-arg x :type (not boolean)) [-x arg] [-y arg] (:short-arg y :type (not boolean))) (:long-arg foo :type boolean) [--foo] (:long-arg foo :type (not boolean)) [--foo bar] |# ;; ;; If there are any optional non-positional args (i.e. optional args with ;; short-arg or long-arg specified, then all the lisp args must be keyworded. ;; ;; @@@ Make argument type classes work, with specific type ;; validation and completion methods. (defun maybe-flatten (arg value) "If ‘arg’ is flattenable, return ‘value’ flattened." (if (and (arg-flattenable-p arg) (consp value)) (flatten value) value)) (defun convert-and-flatten-arg (arg value) (maybe-flatten arg (convert-arg arg (word-word value) (word-quoted value)))) (defun push-arg (arg value list &key (convert t)) "Push the word ‘value’ of ‘arg’ on ‘list’, converting it and flattening it, as appropriate. Return the new list." (push (maybe-flatten arg (if convert (convert-arg arg (word-word value) (word-quoted value)) value)) list)) (defmacro move-arg (old new i arg) "Move the I'th item from the OLD to the NEW list, and return both." `(progn (setf ,new (push-arg ,arg (nth ,i ,old) ,new) ,old (delete-nth ,i ,old)))) (defun arg-key (arg) (intern (string-upcase (arg-name arg)) :keyword)) (defmacro move-key (old new i arg keyworded) "Move the I'th item from the OLD to the NEW list, and return both." `(progn (when ,keyworded (setf ,new (push (arg-key ,arg) ,new))) (setf ,new (push-arg ,arg (nth ,i ,old) ,new)) (setf ,old (delete-nth ,i ,old)))) (defmacro push-key (new arg value keyworded) "Push a possibly keyworded arg VALUE to the NEW list." (with-names (val) `(progn (when ,keyworded (setf ,new (push (arg-key ,arg) ,new))) (let ((,val ,value)) (setf ,new (push-arg ,arg ,val ,new)))))) (defmacro move-flag (old new i arg) `(progn (setf ,new (push (arg-key ,arg) ,new)) (setf ,new (push-arg ,arg (nth (1+ ,i) ,old) ,new)) (setf ,old (delete-nth ,i ,old)) ; flag (setf ,old (delete-nth ,i ,old)) ; arg (setf possible-flags (delete ,arg possible-flags)))) (defmacro move-boolean-2 (old new i arg) `(progn (setf ,new (push (arg-key ,arg) ,new)) (setf ,new (push t ,new)) (setf ,old (delete-nth ,i ,old)))) (defmacro move-boolean (old new i arg val) (declare (ignore old i)) `(progn (setf ,new (push (arg-key ,arg) ,new)) (setf ,new (push ,val ,new)) (setf possible-flags (delete ,arg possible-flags)))) (defmacro move-repeating (old new start arg keyworded &optional until) (declare (ignore keyworded)) (let ((did-one (gensym "move-repeating-did-one"))) `(progn (let (,did-one) (declare (ignorable ,did-one)) ;; @@@ remove if fixed (if ,until (error "can't do until yet") ;; @@@ (progn (setf ,new (push (arg-key ,arg) ,new)) (setf ,new (push-arg ,arg (mapcar #'(lambda (x) (convert-arg ,arg (word-word x) (word-quoted x))) (nthcdr ,start ,old)) ,new :convert nil)) (when (length (nthcdr ,start ,old)) (setf ,did-one t)) (setf ,old (subseq ,old 0 ,start)) ;; Push default if we have one and didn't get any values. (when (and (not ,did-one) (arg-default ,arg)) (setf ,new (push (arg-key ,arg) ,new)) (setf ,new (push-arg ,arg (eval (arg-default ,arg)) ,new :convert nil))))))))) ;; I used to handle default values to arguments here, but they were not getting ;; evaluated properly, so it's probably best to let the command function handle ;; defaulting arguments. It could be confusing to have two different defaulting ;; mechanisms anyway. ;; ;; @@@ But the problem is that when the command function defun gets constructed ;; at compile time, default arguments from the argument class may not be ;; availible yet if the argument class is defined in the same file, since the ;; class may not be fully defined until the end of the compilation phase? ;; ;; So far the only workaround I have is to define the argument class in ;; a different compilation unit (a.k.a. file), which is very inconvenient. ;; There must be another way. ;;; @@@ Potential change: ;;; - defaults get normally evaled at defcommand time ;;; - defaults get re-evaled at arg popping time ;; SO, the default can be the value from the defcommand environment ;; OR if it's quoted or self-quoting, the value at command calling time ;; Maybe this will resolve the problems? But you have to be careful to ;; quote defaults in defcommands. (defun extract-short-boolean-options (command posix-args) "Returns POSIX-ARGS with boolean options removed and as the second value, a list of the converted boolean options." (let* (option-list new-args) (loop :with boolean-taken :and boolean-value #| :and flag-taken |# :for a :in posix-args :when (and (>= (length a) 2) (is-flag-char (char a 0)) (not (is-flag-char (char a 1)))) :do (setf boolean-value (is-normal-flag-char (char a 0)) #| flag-taken nil |#) (loop :for cc :from 1 :below (length a) :do (setf boolean-taken nil) (loop :for arg :in (command-arglist command) :do (if (and (eql (arg-short-arg arg) (char a cc)) (eq (arg-type arg) 'boolean)) (progn (dbugf :lish-arg "short boolean arg ~s~%" arg) (push (arg-key arg) option-list) (push boolean-value option-list) (setf boolean-taken t)))) (when (not boolean-taken) ;; @@@ and some other option not to warn? (warn "Unrecogized boolean flag ~a" (char a cc)))) :else :do (push a new-args)) (values (nreverse new-args) (nreverse option-list)))) (defun extract-long-boolean-options (command posix-args) "Returns POSIX-ARGS with long boolean options removed and as the second value, a list of the converted boolean options." (let* (option-list new-args) (loop :with flag-taken :and boolean-value = t :for a :in posix-args :when (and (>= (length a) 2) (is-flag-char (char a 0)) (is-flag-char (char a 1))) :do (setf flag-taken nil) (loop :for arg :in (command-arglist command) :do (if (and (string-equal (arg-long-arg arg) a :start2 2) (eq (arg-type arg) 'boolean)) (progn (dbugf :lish-arg "long boolean arg ~s~%" arg) (push (arg-key arg) option-list) (push boolean-value option-list) (setf flag-taken t)))) (when (not flag-taken) ;; @@@ and some other option not to warn? (warn "Unrecogized long boolean flag ~a" a)) :else :do (push a new-args)) (values (nreverse new-args) (nreverse option-list)))) (defun extract-non-flagged (command posix-args) "Returns POSIX-ARGS with non-flagged arguments removed and as the second value, a list of the converted arguments." (declare (ignore command posix-args)) ) (defun extract-non-flagged-optional (command posix-args) "Returns POSIX-ARGS with non-flagged optional arguments removed and as the second value, a list of the converted arguments." (declare (ignore command posix-args)) ) #| @@@@ (defun extract-repeating (command posix-args) "Returns POSIX-ARGS with non flagged arguments removed and as the second value, a list of the converted arguments." (let (new-args) (loop :for arg :in (command-arglist command) :do (if (arg-repeating arg) (cond ((and (zerop (length posix-args)) (not (arg-optional arg))) (error "Missing mandatory argument: ~a." (arg-name arg))) ; ((setf end-flag (arg-end-flag arg command)) ; ;; collect until end flag ; (move-repeating (old-list new-list 0 arg keyworded end-flag))) ; (check-for-multipe-repeats ; ;; error ; ) (t ;; collect ;; (move-repeating old-list new-repeating 0 arg keyworded) )))))) |# ;; This, quite stupidly, treats lists like arrays, so is very inefficient. (defmacro cut-range (list head-end tail-start) "Cut the range between HEAD-END TAIL-START from LIST." `(if (zerop ,head-end) (setf ,list (nthcdr ,tail-start ,list)) (rplacd (nthcdr ,head-end ,list) ; double (nthcdr ,tail-start ,list)))) ; bad ;; This is what we should use, but we'd have to fix the whole looping below. (defmacro decent-cut (list head-end tail-start) "Cut the part between HEAD-END and TAIL-START out of LIST." `(if (eq ,head-end ,list) (setf ,list ,tail-start) (rplacd ,head-end ,tail-start))) #| (defun posix-to-lisp-args (command p-args) "Convert POSIX style arguments to lisp arguments. This makes flags like '-t' become keyword arguments, in a way specified in the command's arglist." (let ((arg-list (command-arglist command)) (new-list '()) (has-rest-arg nil) (flag-args '()) (spot arg-list)) ; place we are in position args ;; Pre-scan the command args (loop :for a :in arg-list :do (cond ((arg-rest a) (setf has-rest-arg t)) ((and (arg-optional a) (or (arg-short-arg a) (arg-long-arg a) (arg-old-long-arg a))) (push a flag-args)))) (setf flag-args (nreverse flag-args)) (loop :for p-arg :in p-args :do ;; start state ;; flag-arg ;; first mandatory arg ;; first optional arg (loop :for arg :in arg-list :do (cond ((arg-repeating arg)) ((arg-rest arg)) ((arg-optional arg)) )) |# (defun posix-to-lisp-args (command p-args) "Convert POSIX style arguments to lisp arguments. This makes flags like '-t' become keyword arguments, in a way specified in the command's arglist." ;; (when (= (length p-args) 0) ;; (return-from new-posix-to-lisp-args nil)) ;; (when (equal (command-name command) "env") ;; (break)) (let ((i 0) ; Where we are in the old list, so effectively ; a count of how many posix args we've skipped. ;; (new-list '()) (old-list (copy-list p-args)) ; so we don't modify it (new-flags '()) (new-mandatories '()) (new-optionals '()) (new-repeating '()) ;; (keyworded (args-keyworded (command-arglist command))) (keyworded t) (flag-taken nil) (boolean-taken nil) (boolean-value t) possible-flags #| (optionals '()) |# has-rest-arg) ;; Pre-set some things (loop :for a :in (command-arglist command) :do (cond ((or (arg-short-arg a) (arg-long-arg a)) (push a possible-flags)) ((arg-rest a) (setf has-rest-arg t)))) #| (let ((overrides (remove-if-not #'arg-override (command-arglist command)))) (when (not (null overrides)) (arg-override |# ;; Flagged arguments (optional or manditory) (dbugf :lish-arg "considering flagged: ~s~%" old-list) (loop :with a :and w :while (< i (length old-list)) :do #| (setf a (car old-list)) |# (setf w (nth i old-list) a (word-word w)) (if (and (stringp a) (> (length a) 0) (is-flag-char (char a 0)) ;; Don't consider quoted args as flags. (not (word-quoted w))) (if (and (> (length a) 1) (is-flag-char (char a 0)) (is-flag-char (char a 1))) ; two dash arg ;; --long-arg (progn (setf flag-taken nil boolean-taken nil) (loop :for arg :in (command-arglist command) :do ;; @@@ have to deal with repeating? (when (equalp (subseq a 2) (arg-long-arg arg)) (if (eq (arg-type arg) 'boolean) (progn (dbugf :lish-arg "boolean long arg ~s~%" arg) (move-boolean-2 old-list new-flags i arg)) (progn (dbugf :lish-arg "long arg ~s~%" arg) (move-flag old-list new-flags i arg))) (setf flag-taken t))) (when (not flag-taken) (when (not has-rest-arg) (warn "Unrecognized long option ~a" a)) (incf i))) ;; -abcxyz (short args) (progn (setf boolean-taken nil boolean-value (is-normal-flag-char (char a 0)) flag-taken nil) (loop :for cc :from 1 :below (length a) :do (setf flag-taken nil) (loop :for arg :in (command-arglist command) :do (when (eql (arg-short-arg arg) (char a cc)) (setf flag-taken t) ;; @@@ have to deal with repeating? (if (eq (arg-type arg) 'boolean) (progn (dbugf :lish-arg "short boolean arg ~s~%" arg) (move-boolean old-list new-flags i arg boolean-value) (setf boolean-taken t)) (if (/= cc (1- (length a))) (error "Unrecognized flag ~a." a) (progn (dbugf :lish-arg "short arg ~s~%" arg) (when (>= (1+ i) (length old-list)) (error "Missing arg for -~c" (arg-short-arg arg))) (move-flag old-list new-flags i arg)))))) (when (not flag-taken) (incf i) (when (not has-rest-arg) (warn "Unrecognized option ~a" (char a cc))))) (if boolean-taken (setf old-list (delete-nth i old-list)) (progn (dbugf :lish-arg "skipping flag value ~a ~w~%" i (nth i old-list)) (when (not flag-taken) (incf i)) ;;(setf old-list (delete-nth i old-list)) )))) ;; Arg doesn't start with a dash, so skip it (progn (dbugf :lish-arg "skipping arg ~a ~w~%" i a) (incf i)))) ;; @@@ I don't think we have to do this anymore, becuase the defaults ;; are put in the function definition, and if we provide the flag it messes ;; up :use-supplied-flag. ;; Default any left over defaultable flags ;; (loop :for a :in possible-flags :do ;; (when (arg-default a) ;; (push (arg-key a) new-flags) ;; (push (eval (arg-default a)) new-flags))) (setf new-flags (nreverse new-flags)) ;; Non-flagged mandatories. (setf i 0) (dbugf :lish-arg "considering non-flagged: ~s~%" old-list) (loop :for arglist-index :from 0 :for arg :in (command-arglist command) :do (when (not (or (arg-optional arg) (arg-has-flag arg) ;; (arg-repeating arg) )) (if (not (plusp (length old-list))) (error "Missing mandatory argument: ~a." (arg-name arg)) (progn (dbugf :lish-arg "found mandatory arg ~a~%" arg) ;; (move-arg old-list new-mandatories 0 arg)) (if (arg-repeating arg) (progn (dbugf :lish-arg "it's repeating~%") (let* ((remaining-mandatory-count (count-if (_ (not (arg-optional _))) (subseq (command-arglist command) (1+ arglist-index)))) (snip-len (- (length old-list) remaining-mandatory-count)) (repeating-list (loop :for j :from i :below (+ i snip-len) :for x :in (nthcdr i old-list) :nconc (let ((xx (convert-and-flatten-arg arg x))) (if (listp xx) xx (list xx)))))) (when (zerop snip-len) ;; Really it's not this one missing, it's the next one. (error "Missing mandatory argument: ~a." (arg-name (nth (1+ arglist-index) (command-arglist command))))) (dbugf :lish-arg "remaining-mandatory-count = ~s~%" remaining-mandatory-count) (dbugf :lish-arg "snip-len = ~s~%" snip-len) (dbugf :lish-arg "repeating-list = ~s~%" repeating-list) (push (arg-key arg) new-mandatories) (push repeating-list new-mandatories) ;; cut the repeating args out of old-list (cut-range old-list i (+ i (length repeating-list))) (incf i snip-len) (dbugf :lish-arg "old-list ~s~%i ~s~%" old-list i))) ;; not repeating just move it (progn (dbugf :lish-arg "taking non-reapting mandatory ~s~%" arg) (move-key old-list new-mandatories 0 arg t) (incf i))))))) (setf new-mandatories (nreverse new-mandatories)) ;; Non-flagged optionals (dbugf :lish-arg "considering non-flagged optionals: ~s~%" old-list) (loop :for arg :in (command-arglist command) :do (if (and (arg-optional arg) (not (arg-repeating arg)) (not (arg-has-flag arg))) (if (> (length old-list) 0) (move-key old-list new-optionals 0 arg keyworded) (if (arg-default arg) (push-key new-optionals arg (eval (arg-default arg)) keyworded) ;; (move-key arg new-optionals 0 (eval (arg-default arg)) ;; keyworded) (incf i))))) ;; or skip (setf new-optionals (nreverse new-optionals)) ;; Optional repeating (dbugf :lish-arg "optional repeating i = ~s old-list = ~s~%" i old-list) ;; (setf i 0) (loop #| :with i = 0 :and did-one = nil :and end-flag |# :for arg :in (command-arglist command) :do (when (and (arg-repeating arg) (arg-optional arg)) (move-repeating old-list new-repeating 0 arg keyworded))) #| (if (arg-repeating arg) (cond ;; @@@ I don't think this case can happen anymore, since we deal ;; with it above. ((and (>= i (length old-list)) (not (arg-optional arg))) (error "Missing repeating mandatory argument: ~a." (arg-name arg))) ; ((setf end-flag (arg-end-flag arg command)) ; ;; collect until end flag ; (move-repeating (old-list new-list 0 arg keyworded end-flag))) ; (check-for-multipe-repeats ; ;; error ; ) (t ;; collect (move-repeating old-list new-repeating 0 arg keyworded))))) |# (setf new-repeating (nreverse new-repeating)) (when (> (length old-list) 0) (warn "Extra arguments: ~w" old-list)) (concatenate 'list new-mandatories new-optionals new-repeating new-flags))) (defun posix-synopsis (command) "Return a string with the POSIX style argument synopsis for the COMMAND." (with-output-to-string (str) (format str "~a" (command-name command)) ;; boolean flag options (loop :with first-time = t :for a :in (command-arglist command) :do (when (and (eql (arg-type a) 'boolean) (arg-short-arg a)) (when first-time (setf first-time nil) (format str " [-")) (format str "~c" (arg-short-arg a))) :finally (when (not first-time) (format str "]"))) ;; non-boolean (loop :for a :in (command-arglist command) :do (when (not (and (eql (arg-type a) 'boolean) (arg-short-arg a))) (if (arg-optional a) (format str " [") (format str " ")) (if (arg-short-arg a) (format str "-~a " (arg-short-arg a)) (when (arg-long-arg a) (format str "--~a " (arg-long-arg a)))) (format str "~a" (arg-name a)) (when (arg-repeating a) (format str "...")) (when (arg-optional a) (format str "]")))))) #| (defmacro call-with-keywords (command-name func &rest kw) (with-names (args) `(let ((,args (loop :with arg-kw :for a :in (lish:command-arglist (lish:get-command ,command-name)) :do (setf arg-kw (keywordify (lish:arg-name a))) :if (or (not ,kw) (position arg-kw ,kw)) :collect arg-kw :collect (symbolify (lish:arg-name a))))) (apply ,func ,args)))) |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; These arguemnt types have to come after commands are defined. (defclass arg-command (arg-choice) () (:documentation "A lish command name.")) (defmethod convert-arg ((arg arg-command) (value string) &optional quoted) (declare (ignore arg quoted)) (get-command value)) (defmethod argument-choices ((arg arg-command)) "Return the possible path names." *command-list*) ;; This is for anything that can be the first word of command line. (defclass arg-shell-command (arg-choice) () (:documentation "A lish shell command name.")) (defmethod argument-choices ((arg arg-shell-command)) "Return the possible path names." *command-list*) ;; EOF
46,812
Common Lisp
.lisp
1,172
35.273891
81
0.645704
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
9af8b4fe775b87f3da74e7a0ec5861441e02058bac7f70b652aa8064e78d449a
2,140
[ -1 ]
2,141
fully-loaded.lisp
nibbula_lish/build/fully-loaded.lisp
;;; ;;; fully-loaded.lisp - Load shell commands before dumping Lish. ;;; (let ((*load-verbose* build-init:*build-verbose*)) (push (truename "../los") asdf:*central-registry*) (push (truename "../image/") asdf:*central-registry*) (loop :for s :in '("pager" "puca" "char-picker" "pick-list" "tree-viewer" #+linux "view-html" ;; @@@ cl+ssl fails on mac & windows "view-table" "print-table" "view-tree" "view-image" "view-org" "view-lisp" "dired" ) ;; :do (asdf:load-system s :verbose nil)) :do (ql:quickload s :verbose build-init:*build-verbose*)) (let ((systems (mapcar (dlib:_ (dlib:keywordify (dlib:remove-prefix (dlib:remove-suffix dlib:_ ".asd") "../los/"))) (remove-if (dlib:_ (not (equal (nos:path-to-absolute dlib:_) (namestring (truename dlib:_))))) (glob:glob "../los/*.asd"))))) ;; @@@ stupid work around (setf systems (delete :unzip systems)) (loop :for s :in systems ;; :do (asdf:load-system s :verbose nil))) :do (ql:quickload s :verbose build-init:*build-verbose*))) ;; view-image is useless if it can't view any image types. (dlib:symbol-call :image :load-known-formats) ;; Make sure the magic backend is loaded. (magic:ensure-database)) ;; EOF
1,288
Common Lisp
.lisp
32
35.1875
75
0.620304
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
e4d326648eb9869fb92a4cf090ddaf0ddf9a1141cdf0732afd457ade16aed785
2,141
[ -1 ]
2,142
build-deinit.lisp
nibbula_lish/build/build-deinit.lisp
;;; ;;; build-deinit.lisp - Undo any initialization we should for the built Lish. ;;; (in-package :build-init) ;; We turn this back off. If you want function arguments for your stuff, ;; I'm sorry, but it's on you to turn it back on, or have had it on in the first ;; place. This we don't mess with the normal traditional way. (when *saved-debug-quality* (proclaim `(optimize (debug ,*saved-debug-quality*)))) (delete-package :build-init) ;; End
452
Common Lisp
.lisp
11
39.545455
80
0.7254
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
e5ea709494e32e30b4c5271f30bb3584c8ed4e8ab4f082dd98759ece03d79c08
2,142
[ -1 ]
2,143
lol.lisp
nibbula_lish/build/lol.lisp
;;; ;;; lol.lisp - Load things for Lisp On Linux. ;;; (let ((*load-verbose* nil)) (push (truename "../los") asdf:*central-registry*) (push (truename "../image/") asdf:*central-registry*) (loop :for s :in '("pager" "puca" "char-picker" "pick-list" "tree-viewer" ;; #+linux "view-html" ;; @@@ cl+ssl fails on mac & windows "view-table" "print-table" "view-tree" "view-image" "view-org" "view-lisp" "dired" ) ;; :do (asdf:load-system s :verbose nil)) :do (ql:quickload s :verbose nil)) (let ((systems (mapcar (dlib:_ (dlib:keywordify (dlib:remove-prefix (dlib:remove-suffix dlib:_ ".asd") "../los/"))) (remove-if (dlib:_ (not (equal (nos:path-to-absolute dlib:_) (namestring (truename dlib:_))))) (glob:glob "../los/*.asd"))))) ;; @@@ stupid work around (setf systems (delete :unzip systems)) ;; @@@ temporarily omit ? (setf systems (delete :file systems)) (loop :for s :in systems ;; :do (asdf:load-system s :verbose nil))) :do (ql:quickload s :verbose nil))) ;; view-image is useless if it can't view any image types. (dlib:symbol-call :image :load-known-formats) ;; Make sure the magic backend is loaded. (magic:ensure-database)) ;; EOF
1,275
Common Lisp
.lisp
34
32.441176
75
0.604369
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
06e3ece720fab101d25852f95ff38ceddb0a4d868d51817889a74367bbe18877
2,143
[ -1 ]
2,144
load-quicklisp.lisp
nibbula_lish/build/load-quicklisp.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Try to load Quicklisp, if it's not alread loaded. (defparameter *quicklisp-fail* "Perhaps try installing a new Quicklisp by following the instructions at: https://www.quicklisp.org/beta/") (defparameter *not-strictly-necessary* "Quicklisp is not strictly necessary, but if you don't have it, you will have to make sure all the dependencies are availible to be loaded by ASDF. Since you don't seem to have a Quicklisp installation in ~/quicklisp, we are taking the liberty of installing one for you. I'm sorry. If you want to build with a custom Quicklisp installation, set the environment variable LISH_QUICKLISP to the directory where it's installed. ") (defparameter *proxy-host* "127.0.0.1" "The hostname for the proxy.") (defparameter *proxy-port* 8024 "The TCP port for the proxy.") (defun proxy-url () "Return the proxy URL." (format nil "http://~a:~a" *proxy-host* *proxy-port*)) (defun install-quicklisp () (load "build/quicklisp.lisp") (handler-case (cond ((sf-getenv "LISH_QL_PROXY") (if (zerop (length (sf-getenv "LISH_QL_PROXY"))) (progn (warn "!!!!! INSECURE QUICKLISP INSTALL !!!!!!") (funcall (find-symbol "INSTALL" :quicklisp-quickstart))) (funcall (find-symbol "INSTALL" :quicklisp-quickstart) :proxy (sf-getenv "LISH_QL_PROXY")))) (t (funcall (find-symbol "INSTALL" :quicklisp-quickstart) :proxy (proxy-url)))) (error (c) (print c) (fail "~ We failed to install Quicklisp. This is probably because you don't have a proxy set up. Installing Quicklisp without a proxy is insecure. You can either set up a proxy on the default URL, which is ~s, For example, with the mitmproxy command: $ mitmproxy --listen-host 127.0.0.1 -p 8024 -M \"/^http:/https:\" Or, if you don't want to use the default proxy, set LISH_QL_PROXY to a different one, or if you REALLY want to do it insecurely set LISH_QL_PROXY to empty. Note that: ~a" (proxy-url) *not-strictly-necessary*)))) (when (not (find-package :quicklisp)) (if (sf-getenv "LISH_QUICKLISP") (handler-case (load (sf-getenv "LISH_QUICKLISP")) (error (c) (print c) (fail "LISH_QUICKLISP is set to ~s.~%~ We failed to load the custom Quicklisp. ~a~a" *quicklisp-fail* *not-strictly-necessary*))) (let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" *home*))) (if (probe-file quicklisp-init) (block nil (handler-case (with-unicode-files () (load quicklisp-init)) (error (c) (print c) (format t "~&/~v,,,va~%~ We failed to load Quicklisp from ~s.~%~a~%~a~ ~&\\~v,,,va~%" 40 #\- #\- quicklisp-init *quicklisp-fail* *not-strictly-necessary* 40 #\- #\-) (return nil)))) (progn (format t "Quicklisp was not found at ~s.~%~a" quicklisp-init *not-strictly-necessary*) (install-quicklisp))))))
3,022
Common Lisp
.lisp
77
34.428571
79
0.648483
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
1fe6fc190a1bd48acf91fb7f28b082ed8b9f9e6a6bfe575f0d6c2696513f7dd1
2,144
[ -1 ]
2,145
build-lish.lisp
nibbula_lish/build/build-lish.lisp
;;; ;;; build-lish.lisp - Build Lish ;;; ;; A fake Makefile. (defpackage :build-lish (:documentation "Build Lish.") (:use :cl) (:export #:build-lish )) (defparameter build-lish::*default-target* (or (and (boundp '*target*) (symbol-value '*target*)) 'build-lish::lishfu)) (in-package :build-lish) ;; Do things that are too horrible to mention here. (load "build/horrible.lisp" :verbose nil) (msg "[Start builder on ~a ~a]" (lisp-implementation-type) (lisp-implementation-version)) (defun fail (message &rest args) (format t "~&/~v,,,va~%~%BUILD FAILURE:~%~?~%~&\\~v,,,va~%" 40 #\- #\- message args 40 #\- #\-) (exit-lisp :code 1)) (defvar *build-verbose* (sf-getenv "LISH_BUILD_VERBOSE") "True to build with more compilation messages. Can be set with the environment variable LISH_BUILD_VERBOSE.") (msg "[Load ASDF]") (load "build/load-asdf.lisp" :verbose *build-verbose*) (defvar *home* (or (and (sf-getenv "LISP_HOME") (namestring (probe-file (sf-getenv "LISP_HOME")))) (namestring (user-homedir-pathname))) "Namestring of the home directory.") (defvar *exit-code* 1 "The code we should exit with.") ;; also horrible, but not in horrible becase we need uiop (defun run-with-input-from (stream command) "Run commands with input from a file or stream. COMMAND should be a list of strings." (multiple-value-bind (stupid stupider exit-code) (uiop:run-program command :input stream ;; :output t :output :interactive :error-output t :ignore-error-status t) (declare (ignore stupid stupider)) (format t "~%[Build ~a]~%" (if (zerop exit-code) "Succeeded" "Failed")) (setf *exit-code* exit-code))) (defun split (c string) "Simple low-budget split-sequence." (let ((start 0) end result) (loop :while (and (< start (length string)) (setf end (position c string :start start))) :do (push (subseq string start end) result) (setf start (1+ end))) (push (subseq string start) result) (nreverse result))) ;; Very low-budget, unfancy, and brittle. (defun increment-build-version (file) "Increment the last component of the dotted version string in FILE." (format t "increment-build-version ~s~%" file) (let* ((vers (read-file-form file)) (vers-nums (mapcar (lambda (x) (parse-integer x :junk-allowed t)) (split #\. vers))) (new-vers (format nil "~a.~a.~a" (first vers-nums) (second vers-nums) (1+ (third vers-nums))))) (when (not (every #'integerp vers-nums)) (cerror "Ok, whatever. Don't increment the version then." "The version number incrementing seems to have failed.") (return-from increment-build-version nil)) (with-open-file (stream file :direction :output :if-exists :overwrite) (write new-vers :stream stream) (terpri stream)))) (defun maybe-increment-build-version (file) "Only increment the version for maintainers." (when (sf-getenv "LISH_MAINTAINER") (increment-build-version file))) ;; So, ideally we would increment the build version number only if the build ;; succeeds, but that seems like a pain, since we would have to pass the new ;; version nubmer to both ASDF and the code being built, without setting it ;; in the version.lisp file. Perhaps in the future we can work that out. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Build Lishes of various kinds. ;; (defparameter *default-target* 'lishfu) (defparameter *targets* '('lish)) (defparameter *version-file* "version.lisp") (defparameter *install-dir* (merge-pathnames "bin" *home*)) (defparameter *lisp* (or (sf-getenv "LISP") "sbcl")) (defun impl (i) (search i *lisp* :test #'equalp)) (defparameter *lisp-flags* (cond ((impl "sbcl") `("--noinform" "--noprint" "--disable-debugger")) (t '())) "Command line arguments to pass to the lisp.") (defparameter *lisp-plain-flags* (cond ((impl "sbcl") `("--no-userinit")) ((impl "ccl") `("--no-init")) ((impl "clisp") `("-norc")) (t "")) "Command line arguments to pass to the lisp for.") (defgeneric build (target) (:documentation "Build a thing.")) (defmethod build (target) (format *error-output* "I don't know how to build ~a" target)) (defgeneric install (target) (:documentation "Install a thing.")) (defmethod install (target) (format *error-output* "I don't know how to install ~a" target)) (defun install-file (file &key (dir *install-dir*)) (declare (ignore file dir)) ;; (when (not (directory-p dir)) ;; (ensure-directories-exist dir)) ;; (copy-file file dir) ) ;; I know it seems dum to have Lisp code as strings, but it seems simpler ;; because of package issues. (defmethod build ((target (eql 'lish))) "Normal lish." (msg "[Build target ~s]" target) (with-input-from-string (stream (format nil "(load \"build/build-init.lisp\" :verbose ~a~:*) ~ (ql:quickload :dlib :verbose ~a~:*) ~ (ql:quickload :tiny-repl :verbose ~a~:*) ~ (ql:quickload :deblarg :verbose ~a~:*) ~ (ql:quickload :lish :verbose ~a~:*) ~ (load \"build/build-deinit.lisp\" :verbose ~a~:*) ~ (lish:make-standalone :smaller t)" *build-verbose*)) (maybe-increment-build-version *version-file*) (run-with-input-from stream `(,*lisp* ,@*lisp-flags* "--" "-norl")))) (defmethod build ((target (eql 'lishfu))) (msg "[Build target ~s]" target) (with-input-from-string (stream (format nil "(load \"build/build-init.lisp\" :verbose ~a~:*) ~ (ql:quickload :dlib :verbose ~a~:*) ~ (ql:quickload :tiny-repl :verbose ~a~:*) ~ (ql:quickload :deblarg :verbose ~a~:*) ~ (ql:quickload :lish :verbose ~a~:*) ~ (load \"build/fully-loaded.lisp\" :verbose ~a~:*) ~ (load \"build/build-deinit.lisp\" :verbose ~a~:*) ~ (lish:make-standalone :smaller t)" *build-verbose*)) (maybe-increment-build-version *version-file*) (run-with-input-from stream `(,*lisp* ,@*lisp-flags* "--" "-norl")))) (defmethod build ((target (eql 'lol))) (msg "[Build target ~s]" target) (with-input-from-string (stream (format nil "(load \"build/build-init.lisp\" :verbose ~a~:*) ~ (ql:quickload :dlib :verbose ~a~:*) ~ (ql:quickload :tiny-repl :verbose ~a~:*) ~ (ql:quickload :deblarg :verbose ~a~:*) ~ (ql:quickload :lish :verbose ~a~:*) ~ (load \"build/lol.lisp\" :verbose ~a~:*) ~ (load \"build/build-deinit.lisp\" :verbose ~a~:*) ~ (lish:make-standalone :smaller t)" *build-verbose*)) (maybe-increment-build-version *version-file*) (run-with-input-from stream `(,*lisp* ,@*lisp-flags* "--" "-norl")))) (defmethod build ((target (eql 'run))) (msg "[Build target ~s]" target) (load "build/build-init.lisp" :verbose nil) (let ((ql (intern "QUICKLOAD" (find-package :ql)))) (funcall ql :dlib :verbose nil) (funcall ql :tiny-repl :verbose nil) (funcall ql :deblarg :verbose nil) (funcall ql :lish :verbose nil) (load "build/fully-loaded.lisp" :verbose nil) (funcall (intern "LISH" (find-package :lish)) :debug t) (setf *exit-code* 0))) ;; Plain, aka without my (or your) startup (defmethod build ((target (eql 'lishp))) (msg "[Build target ~s]" target) (with-input-from-string (stream (format nil "(load \"build/build-init.lisp\") ~ (ql:quickload :dlib :verbose ~a~:*) ~ (ql:quickload :lish :verbose ~a~:*) ~ (load \"build/build-deinit.lisp\" :verbose ~a~:*) ~ (lish:make-standalone :smaller t)" *build-verbose*)) (maybe-increment-build-version *version-file*) (run-with-input-from stream `(,*lisp* ,@*lisp-flags* ,@*lisp-plain-flags* "--" "-norl")))) (defmethod build ((target (eql 'lishpfu))) (msg "[Build target ~s]" target) (with-input-from-string (stream (format nil "(load \"build/build-init.lisp\") ~ (ql:quickload :dlib :verbose ~a~:*) ~ (ql:quickload :tiny-repl :verbose ~a~:*) ~ (ql:quickload :deblarg :verbose ~a~:*) ~ (ql:quickload :lish :verbose ~a~:*) ~ (load \"build/fully-loaded.lisp\" :verbose ~a~:*) ~ (load \"build/build-deinit.lisp\" :verbose ~a~:*) ~ (lish:make-standalone :smaller t)" *build-verbose*)) (maybe-increment-build-version *version-file*) (run-with-input-from stream `(,*lisp* ,@*lisp-flags* ,@*lisp-plain-flags* "--" "-norl")))) #| (defun install () (loop :for target :in *targets* :do (build targets) (install-one target))) (defun clean-one (file) (delete-file file)) (defun clean () (loop :for target :in *targets* :do (clean-one target))) |# ;; Main or something. (defun main () (let ((env-target (sf-getenv "TARGET"))) (when (and env-target (not (zerop (length env-target)))) (setf *default-target* (intern (string-upcase env-target))))) (flet ((env-or (env default-value) (let ((result (sf-getenv env))) (or (and result (split #\space result)) default-value)))) (setf *lisp-flags* (env-or "LISH_FLAGS" *lisp-flags*) *lisp-plain-flags* (env-or "LISH_PLAIN_FLAGS" *lisp-plain-flags*))) (let (pos target) (if (and (> (length (lisp-args)) 1) (setf pos (position "--" (lisp-args) :test #'equal))) (setf target (intern (string-upcase (nth (1+ pos) (lisp-args))))) (setf target *default-target*)) (msg "[Target ~s]" target) (build target)) (when (not (sf-getenv "NO_EXIT")) (exit-lisp :code *exit-code*))) (main) ;; EOF
9,472
Common Lisp
.lisp
244
34.77459
77
0.639016
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
28290c8e3aba38e57abdbd09c9431b657991fc8f00003f9cacd73b0c41f9e956
2,145
[ -1 ]
2,146
quicklisp.lisp
nibbula_lish/build/quicklisp.lisp
;;;; ;;;; This is quicklisp.lisp, the quickstart file for Quicklisp. To use ;;;; it, start Lisp, then (load "quicklisp.lisp") ;;;; ;;;; Quicklisp is beta software and comes with no warranty of any kind. ;;;; ;;;; For more information about the Quicklisp beta, see: ;;;; ;;;; http://www.quicklisp.org/beta/ ;;;; ;;;; If you have any questions or comments about Quicklisp, please ;;;; contact: ;;;; ;;;; Zach Beane <[email protected]> ;;;; (cl:in-package #:cl-user) (cl:defpackage #:qlqs-user (:use #:cl)) (cl:in-package #:qlqs-user) (defpackage #:qlqs-info (:export #:*version*)) (defvar qlqs-info:*version* "2015-01-28") (defpackage #:qlqs-impl (:use #:cl) (:export #:*implementation*) (:export #:definterface #:defimplementation) (:export #:lisp #:abcl #:allegro #:ccl #:clasp #:clisp #:cmucl #:cormanlisp #:ecl #:gcl #:lispworks #:mkcl #:scl #:sbcl)) (defpackage #:qlqs-impl-util (:use #:cl #:qlqs-impl) (:export #:call-with-quiet-compilation)) (defpackage #:qlqs-network (:use #:cl #:qlqs-impl) (:export #:open-connection #:write-octets #:read-octets #:close-connection #:with-connection)) (defpackage #:qlqs-progress (:use #:cl) (:export #:make-progress-bar #:start-display #:update-progress #:finish-display)) (defpackage #:qlqs-http (:use #:cl #:qlqs-network #:qlqs-progress) (:export #:fetch #:*proxy-url* #:*maximum-redirects* #:*default-url-defaults*)) (defpackage #:qlqs-minitar (:use #:cl) (:export #:unpack-tarball)) (defpackage #:quicklisp-quickstart (:use #:cl #:qlqs-impl #:qlqs-impl-util #:qlqs-http #:qlqs-minitar) (:export #:install #:help #:*proxy-url* #:*asdf-url* #:*quicklisp-tar-url* #:*setup-url* #:*help-message* #:*after-load-message* #:*after-initial-setup-message*)) ;;; ;;; Defining implementation-specific packages and functionality ;;; (in-package #:qlqs-impl) (eval-when (:compile-toplevel :load-toplevel :execute) (defun error-unimplemented (&rest args) (declare (ignore args)) (error "Not implemented"))) (defmacro neuter-package (name) `(eval-when (:compile-toplevel :load-toplevel :execute) (let ((definition (fdefinition 'error-unimplemented))) (do-external-symbols (symbol ,(string name)) (unless (fboundp symbol) (setf (fdefinition symbol) definition)))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun feature-expression-passes-p (expression) (cond ((keywordp expression) (member expression *features*)) ((consp expression) (case (first expression) (or (some 'feature-expression-passes-p (rest expression))) (and (every 'feature-expression-passes-p (rest expression))))) (t (error "Unrecognized feature expression -- ~S" expression))))) (defmacro define-implementation-package (feature package-name &rest options) (let* ((output-options '((:use) (:export #:lisp))) (prep (cdr (assoc :prep options))) (class-option (cdr (assoc :class options))) (class (first class-option)) (superclasses (rest class-option)) (import-options '()) (effectivep (feature-expression-passes-p feature))) (dolist (option options) (ecase (first option) ((:prep :class)) ((:import-from :import) (push option import-options)) ((:export :shadow :intern :documentation) (push option output-options)) ((:reexport-from) (push (cons :export (cddr option)) output-options) (push (cons :import-from (cdr option)) import-options)))) `(eval-when (:compile-toplevel :load-toplevel :execute) ,@(when effectivep prep) (defclass ,class ,superclasses ()) (defpackage ,package-name ,@output-options ,@(when effectivep import-options)) ,@(when effectivep `((setf *implementation* (make-instance ',class)))) ,@(unless effectivep `((neuter-package ,package-name)))))) (defmacro definterface (name lambda-list &body options) (let* ((forbidden (intersection lambda-list lambda-list-keywords)) (gf-options (remove :implementation options :key #'first)) (implementations (set-difference options gf-options))) (when forbidden (error "~S not allowed in definterface lambda list" forbidden)) (flet ((method-option (class body) `(:method ((*implementation* ,class) ,@lambda-list) ,@body))) (let ((generic-name (intern (format nil "%~A" name)))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defgeneric ,generic-name (lisp ,@lambda-list) ,@gf-options ,@(mapcar (lambda (implementation) (destructuring-bind (class &rest body) (rest implementation) (method-option class body))) implementations)) (defun ,name ,lambda-list (,generic-name *implementation* ,@lambda-list))))))) (defmacro defimplementation (name-and-options lambda-list &body body) (destructuring-bind (name &key (for t) qualifier) (if (consp name-and-options) name-and-options (list name-and-options)) (unless for (error "You must specify an implementation name.")) (let ((generic-name (find-symbol (format nil "%~A" name)))) (unless (and generic-name (fboundp generic-name)) (error "~S does not name an implementation function" name)) `(defmethod ,generic-name ,@(when qualifier (list qualifier)) ,(list* `(*implementation* ,for) lambda-list) ,@body)))) ;;; Bootstrap implementations (defvar *implementation* nil) (defclass lisp () ()) ;;; Allegro Common Lisp (define-implementation-package :allegro #:qlqs-allegro (:documentation "Allegro Common Lisp - http://www.franz.com/products/allegrocl/") (:class allegro) (:reexport-from #:socket #:make-socket) (:reexport-from #:excl #:read-vector)) ;;; Armed Bear Common Lisp (define-implementation-package :abcl #:qlqs-abcl (:documentation "Armed Bear Common Lisp - http://common-lisp.net/project/armedbear/") (:class abcl) (:reexport-from #:system #:make-socket #:get-socket-stream)) ;;; Clozure CL (define-implementation-package :ccl #:qlqs-ccl (:documentation "Clozure Common Lisp - http://www.clozure.com/clozurecl.html") (:class ccl) (:reexport-from #:ccl #:make-socket)) ;;; CLASP (define-implementation-package :clasp #:qlqs-clasp (:documentation "CLASP - http://github.com/drmeister/clasp") (:class clasp) (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:host-ent-address #:socket-connect #:socket-make-stream #:inet-socket)) ;;; GNU CLISP (define-implementation-package :clisp #:qlqs-clisp (:documentation "GNU CLISP - http://clisp.cons.org/") (:class clisp) (:reexport-from #:socket #:socket-connect) (:reexport-from #:ext #:read-byte-sequence)) ;;; CMUCL (define-implementation-package :cmu #:qlqs-cmucl (:documentation "CMU Common Lisp - http://www.cons.org/cmucl/") (:class cmucl) (:reexport-from #:ext #:*gc-verbose*) (:reexport-from #:system #:make-fd-stream) (:reexport-from #:extensions #:connect-to-inet-socket)) (defvar qlqs-cmucl:*gc-verbose* nil) ;;; Scieneer CL (define-implementation-package :scl #:qlqs-scl (:documentation "Scieneer Common Lisp - http://www.scieneer.com/scl/") (:class scl) (:reexport-from #:system #:make-fd-stream) (:reexport-from #:extensions #:connect-to-inet-socket)) ;;; ECL (define-implementation-package :ecl #:qlqs-ecl (:documentation "ECL - http://ecls.sourceforge.net/") (:class ecl) (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:host-ent-address #:socket-connect #:socket-make-stream #:inet-socket)) ;;; LispWorks (define-implementation-package :lispworks #:qlqs-lispworks (:documentation "LispWorks - http://www.lispworks.com/") (:class lispworks) (:prep (require "comm")) (:reexport-from #:comm #:open-tcp-stream #:get-host-entry)) ;;; SBCL (define-implementation-package :sbcl #:qlqs-sbcl (:class sbcl) (:documentation "Steel Bank Common Lisp - http://www.sbcl.org/") (:prep (require 'sb-bsd-sockets)) (:intern #:host-network-address) (:reexport-from #:sb-ext #:compiler-note) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:inet-socket #:host-ent-address #:socket-connect #:socket-make-stream)) ;;; MKCL (define-implementation-package :mkcl #:qlqs-mkcl (:class mkcl) (:documentation "ManKai Common Lisp - http://common-lisp.net/project/mkcl/") (:prep (require 'sockets)) (:intern #:host-network-address) (:reexport-from #:sb-bsd-sockets #:get-host-by-name #:inet-socket #:host-ent-address #:socket-connect #:socket-make-stream)) ;;; ;;; Utility function ;;; (in-package #:qlqs-impl-util) (definterface call-with-quiet-compilation (fun) (:implementation t (let ((*load-verbose* nil) (*compile-verbose* nil) (*load-print* nil) (*compile-print* nil)) (handler-bind ((warning #'muffle-warning)) (funcall fun))))) (defimplementation (call-with-quiet-compilation :for sbcl :qualifier :around) (fun) (declare (ignorable fun)) (handler-bind ((qlqs-sbcl:compiler-note #'muffle-warning)) (call-next-method))) (defimplementation (call-with-quiet-compilation :for cmucl :qualifier :around) (fun) (declare (ignorable fun)) (let ((qlqs-cmucl:*gc-verbose* nil)) (call-next-method))) ;;; ;;; Low-level networking implementations ;;; (in-package #:qlqs-network) (definterface host-address (host) (:implementation t host) (:implementation mkcl (qlqs-mkcl:host-ent-address (qlqs-mkcl:get-host-by-name host))) (:implementation sbcl (qlqs-sbcl:host-ent-address (qlqs-sbcl:get-host-by-name host)))) (definterface open-connection (host port) (:implementation t (declare (ignorable host port)) (error "Sorry, quicklisp in implementation ~S is not supported yet." (lisp-implementation-type))) (:implementation allegro (qlqs-allegro:make-socket :remote-host host :remote-port port)) (:implementation abcl (let ((socket (qlqs-abcl:make-socket host port))) (qlqs-abcl:get-socket-stream socket :element-type '(unsigned-byte 8)))) (:implementation ccl (qlqs-ccl:make-socket :remote-host host :remote-port port)) (:implementation clasp (let* ((endpoint (qlqs-clasp:host-ent-address (qlqs-clasp:get-host-by-name host))) (socket (make-instance 'qlqs-clasp:inet-socket :protocol :tcp :type :stream))) (qlqs-clasp:socket-connect socket endpoint port) (qlqs-clasp:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation clisp (qlqs-clisp:socket-connect port host :element-type '(unsigned-byte 8))) (:implementation cmucl (let ((fd (qlqs-cmucl:connect-to-inet-socket host port))) (qlqs-cmucl:make-fd-stream fd :element-type '(unsigned-byte 8) :binary-stream-p t :input t :output t))) (:implementation scl (let ((fd (qlqs-scl:connect-to-inet-socket host port))) (qlqs-scl:make-fd-stream fd :element-type '(unsigned-byte 8) :input t :output t))) (:implementation ecl (let* ((endpoint (qlqs-ecl:host-ent-address (qlqs-ecl:get-host-by-name host))) (socket (make-instance 'qlqs-ecl:inet-socket :protocol :tcp :type :stream))) (qlqs-ecl:socket-connect socket endpoint port) (qlqs-ecl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation lispworks (qlqs-lispworks:open-tcp-stream host port :direction :io :errorp t :read-timeout nil :element-type '(unsigned-byte 8) :timeout 5)) (:implementation mkcl (let* ((endpoint (qlqs-mkcl:host-ent-address (qlqs-mkcl:get-host-by-name host))) (socket (make-instance 'qlqs-mkcl:inet-socket :protocol :tcp :type :stream))) (qlqs-mkcl:socket-connect socket endpoint port) (qlqs-mkcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full))) (:implementation sbcl (let* ((endpoint (qlqs-sbcl:host-ent-address (qlqs-sbcl:get-host-by-name host))) (socket (make-instance 'qlqs-sbcl:inet-socket :protocol :tcp :type :stream))) (qlqs-sbcl:socket-connect socket endpoint port) (qlqs-sbcl:socket-make-stream socket :element-type '(unsigned-byte 8) :input t :output t :buffering :full)))) (definterface read-octets (buffer connection) (:implementation t (read-sequence buffer connection)) (:implementation allegro (qlqs-allegro:read-vector buffer connection)) (:implementation clisp (qlqs-clisp:read-byte-sequence buffer connection :no-hang nil :interactive t))) (definterface write-octets (buffer connection) (:implementation t (write-sequence buffer connection) (finish-output connection))) (definterface close-connection (connection) (:implementation t (ignore-errors (close connection)))) (definterface call-with-connection (host port fun) (:implementation t (let (connection) (unwind-protect (progn (setf connection (open-connection host port)) (funcall fun connection)) (when connection (close connection)))))) (defmacro with-connection ((connection host port) &body body) `(call-with-connection ,host ,port (lambda (,connection) ,@body))) ;;; ;;; A text progress bar ;;; (in-package #:qlqs-progress) (defclass progress-bar () ((start-time :initarg :start-time :accessor start-time) (end-time :initarg :end-time :accessor end-time) (progress-character :initarg :progress-character :accessor progress-character) (character-count :initarg :character-count :accessor character-count :documentation "How many characters wide is the progress bar?") (characters-so-far :initarg :characters-so-far :accessor characters-so-far) (update-interval :initarg :update-interval :accessor update-interval :documentation "Update the progress bar display after this many internal-time units.") (last-update-time :initarg :last-update-time :accessor last-update-time :documentation "The display was last updated at this time.") (total :initarg :total :accessor total :documentation "The total number of units tracked by this progress bar.") (progress :initarg :progress :accessor progress :documentation "How far in the progress are we?") (pending :initarg :pending :accessor pending :documentation "How many raw units should be tracked in the next display update?")) (:default-initargs :progress-character #\= :character-count 50 :characters-so-far 0 :update-interval (floor internal-time-units-per-second 4) :last-update-time 0 :total 0 :progress 0 :pending 0)) (defgeneric start-display (progress-bar)) (defgeneric update-progress (progress-bar unit-count)) (defgeneric update-display (progress-bar)) (defgeneric finish-display (progress-bar)) (defgeneric elapsed-time (progress-bar)) (defgeneric units-per-second (progress-bar)) (defmethod start-display (progress-bar) (setf (last-update-time progress-bar) (get-internal-real-time)) (setf (start-time progress-bar) (get-internal-real-time)) (fresh-line) (finish-output)) (defmethod update-display (progress-bar) (incf (progress progress-bar) (pending progress-bar)) (setf (pending progress-bar) 0) (setf (last-update-time progress-bar) (get-internal-real-time)) (let* ((showable (floor (character-count progress-bar) (/ (total progress-bar) (progress progress-bar)))) (needed (- showable (characters-so-far progress-bar)))) (setf (characters-so-far progress-bar) showable) (dotimes (i needed) (write-char (progress-character progress-bar))) (finish-output))) (defmethod update-progress (progress-bar unit-count) (incf (pending progress-bar) unit-count) (let ((now (get-internal-real-time))) (when (< (update-interval progress-bar) (- now (last-update-time progress-bar))) (update-display progress-bar)))) (defmethod finish-display (progress-bar) (update-display progress-bar) (setf (end-time progress-bar) (get-internal-real-time)) (terpri) (format t "~:D bytes in ~$ seconds (~$KB/sec)" (total progress-bar) (elapsed-time progress-bar) (/ (units-per-second progress-bar) 1024)) (finish-output)) (defmethod elapsed-time (progress-bar) (/ (- (end-time progress-bar) (start-time progress-bar)) internal-time-units-per-second)) (defmethod units-per-second (progress-bar) (if (plusp (elapsed-time progress-bar)) (/ (total progress-bar) (elapsed-time progress-bar)) 0)) (defun kb/sec (progress-bar) (/ (units-per-second progress-bar) 1024)) (defparameter *uncertain-progress-chars* "?") (defclass uncertain-size-progress-bar (progress-bar) ((progress-char-index :initarg :progress-char-index :accessor progress-char-index) (units-per-char :initarg :units-per-char :accessor units-per-char)) (:default-initargs :total 0 :progress-char-index 0 :units-per-char (floor (expt 1024 2) 50))) (defmethod update-progress :after ((progress-bar uncertain-size-progress-bar) unit-count) (incf (total progress-bar) unit-count)) (defmethod progress-character ((progress-bar uncertain-size-progress-bar)) (let ((index (progress-char-index progress-bar))) (prog1 (char *uncertain-progress-chars* index) (setf (progress-char-index progress-bar) (mod (1+ index) (length *uncertain-progress-chars*)))))) (defmethod update-display ((progress-bar uncertain-size-progress-bar)) (setf (last-update-time progress-bar) (get-internal-real-time)) (multiple-value-bind (chars pend) (floor (pending progress-bar) (units-per-char progress-bar)) (setf (pending progress-bar) pend) (dotimes (i chars) (write-char (progress-character progress-bar)) (incf (characters-so-far progress-bar)) (when (<= (character-count progress-bar) (characters-so-far progress-bar)) (terpri) (setf (characters-so-far progress-bar) 0) (finish-output))) (finish-output))) (defun make-progress-bar (total) (if (or (not total) (zerop total)) (make-instance 'uncertain-size-progress-bar) (make-instance 'progress-bar :total total))) ;;; ;;; A simple HTTP client ;;; (in-package #:qlqs-http) ;;; Octet data (deftype octet () '(unsigned-byte 8)) (defun make-octet-vector (size) (make-array size :element-type 'octet :initial-element 0)) (defun octet-vector (&rest octets) (make-array (length octets) :element-type 'octet :initial-contents octets)) ;;; ASCII characters as integers (defun acode (char) (cond ((eql char :cr) 13) ((eql char :lf) 10) (t (let ((code (char-code char))) (if (<= 0 code 127) code (error "Character ~S is not in the ASCII character set" char)))))) (defvar *whitespace* (list (acode #\Space) (acode #\Tab) (acode :cr) (acode :lf))) (defun whitep (code) (member code *whitespace*)) (defun ascii-vector (string) (let ((vector (make-octet-vector (length string)))) (loop for char across string for code = (char-code char) for i from 0 if (< 127 code) do (error "Invalid character for ASCII -- ~A" char) else do (setf (aref vector i) code)) vector)) (defun ascii-subseq (vector start end) "Return a subseq of octet-specialized VECTOR as a string." (let ((string (make-string (- end start)))) (loop for i from 0 for j from start below end do (setf (char string i) (code-char (aref vector j)))) string)) (defun ascii-downcase (code) (if (<= 65 code 90) (+ code 32) code)) (defun ascii-equal (a b) (eql (ascii-downcase a) (ascii-downcase b))) (defmacro acase (value &body cases) (flet ((convert-case-keys (keys) (mapcar (lambda (key) (etypecase key (integer key) (character (char-code key)) (symbol (ecase key (:cr 13) (:lf 10) ((t) t))))) (if (consp keys) keys (list keys))))) `(case ,value ,@(mapcar (lambda (case) (destructuring-bind (keys &rest body) case `(,(if (eql keys t) t (convert-case-keys keys)) ,@body))) cases)))) ;;; Pattern matching (for finding headers) (defclass matcher () ((pattern :initarg :pattern :reader pattern) (pos :initform 0 :accessor match-pos) (matchedp :initform nil :accessor matchedp))) (defun reset-match (matcher) (setf (match-pos matcher) 0 (matchedp matcher) nil)) (define-condition match-failure (error) ()) (defun match (matcher input &key (start 0) end error) (let ((i start) (end (or end (length input))) (match-end (length (pattern matcher)))) (with-slots (pattern pos) matcher (loop (cond ((= pos match-end) (let ((match-start (- i pos))) (setf pos 0) (setf (matchedp matcher) t) (return (values match-start (+ match-start match-end))))) ((= i end) (return nil)) ((= (aref pattern pos) (aref input i)) (incf i) (incf pos)) (t (if error (error 'match-failure) (if (zerop pos) (incf i) (setf pos 0))))))))) (defun ascii-matcher (string) (make-instance 'matcher :pattern (ascii-vector string))) (defun octet-matcher (&rest octets) (make-instance 'matcher :pattern (apply 'octet-vector octets))) (defun acode-matcher (&rest codes) (make-instance 'matcher :pattern (make-array (length codes) :element-type 'octet :initial-contents (mapcar 'acode codes)))) ;;; "Connection Buffers" are a kind of callback-driven, ;;; pattern-matching chunky stream. Callbacks can be called for a ;;; certain number of octets or until one or more patterns are seen in ;;; the input. cbufs automatically refill themselves from a ;;; connection as needed. (defvar *cbuf-buffer-size* 8192) (define-condition end-of-data (error) ()) (defclass cbuf () ((data :initarg :data :accessor data) (connection :initarg :connection :accessor connection) (start :initarg :start :accessor start) (end :initarg :end :accessor end) (eofp :initarg :eofp :accessor eofp)) (:default-initargs :data (make-octet-vector *cbuf-buffer-size*) :connection nil :start 0 :end 0 :eofp nil) (:documentation "A CBUF is a connection buffer that keeps track of incoming data from a connection. Several functions make it easy to treat a CBUF as a kind of chunky, callback-driven stream.")) (define-condition cbuf-progress () ((size :initarg :size :accessor cbuf-progress-size :initform 0))) (defun call-processor (fun cbuf start end) (signal 'cbuf-progress :size (- end start)) (funcall fun (data cbuf) start end)) (defun make-cbuf (connection) (make-instance 'cbuf :connection connection)) (defun make-stream-writer (stream) "Create a callback for writing data to STREAM." (lambda (data start end) (write-sequence data stream :start start :end end))) (defgeneric size (cbuf) (:method ((cbuf cbuf)) (- (end cbuf) (start cbuf)))) (defgeneric emptyp (cbuf) (:method ((cbuf cbuf)) (zerop (size cbuf)))) (defgeneric refill (cbuf) (:method ((cbuf cbuf)) (when (eofp cbuf) (error 'end-of-data)) (setf (start cbuf) 0) (setf (end cbuf) (read-octets (data cbuf) (connection cbuf))) (cond ((emptyp cbuf) (setf (eofp cbuf) t) (error 'end-of-data)) (t (size cbuf))))) (defun process-all (fun cbuf) (unless (emptyp cbuf) (call-processor fun cbuf (start cbuf) (end cbuf)))) (defun multi-cmatch (matchers cbuf) (let (start end) (dolist (matcher matchers (values start end)) (multiple-value-bind (s e) (match matcher (data cbuf) :start (start cbuf) :end (end cbuf)) (when (and s (or (null start) (< s start))) (setf start s end e)))))) (defun cmatch (matcher cbuf) (if (consp matcher) (multi-cmatch matcher cbuf) (match matcher (data cbuf) :start (start cbuf) :end (end cbuf)))) (defun call-until-end (fun cbuf) (handler-case (loop (process-all fun cbuf) (refill cbuf)) (end-of-data () (return-from call-until-end)))) (defun show-cbuf (context cbuf) (format t "cbuf: ~A ~D - ~D~%" context (start cbuf) (end cbuf))) (defun call-for-n-octets (n fun cbuf) (let ((remaining n)) (loop (when (<= remaining (size cbuf)) (let ((end (+ (start cbuf) remaining))) (call-processor fun cbuf (start cbuf) end) (setf (start cbuf) end) (return))) (process-all fun cbuf) (decf remaining (size cbuf)) (refill cbuf)))) (defun call-until-matching (matcher fun cbuf) (loop (multiple-value-bind (start end) (cmatch matcher cbuf) (when start (call-processor fun cbuf (start cbuf) end) (setf (start cbuf) end) (return))) (process-all fun cbuf) (refill cbuf))) (defun ignore-data (data start end) (declare (ignore data start end))) (defun skip-until-matching (matcher cbuf) (call-until-matching matcher 'ignore-data cbuf)) ;;; Creating HTTP requests as octet buffers (defclass octet-sink () ((storage :initarg :storage :accessor storage)) (:default-initargs :storage (make-array 1024 :element-type 'octet :fill-pointer 0 :adjustable t)) (:documentation "A simple stream-like target for collecting octets.")) (defun add-octet (octet sink) (vector-push-extend octet (storage sink))) (defun add-octets (octets sink &key (start 0) end) (setf end (or end (length octets))) (loop for i from start below end do (add-octet (aref octets i) sink))) (defun add-string (string sink) (loop for char across string for code = (char-code char) do (add-octet code sink))) (defun add-strings (sink &rest strings) (mapc (lambda (string) (add-string string sink)) strings)) (defun add-newline (sink) (add-octet 13 sink) (add-octet 10 sink)) (defun sink-buffer (sink) (subseq (storage sink) 0)) (defvar *proxy-url* nil) (defun full-proxy-path (host port path) (format nil "~:[http~;https~]://~A~:[:~D~;~*~]~A" (= port 443) host (or (= port 80) (= port 443)) port path)) (defun make-request-buffer (host port path &key (method "GET")) (setf method (string method)) (when *proxy-url* (setf path (full-proxy-path host port path))) (let ((sink (make-instance 'octet-sink))) (flet ((add-line (&rest strings) (apply #'add-strings sink strings) (add-newline sink))) (add-line method " " path " HTTP/1.1") (add-line "Host: " host (if (= port 80) "" (format nil ":~D" port))) (add-line "Connection: close") ;; FIXME: get this version string from somewhere else. (add-line "User-Agent: quicklisp-bootstrap/" qlqs-info:*version*) (add-newline sink) (sink-buffer sink)))) (defun sink-until-matching (matcher cbuf) (let ((sink (make-instance 'octet-sink))) (call-until-matching matcher (lambda (buffer start end) (add-octets buffer sink :start start :end end)) cbuf) (sink-buffer sink))) ;;; HTTP headers (defclass header () ((data :initarg :data :accessor data) (status :initarg :status :accessor status) (name-starts :initarg :name-starts :accessor name-starts) (name-ends :initarg :name-ends :accessor name-ends) (value-starts :initarg :value-starts :accessor value-starts) (value-ends :initarg :value-ends :accessor value-ends))) (defmethod print-object ((header header) stream) (print-unreadable-object (header stream :type t) (prin1 (status header) stream))) (defun matches-at (pattern target pos) (= (mismatch pattern target :start2 pos) (length pattern))) (defun header-value-indexes (field-name header) (loop with data = (data header) with pattern = (ascii-vector (string-downcase field-name)) for start across (name-starts header) for i from 0 when (matches-at pattern data start) return (values (aref (value-starts header) i) (aref (value-ends header) i)))) (defun ascii-header-value (field-name header) (multiple-value-bind (start end) (header-value-indexes field-name header) (when start (ascii-subseq (data header) start end)))) (defun all-field-names (header) (map 'list (lambda (start end) (ascii-subseq (data header) start end)) (name-starts header) (name-ends header))) (defun headers-alist (header) (mapcar (lambda (name) (cons name (ascii-header-value name header))) (all-field-names header))) (defmethod describe-object :after ((header header) stream) (format stream "~&Decoded headers:~% ~S~%" (headers-alist header))) (defun content-length (header) (let ((field-value (ascii-header-value "content-length" header))) (when field-value (let ((value (ignore-errors (parse-integer field-value)))) (or value (error "Content-Length header field value is not a number -- ~A" field-value)))))) (defun chunkedp (header) (string= (ascii-header-value "transfer-encoding" header) "chunked")) (defun location (header) (ascii-header-value "location" header)) (defun status-code (vector) (let* ((space (position (acode #\Space) vector)) (c1 (- (aref vector (incf space)) 48)) (c2 (- (aref vector (incf space)) 48)) (c3 (- (aref vector (incf space)) 48))) (+ (* c1 100) (* c2 10) (* c3 1)))) (defun force-downcase-field-names (header) (loop with data = (data header) for start across (name-starts header) for end across (name-ends header) do (loop for i from start below end for code = (aref data i) do (setf (aref data i) (ascii-downcase code))))) (defun skip-white-forward (pos vector) (position-if-not 'whitep vector :start pos)) (defun skip-white-backward (pos vector) (let ((nonwhite (position-if-not 'whitep vector :end pos :from-end t))) (if nonwhite (1+ nonwhite) pos))) (defun contract-field-value-indexes (header) "Header field values exclude leading and trailing whitespace; adjust the indexes in the header accordingly." (loop with starts = (value-starts header) with ends = (value-ends header) with data = (data header) for i from 0 for start across starts for end across ends do (setf (aref starts i) (skip-white-forward start data)) (setf (aref ends i) (skip-white-backward end data)))) (defun next-line-pos (vector) (let ((pos 0)) (labels ((finish (&optional (i pos)) (return-from next-line-pos i)) (after-cr (code) (acase code (:lf (finish pos)) (t (finish (1- pos))))) (pending (code) (acase code (:cr #'after-cr) (:lf (finish pos)) (t #'pending)))) (let ((state #'pending)) (loop (setf state (funcall state (aref vector pos))) (incf pos)))))) (defun make-hvector () (make-array 16 :fill-pointer 0 :adjustable t)) (defun process-header (vector) "Create a HEADER instance from the octet data in VECTOR." (let* ((name-starts (make-hvector)) (name-ends (make-hvector)) (value-starts (make-hvector)) (value-ends (make-hvector)) (header (make-instance 'header :data vector :status 999 :name-starts name-starts :name-ends name-ends :value-starts value-starts :value-ends value-ends)) (mark nil) (pos (next-line-pos vector))) (unless pos (error "Unable to process HTTP header")) (setf (status header) (status-code vector)) (labels ((save (value vector) (vector-push-extend value vector)) (mark () (setf mark pos)) (clear-mark () (setf mark nil)) (finish () (if mark (save mark value-ends) (save pos value-ends)) (force-downcase-field-names header) (contract-field-value-indexes header) (return-from process-header header)) (in-new-line (code) (acase code ((#\Tab #\Space) (setf mark nil) #'in-value) (t (when mark (save mark value-ends)) (clear-mark) (save pos name-starts) (in-name code)))) (after-cr (code) (acase code (:lf #'in-new-line) (t (in-new-line code)))) (pending-value (code) (acase code ((#\Tab #\Space) #'pending-value) (:cr #'after-cr) (:lf #'in-new-line) (t (save pos value-starts) #'in-value))) (in-name (code) (acase code (#\: (save pos name-ends) (save (1+ pos) value-starts) #'in-value) ((:cr :lf) (finish)) ((#\Tab #\Space) (error "Unexpected whitespace in header field name")) (t (unless (<= 0 code 127) (error "Unexpected non-ASCII header field name")) #'in-name))) (in-value (code) (acase code (:lf (mark) #'in-new-line) (:cr (mark) #'after-cr) (t #'in-value)))) (let ((state #'in-new-line)) (loop (incf pos) (when (<= (length vector) pos) (error "No header found in response")) (setf state (funcall state (aref vector pos)))))))) ;;; HTTP URL parsing (defclass url () ((hostname :initarg :hostname :accessor hostname :initform nil) (port :initarg :port :accessor port :initform 80) (path :initarg :path :accessor path :initform "/"))) (defun parse-urlstring (urlstring) (setf urlstring (string-trim " " urlstring)) (let* ((pos (mismatch urlstring "http://" :test 'char-equal)) (mark pos) (url (make-instance 'url))) (labels ((save () (subseq urlstring mark pos)) (mark () (setf mark pos)) (finish () (return-from parse-urlstring url)) (hostname-char-p (char) (position char "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_." :test 'char-equal)) (at-start (char) (case char (#\/ (setf (port url) nil) (mark) #'in-path) (t #'in-host))) (in-host (char) (case char ((#\/ :end) (setf (hostname url) (save)) (mark) #'in-path) (#\: (setf (hostname url) (save)) (mark) #'in-port) (t (unless (hostname-char-p char) (error "~S is not a valid URL" urlstring)) #'in-host))) (in-port (char) (case char ((#\/ :end) (setf (port url) (parse-integer urlstring :start (1+ mark) :end pos)) (mark) #'in-path) (t (unless (digit-char-p char) (error "Bad port in URL ~S" urlstring)) #'in-port))) (in-path (char) (case char ((#\# :end) (setf (path url) (save)) (finish))) #'in-path)) (let ((state #'at-start)) (loop (when (<= (length urlstring) pos) (funcall state :end) (finish)) (setf state (funcall state (aref urlstring pos))) (incf pos)))))) (defun url (thing) (if (stringp thing) (parse-urlstring thing) thing)) (defgeneric request-buffer (method url) (:method (method url) (setf url (url url)) (make-request-buffer (hostname url) (port url) (path url) :method method))) (defun urlstring (url) (format nil "~@[http://~A~]~@[:~D~]~A" (hostname url) (and (/= 80 (port url)) (port url)) (path url))) (defmethod print-object ((url url) stream) (print-unreadable-object (url stream :type t) (prin1 (urlstring url) stream))) (defun merge-urls (url1 url2) (setf url1 (url url1)) (setf url2 (url url2)) (make-instance 'url :hostname (or (hostname url1) (hostname url2)) :port (or (port url1) (port url2)) :path (or (path url1) (path url2)))) ;;; Requesting an URL and saving it to a file (defparameter *maximum-redirects* 10) (defvar *default-url-defaults* (url "http://src.quicklisp.org/")) (defun read-http-header (cbuf) (let ((header-data (sink-until-matching (list (acode-matcher :lf :lf) (acode-matcher :cr :cr) (acode-matcher :cr :lf :cr :lf)) cbuf))) (process-header header-data))) (defun read-chunk-header (cbuf) (let* ((header-data (sink-until-matching (acode-matcher :cr :lf) cbuf)) (end (or (position (acode :cr) header-data) (position (acode #\;) header-data)))) (values (parse-integer (ascii-subseq header-data 0 end) :radix 16)))) (defun save-chunk-response (stream cbuf) "For a chunked response, read all chunks and write them to STREAM." (let ((fun (make-stream-writer stream)) (matcher (acode-matcher :cr :lf))) (loop (let ((chunk-size (read-chunk-header cbuf))) (when (zerop chunk-size) (return)) (call-for-n-octets chunk-size fun cbuf) (skip-until-matching matcher cbuf))))) (defun save-response (file header cbuf) (with-open-file (stream file :direction :output :if-exists :supersede :element-type 'octet) (let ((content-length (content-length header))) (cond ((chunkedp header) (save-chunk-response stream cbuf)) (content-length (call-for-n-octets content-length (make-stream-writer stream) cbuf)) (t (call-until-end (make-stream-writer stream) cbuf)))))) (defun call-with-progress-bar (size fun) (let ((progress-bar (make-progress-bar size))) (start-display progress-bar) (flet ((update (condition) (update-progress progress-bar (cbuf-progress-size condition)))) (handler-bind ((cbuf-progress #'update)) (funcall fun))) (finish-display progress-bar))) (defun fetch (url file &key (follow-redirects t) quietly (maximum-redirects *maximum-redirects*)) "Request URL and write the body of the response to FILE." (setf url (merge-urls url *default-url-defaults*)) (setf file (merge-pathnames file)) (let ((redirect-count 0) (original-url url) (connect-url (or (url *proxy-url*) url)) (stream (if quietly (make-broadcast-stream) *trace-output*))) (loop (when (<= maximum-redirects redirect-count) (error "Too many redirects for ~A" original-url)) (with-connection (connection (hostname connect-url) (port connect-url)) (let ((cbuf (make-instance 'cbuf :connection connection)) (request (request-buffer "GET" url))) (write-octets request connection) (let ((header (read-http-header cbuf))) (loop while (= (status header) 100) do (setf header (read-http-header cbuf))) (cond ((= (status header) 200) (let ((size (content-length header))) (format stream "~&; Fetching ~A~%" url) (if (and (numberp size) (plusp size)) (format stream "; ~$KB~%" (/ size 1024)) (format stream "; Unknown size~%")) (if quietly (save-response file header cbuf) (call-with-progress-bar (content-length header) (lambda () (save-response file header cbuf)))))) ((not (<= 300 (status header) 399)) (error "Unexpected status for ~A: ~A" url (status header)))) (if (and follow-redirects (<= 300 (status header) 399)) (let ((new-urlstring (ascii-header-value "location" header))) (when (not new-urlstring) (error "Redirect code ~D received, but no Location: header" (status header))) (incf redirect-count) (setf url (merge-urls new-urlstring url)) (format stream "~&; Redirecting to ~A~%" url)) (return (values header (and file (probe-file file))))))))))) ;;; A primitive tar unpacker (in-package #:qlqs-minitar) (defun make-block-buffer () (make-array 512 :element-type '(unsigned-byte 8) :initial-element 0)) (defun skip-n-blocks (n stream) (let ((block (make-block-buffer))) (dotimes (i n) (read-sequence block stream)))) (defun ascii-subseq (vector start end) (let ((string (make-string (- end start)))) (loop for i from 0 for j from start below end do (setf (char string i) (code-char (aref vector j)))) string)) (defun block-asciiz-string (block start length) (let* ((end (+ start length)) (eos (or (position 0 block :start start :end end) end))) (ascii-subseq block start eos))) (defun prefix (header) (when (plusp (aref header 345)) (block-asciiz-string header 345 155))) (defun name (header) (block-asciiz-string header 0 100)) (defun payload-size (header) (values (parse-integer (block-asciiz-string header 124 12) :radix 8))) (defun nth-block (n file) (with-open-file (stream file :element-type '(unsigned-byte 8)) (let ((block (make-block-buffer))) (skip-n-blocks (1- n) stream) (read-sequence block stream) block))) (defun payload-type (code) (case code (0 :file) (48 :file) (53 :directory) (t :unsupported))) (defun full-path (header) (let ((prefix (prefix header)) (name (name header))) (if prefix (format nil "~A/~A" prefix name) name))) (defun save-file (file size stream) (multiple-value-bind (full-blocks partial) (truncate size 512) (ensure-directories-exist file) (with-open-file (outstream file :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)) (let ((block (make-block-buffer))) (dotimes (i full-blocks) (read-sequence block stream) (write-sequence block outstream)) (when (plusp partial) (read-sequence block stream) (write-sequence block outstream :end partial)))))) (defun unpack-tarball (tarfile &key (directory *default-pathname-defaults*)) (let ((block (make-block-buffer))) (with-open-file (stream tarfile :element-type '(unsigned-byte 8)) (loop (let ((size (read-sequence block stream))) (when (zerop size) (return)) (unless (= size 512) (error "Bad size on tarfile")) (when (every #'zerop block) (return)) (let* ((payload-code (aref block 156)) (payload-type (payload-type payload-code)) (tar-path (full-path block)) (full-path (merge-pathnames tar-path directory)) (payload-size (payload-size block))) (case payload-type (:file (save-file full-path payload-size stream)) (:directory (ensure-directories-exist full-path)) (t (warn "Unknown tar block payload code -- ~D" payload-code) (skip-n-blocks (ceiling (payload-size block) 512) stream))))))))) (defun contents (tarfile) (let ((block (make-block-buffer)) (result '())) (with-open-file (stream tarfile :element-type '(unsigned-byte 8)) (loop (let ((size (read-sequence block stream))) (when (zerop size) (return (nreverse result))) (unless (= size 512) (error "Bad size on tarfile")) (when (every #'zerop block) (return (nreverse result))) (let* ((payload-type (payload-type (aref block 156))) (tar-path (full-path block)) (payload-size (payload-size block))) (skip-n-blocks (ceiling payload-size 512) stream) (case payload-type (:file (push tar-path result)) (:directory (push tar-path result))))))))) ;;; ;;; The actual bootstrapping work ;;; (in-package #:quicklisp-quickstart) (defvar *home* (merge-pathnames (make-pathname :directory '(:relative "quicklisp")) (user-homedir-pathname))) (defun qmerge (pathname) (merge-pathnames pathname *home*)) (defun renaming-fetch (url file) (let ((tmpfile (qmerge "tmp/fetch.dat"))) (fetch url tmpfile) (rename-file tmpfile file))) (defvar *quickstart-parameters* nil "This plist is populated with parameters that may carry over to the initial configuration of the client, e.g. :proxy-url or :initial-dist-url") (defvar *quicklisp-hostname* "beta.quicklisp.org") (defvar *client-info-url* (format nil "http://~A/client/quicklisp.sexp" *quicklisp-hostname*)) (defclass client-info () ((setup-url :reader setup-url :initarg :setup-url) (asdf-url :reader asdf-url :initarg :asdf-url) (client-tar-url :reader client-tar-url :initarg :client-tar-url) (version :reader version :initarg :version) (plist :reader plist :initarg :plist) (source-file :reader source-file :initarg :source-file))) (defmethod print-object ((client-info client-info) stream) (print-unreadable-object (client-info stream :type t) (prin1 (version client-info) stream))) (defun safely-read (stream) (let ((*read-eval* nil)) (read stream))) (defun fetch-client-info-plist (url) "Fetch and return the client info data at URL." (let ((local-client-info-file (qmerge "tmp/client-info.sexp"))) (ensure-directories-exist local-client-info-file) (renaming-fetch url local-client-info-file) (with-open-file (stream local-client-info-file) (list* :source-file local-client-info-file (safely-read stream))))) (defun fetch-client-info (url) (let ((plist (fetch-client-info-plist url))) (destructuring-bind (&key setup asdf client-tar version source-file &allow-other-keys) plist (unless (and setup asdf client-tar version) (error "Invalid data from client info URL -- ~A" url)) (make-instance 'client-info :setup-url (getf setup :url) :asdf-url (getf asdf :url) :client-tar-url (getf client-tar :url) :version version :plist plist :source-file source-file)))) (defun client-info-url-from-version (version) (format nil "http://~A/client/~A/client-info.sexp" *quicklisp-hostname* version)) (defun distinfo-url-from-version (version) (format nil "http://~A/dist/~A/distinfo.txt" *quicklisp-hostname* version)) (defvar *help-message* (format nil "~&~% ==== quicklisp quickstart install help ====~%~% ~ quicklisp-quickstart:install can take the following ~ optional arguments:~%~% ~ :path \"/path/to/installation/\"~%~% ~ :proxy \"http://your.proxy:port/\"~%~% ~ :client-url <url>~%~% ~ :client-version <version>~%~% ~ :dist-url <url>~%~% ~ :dist-version <version>~%~%")) (defvar *after-load-message* (format nil "~&~% ==== quicklisp quickstart ~A loaded ====~%~% ~ To continue with installation, evaluate: (quicklisp-quickstart:install)~%~% ~ For installation options, evaluate: (quicklisp-quickstart:help)~%~%" qlqs-info:*version*)) (defvar *after-initial-setup-message* (with-output-to-string (*standard-output*) (format t "~&~% ==== quicklisp installed ====~%~%") (format t " To load a system, use: (ql:quickload \"system-name\")~%~%") (format t " To find systems, use: (ql:system-apropos \"term\")~%~%") (format t " To load Quicklisp every time you start Lisp, use: (ql:add-to-init-file)~%~%") (format t " For more information, see http://www.quicklisp.org/beta/~%~%"))) (defun initial-install (&key (client-url *client-info-url*) dist-url) (setf *quickstart-parameters* (list :proxy-url *proxy-url* :initial-dist-url dist-url)) (ensure-directories-exist (qmerge "tmp/")) (let ((client-info (fetch-client-info client-url)) (tmptar (qmerge "tmp/quicklisp.tar")) (setup (qmerge "setup.lisp")) (asdf (qmerge "asdf.lisp"))) (renaming-fetch (client-tar-url client-info) tmptar) (unpack-tarball tmptar :directory (qmerge "./")) (renaming-fetch (setup-url client-info) setup) (renaming-fetch (asdf-url client-info) asdf) (rename-file (source-file client-info) (qmerge "client-info.sexp")) (load setup :verbose nil :print nil) (write-string *after-initial-setup-message*) (finish-output))) (defun help () (write-string *help-message*) t) (defun non-empty-file-namestring (pathname) (let ((string (file-namestring pathname))) (unless (or (null string) (equal string "")) string))) (defun install (&key ((:path *home*) *home*) ((:proxy *proxy-url*) *proxy-url*) client-url client-version dist-url dist-version) (setf *home* (merge-pathnames *home* (truename *default-pathname-defaults*))) (let ((name (non-empty-file-namestring *home*))) (when name (warn "Making ~A part of the install pathname directory" name) ;; This corrects a pathname like "/foo/bar" to "/foo/bar/" and ;; "foo" to "foo/" (setf *home* (make-pathname :defaults *home* :directory (append (pathname-directory *home*) (list name)))))) (let ((setup-file (qmerge "setup.lisp"))) (when (probe-file setup-file) (multiple-value-bind (result proceed) (with-simple-restart (load-setup "Load ~S" setup-file) (error "Quicklisp has already been installed. Load ~S instead." setup-file)) (declare (ignore result)) (when proceed (return-from install (load setup-file)))))) (if (find-package '#:ql) (progn (write-line "!!! Quicklisp has already been set up. !!!") (write-string *after-initial-setup-message*) t) (call-with-quiet-compilation (lambda () (let ((client-url (or client-url (and client-version (client-info-url-from-version client-version)) *client-info-url*)) ;; It's ok for dist-url to be nil; there's a default in ;; the client (dist-url (or dist-url (and dist-version (distinfo-url-from-version dist-version))))) (initial-install :client-url client-url :dist-url dist-url)))))) (write-string *after-load-message*) ;;; End of quicklisp.lisp
57,144
Common Lisp
.lisp
1,531
27.890268
96
0.570423
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
4412bdd01e82333f756f982fe7db8d7d65258bfd6946ca37bff8ca72c15b5fe0
2,146
[ 293688, 312054, 334892 ]
2,147
build-init.lisp
nibbula_lish/build/build-init.lisp
;;; ;;; build-init.lisp - Initialization for built Lish. ;;; (defpackage :build-init (:documentation "Initialization for built Lish.") (:use :cl) (:export #:*build-verbose*)) (in-package :build-init) ;; Do things that are too horrible to mention here. (load "build/horrible.lisp" :verbose nil) (msg "[Build initializing...]") (defun fail (message &rest args) (format t "~&/~v,,,va~%~%BUILD FAILURE:~%~?~%~&\\~v,,,va~%" 40 #\- #\- message args 40 #\- #\-) (exit-lisp :code 1)) (defvar *build-verbose* (sf-getenv "LISH_BUILD_VERBOSE") "True to build with more compilation messages. Can be set with the environment variable LISH_BUILD_VERBOSE.") (load "build/load-asdf.lisp" :verbose *build-verbose*) (defvar *home* (or (and (sf-getenv "LISP_HOME") (namestring (probe-file (sf-getenv "LISP_HOME")))) (namestring (user-homedir-pathname))) "Namestring of the home directory.") (load "build/load-quicklisp.lisp" :verbose nil) (push (truename "../") asdf:*central-registry*) (push (truename "../lib/") asdf:*central-registry*) (push (truename "../opsys/") asdf:*central-registry*) (push (truename "../io/") asdf:*central-registry*) (push (truename "../iof/") asdf:*central-registry*) (push (truename "../terminal/") asdf:*central-registry*) (push (truename "../inator/") asdf:*central-registry*) (push (truename "../syntax/") asdf:*central-registry*) (push (truename "../rl/") asdf:*central-registry*) (push (truename "../deblarg/") asdf:*central-registry*) (push (truename "../unicode/") asdf:*central-registry*) (push (truename "../tools/") asdf:*central-registry*) (push (truename "./") asdf:*central-registry*) ;; Suppress the fucking ASDF warnings. #+(or) ; we're in an alternate future (let ((bitch (find-symbol "*SUPPRESS-DEFINITION-WARNINGS*" :asdf)) (troublemakers '(:cl-ppcre-test :puri-tests :cl-base64-tests :flexi-streams-test :openssl-1.1.0 :trivial-garbage-tests :cl-fad-test :hunchentoot-test :hunchentoot-dev))) (if bitch (set bitch troublemakers) ;; yes, I mean set. (progn (setf bitch (find-symbol "*KNOWN-SYSTEMS-WITH-BAD-SECONDARY-SYSTEM-NAMES*" :asdf)) (if bitch (set bitch (uiop:list-to-hash-set troublemakers)) (format t "~&I'm very sorry, but you're not running a recent ~ enough version of ASDF, so you will probably see ~ useless warnings.~%"))))) ;; We really want to set debug up so that we can get function arguments. ;; This will porbably be turned back off in build-deinit.lisp. (defparameter *saved-debug-quality* nil) (let ((debug (cadr (assoc 'debug (optimization-qualities))))) (when (< debug 2) (setf *saved-debug-quality* debug) (proclaim `(optimize (debug 2))))) (in-package :cl-user) ;; End
2,823
Common Lisp
.lisp
63
41.492063
74
0.664361
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
61293cff17ffefbf6cd19c936309907745a3ab0eda3bc1e5be51069a111997c5
2,147
[ -1 ]
2,148
load-asdf.lisp
nibbula_lish/build/load-asdf.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Try to load ASDF, if it's not already loaded. (when (not (find-package :asdf)) (if (sf-getenv "LISH_ASDF") (handler-case (load (sf-getenv "LISH_ASDF")) (error (c) (print c) (fail "LISH_ASDF is set to ~s.~%~ We failed to load the custom ASDF. You'll have to figure it ~ out, or maybe just upgrade your Lisp to one that comes with a working ASDF ~ built-in?" (sf-getenv "LISH_ASDF")))) (handler-case (require :asdf) (error (c) (print c) (fail "We failed to (require :asdf), which probably means ASDF is ~ missing. You can upgrade your Lisp to one that comes with ASDF built-in, or ~ you can set the environment variable LISH_ASDF to the file name of an ASDF ~ to load, and try again."))))) (when (not (find-package :uiop)) (fail "Your ASDF is so old it doesn't have UIOP. Please get a newer ASDF."))
938
Common Lisp
.lisp
22
38.863636
78
0.612691
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
c7d0206a5eb6ca780d45035d2cfb62f3217897e0c3cca0403057dfbdc36ffc3a
2,148
[ -1 ]
2,149
horrible.lisp
nibbula_lish/build/horrible.lisp
;;; ;;; horrible.lisp - Things are in here so you don't have look at them. ;;; (defvar *build-messages* t) (defun msg (fmt &rest args) (when *build-messages* (format t "~&~?~%" fmt args) (finish-output))) (defun sf-getenv (s) #+clisp (ext:getenv s) #+sbcl (sb-ext:posix-getenv s) #+openmcl (ccl::getenv s) #+cmu (let ((v (assoc (intern (string-upcase s) :keyword) ext:*environment-list*))) (if v (cdr v))) #+ecl (si::getenv s) #+excl (sys::getenv s) #+lispworks (hcl:getenv s) #+gcl (system:getenv s) #+abcl (ext:getenv s) #+clasp (ext:getenv s) #+cormanlisp ;; @@@ maybe we could get this added to cormanlisp? (let (name null-pointer value size result blurp) (unwind-protect (progn (setf name (ct:lisp-string-to-c-string s) null-pointer (ct:malloc 1) size (win:getenvironmentvariable name null-pointer 0)) (if (and (zerop size) (= (win:getlasterror) 203)) (setf result nil) (progn (setf value (ct:malloc (1+ size)) blurp (win:getenvironmentvariable name value size)) (when (/= (1+ blurp) size) (error "corman bootstrap getenv failed?.")) (setf result (ct:c-string-to-lisp-string value))))) (when null-pointer (ct:free null-pointer)) (when value (ct:free value))) result) #-(or clisp sbcl openmcl cmu ecl excl lispworks gcl abcl clasp cormanlisp) (error "PORTABILITY BUG: I don't know how to getenv.")) (defun exit-lisp (&key code abort timeout) "Halt the entire Lisp system." ;; But not necessarily the operating system. (declare (ignorable code timeout abort)) (when (not code) (setf code (if abort 1 0))) #+openmcl (ccl::quit code) #+ccl (ccl::quit code) #+cmu (ext:quit) ;; #+sbcl (sb-ext:quit) #+sbcl (sb-ext:exit :code code :abort abort :timeout timeout) #+excl (excl:exit code) #+lispworks (lispworks:quit :status code) #+clisp (funcall 'ext:quit) #+ecl (ext:quit code) #+clasp (ext:quit code) #+abcl (ext:quit :status code) #+cormanlisp (win32:exitprocess code) #-(or openmcl ccl cmu sbcl excl lispworks clisp ecl clasp abcl) (error "PORTABILITY BUG: I don't know how to even EXIT-LISP!")) ;; Workaround for some implementations default encoding (defmacro with-unicode-files (() &body body) `(let (#+lispworks (system:*file-encoding-detection-algorithm* '(utf-8-file-encoding))) ,@body)) (defun lisp-args (#| &key all-p |#) "Arguments given when starting the Lisp system." #+sbcl sb-ext:*posix-argv* #+clisp (ext:argv) #+cmu ext:*command-line-strings* #+openmcl (ccl::command-line-arguments) #+excl (sys:command-line-arguments) #+ecl (ext:command-args) #-(or sbcl clisp cmu openmcl excl ecl) (error "PORTABILITY BUG: I don't know how to get the program arguments.")) ;; Minimal crap taken from dlib. (defmacro _ (&rest exprs) "Shorthand for single argument lambda. The single argument is named '_'." `(lambda (_) (declare (ignorable _)) ,@exprs)) (defun begins-with (prefix thing &key (test #'eql)) "True if THAT begins with THIS." (let ((pos (search prefix thing :test test))) (and pos (zerop pos)))) (defun remove-prefix (sequence prefix &key (test #'eql)) "Remove PREFIX from SEQUENCE. SEQUENCE and PREFIX are both sequences. If SEQUENCE is is not prefixed by PREFIX, just return SEQUENCE." (if (begins-with prefix sequence :test test) (subseq sequence (length prefix)) (copy-seq sequence))) (defun remove-suffix (sequence suffix &key (test #'eql)) "Remove SUFFIX from the end of SEQUENCE. If SEQUENCE doesn't end in SUFFIX, just return SEQUENCE. Elements are compared with TEST which defaults to EQL." (let ((pos (search suffix sequence :from-end t :test test))) (if (and pos (= pos (- (length sequence) (length suffix)))) (subseq sequence 0 pos) (copy-seq sequence)))) (defun optimization-qualities () "Return a list of optimization qualities currently in effect." #+sbcl (map 'list (lambda (_) (list _ (sb-c::policy-quality sb-c::*policy* _))) '(compilation-speed debug safety space speed)) ;; @@@ at some point *policy* was changed from a list to struct with numbers #+(and sbcl some-old-version) sb-c::*policy* #+ccl (ccl:declaration-information 'optimize nil) #+ecl (list c::*debug* c::*speed* c::*safety* c::*space*) #+clisp (loop :for q :in '(speed space safety debug compilation-speed) :collect (list q (gethash x system::*optimize* 1)))) (defun read-file-form (file) "Read the first form from ‘file’ and return it." (with-open-file (s file :direction :input) (let ((*read-eval* nil)) (read-preserving-whitespace s nil)))) ;; End
4,672
Common Lisp
.lisp
118
36.050847
78
0.67769
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
2a978f9ba0efeb486296bdda83ce2ce6e1ba810fed2dac09003e09b729678923
2,149
[ -1 ]
2,150
lish-test.asd
nibbula_lish/lish-test.asd
;;; -*- Lisp -*- ;;; lish-test.asd -- System definition for lish-test ;;; (defsystem lish-test :name "lish-test" :description "Tests for Lish." :version "0.1.0" :author "Nibby Nebbulous <nibbula -(. @ .)- gmail.com>" :license "GPL-3.0-only" :source-control :git :long-description "Haphazard and surely incomplete tests for the Lish shell." :depends-on (:test :lish :dlib) :components ((:file "lish-test")) :in-order-to ((test-op load-op :list-test)) :perform (asdf:test-op :after (op c) (funcall (intern (symbol-name '#:run) :lish-test))))
663
Common Lisp
.asd
18
32.444444
71
0.56677
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
f8506b68e1080c14ed0eb7e25ef88c9e941afece8f5de707d3f2c196293f493b
2,150
[ -1 ]
2,151
lish.asd
nibbula_lish/lish.asd
;;; -*- Lisp -*- ;;; lish.asd -- System definition for LISH package ;;; (defsystem lish :name "lish" :description "Lispy system command shell." ;;:version "0.1.0" :version (:read-file-form "version.lisp") :author "Nibby Nebbulous <nibbula -(. @ .)- gmail.com>" :licence "GPL-3.0-only" :source-control :git :long-description "Lish is a Lisp shell. Don't hold your breath." :entry-point "lish:shell-toplevel" :defsystem-depends-on (:lish-config) :depends-on (;; Things in yew :dlib :opsys :dlib-misc :stretchy :char-util :glob :table :table-print :reader-ext :dlib-interactive :completion :keymap :terminal :terminal-ansi :rl :fatchar :fatchar-io :magic :theme :theme-default :style :collections :ostring :ochar :grout :utf8b-stream :dtime :locale :string-expand ;; Things in not in yew #+use-re :re #-use-re :cl-ppcre :chipz) :components ((:file "package") (:file "vars" :depends-on ("package")) (:file "types" :depends-on ("package")) (:file "args" :depends-on ("package" "types" "vars")) (:file "reader" :depends-on ("package" "vars")) (:file "jobs" :depends-on ("package" "vars")) (:file "commands" :depends-on ("package" "vars" "types" "args")) (:file "shell" :depends-on ("package" "vars" "types" "args" "commands")) (:file "prompt" :depends-on ("package" "vars" "args" "commands" "shell")) (:file "expand" :depends-on ("package" "vars" "types" "args" "jobs" "commands" "shell" "prompt")) (:file "complete" :depends-on ("package" "vars" "args" "commands" "expand")) (:file "lish" :depends-on ("package" "vars" "types" "args" "jobs" "commands" "shell" "prompt" "complete" "expand")) (:file "piping" :depends-on ("package" "vars" "args" "commands" "shell" "lish")) (:file "builtin" :depends-on ("package" "vars" "args" "jobs" "commands" "shell" "complete" "lish")) (:file "mine" :depends-on ("package" "vars" "args" "commands" "shell" "lish" "piping"))) :in-order-to ((asdf:test-op (asdf:test-op :lish-test))))
2,263
Common Lisp
.asd
50
39.26
81
0.575949
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
bdc84179c8517373cfde9e4d0720c05dd465ef05ae4f54e7ed3693423c53e3b4
2,151
[ -1 ]
2,152
lish-config.asd
nibbula_lish/lish-config.asd
;;; -*- Lisp -*- ;;; lish-config.asd - System definition for lish-config ;;; (defsystem lish-config :name "lish-config" :description "Configuration for Lish" :version "0.1.0" :author "Nibby Nebbulous <nibbula -(. @ .)- uucp!gmail.com>" :license "GPL-3.0-only" :source-control :git :long-description "Configuration for Lish" :depends-on (:config) :components ((:file "lish-config")))
472
Common Lisp
.asd
14
31.214286
74
0.579869
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
0b533b27bc40c14a4b8b0231f6eac5b53901e75b677208307eccee7dd6b5fd85
2,152
[ -1 ]
2,155
build.bat
nibbula_lish/build.bat
@echo off rem This is only for SBCL currently. rem Also it doesn't work unless you've already done a grovelling compile run rem under cygwin or something, and a platform appropriate libffi.dll is in the rem path. rem rem There are multiple difficult problems: rem 1. Make implementations be able to call by struct value on supported rem platforms. CCL can call by struct value, but sbcl can't. rem 2. Make CFFI be able to use the implmentation's call by struct value rem without libffi on supported implementations. rem 3. Replace whatever grovels with a non-grovelling version. rem Either: rem - Replace whatever it is by my version which uses opsys rem - Make a patched version of whatever by replacing grovelling with rem opsys calls and maintain a fork. rem rem I suppose a workaround could be if we supply a libffi.dll and the groveller rem output and copy them in to place here? rem rem Another problem is that the compiling doesn't flush the output enough, so rem we don't see progess as it happens. This seems like no too hard to fix. rem set LISP=sbcl set LISH_PLAIN_FLAGS=--no-userinit set LISH_FLAGS=--noinform --noprint --disable-debugger --no-sysinit set TARGET=lishpfu rem echo "[Using %LISP% %LISH_FLAGS% %LISH_PLAIN_FLAGS% ]" rem %LISP% %BATCH_ARGS% %LISH_PLAIN_FLAGS% --load build/build-lish.lisp rem sbcl --noinform --noprint --no-userinit --disble-debugger -no-sysinit --load build/build-lish.lisp sbcl --noinform --noprint --no-userinit --disable-debugger --no-sysinit --load "build/build-lish.lisp"
1,555
Common Lisp
.l
30
50.633333
102
0.775658
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
5e1170e58983735b1cf74971b9411c5d858adfaa2bc5c942a95e39dcd2f39f30
2,155
[ -1 ]
2,164
build.sh
nibbula_lish/build.sh
#!/usr/bin/env sh # # build.sh - Build Lish # fail() { echo echo "Building Lish failed. Sorry." echo echo "/-------------------------------------------------------------------\\" echo echo " If it failed for some missing requirement, it should say so" echo " somewhere above." echo echo " If it failed due to something in an initialization file, you can" echo " use the '-p' option, to try building without loading the" echo " initialization file. For example:" echo echo "sh build.sh -p" echo echo " Or you may need to set PLAIN_LISP_FLAGS to command line arguments to" echo " run Lisp without loading the initialization file. For example:" echo echo "PLAIN_LISP_FLAGS=--no-init sh build.sh" echo echo "\\-------------------------------------------------------------------/" } if [ -n "$1" ]; then export TARGET="$1" fi #${SHELL:-sh} ./run_lisp.sh "build/build-lish.lisp" || fail /usr/bin/env sh ./run_lisp.sh "build/build-lish.lisp" || fail exit 0
1,003
Common Lisp
.l
33
28
79
0.593168
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
04ae1b71b762a053bb28fdb42670db2b26c1a494f095e9b91f8f7cf456af9b84
2,164
[ -1 ]
2,165
Makefile
nibbula_lish/Makefile
## ## Makefile - fake makefile for lish ## # This is just so that just saying 'make' can work. default: sh ./build.sh install: sh ./build.sh install clean: sh ./build.sh clean .PHONY: default install clean
214
Common Lisp
.l
11
17.727273
51
0.737374
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
0b1571d51137382b4698799e6b329885c33c2359fe9adbd5490494218910faf2
2,165
[ -1 ]
2,171
install.sh
nibbula_lish/install.sh
#!/usr/bin/env sh # # install.sh - Install Lish # # This is really just a stupid ‘cp’ command. You can just ‘cp’ lish to your bin. # # @@@ We could write this in lish, like the build script, but unfortunately # we'd need to make sure "los" is around and/or loaded, for "mkdir -p" and # "cp" and maybe "really", or make ½-assed versions of them. It doesn't # actually help much with portability, since non-unix OS's will likely be # totally different. # # @@@ Someday convert to lish, since we at least should have the lish executable # and be able to use that even if it doesn't have los! fail() { echo "$@" echo "Installing Lish failed. Sorry." exit 1 } program_name=${LISH:=lish} prefix=${PREFIX:=/usr/local/} destination="${PREFIX}/bin/" try_sudo= if [ -z "$program_name" ]; then fail '$LISH is not set or is empty.' fi if [ ! -e "$program_name" ]; then fail "$program_name doesn't exist." fi if [ ! -f "$program_name" ]; then fail "$program_name isn't a regular file." fi if [ ! -x "$program_name" ]; then fail "$program_name isn't executable." fi if [ ! -w "$destination" ]; then if [ "$1" = '-i' ]; then echo "The destination $destination is not writable." if type sudo > /dev/null ; then echo "Trying sudo" try_sudo=sudo elif type doas > /dev/null ; then echo "Trying doas" try_sudo=doas elif type su > /dev/null ; then echo "Trying su" try_sudo=su else echo "I can't find a way to get root." fi else fail "The destination $destination is not writable. \ Maybe be root or try -i ?" fi fi if [ ! -d "$destination" ]; then printf "Making $destination..." $try_sudo mkdir -p "$destination" || \ fail "Can't make the destination. Maybe you need root?" echo "OK" fi new_name="${destination}/${program_name}" if [ -f "${new_name}" ] ; then printf "Trying to rename current $program_name in $destination..." $try_sudo mv "${new_name}" "${new_name}_bak" || \ fail "Couldn't rename ${new_name} to ${new_name}_bak. Maybe you need root?" echo "OK" fi printf "Copying $program_name to $destination..." $try_sudo cp "$program_name" "$destination" || \ fail "Couldn't copy $program_name to $destination. Maybe you need root?" echo "OK" echo "Install succeeded." exit 0
2,292
Common Lisp
.l
75
27.826667
80
0.668486
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
0a485171e1fc41d3ea7676d332f8a357b8aea400865ec3d9a0ac6e1793996ac7
2,171
[ -1 ]
2,184
lish-examples.md
nibbula_lish/docs/lish-examples.md
Lish examples ============= Many features of Lisp should be familiar from POSIX shells. You can use `|` for pipes between processes: ``` Lish> echo hello world | wc 1 2 12 ``` A dollar sign in a shell command performs variable substitution ``` Lish> echo My home directory is $HOME My home directory is /home/user ``` Lish is built on Common Lisp, and evaluates s-expressions: ``` Lish> (+ 1 2 3) 6 ``` The results of expressions can be passed as inputs to shell commands ``` Lish> echo (loop for i from 0 below 10 collect i) 0 1 2 3 4 5 6 7 8 9 ``` Environment variables --------------------- Variables are set with `export`, with or without an `=` between the name and the value: ``` Lish> export name "Mister Noodle" Lish> echo $name Mister Noodle ``` **Note**: Using single quotes results in: ``` Lish> export name 'Mister Noodle' WARNING: Extra arguments: (Noodle') Lish> echo $name 'Mister ``` In Common Lisp, single quotes are used as a prefix to prevent evaluation of expressions, but only just before and inside parentheses. To avoid confusion between syntaxes, Lish only uses single quote in the Lisp way. The un-specialness of single quotes otherwise, can help in avoiding getting tripped up by English contractions: ``` echo If'n '(+ 2 3) weren't indeed (+ 2 3), 'twould be broke'd. ``` Here the single quote is used in the Lisp way to prevent evaluation of (+ 2 3), but otherwise use verbatim in commands. Variables are not split after substitution: ``` Lish> mkdir $name Lish> ls Mister Noodle ``` A single directory was created rather than two, which `bash` would have created unless `$name` were quoted. As in `bash` and many other shells, the `PATH` environment variable is a string containing a `:` separated list of paths. These paths are searched from first to last for executables: ``` Lish> echo $PATH /home/testuser/local/bin:/usr/local/bin:/usr/bin:/bin ``` Environment variables can be accessed inside Lisp expressions using `nos:env`, which returns a string. For exmaple this string can be split using the split function. ``` Lish> (split #\: (nos:env "PATH")) ("/home/user/local/bin" "/usr/local/bin" "/usr/bin" "/bin" "/usr/local/games" "/usr/games") ``` But note that for this purpose it's probably best to use (nos:command-path-list) since the layout of the PATH variable differs between operating systems. A loop over all the entries in `PATH`: ``` Lish> (loop for entry in (nos:command-path-list) do - (format t "entry: ~a~%" entry)) entry: /home/testuser/local/bin entry: /usr/local/bin entry: /usr/bin entry: /bin entry: /usr/local/games entry: /usr/games NIL ``` The environment variable locations are also setf'able: ``` Lish> (setf (nos:environment-variable "TEST") "some string") Lish> echo $TEST some string ``` The value must be a string or `nil`, so setting an environment variable to a number, for example, results in a type error. Command substitution -------------------- `!$` returns the lines output from a command as a string of words. This is basically like `$(command)` or backticks in POSIX shells. ``` Lish> echo In (!$ 'pwd), running (!$ 'uname) In /home/testuser , running Linux ``` ``` Lish> export os (!$ 'uname) Lish> echo $os Linux ``` There are a number command substitution functions, depending on how you want the output. For convenience they are named with very short names, starting with `!`. These functions aren't special or part of the syntax. You can define your own command substitution functions to suit your needs. For instance, `!_` turns the output in to a list of lines. ``` echo You have (count-if (_ (begins-with "??" _)) (!_ "git status --porcelain")) untracked files. ``` `!@` spreads the entire output into separate words, instead of one word. So, ``` touch (!$= "echo" "foo bar") ``` creates one file named "foo bar", but ``` touch (!@= "echo" "foo bar") ``` creates two files named "foo" and "bar". Separating commands ------------------- Lish uses lisp style comments, which begin with `;`. The usual way to separate commands therefore doesn't work: ``` Lish> echo hello; echo world hello ``` Instead you can use `^`, which was chosen since it's mostly unused in other shells: ``` Lish> echo hello ^ echo world hello world ``` Loops ----- ``` Lish> (dotimes (i 5) - (! "touch file_" i ".txt"))) NIL Lish> ls file_0.txt file_1.txt file_2.txt file_3.txt file_4.txt ``` But Lish, like some other shells, supports brace expansion. So a simpler way to do this is: ``` Lish> touch file_{0..5}.txt ``` The `glob` function can be used to get lists of files and directories: ``` Lish> (loop for file in (glob "*.txt") do - (! "cp " file " " file ".bak")) Lish> ls file_0.txt file_2.txt.bak file_0.txt.bak file_3.txt file_1.txt file_3.txt.bak file_1.txt.bak file_4.txt file_2.txt file_4.txt.bak ``` Prompt ------ The default prompt is configured using a bash-style prompt string. Like other user-configurable Lish options, it can be set using the `opt` built-in command. See `help opt` for a list. ``` Lish> opt prompt "[%u@%h %W]\$ " [user@lisa user]$ ``` The prompt can also be generated using a function, which takes a shell as its first argument (but can safely ignore it). Setting `prompt-function` to `nil` reverts to the default behaviour. ``` Lish> opt prompt-function (lambda (sh) (declare (ignorable sh)) "My prompt> ") My prompt> My prompt> opt prompt-function nil Lish> ``` Colors, styles, and evaluated pieces can be put in the `prompt-string`. For example, here's a fancy prompt showing many features of prompt formatting: ``` opt prompt '((:cyan "%h") ":" (:magenta "%i") ":" (:white (:underline "%w")) " " (:red (make-string (1+ *lish-level*) :initial-element #\@)) #\space) ``` For the details on thism one can look at the documentation for `format-prompt` and `symbolic-prompt-to-string` which can usually be dredged up by the standard Lisp functions `describe` or `documentation`, e.g.: ``` (describe 'format-prompt) ``` and ``` (documentation 'symbolic-prompt-to-string 'function) ``` Lisp functions -------------- In a previous exmaple, we had shown how to evaluate Lisp s-expressions (a.k.a expressions in parentheses), but Lish can also call Lisp functions without parentheses: ``` Lish> lisp-implementation-version "1.3.7.62-a2d1969-dirty" Lish> sin pi 1.2246467991473532d-16 ``` Although note if you something like say: ``` Lish> sleep .5 Lish> ; delayed by 1/2 a second. ``` you will probably get the system sleep command, instead of the Common Lisp sleep function. You can tell which one you might get first by using the `type` command, like in other shells. ``` Lish> type -a sleep sleep is /bin/sleep sleep is the function #<FUNCTION SLEEP> ``` One feature of Lish is that Lisp functions and Lish commmands can return objects, and those objects are passed to subsequent functions in a pipeline. If that command happens to be a Lisp function with at least one less argument than it expects, that argument is taken from the result of the previous command in pipeline: ``` Lish> get-universal-time | decode-universal-time 50 ; 9 ; 4 ; 25 ; 5 ; 2018 ; 4 ; T ; 8 Lish> sin pi | expt 2 1.0d0 Lish> (expt 2 (sin pi)) ; Same as the last line, but in s-exp style. 1.0d0 Lish> glob "/bin/d*" | mapcar 'reverse | mapcar 'string-capitalize ``` These examples utilize "parenless" function calls, which take the pipe output as the last argument. If the argument you want to pass isn't in the last position, you can use the variable *input*. ``` Lish> list 9 3 29 24 23 7 | (sort *input* #'<) ``` Note: The corresponding variable *output*, works in shell commands, but not in normal functions, since *output* always gets set to the return value.
7,744
Common Lisp
.l
255
29.015686
107
0.729279
nibbula/lish
108
9
3
GPL-3.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
79ff120896afbcd350cd5f87154c28558425870f9fb47dc676b7370bf705dd55
2,184
[ -1 ]
2,199
entry.lisp
VitoVan_calm/entry.lisp
#-quicklisp (let ((quicklisp-setup (probe-file "quicklisp/setup.lisp"))) (when quicklisp-setup (load quicklisp-setup))) ;; https://groups.google.com/g/quicklisp/c/wrULkRePVE4 #+win32 (quicklisp-client::make-system-index "quicklisp/local-projects/") ;; Load CALM #-calm (load "calm.asd") #-calm (ql:quickload :calm) (in-package #:calm) (calm-config) ;; switch to the CALM_APP_DIR (uiop:chdir *calm-env-app-dir*) (defun copy-dist-files (pathname) ;; copy files (let* ((ori-lib-dir (merge-pathnames "lib/" *calm-env-calm-home*)) (dist-dir (merge-pathnames pathname *calm-env-app-dir*)) (ori-assets-dir (merge-pathnames "assets/" *calm-env-app-dir*)) (dist-assets-dir (merge-pathnames "assets/" dist-dir)) (ori-fonts-dir (merge-pathnames "fonts/" *calm-env-app-dir*)) (dist-fonts-dir (merge-pathnames "fonts/" dist-dir)) (dist-lib-dir (merge-pathnames "lib/" dist-dir)) (dist-bin-dir (merge-pathnames "bin/" dist-dir)) (calm-bin #+win32 "calmNoConsole.exe" #-win32 "calm")) ;; clean old dist (uiop:delete-directory-tree dist-dir :validate t :if-does-not-exist :ignore) ;; mkdir (mapcar #'ensure-directories-exist (list dist-bin-dir)) ;; copy dependencies (u:copy-dir ori-lib-dir dist-lib-dir) ;; copy assets (u:copy-dir ori-assets-dir dist-assets-dir) ;; copy fonts (u:copy-dir ori-fonts-dir dist-fonts-dir) ;; copy calm launcher (u:copy-file (merge-pathnames calm-bin *calm-env-calm-home*) (merge-pathnames (str:concat "calm" #+win32 ".exe") dist-dir)))) (defun dist (pathname) (u:calm-log "binary pathname ~A~%" pathname) (copy-dist-files pathname) ;; load `canvas.lisp' (load (merge-pathnames "canvas.lisp" *calm-env-app-dir*)) ;; dump binary (sb-ext:save-lisp-and-die (merge-pathnames (str:concat "bin/calm-app" #+win32 ".exe") pathname) :compression 22 #+win32 :application-type #+win32 :gui :executable t :toplevel #'calm:calm-start)) (defun dist-by-new-process () (let ((calm-bin-abs (str:concat (namestring *calm-env-calm-home*) "calm" #+win32 ".exe"))) ;; the following command will quit SBCL, ;; so exec it as external cmd instead of load lisp file (u:calm-log-fancy "dumping binary, this may take a few minutes...") (u:exec (str:concat calm-bin-abs " dist")))) (defun publish-web () (u:load-from-calm "s/usr/web/wasm.lisp") (u:load-from-calm "s/usr/web/load-and-compile.lisp") (u:load-from-calm "s/usr/web/post-compile.lisp")) (defun publish () (setf (uiop:getenv "DIST_DIR") (uiop:native-namestring (uiop:merge-pathnames* "dist/" *calm-env-app-dir*))) #+darwin (progn (dist-by-new-process) (u:calm-log "building macOS Application...") (u:load-from-calm "s/usr/macos/bundle.lisp") (u:calm-log "building macOS DMG, this may take a while...") (u:load-from-calm "s/usr/macos/dmg.lisp")) #+win32 (progn (u:load-from-calm "s/usr/windows/icon.lisp") (setf (uiop:getenv "CALM_WITH_ICON") "YES_MY_LORD") (dist-by-new-process) (u:calm-log "building Windows Installer...") (u:load-from-calm "s/usr/windows/installer.lisp")) #+linux (progn (dist-by-new-process) (u:calm-log "building Linux AppImage...") (u:load-from-calm "s/usr/linux/appimage.lisp"))) (alexandria:switch (*calm-env-calm-cmd* :test #'equal) ("test" (u:calm-log-fancy "Nothing to test.") (uiop:quit 0)) ("alive" (u:load-from-calm "s/dev/all/start-alive.lisp")) ("show" (calm:calm-load-and-start)) ("hello" (u:copy-file (merge-pathnames "s/usr/all/panic.lisp" *calm-env-calm-home*) (merge-pathnames "canvas.lisp" *calm-env-app-dir*)) (ensure-directories-exist (merge-pathnames "assets/" *calm-env-app-dir*)) (ensure-directories-exist (merge-pathnames "fonts/" *calm-env-app-dir*)) (u:copy-file (merge-pathnames "s/usr/all/fonts.conf" *calm-env-calm-home*) (merge-pathnames "fonts/fonts.conf" *calm-env-app-dir*)) (u:calm-log-fancy "Hello, sample files and directories created, please enjoy")) ("publish" (publish)) ("publish-web" (publish-web)) ("publish-with-options" (setf (uiop:getenv "CALM_ASK_ME") "yes-please") (publish)) ("publish-web-with-options" (setf (uiop:getenv "CALM_ASK_ME") "yes-please") (publish-web)) ;; rebuild calm.core ;; this could speed up your CALM command #+sbcl ("core" (sb-ext:save-lisp-and-die (merge-pathnames *calm-env-calm-home* "calm.core"))) #+darwin ("make-bundle" (u:load-from-calm "s/usr/macos/bundle.lisp")) #+darwin ("make-dmg" (u:load-from-calm "s/usr/macos/dmg.lisp")) #+win32 ("make-installer" (u:load-from-calm "s/usr/windows/installer.lisp")) #+win32 ("set-icon" (u:load-from-calm "s/usr/windows/icon.lisp")) #+linux ("make-appimage" (u:load-from-calm "s/usr/linux/appimage.lisp")) #+sbcl ("dist" (dist #p"dist/")) (t (format t "UNKOWN CALM_CMD: ~A~%" *calm-env-calm-cmd*))) (uiop:quit)
4,998
Common Lisp
.lisp
128
34.875
109
0.664604
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
c41de427fae6719ce0d8a47225a90b9548d14d6631fdd09e0bacc05aa7d3a936
2,199
[ -1 ]
2,200
package.lisp
VitoVan_calm/src/package.lisp
(uiop:define-package :c (:use :cl) (:use-reexport :cl-cairo2) (:export :rrectangle :open-audio-if-not-yet :play-music :play-wav :playing :halt-music :halt-wav :volume-wav :volume-music :get-ticks :keq :show-png :select-font-family :with-state :markup->layout :show-layout :show-markup )) (defpackage :calm-utils (:use :cl) (:export :load-from-app :load-from-calm :get-from-env-or-ask :set-cursor :exec :exec-if :touch-file :copy-file :copy-dir :calm-log :calm-log-fancy)) (defpackage :calm (:use :cl) (:local-nicknames (:u :calm-utils)) (:export :calm-init :calm-start :calm-load-and-start)) (defpackage :fontconfig (:use :cl) (:export :maybe-enum :weight :slant :fc-init :fc-init-reinitialize :fc-create-pattern :fc-pattern-add-string :fc-pattern-add-integer :destroy-pattern))
934
Common Lisp
.lisp
56
12.910714
28
0.645235
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
478b6811b06ef941c31af31042fb6f49ccd9477d8e00dc5531f343e727e24712
2,200
[ -1 ]
2,201
fontconfig.lisp
VitoVan_calm/src/fontconfig.lisp
;; some of the code borrowed from: https://github.com/Shinmera/font-discovery (in-package #:fontconfig) (cffi:define-foreign-library :fontconfig (:darwin (:or "libfontconfig.1.dylib" "libfontconfig.dylib")) (:unix (:or "libfontconfig.so.1" "libfontconfig.so")) (:windows (:or "libfontconfig-1.dll" "libfontconfig.dll")) (t (:default "libfontconfig"))) (cffi:load-foreign-library :fontconfig) (cffi:defcenum weight (:thin 0) (:extra-light 40) (:ultra-light 40) (:light 50) (:demi-light 55) (:semi-light 55) (:book 75) (:regular 80) (:normal 80) (:medium 100) (:demi-bold 180) (:semi-bold 180) (:bold 200) (:extra-bold 205) (:black 210) (:heavy 210)) (cffi:defcenum slant (:normal 0) (:roman 0) (:italic 100) (:oblique 110)) (defun maybe-enum (type thing) (etypecase thing (keyword (cffi:foreign-enum-value type thing)) (integer thing))) (cffi:defcfun (fc-init "FcInit") :pointer) (cffi:defcfun (fc-init-reinitialize "FcInitReinitialize") :pointer) (cffi:defcfun (fc-create-pattern "FcPatternCreate") :pointer) (cffi:defcfun (fc-pattern-add-string "FcPatternAddString") :bool (pattern :pointer) (object :string) (string :string)) (cffi:defcfun (fc-pattern-add-integer "FcPatternAddInteger") :bool (pattern :pointer) (object :string) (i :int)) (cffi:defcfun (destroy-pattern "FcPatternDestroy") :void (pattern :pointer))
1,401
Common Lisp
.lisp
47
27.042553
77
0.708861
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
2470f080f58b8b4d906da29afed8b5854cee2ccc8a9c0f4f8a76e6ece288bdbf
2,201
[ -1 ]
2,202
utils.lisp
VitoVan_calm/src/utils.lisp
(in-package #:calm-utils) (defmacro calm-log-fancy (control-string &rest rest) `(progn (format t "~%") (format t " ____ _ _ __ __ / ___| / \\ | | | \\/ | | | / _ \\ | | | |\\/| | | |___ / ___ \\ | |___ | | | | \\____| /_/ \\_\\ |_____| |_| |_| CALM: ~A, ~A: ~A~% " (slot-value (asdf:find-system 'calm) 'asdf:version) (lisp-implementation-type) (lisp-implementation-version)) (format t ,control-string ,@rest) (format t "~%~%"))) (defmacro calm-log (control-string &rest rest) `(format t ,control-string ,@rest)) (defun load-from-app (pathname) "load lisp files from the `CALM_APP_DIR' directory, e.g. use (load-from-app \"config.lisp\") to load your custom configuration file" (load (or (uiop:absolute-pathname-p pathname) (uiop:merge-pathnames* pathname (uiop:getenv "CALM_APP_DIR"))))) (defun load-from-calm (pathname) "load lisp files from the `CALM_HOME' directory, e.g. use (load-from-calm \"config.lisp\") to load your custom configuration file" (load (or (uiop:absolute-pathname-p pathname) (uiop:merge-pathnames* pathname (uiop:getenv "CALM_HOME"))))) ;; ;; command utilities ;; (defun exec (command &key (expected-exit-code 0) (ignore-error-status nil)) (format t "EXECUTING CMD: ~A~%" command) (let ((exit-code (nth-value 2 (uiop:run-program command :output :interactive :input :interactive :error-output t :ignore-error-status t)))) (if (= exit-code expected-exit-code) exit-code (if ignore-error-status exit-code (error (format nil "exec failed: ~A, exit code: ~A~%" command exit-code)))))) (defun exec-if (test then else &key (re-exec-then nil) (expected-exit-code 0) (then-expected-exit-code 0) (else-expected-exit-code 0)) "exec `test', if the exit-code is as expected, then exec `then', else run `else'. if `re-exec-then' is T, then exec `then' again after the exec of `else' " (let ((exit-code (nth-value 2 (uiop:run-program test :output t :error-output t :ignore-error-status t)))) (if (= exit-code expected-exit-code) (exec then :expected-exit-code then-expected-exit-code) (progn (exec else :expected-exit-code else-expected-exit-code) (when re-exec-then (exec then :expected-exit-code then-expected-exit-code)))))) ;; ;; file utilities ;; ;; thank you, Zach Beane ;; https://lisptips.com/post/11136367093/touching-a-file (defun touch-file (filename) (open filename :direction :probe :if-does-not-exist :create)) (defun copy-file (from to) "`uiop:copy-file' will remove some file attributes, so let's use the platform command" (setf from (if (stringp from) from (uiop:native-namestring from))) (setf to (if (stringp to) to (uiop:native-namestring to))) (format t "copying file from ~A to ~A~%" from to) (if (probe-file from) (exec #-win32 (str:concat "cp \"" from "\" \"" to "\"") #+win32 (str:concat "copy /y \"" from "\" \"" to "\"")) (format t "File NOT Found: ~A~%" from))) (defun copy-dir (from to) "Let's just cut the shit of loading `cl-fad' and writing yet another clumsy common lisp utility function to recursively copy file system directories and lost all the file attributes. Just use the `cp' command for whoever's sake" (setf from (if (stringp from) from (uiop:native-namestring from))) (setf to (if (stringp to) to (uiop:native-namestring to))) (format t "copying dir from ~A to ~A~%" from to) (if (probe-file from) (exec #-win32 (str:concat "cp -R \"" from "\" \"" to "\"") #+win32 (str:concat "robocopy /mir \"" from " \" \"" to " \"") ;; extra space to avoid escaping \" ;; I don't know why those Windows fuckers decide to ;; make the `exit-code' to 1 when `robocopy' ran successfully. ;; I won't argue with anyone, but this worth a comment. ;; ;; https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy ;; ;; 0 No files were copied. ;; 0 No failure was encountered. ;; 0 No files were mismatched. ;; 0 The files already exist in the destination directory; therefore, the copy operation was skipped. ;; ;; 1 All files were copied successfully. ;; #+win32 :expected-exit-code #+win32 1 :ignore-error-status t) (format t "Directory NOT Found: ~A~%" from))) #-jscl (defun set-cursor (type) (cond ((equal type :hand) (sdl2-ffi.functions:sdl-set-cursor (sdl2-ffi.functions:sdl-create-system-cursor sdl2-ffi:+sdl-system-cursor-hand+))) ((equal type :arrow) (sdl2-ffi.functions:sdl-set-cursor (sdl2-ffi.functions:sdl-create-system-cursor sdl2-ffi:+sdl-system-cursor-arrow+))))) ;; ;; env utils ;; (defun get-from-env-or-ask (var-name &optional default-value) "`var-name' should be a string, or something could be fed to (string x) this function will: 1. (uiop:getenv \"VAR_NAME\"), return the value if it were found 2. ask user to input a new value for this, and return" (let* ((env-name (str:replace-all "-" "_" (str:upcase (string var-name)))) (env-value (uiop:getenv env-name)) (current-value (or env-value default-value))) ;; if there exists default value or env value, ;; and the user don't want to be bothered (by default, we don't bother them), (if (and (or default-value env-value) (not (uiop:getenv "CALM_ASK_ME"))) ;; the current value will be used, no question will be asked current-value ;; ask the user, and provide the current value (or env-value (progn (format t "Please set value for \"~A\" [default: ~A]: ~%" (str:replace-all "-" " " (string var-name)) current-value) (let* ((input-line (read-line)) (result (if (str:empty? input-line) current-value input-line))) ;; update ENV to match the user input (setf (uiop:getenv env-name) (princ-to-string result)) result))))))
6,186
Common Lisp
.lisp
135
39.851852
144
0.621107
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
7acc759796b2f34585bb06ebd22189d787c6399ceb7827fde8a6c9a60a114d54
2,202
[ -1 ]
2,203
events.lisp
VitoVan_calm/src/events.lisp
(in-package :calm) (defun internal-on-textinput (text) (when (fboundp 'on-textinput) (on-textinput text))) (defun internal-on-keydown (key) (setf *calm-redraw* t) (when (fboundp 'on-keydown) (on-keydown key))) (defun internal-on-keyup (key) (setf *calm-redraw* t) (when (fboundp 'on-keyup) (on-keyup key))) (defun internal-on-mousewheel (x y direction) (setf *calm-redraw* t) (when (fboundp 'on-mousewheel) (on-mousewheel x y direction))) (defun internal-on-mousemotion (&key x y) (setf *calm-state-mouse-x* x *calm-state-mouse-y* y *calm-redraw* t *calm-state-mouse-just-clicked* nil) (when (fboundp 'on-mousemotion) (on-mousemotion :x x :y y))) (defun internal-on-mousebuttonup (&key button x y clicks) (setf *calm-state-mouse-up* button *calm-state-mouse-down* nil *calm-redraw* t *calm-state-mouse-just-clicked* t) (when (fboundp 'on-mousebuttonup) (on-mousebuttonup :button button :x x :y y :clicks clicks))) (defun internal-on-mousebuttondown (&key button x y clicks) (setf *calm-state-mouse-up* nil *calm-state-mouse-down* button *calm-redraw* t *calm-state-mouse-just-clicked* nil) (when (fboundp 'on-mousebuttondown) (on-mousebuttondown :button button :x x :y y :clicks clicks))) (defun internal-on-fingermotion (&key x y dx dy pressure finger-id) (setf *calm-state-finger-x* x *calm-state-finger-y* y *calm-redraw* t *calm-state-finger-just-tapped* nil) (format t "finger motion~%") (when (fboundp 'on-fingermotion) (on-fingermotion :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (defun internal-on-fingerup (&key x y dx dy pressure finger-id) (setf *calm-state-finger-up* finger-id *calm-state-finger-down* nil *calm-redraw* t *calm-state-finger-just-tapped* t) (format t "finger up~%") (when (fboundp 'on-fingerup) (on-fingerup :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (defun internal-on-fingerdown (&key x y dx dy pressure finger-id) (setf *calm-state-finger-up* nil *calm-state-finger-down* finger-id *calm-redraw* t *calm-state-finger-just-tapped* nil) (format t "finger down~%") (when (fboundp 'on-fingerdown) (on-fingerdown :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (defun internal-on-windowresized (width height) (setf *calm-redraw* t) (when (fboundp 'on-windowresized) (on-windowresized width height))) (defun internal-on-windowenter () (setf *calm-state-mouse-inside-window* t *calm-redraw* t) (when (fboundp 'on-windowenter) (on-windowenter))) (defun internal-on-windowleave () (setf *calm-state-mouse-inside-window* nil *calm-redraw* t) (when (fboundp 'on-windowleave) (on-windowleave)))
2,809
Common Lisp
.lisp
79
31.708861
87
0.688073
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
2cb831fed369983f08d4169e4c67bd622c920825db34d71994c97dbd7af07992
2,203
[ -1 ]
2,204
cairo.lisp
VitoVan_calm/src/cairo.lisp
(in-package #:cl-cairo2) (cffi:defcfun ("cairo_ft_font_face_create_for_pattern" cairo_ft_font_face_create_for_pattern) :pointer (pattern :pointer)) (define-flexible (select-font-face-fc pointer family slant weight) (let ((pattern (fontconfig:fc-create-pattern))) (fontconfig:fc-pattern-add-string pattern "family" family) (fontconfig:fc-pattern-add-integer pattern "slant" (fontconfig:maybe-enum 'fontconfig:slant slant)) (fontconfig:fc-pattern-add-integer pattern "weight" (fontconfig:maybe-enum 'fontconfig:weight weight)) (let ((font-face (cairo_ft_font_face_create_for_pattern pattern))) (cairo_set_font_face pointer font-face) (cairo_font_face_destroy font-face)) (fontconfig:destroy-pattern pattern)))
746
Common Lisp
.lisp
12
58
106
0.75
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
41ea03415a49ad1d44c8a7e0143346a5cc5af7d32aacfb1ccb529f934123faca
2,204
[ -1 ]
2,205
c.lisp
VitoVan_calm/src/c.lisp
(in-package #:c) ;; ;; cairo state ;; (defmacro with-state (&body body) `(progn (c:save) ,@body (c:restore))) ;; ;; drawing ;; (defun rrectangle (x y width height &key (radius 8)) "rounded rectangle" (let ((degrees (/ pi 180))) (c:new-sub-path) (c:arc (- (+ x width) radius) (+ y radius) radius (* -90 degrees) (* 0 degrees)) (c:arc (- (+ x width) radius) (- (+ y height) radius) radius (* 0 degrees) (* 90 degrees)) (c:arc (+ x radius) (- (+ y height) radius) radius (* 90 degrees) (* 180 degrees)) (c:arc (+ x radius) (+ y radius) radius (* 180 degrees) (* 270 degrees)) (c:close-path))) (defun show-png (pathname x y width height) (with-state (let* ((png-pathname #+jscl (concatenate 'string "/usr/share/" pathname) ;; /usr/share/assets/ will be embedded #-jscl (or (uiop:absolute-pathname-p pathname) (uiop:merge-pathnames* pathname (uiop:getenv "CALM_APP_DIR")))) (surface (c:image-surface-create-from-png png-pathname)) (img-width (c:image-surface-get-width surface)) (img-height (c:image-surface-get-height surface)) (x-multiplier (/ width img-width)) (y-multiplier (/ height img-height))) (format t "showing png: ~A surface: ~A w:~A iw:~A~%" png-pathname surface width img-width) (c:move-to x y) (c:rectangle x y width height) (when (and (<= x-multiplier 1) (<= y-multiplier 1)) ;; (format t "~A~%" z) (c:scale x-multiplier y-multiplier) (c:translate (* (/ (- 1 x-multiplier) x-multiplier) x) (* (/ (- 1 y-multiplier) y-multiplier) y))) (c:set-source-surface surface x y) (c:fill-path)))) ;; ;; text utilities ;; #-jscl (defun escape-char (char s) "char escaping for pango-markup" (case char (#\< (write-string "&lt;" s)) (#\> (write-string "&gt;" s)) (#\& (write-string "&amp;" s)) (#\' (write-string "&#39;" s)) (T (write-char char s)))) #-jscl (defun escape-string (string) "string escaping for Pango Markup" (with-output-to-string (o) (loop for char across string do (escape-char char o)))) #-jscl (defun markup->layout (markup &key (font-size calm::*calm-default-font-size*) (width calm::*calm-window-width*) (height calm::*calm-window-height*) (align :left) (ellipsize :end) (cr cl-cairo2:*context*)) (let* ((ns-pango (gir:require-namespace "Pango")) (ns-pango-cairo (gir:require-namespace "PangoCairo")) (font-desc (gir:invoke (ns-pango "FontDescription" 'new))) (layout (gir:invoke (ns-pango-cairo 'create_layout) (slot-value cr 'cairo:pointer)))) (gir:invoke (font-desc 'set_family) calm::*calm-default-font-family*) (gir:invoke (font-desc 'set_weight) (gir:nget ns-pango "Weight" :normal)) (gir:invoke (font-desc 'set_absolute_size) (coerce (* font-size (gir:nget ns-pango "SCALE")) 'double-float)) (gir:invoke (layout 'set_font_description) font-desc) (gir:invoke (layout 'set_width) (if (= width -1) -1 (gir:invoke (ns-pango 'units_from_double) (coerce width 'double-float)))) (gir:invoke (layout 'set_height) (if (= height -1) -1 (gir:invoke (ns-pango 'units_from_double) (coerce height 'double-float)))) (gir:invoke (layout 'set_markup) markup -1) (gir:invoke (layout 'set_ellipsize) (gir:nget ns-pango "EllipsizeMode" ellipsize)) (gir:invoke (layout 'set_alignment) (gir:nget ns-pango "Alignment" align)) (multiple-value-bind (_ w h) (gir:invoke (layout 'get_pixel_size)) (declare (ignore _)) (values layout w h)))) #-jscl (defun show-layout (layout &key (cr cl-cairo2:*context*)) "show Pango Layout" (let ((ns-pango-cairo (gir:require-namespace "PangoCairo"))) (gir:invoke (ns-pango-cairo 'show_layout) (slot-value cr 'cairo:pointer) layout))) #-jscl (defun show-markup (markup &key (font-size calm::*calm-default-font-size*) (width calm::*calm-window-width*) (height calm::*calm-window-height*) (align :left) (ellipsize :end) (cr cl-cairo2:*context*)) "show Pango Markup" (multiple-value-bind (layout w h) (markup->layout markup :font-size font-size :width width :height height :align align :ellipsize ellipsize :cr cr) (declare (ignore w h)) (show-layout layout :cr cr))) (defun open-audio-if-not-yet () (when (and (not calm::*calm-state-audio-open*) ;; not opened yet #-jscl (null (uiop:getenv "CI")) ;; not CI ) ;; ;; if we put the following code outside of this function, ;; it will open-audio right after the library is loaded, ;; which will cause problem for save-lisp-and-die ;; ;; init is optional ;; https://wiki.libsdl.org/SDL2_mixer/Mix_Init ;; (sdl2-mixer:init) #+jscl (#j:_Mix_OpenAudio calm::*calm-audio-frequency* calm::*calm-audio-format* calm::*calm-audio-channels* calm::*calm-audio-chunksize*) #-jscl (sdl2-mixer:open-audio calm::*calm-audio-frequency* calm::*calm-audio-format* ;; channels: number of channels (1 is mono, 2 is stereo, etc). calm::*calm-audio-channels* calm::*calm-audio-chunksize*) #+jscl (#j:_Mix_AllocateChannels calm::*calm-audio-numchans*) #-jscl (sdl2-mixer:allocate-channels calm::*calm-audio-numchans*) (setf calm::*calm-state-audio-open* t)) calm::*calm-state-audio-open*) (defun play-music (pathname &key (loops 0)) ;; (format t "playing music: ~A~%" pathname) (when (open-audio-if-not-yet) (let* ((music-pathname #+jscl (concatenate 'string "/usr/share/" pathname) ;; /usr/share/assets/ will be embedded #-jscl (or (uiop:absolute-pathname-p pathname) (uiop:merge-pathnames* pathname (uiop:getenv "CALM_APP_DIR")))) (music-object-cache (cdr (assoc music-pathname calm::*calm-state-loaded-audio* #+jscl :test #+jscl #'string=))) (music-object (or music-object-cache #+jscl (let ((music-pathname-ptr (#j:allocateUTF8 music-pathname))) (prog1 (#j:_Mix_LoadMUS music-pathname-ptr) (#j:_free music-pathname-ptr))) #-jscl (sdl2-mixer:load-music music-pathname)))) (unless music-object-cache (push (cons music-pathname music-object) calm::*calm-state-loaded-audio*)) #+jscl (#j:_Mix_PlayMusic music-object loops) #-jscl (sdl2-mixer:play-music music-object loops)))) (defun play-wav (pathname &key (loops 0) (channel -1)) ;; (format t "playing wav: ~A~%" pathname) (when (open-audio-if-not-yet) (let* ((wav-pathname #+jscl (concatenate 'string "/usr/share/" pathname) ;; /usr/share/assets/ will be embedded #-jscl (or (uiop:absolute-pathname-p pathname) (uiop:merge-pathnames* pathname (uiop:getenv "CALM_APP_DIR")))) (wav-object-cache (cdr (assoc wav-pathname calm::*calm-state-loaded-audio* #+jscl :test #+jscl #'string=))) (wav-object (or wav-object-cache #+jscl (let* ((wav-pathname-allocated-ptr (#j:allocateUTF8 wav-pathname)) (rb-allocated-ptr (#j:allocateUTF8 "rb")) (rwops (#j:_SDL_RWFromFile wav-pathname-allocated-ptr rb-allocated-ptr)) (spec (#j:_Mix_LoadWAV_RW rwops 1 nil nil nil))) (#j:_free wav-pathname-allocated-ptr) (#j:_free rb-allocated-ptr) spec) #-jscl (sdl2-mixer:load-wav wav-pathname)))) (unless wav-object-cache (push (cons wav-pathname wav-object) calm::*calm-state-loaded-audio*)) ;; only play when there is/are available channel(s) (when (< (playing) calm::*calm-audio-numchans*) #+jscl (#j:_Mix_PlayChannelTimed channel wav-object loops -1) #-jscl (sdl2-mixer:play-channel channel wav-object loops))))) #+jscl (defun play-audio (audio-url &key (loop-audio-p nil) (volume 1)) ;; (format t "playing audio: ~A~%" audio-url) (let* ((audio-object-cache (cdr (assoc audio-url calm::*calm-state-loaded-audio* :test #'string=))) (audio-object (or audio-object-cache ;; https://github.com/jscl-project/jscl/wiki/JSCL-and-manipulations-with-JS-objects (#j:window:eval (concatenate 'string "new Audio('" audio-url "')")) ))) (unless audio-object-cache (push (cons audio-url audio-object) calm::*calm-state-loaded-audio*)) (when loop-audio-p (setf (jscl::oget audio-object "loop") t)) (setf (jscl::oget audio-object "volume") volume) ((jscl::oget audio-object "play")))) (defun playing () #+jscl (#j:_Mix_Playing -1) #-jscl (sdl2-mixer:playing -1)) (defun volume-music (music-volume) #+jscl (#j:_Mix_VolumeMusic music-volume) #-jscl (sdl2-mixer:volume-music music-volume)) (defun volume-wav (wav-volume &key (channel -1)) #+jscl (#j:_Mix_Volume channel wav-volume) #-jscl (sdl2-mixer:volume channel wav-volume)) (defun halt-music () #+jscl (#j:_Mix_HaltMusic) #-jscl (sdl2-mixer:halt-music)) (defun halt-wav (&optional (channel -1)) #+jscl (#j:_Mix_HaltChannel channel) #-jscl (sdl2-mixer:halt-channel channel)) #+jscl (defun halt-audio (&optional (url nil)) (loop for object in calm::*calm-state-loaded-audio* when (or (null url) (string= (car object) url)) do (format t "halting: ~A~%" object) ((jscl::oget (cdr object) "pause")))) (defun get-ticks () #+jscl (#j:_SDL_GetTicks) #-jscl (sdl2:get-ticks)) #+jscl (eval-when (:compile-toplevel) (ql:quickload "sdl2")) (defmacro keq (key &rest scancodes) "Key Event in JSCL + WebAssembly returns scancode value, since it has to be primitive values. But on desktop, we use SCANCODE directly, so here is a macro to unify this behaviour. " (let ((scancode-value-list (mapcar #'sdl2:scancode-key-to-value scancodes))) `(member ,key (if (keywordp ,key) ',scancodes ',scancode-value-list)))) (defun select-font-family (family slant weight) #+jscl (c:select-font-face family slant weight) #-jscl (cl-cairo2::select-font-face-fc family slant weight))
11,190
Common Lisp
.lisp
268
32.481343
112
0.574183
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
14777ac6067ccfc3d2c545249360b36a64fadfe19bdd5cd60e87a25b38307209
2,205
[ -1 ]
2,206
config.lisp
VitoVan_calm/src/config.lisp
(in-package :calm) ;; init config (defparameter *calm-window* nil) #-jscl (defparameter *calm-window-x* :centered) #-jscl (defparameter *calm-window-y* :centered) (defparameter *calm-window-width* 600) (defparameter *calm-window-height* 150) (defparameter *calm-window-title* "CALM") #-jscl (defparameter *calm-window-flags* '(:shown :allow-highdpi)) #-jscl (defparameter *calm-renderer-flags* '(:accelerated :presentvsync)) #-jscl (defparameter *calm-default-font-size* 80) #-jscl (defparameter *calm-default-font-family* "Arial") ;; debug variable (defparameter *calm-debug-variable-a* nil) (defparameter *calm-debug-variable-b* nil) (defparameter *calm-debug-variable-c* nil) ;; ;; use OpenGL on Linux to avoid weird window flashing: (like it was closed and then opened again) ;; #+(and linux (not jscl)) (push :opengl *calm-window-flags*) #-jscl (defparameter *calm-delay* 42) #+jscl (defparameter *calm-fps* 42) (defparameter *calm-redraw* t "The canvas will be painted again and again by calling the `draw' function, setting it to `NIL' means you don't want the canvas to be painted again, setting it back to `t' will paint the canvas again and again by calling the `draw' function, again. ") #-jscl (defparameter *calm-audio-format* sdl2-ffi:+audio-s32sys+) #+jscl (defparameter *calm-audio-format* 32800) (defparameter *calm-audio-frequency* 44100) (defparameter *calm-audio-channels* 2) ;; ;; chunksize: audio buffer size in sample FRAMES (total samples divided by channel count). ;; I thought it should be: (* calm::*calm-audio-channels* calm::*calm-audio-frequency*) ;; but, it was delayed, I have to set it to `1024' according to this: ;; https://stackoverflow.com/questions/983997/i-have-an-unintended-delay-in-playing-a-mix-chunk #-jscl (defparameter *calm-audio-chunksize* 1024) ;; but, when it is on the browser, ;; I have to set it to a very large value to make things a little more smooth, ;; it still suffers some wierd noises sometimes. ;; I don't know why, please enlight me if you know something about this #+jscl (defparameter *calm-audio-chunksize* (* 4 1024)) ;; the number of channels (defparameter *calm-audio-numchans* 8) ;; runtime variables (defparameter *calm-state-mouse-inside-window* nil) (defparameter *calm-state-mouse-x* 0) (defparameter *calm-state-mouse-y* 0) (defparameter *calm-state-mouse-up* nil) (defparameter *calm-state-mouse-down* nil) (defparameter *calm-state-mouse-just-clicked* nil) (defparameter *calm-state-finger-x* 0) (defparameter *calm-state-finger-y* 0) (defparameter *calm-state-finger-just-tapped* nil) (defparameter *calm-state-audio-open* nil) (defparameter *calm-state-loaded-audio* nil) ;; env #-jscl (defparameter *calm-env-calm-home* nil) #-jscl (defparameter *calm-env-calm-cmd* nil) #-jscl (defparameter *calm-env-app-dir* nil) #-jscl (defparameter *calm-env-host-lisp* nil) (pushnew :calm *features*) #+jscl (defparameter *configured* nil) #+jscl (defun jscl-draw () (unless *configured* ;; this has to be called in jscl-draw, since by then the wasm has finally initialised. (let ((title-ptr (#j:allocateUTF8 *calm-window-title*))) (#j:_config title-ptr) (#j:_free title-ptr)) (setf *configured* t)) ;; draw something (internal-draw)) #-jscl (defun calm-config () (setf *calm-env-calm-home* (uiop:getenv "CALM_HOME") *calm-env-app-dir* (uiop:getenv "CALM_APP_DIR") *calm-env-calm-cmd* (uiop:getenv "CALM_CMD") *calm-env-host-lisp* (uiop:getenv "CALM_HOST_LISP")) ;; ;; for macOS bundled CALM Application (not CALM itself) ;; ;; on macOS, if the CALM_HOME env contains ".app/Contents/MacOS", ;; and the user launched through LaunchPad, ;; then CALM_APP_DIR won't be able to be set correctly, ;; since the `pwd` will be given as "/Users/jack/" instead of the real location, ;; so we should set CALM_APP_DIR to CALM_HOME ;; ;; but, we can't just detect this by `(str:contains? ".app/Contents/MacOS" (uiop:getenv "CALM_HOME"))` ;; because if we have packed CALM as an APP, then it will always find the canvas.lisp inside the app bundle, ;; instead of the current directory. ;; ;; so, let's check if calm.asd exists inside the app bundle, ;; and if it exists, then we will know it's CALM as an APP instead of an application made with CALM. (when (and ;; why `featurep' instead of `#+darwin'? ;; track: https://github.com/jscl-project/jscl/issues/475 (uiop:featurep :darwin) (str:contains? ".app/Contents/MacOS" (namestring *calm-env-calm-home*)) (not (probe-file (merge-pathnames "calm.asd" *calm-env-calm-home*)))) (setf (uiop:getenv "CALM_APP_DIR") *calm-env-calm-home* *calm-env-app-dir* *calm-env-calm-home*)) ;; ;; for CALM itself ;; to know if CALM has already successfully started once ;; ;; touch file: .calm-initialised (when (and (not (probe-file ".calm-initialised")) (probe-file "calm.asd")) (u:touch-file ".calm-initialised") (format t "~A~%" "CALM initialised successfully.")) ;; ;; config libs ;; (setf cffi:*foreign-library-directories* nil) (pushnew (merge-pathnames "lib/" *calm-env-calm-home*) cffi:*foreign-library-directories*) ;; ;; config gir typelib ;; (gir:repository-prepend-search-path (uiop:native-namestring (merge-pathnames "lib/" *calm-env-calm-home*))) ;; ;; DPI awareness ;; https://github.com/libsdl-org/SDL/pull/5778 (setf (uiop:getenv "SDL_WINDOWS_DPI_SCALING") "1") ;; let pango use fontconfig to get cross-platform font loading support (setf (uiop:getenv "PANGOCAIRO_BACKEND") "fontconfig") ;; ;; set fontconfig config ;; (setf (uiop:getenv "FONTCONFIG_PATH") (uiop:native-namestring (merge-pathnames "fonts/" *calm-env-app-dir*))) (let ((app-fonts-conf (merge-pathnames "fonts/fonts.conf" *calm-env-app-dir*)) (calm-fonts-conf (merge-pathnames "s/usr/all/fonts.conf" *calm-env-calm-home*))) ;; ;; this is only needed by fontconfig @ fedora-32: ;; https://bodhi.fedoraproject.org/updates/?search=fontconfig&releases=F32 ;; when a non-exist fonts.conf was set, something weird will happen: ;; like text was stretched ;; ;; why using granny's fedora? ;; because we want to lower the glibc dependency ;; https://github.com/AppImage/appimage.github.io/pull/3166 ;; Ubuntu 20.04 LTS with GLIBC_2.31 won't be died till 2030, so... ;; https://wiki.ubuntu.com/Releases (if (probe-file app-fonts-conf) ;; if there exists a fonts.conf inside app dir, use it (setf (uiop:getenv "FONTCONFIG_FILE") (uiop:native-namestring app-fonts-conf)) ;; if not, use CALM default (this won't be available in distribution mode, but anyway...) (setf (uiop:getenv "FONTCONFIG_FILE") (uiop:native-namestring calm-fonts-conf))) (format t "fontpath: ~A~%" (uiop:getenv "FONTCONFIG_PATH")) (format t "fontfile: ~A~%" (uiop:getenv "FONTCONFIG_FILE")) ;; https://www.freedesktop.org/software/fontconfig/fontconfig-user.html#DEBUG ;; (setf (uiop:getenv "FC_DEBUG") "1024") ;; reinit fc, if there exists fonts.conf (when (or (probe-file app-fonts-conf) (probe-file calm-fonts-conf)) (fontconfig:fc-init-reinitialize))) ) #+jscl (defun get-calm-redraw () *calm-redraw*) #+jscl (defun calm-config () (setf #j:draw #'jscl-draw) (when (fboundp 'think) (setf #j:think #'think)) (setf #j:get_calm_redraw #'get-calm-redraw) (setf #j:on_mousewheel #'internal-on-mousewheel) (setf #j:on_mousemotion #'(lambda (x y) (internal-on-mousemotion :x x :y y))) (setf #j:on_mousebuttonup #'(lambda (button x y clicks) (internal-on-mousebuttonup :button button :x x :y y :clicks clicks))) (setf #j:on_mousebuttondown #'(lambda (button x y clicks) (internal-on-mousebuttondown :button button :x x :y y :clicks clicks))) (setf #j:on_fingermotion #'(lambda (x y dx dy pressure finger-id) (internal-on-fingermotion :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (setf #j:on_fingerup #'(lambda (x y dx dy pressure finger-id) (internal-on-fingerup :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (setf #j:on_fingerdown #'(lambda (x y dx dy pressure finger-id) (internal-on-fingerdown :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id))) (setf #j:on_windowresized #'internal-on-windowresized) (setf #j:on_windowenter #'internal-on-windowenter) (setf #j:on_windowleave #'internal-on-windowleave) (setf #j:on_keydown #'internal-on-keydown) (setf #j:on_keyup #'internal-on-keyup) ;; create env (#j:window:eval "var JSCL_ENV = {};") (setf #j:JSCL_ENV:CALM_FPS *calm-fps*) (setf #j:JSCL_ENV:CALM_WINDOW_WIDTH *calm-window-width*) (setf #j:JSCL_ENV:CALM_WINDOW_HEIGHT *calm-window-height*) ;; https://experienceleague.adobe.com/docs/target/using/experiences/vec/mobile-viewports.html (if (or (<= #j:screen:width 800) (<= #j:screen:height 600)) ;; scale canvas on mobile device (let ((scale (write-to-string ;; track ;; https://github.com/jscl-project/jscl/issues/481 (/ *calm-window-width* #j:screen:width))) (#j:canvas (#j:document:getElementById "canvas"))) (setf #j:canvas:style:transformOrigin "center") (setf #j:canvas:style:transform (concatenate 'string "scale(" scale ")"))) ;; remove canvas scale (let ((#j:canvas (#j:document:getElementById "canvas"))) (setf #j:canvas:style:transformOrigin "unset") (setf #j:canvas:style:transform "unset"))) )
9,629
Common Lisp
.lisp
217
40.728111
142
0.696255
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
2b7ef260ace74c2ac6c09b671009b88ea579f1b8d64711a5f0be7c32f5ae6821
2,206
[ -1 ]
2,207
calm.lisp
VitoVan_calm/src/calm.lisp
(in-package :calm) #-jscl (defun calm-quit () (when *calm-state-audio-open* (sdl2-mixer:close-audio)) ;; on Linux & Windows, uiop:quit will hang a while ;; don't know why, fix it recklessly. (if (uiop:featurep :darwin) (uiop:quit) (uiop:quit 0 nil))) (defun internal-draw () "default drawing function, user should defun `draw'" (cond ((fboundp 'draw) (funcall 'draw) (setf *calm-redraw* nil)) ((fboundp 'draw-once) (funcall 'draw-once) (setf *calm-redraw* nil)) ((fboundp 'draw-forever) (funcall 'draw-forever)) (t (c:set-source-rgb (/ 12 255) (/ 55 255) (/ 132 255)) (c:paint) (c:set-source-rgb 1 1 1) (c:move-to 30 100) (c:set-font-size 84) (c:show-text "DON'T PANIC")))) (defun internal-think () "default thinking function, user should defun `think' You may not be drawing something, but you are always thinking." (when (fboundp 'think) (funcall 'think))) #-jscl (defun calm-init () (sdl2:with-init (:everything) (sdl2:with-window (calm-window :title *calm-window-title* :x *calm-window-x* :y *calm-window-y* :w *calm-window-width* :h *calm-window-height* :flags *calm-window-flags*) ;; make SDL2 Window variable available, ;; so we can call SDL2 Window related functions, ;; such as `sdl2-ffi.functions:sdl-set-window-always-on-top', `sdl2:get-window-position', etc. (setf *calm-window* calm-window) ;; window icon for Linux (let ((window-icon (str:concat (uiop:getenv "CALM_HOME") "build/app.png"))) ;; this file should only exist on Linux, it was copied by `s/usr/linux/appimage.lisp' (when (probe-file window-icon) (sdl2-ffi.functions:sdl-set-window-icon ;; on Wayland, this doesn't work, who should I blame? calm-window (sdl2-image:load-image window-icon)))) (sdl2:with-renderer (calm-renderer calm-window :flags *calm-renderer-flags*) (multiple-value-bind (calm-renderer-width calm-renderer-height) (sdl2:get-renderer-output-size calm-renderer) (let ((cairo-x-multiplier (/ calm-renderer-width *calm-window-width*)) (cairo-y-multiplier (/ calm-renderer-height *calm-window-height*)) (texture (sdl2:create-texture calm-renderer sdl2:+pixelformat-argb8888+ sdl2-ffi:+sdl-textureaccess-streaming+ calm-renderer-width calm-renderer-height))) (sdl2:with-event-loop (:method :poll) (:quit () (sdl2:destroy-texture texture) (calm-quit)) (:mousewheel (:x x :y y :direction direction) (internal-on-mousewheel x y direction)) (:textinput (:text text) (internal-on-textinput text)) (:textediting (:text text :start start :length length) (u:calm-log "~%TEXT-EDITING: ~A ~A ~A~%" text start length)) (:keydown (:keysym k :state s) (internal-on-keydown (sdl2:scancode k))) (:keyup (:keysym k :state s) (internal-on-keyup (sdl2:scancode k))) (:windowevent (:event e) (u:calm-log "SDL2 Window EVENT: ~A ~%" e) (cond ((equal e sdl2-ffi:+sdl-windowevent-minimized+) (setf *calm-redraw* nil)) ((equal e sdl2-ffi:+sdl-windowevent-hidden+) (setf *calm-redraw* nil)) ((equal e sdl2-ffi:+sdl-windowevent-restored+) (setf *calm-redraw* t)) ((equal e sdl2-ffi:+sdl-windowevent-shown+) (setf *calm-redraw* t)) ((equal e sdl2-ffi:+sdl-windowevent-enter+) (internal-on-windowenter)) ((equal e sdl2-ffi:+sdl-windowevent-leave+) (internal-on-windowleave)) ((equal e sdl2-ffi:+sdl-windowevent-resized+) (multiple-value-bind (new-window-width new-window-height) (sdl2:get-window-size calm-window) (internal-on-windowresized new-window-width new-window-height) (multiple-value-bind (new-renderer-width new-renderer-height) (sdl2:get-renderer-output-size calm-renderer) (let ((new-x-multiplier (/ new-renderer-width new-window-width)) (new-y-multiplier (/ new-renderer-height new-window-height)) (new-texture (sdl2:create-texture calm-renderer sdl2:+pixelformat-argb8888+ sdl2-ffi:+sdl-textureaccess-streaming+ new-renderer-width new-renderer-height))) (sdl2:destroy-texture texture) (setf calm-renderer-width new-renderer-width calm-renderer-height new-renderer-height cairo-x-multiplier new-x-multiplier cairo-y-multiplier new-y-multiplier texture new-texture))))) ((equal e sdl2-ffi:+sdl-windowevent-close+) (sdl2:destroy-texture texture) (calm-quit)))) (:mousemotion (:x x :y y) (internal-on-mousemotion :x x :y y)) (:mousebuttonup (:button button :x x :y y :clicks clicks) (internal-on-mousebuttonup :button button :x x :y y :clicks clicks)) (:mousebuttondown (:button button :x x :y y :clicks clicks) (internal-on-mousebuttondown :button button :x x :y y :clicks clicks)) (:fingermotion (:x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id) (internal-on-fingermotion :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id)) (:fingerup (:x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id) (internal-on-fingerup :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id)) (:fingerdown (:x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id) (internal-on-fingerdown :x x :y y :dx dx :dy dy :pressure pressure :finger-id finger-id)) (:idle () (internal-think) (when *calm-redraw* (unwind-protect (progn (sdl2:set-texture-blend-mode texture sdl2-ffi:+sdl-blendmode-blend+) (let* ((pixels-and-pitch (multiple-value-list (sdl2:lock-texture texture))) (cr-surface (c:create-image-surface-for-data (car pixels-and-pitch) :argb32 calm-renderer-width calm-renderer-height (cadr pixels-and-pitch))) (cr-context (c:create-context cr-surface))) (unwind-protect (progn (c:with-context (cr-context) ;; set current context (setf c:*context* cr-context) ;; set current surface (setf c:*surface* cr-surface) (c:scale cairo-x-multiplier cairo-y-multiplier) (c:set-antialias :BEST) (c:font-options-set-antialias (c:get-font-options) :CAIRO_ANTIALIAS_BEST) ;; default background (c:set-source-rgb 1 1 1) (c:paint) ;; default font size (c:set-font-size *calm-default-font-size*) ;; default font face (c:select-font-family *calm-default-font-family* :normal :normal) ;; default color (c:set-source-rgb 0 0 0) ;; default position (c:move-to 200 150) (internal-draw) )) (sdl2:unlock-texture texture) (sdl2:render-copy calm-renderer texture) (sdl2:render-present calm-renderer) (c:destroy cr-surface) (c:destroy cr-context)))))) (when *calm-delay* (sdl2:delay *calm-delay*)))))))))) #-jscl (defun calm-start () "Start the window" (calm::calm-config) (cond ((uiop:featurep :linux) (calm::calm-init)) ((uiop:featurep '(:or :darwin :win32)) (sdl2:make-this-thread-main #'calm::calm-init)) (t "unsupported system?"))) #-jscl (defun calm-load-and-start () "Load canvas.lisp and then start" (calm::calm-config) (let ((canvas-file (merge-pathnames "canvas.lisp" (uiop:getcwd)))) (if (probe-file canvas-file) (load canvas-file) (u:calm-log "canvas.lisp NOT FOUND: ~A~%" canvas-file))) (cond ((uiop:featurep :linux) (calm::calm-init)) ((uiop:featurep '(:or :darwin :win32)) (sdl2:make-this-thread-main #'calm::calm-init)) (t "unsupported system?")))
10,326
Common Lisp
.lisp
172
38.215116
174
0.481313
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
5440da95d609969fd986f3bd02f6451330ea788ae2d191aa1fdbcf54b28c3e97
2,207
[ -1 ]
2,208
package.lisp
VitoVan_calm/src/web/package.lisp
(defpackage :common-lisp-user) (defpackage :c ;; we do not need to write all those exports again and again, ;; but something seem to be not feasible in JSCL. ;; track: https://github.com/jscl-project/jscl/issues/471 ;; so for now, I have to write exports in the defpackage again (:use cl) (:export ;; cairo_t :create :reference :destroy :status :save :restore :get-target :push-group :push-group-with-content :pop-group :pop-group-to-source :get-group-target :set-source-rgb :set-source-rgba :set-source :set-source-surface :get-source :set-antialias :get-antialias :set-dash :get-dash-count :get-dash :set-fill-rule :get-fill-rule :set-line-cap :get-line-cap :set-line-join :get-line-join :set-line-width :get-line-width :set-miter-limit :get-miter-limit :set-operator :get-operator :set-tolerance :get-tolerance :clip :clip-preserve :clip-extents :in-clip :reset-clip :rectangle-list-destroy :copy-clip-rectangle-list :fill-path :fill-preserve :fill-extents :in-fill :mask :mask-surface :paint :paint-with-alpha :stroke :stroke-preserve :stroke-extents :in-stroke :copy-page :show-page :get-reference-count :set-user-data :get-user-data ;; paths :copy-path :copy-path-flat :path-destroy :append-path :has-current-point :get-current-point :new-path :new-sub-path :close-path :arc :arc-negative :curve-to :line-to :move-to :rectangle :glyph-path :text-path :rel-curve-to :rel-line-to :rel-move-to :path-extents ;; transformations :translate :scale :rotate :transform :set-matrix :get-matrix :identity-matrix :user-to-device :user-to-device-distance :device-to-user :device-to-user-distance ;; text :select-font-face :set-font-size :set-font-matrix :get-font-matrix :set-font-options :get-font-options :set-font-face :get-font-face :set-scaled-font :get-scaled-font :show-text :show-glyphs :show-text-glyphs :font-extents :text-extents :glyph-extents :toy-font-face-create :toy-font-face-get-family :toy-font-face-get-slant :toy-font-face-get-weight :glyph-allocate :glyph-free :text-cluster-allocate :text-cluster-free :image-surface-create-from-png :image-surface-get-width :image-surface-get-height :defcairo :rrectangle :open-audio-if-not-yet :playing :play-music :play-wav :play-audio :halt-music :halt-wav :halt-audio :volume-wav :volume-music :get-ticks :keq :show-png :select-font-family :with-state )) (defpackage :calm (:use cl) (:export :draw :_draw :config ))
2,837
Common Lisp
.lisp
156
14.198718
64
0.670668
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
dbc977a5b25bbee85537da4d1363320af614092bede7e4864152a2a6da589bd1
2,208
[ -1 ]
2,209
cairo.lisp
VitoVan_calm/src/web/cairo.lisp
(in-package :c) ;; ;; c enums ;; copied from https://github.com/rpav/cl-cairo2/blob/master/src/tables.lisp ;; (defmacro exporting-table (name definition) `(progn (defparameter ,name ,definition) (export ',name))) (exporting-table table-format '((:CAIRO_FORMAT_ARGB32 . :argb32) (:CAIRO_FORMAT_RGB24 . :rgb24) (:CAIRO_FORMAT_A8 . :a8) (:CAIRO_FORMAT_A1 . :a1) (:CAIRO_FORMAT_RGB16_565 . :rgb16_565) (:CAIRO_FORMAT_RGB30 . :rgb30))) (exporting-table table-antialias '((:CAIRO_ANTIALIAS_DEFAULT . :default) (:CAIRO_ANTIALIAS_NONE . :none) (:CAIRO_ANTIALIAS_GRAY . :gray) (:CAIRO_ANTIALIAS_SUBPIXEL . :subpixel) (:CAIRO_ANTIALIAS_FAST . :fast) (:CAIRO_ANTIALIAS_GOOD . :good) (:CAIRO_ANTIALIAS_BEST . :best))) (exporting-table table-fill-rule '((:CAIRO_FILL_RULE_WINDING . :winding) (:CAIRO_FILL_RULE_EVEN_ODD . :odd))) (exporting-table table-line-cap '((:CAIRO_LINE_CAP_BUTT . :butt) (:CAIRO_LINE_CAP_ROUND . :round) (:CAIRO_LINE_CAP_SQUARE . :square))) (exporting-table table-line-join '((:CAIRO_LINE_JOIN_MITER . :miter) (:CAIRO_LINE_JOIN_ROUND . :round) (:CAIRO_LINE_JOIN_BEVEL . :bevel))) (exporting-table table-operator '((:CAIRO_OPERATOR_CLEAR . :clear) (:CAIRO_OPERATOR_SOURCE . :source) (:CAIRO_OPERATOR_OVER . :over) (:CAIRO_OPERATOR_IN . :in) (:CAIRO_OPERATOR_OUT . :out) (:CAIRO_OPERATOR_ATOP . :atop) (:CAIRO_OPERATOR_DEST . :dest) (:CAIRO_OPERATOR_DEST_OVER . :dest-over) (:CAIRO_OPERATOR_DEST_IN . :dest-in) (:CAIRO_OPERATOR_DEST_OUT . :dest-out) (:CAIRO_OPERATOR_DEST_ATOP . :dest-atop) (:CAIRO_OPERATOR_XOR . :xor) (:CAIRO_OPERATOR_ADD . :add) (:CAIRO_OPERATOR_SATURATE . :saturate) (:CAIRO_OPERATOR_MULTIPLY . :multiply) (:CAIRO_OPERATOR_SCREEN . :screen) (:CAIRO_OPERATOR_OVERLAY . :overlay) (:CAIRO_OPERATOR_DARKEN . :darken) (:CAIRO_OPERATOR_LIGHTEN . :lighten) (:CAIRO_OPERATOR_COLOR_DODGE . :dodge) (:CAIRO_OPERATOR_COLOR_BURN . :burn) (:CAIRO_OPERATOR_HARD_LIGHT . :hard-light) (:CAIRO_OPERATOR_SOFT_LIGHT . :soft-light) (:CAIRO_OPERATOR_DIFFERENCE . :difference) (:CAIRO_OPERATOR_EXCLUSION . :exclusion) (:CAIRO_OPERATOR_HSL_HUE . :hue) (:CAIRO_OPERATOR_HSL_SATURATION . :saturation) (:CAIRO_OPERATOR_HSL_COLOR . :color) (:CAIRO_OPERATOR_HSL_LUMINOSITY . :luminosity))) (exporting-table table-font-slant '((:CAIRO_FONT_SLANT_NORMAL . :normal) (:CAIRO_FONT_SLANT_ITALIC . :italic) (:CAIRO_FONT_SLANT_OBLIQUE . :oblique))) (exporting-table table-font-weight '((:CAIRO_FONT_WEIGHT_NORMAL . :normal) (:CAIRO_FONT_WEIGHT_BOLD . :bold))) (exporting-table table-subpixel-order '((:CAIRO_SUBPIXEL_ORDER_DEFAULT . :default) (:CAIRO_SUBPIXEL_ORDER_RGB . :rgb) (:CAIRO_SUBPIXEL_ORDER_BGR . :bgr) (:CAIRO_SUBPIXEL_ORDER_VRGB . :vrgb) (:CAIRO_SUBPIXEL_ORDER_VBGR . :vbgr))) (exporting-table table-hint-style '((:CAIRO_HINT_STYLE_DEFAULT . :default) (:CAIRO_HINT_STYLE_NONE . :none) (:CAIRO_HINT_STYLE_SLIGHT . :slight) (:CAIRO_HINT_STYLE_MEDIUM . :medium) (:CAIRO_HINT_STYLE_FULL . :full))) (exporting-table table-hint-metrics '((:CAIRO_HINT_METRICS_DEFAULT . :default) (:CAIRO_HINT_METRICS_OFF . :off) (:CAIRO_HINT_METRICS_ON . :on))) (exporting-table table-status '((:CAIRO_STATUS_SUCCESS . :success) (:CAIRO_STATUS_NO_MEMORY . :no-memory) (:CAIRO_STATUS_INVALID_RESTORE . :invalid-restore) (:CAIRO_STATUS_INVALID_POP_GROUP . :invalid-pop-group) (:CAIRO_STATUS_NO_CURRENT_POINT . :no-current-point) (:CAIRO_STATUS_INVALID_MATRIX . :invalid-matrix) (:CAIRO_STATUS_INVALID_STATUS . :invalid-status) (:CAIRO_STATUS_NULL_POINTER . :null-pointer) (:CAIRO_STATUS_INVALID_STRING . :invalid-string) (:CAIRO_STATUS_INVALID_PATH_DATA . :invalid-path-data) (:CAIRO_STATUS_READ_ERROR . :read-error) (:CAIRO_STATUS_WRITE_ERROR . :write-error) (:CAIRO_STATUS_SURFACE_FINISHED . :surface-finished) (:CAIRO_STATUS_SURFACE_TYPE_MISMATCH . :surface-type-mismatch) (:CAIRO_STATUS_PATTERN_TYPE_MISMATCH . :pattern-type-mismatch) (:CAIRO_STATUS_INVALID_CONTENT . :invalid-content) (:CAIRO_STATUS_INVALID_FORMAT . :invalid-format) (:CAIRO_STATUS_INVALID_VISUAL . :invalid-visual) (:CAIRO_STATUS_FILE_NOT_FOUND . :file-not-found) (:CAIRO_STATUS_INVALID_DASH . :invalid-dash) (:CAIRO_STATUS_INVALID_DSC_COMMENT . :invalid-dsc-comment) (:CAIRO_STATUS_INVALID_INDEX . :invalid-index) (:CAIRO_STATUS_CLIP_NOT_REPRESENTABLE . :clip-not-representable) (:CAIRO_STATUS_TEMP_FILE_ERROR . :temp-file-error) (:CAIRO_STATUS_INVALID_STRIDE . :invalid-stride) (:CAIRO_STATUS_FONT_TYPE_MISMATCH . :font-type-mismatch) (:CAIRO_STATUS_USER_FONT_IMMUTABLE . :user-font-immutable) (:CAIRO_STATUS_USER_FONT_ERROR . :user-font-error) (:CAIRO_STATUS_NEGATIVE_COUNT . :negative-count) (:CAIRO_STATUS_INVALID_CLUSTERS . :invalid-clusters) (:CAIRO_STATUS_INVALID_SLANT . :invalid-slant) (:CAIRO_STATUS_INVALID_WEIGHT . :invalid-weight) (:CAIRO_STATUS_INVALID_SIZE . :invalid-size) (:CAIRO_STATUS_USER_FONT_NOT_IMPLEMENTED . :user-font-not-implemented) (:CAIRO_STATUS_DEVICE_TYPE_MISMATCH . :device-type-mismatch) (:CAIRO_STATUS_DEVICE_ERROR . :device-error) (:CAIRO_STATUS_INVALID_MESH_CONSTRUCTION . :invalid-mesh-construction) (:CAIRO_STATUS_DEVICE_FINISHED . :device-finished) (:CAIRO_STATUS_LAST_STATUS . :last-status))) (exporting-table table-pattern-type '((:CAIRO_PATTERN_TYPE_SOLID . :solid) (:CAIRO_PATTERN_TYPE_SURFACE . :surface) (:CAIRO_PATTERN_TYPE_LINEAR . :linear) (:CAIRO_PATTERN_TYPE_RADIAL . :radial))) (exporting-table table-extend '((:CAIRO_EXTEND_NONE . :none) (:CAIRO_EXTEND_REPEAT . :repeat) (:CAIRO_EXTEND_REFLECT . :reflect) (:CAIRO_EXTEND_PAD . :pad))) (exporting-table table-filter '((:CAIRO_FILTER_FAST . :fast) (:CAIRO_FILTER_GOOD . :good) (:CAIRO_FILTER_BEST . :best) (:CAIRO_FILTER_NEAREST . :nearest) (:CAIRO_FILTER_BILINEAR . :bilinear) (:CAIRO_FILTER_GAUSSIAN . :gaussian))) (exporting-table table-content '((:cairo_content_color . :color) (:cairo_content_alpha . :alpha) (:cairo_content_color_alpha . :color-alpha))) (defun lookup-cairo-enum (cairo-enum table) (let ((enum (cdr (assoc cairo-enum table)))) (unless enum (error "Could not find cairo-enum ~a in ~a." cairo-enum table)) enum)) (defun lookup-enum (enum table) (let ((cairo-enum (car (rassoc enum table)))) (unless cairo-enum (error "Could not find enum ~a in ~a." enum table)) cairo-enum)) ;; copy ended here ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; init wasm functions ;; (defun calljs (func-name &rest args) (let* ((allocated-string-pointers nil) (args-with-string-pointers (mapcar (lambda (x) (if (stringp x) (let ((string-pointer (#j:allocateUTF8 x))) (push string-pointer allocated-string-pointers) string-pointer) x)) args))) ;; (format t "Calling ~A with args: ~A, args-with-string-pointers: ~A~%" func-name args args-with-string-pointers) (prog1 (apply (jscl::oget jscl::*root* func-name) args-with-string-pointers) (mapcar #j:_free allocated-string-pointers)))) (defun calljs-cairo-with-raw-args (func-name with-cairo-ptr raw-args &rest runtime-args) (loop for arg in raw-args for i = 0 then (incf i) ;; extra `when' for JSCL: Uncaught Error: CAR called on non-list argument for name = (when (listp arg) (first arg)) ;; extra `when' for JSCL: Uncaught Error: CAR called on non-list argument for table = (when (listp arg) (symbol-value (second arg))) for var = (nth i runtime-args) when (listp arg) do (setf (nth i runtime-args) (lookup-enum-value var table)) ) (if with-cairo-ptr (apply #'calljs (concatenate 'list (list func-name (jscl::oget jscl::*root* "_cr")) runtime-args)) (apply #'calljs (concatenate 'list (list func-name) runtime-args)))) (defmacro defcairo (name &rest args) `(defcairo-raw ,name t nil ,@args)) (defmacro defcairo-raw (name with-cairo-ptr result-parser &rest args) "e.g., no enum: (defcairo set-antialias antialias) call: (set-antialias 6) with enum (defcairo set-antialias (antialias table-antialias)) call: (set-antialias :best) https://www.cairographics.org/manual/cairo-cairo-t.html#cairo-antialias-t with or without custom Lisp function name: (defcairo set-source-rgba red green blue alpha) (defcairo (set-source-rgba my-set-source-rgba) red green blue alpha) " (let* ((js-func-name (concatenate 'string "_cairo_" (substitute #\_ #\- (string-downcase (write-to-string (if (listp name) (first name) name)))))) (lisp-func-name (if (listp name) (second name) name)) (args-without-enum-table (mapcar (lambda (x) (if (listp x) (first x) x)) args))) (if result-parser `(progn (defun ,lisp-func-name ,args-without-enum-table ;; (format t "lisp-func-name ~A, args-without-enum-table ~A~%" ',lisp-func-name ',args-without-enum-table) (funcall ,result-parser (calljs-cairo-with-raw-args ,js-func-name ,with-cairo-ptr ',args ,@args-without-enum-table))) (export ',lisp-func-name)) `(progn (defun ,lisp-func-name ,args-without-enum-table ;; (format t "lisp-func-name ~A, args-without-enum-table ~A~%" ',lisp-func-name ',args-without-enum-table) (calljs-cairo-with-raw-args ,js-func-name ,with-cairo-ptr ',args ,@args-without-enum-table)) (export ',lisp-func-name)) ))) ;; cairo_t ;; https://www.cairographics.org/manual/cairo-cairo-t.html (defcairo create target) (defcairo reference) (defcairo destroy) (defcairo status) (defcairo save) (defcairo restore) (defcairo get-target) (defcairo push-group) (defcairo push-group-with-content content) (defcairo pop-group) (defcairo pop-group-to-source) (defcairo get-group-target) (defcairo set-source-rgb red green blue) (defcairo set-source-rgba red green blue alpha) (defcairo set-source source) (defcairo set-source-surface surface x y) (defcairo get-source) (defcairo set-antialias (antialias table-antialias)) (defcairo get-antialias) (defcairo set-dash const dashes int num-dashes offset) (defcairo get-dash-count) (defcairo get-dash dashes offset) (defcairo set-fill-rule (fill-rule table-fill-rule)) (defcairo get-fill-rule) (defcairo set-line-cap (line-cap table-line-cap)) (defcairo get-line-cap) (defcairo set-line-join (line-join table-line-join)) (defcairo get-line-join) (defcairo set-line-width width) (defcairo get-line-width) (defcairo set-miter-limit limit) (defcairo get-miter-limit) (defcairo set-operator (op table-operator)) (defcairo get-operator) (defcairo set-tolerance tolerance) (defcairo get-tolerance) (defcairo clip) (defcairo clip-preserve) (defcairo clip-extents x1 y1 x2 y2) (defcairo in-clip x y) (defcairo reset-clip) (defcairo rectangle-list-destroy rectangle-list) (defcairo copy-clip-rectangle-list) (defcairo (fill fill-path)) (defcairo fill-preserve) (defcairo fill-extents x1 y1 x2 y2) (defcairo-raw in-fill t #'(lambda (x) (not (zerop x))) x y) (defcairo mask pattern) (defcairo mask-surface surface surface-x surface-y) (defcairo paint) (defcairo paint-with-alpha alpha) (defcairo stroke) (defcairo stroke-preserve) (defcairo stroke-extents x1 y1 x2 y2) (defcairo in-stroke x y) (defcairo copy-page) (defcairo show-page) (defcairo get-reference-count) (defcairo set-user-data destroy) (defcairo get-user-data key) ;; paths ;; https://www.cairographics.org/manual/cairo-Paths.html (defcairo copy-path) (defcairo copy-path-flat) (defcairo path-destroy path) (defcairo append-path path) (defcairo has-current-point) (defcairo get-current-point x y) (defcairo new-path) (defcairo new-sub-path) (defcairo close-path) (defcairo arc xc yc radius angle1 angle2) (defcairo arc-negative xc yc radius angle1 angle2) (defcairo curve-to x1 y1 x2 y2 x3 y3) (defcairo line-to x y) (defcairo move-to x y) (defcairo rectangle x y width height) (defcairo glyph-path glyphs int num-glyphs) (defcairo text-path const char *utf8) (defcairo rel-curve-to dx1 dy1 dx2 dy2 dx3 dy3) (defcairo rel-line-to dx dy) (defcairo rel-move-to dx dy) (defcairo path-extents x1 y1 x2 y2) ;; Transformations ;; https://www.cairographics.org/manual/cairo-Transformations.html (defcairo translate tx ty) (defcairo scale sx sy) (defcairo rotate angle) (defcairo transform matrix) (defcairo set-matrix matrix) (defcairo get-matrix matrix) (defcairo identity-matrix) (defcairo user-to-device x y) (defcairo user-to-device-distance dx dy) (defcairo device-to-user x y) (defcairo device-to-user-distance dx dy) ;; text ;; https://www.cairographics.org/manual/cairo-text.html (defcairo select-font-face family slant weight) (defcairo set-font-size size) (defcairo set-font-matrix matrix) (defcairo get-font-matrix matrix) (defcairo set-font-options options) (defcairo get-font-options options) (defcairo set-font-face font-face) (defcairo get-font-face) (defcairo set-scaled-font scaled-font) (defcairo get-scaled-font) (defcairo show-text utf8) (defcairo show-glyphs glyphs num-glyphs) (defcairo show-text-glyphs utf8 utf8-len glyphs num-glyphs clusters num-clusters cluster-flags) (defcairo font-extents extents) (defcairo text-extents utf8 extents) (defcairo glyph-extents glyphs num-glyphs extents) (defcairo toy-font-face-create family slant weight) (defcairo toy-font-face-get-family font-face) (defcairo toy-font-face-get-slant font-face) (defcairo toy-font-face-get-weight font-face) (defcairo glyph-allocate num-glyphs) (defcairo glyph-free glyphs) (defcairo text-cluster-allocate num-clusters) (defcairo text-cluster-free clusters) ;; Image Surfaces ;; https://www.cairographics.org/manual/cairo-Image-Surfaces.html (defcairo-raw image-surface-get-width nil nil surface) (defcairo-raw image-surface-get-height nil nil surface) ;; PNG Support ;; https://www.cairographics.org/manual/cairo-PNG-Support.html (defcairo-raw image-surface-create-from-png nil nil filename) (defun lookup-enum-value (enum table) (let ((enum-position (position enum table :test #'(lambda (a b) (eq a (cdr b)))))) (unless enum-position (error "Could not find enum ~a in ~a." enum table)) enum-position))
14,701
Common Lisp
.lisp
369
35.780488
130
0.696291
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
ace43ee1742af443594726901878fe7395e875099d1e28217c48713739951542
2,209
[ -1 ]
2,210
canvas.lisp
VitoVan_calm/docs/examples/meditator/canvas.lisp
;; ;; Meditator © 2023 by Vito Van ;; is licensed under CC BY-NC-SA 4.0. ;; To view a copy of this license, visit ;; http://creativecommons.org/licenses/by-nc-sa/4.0/ ;; To obtain a commercial license, visit: ;; https://www.buymeacoffee.com/vitovan/e/119067 ;; (in-package #:calm) (defparameter *meditator-version* "0.0.1") (setf *calm-window-width* 600) (setf *calm-window-height* 500) (setf *calm-window-title* "Meditator") (defun draw-button () (c:new-path) (c:set-source-rgb (/ 210 255) (/ 0 255) (/ 22 255)) (c:set-line-width 2) (c:arc 550 50 15 0 (* 2 pi)) (if (c:in-fill *calm-state-mouse-x* *calm-state-mouse-y*) (progn (c:fill-path) #-jscl (u:set-cursor :hand) (when *calm-state-mouse-just-clicked* (setf *calm-state-mouse-just-clicked* nil) (c:play-music "assets/bowl.wav")) (c:arc 370 105 5 (* 1.7 pi) (* 0.3 pi)) (c:stroke) (c:arc 375 105 10 (* 1.7 pi) (* 0.3 pi)) (c:stroke) (c:arc 380 105 15 (* 1.7 pi) (* 0.3 pi)) (c:stroke)) (progn (c:stroke) #-jscl (u:set-cursor :arrow) ))) (defun draw () (c:set-source-rgb (/ 12 255) (/ 55 255) (/ 132 255)) (c:new-path) (c:set-line-width 5) (c:set-line-cap :round) (c:arc 300 110 60 0 (* 2 pi)) (c:stroke) (c:move-to 250 150) (c:curve-to 150 200 120 350 200 400) (c:stroke) (c:move-to 350 150) (c:curve-to 450 200 480 350 400 400) (c:stroke) (c:move-to 380 170) (c:curve-to 340 260 240 280 180 280) (c:stroke) (c:move-to 210 180) (c:curve-to 230 220 280 230 330 230) (c:stroke) (c:move-to 170 380) (c:curve-to 100 460 250 420 300 380) (c:stroke) (c:move-to 430 380) (c:curve-to 470 460 350 420 280 360) (c:stroke) (draw-button))
1,876
Common Lisp
.lisp
62
24.758065
59
0.57246
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
ce7179ad77cccebc3af0661c61c2fbb734a14d02d907548581b93041e4fe2b62
2,210
[ -1 ]
2,211
canvas.lisp
VitoVan_calm/docs/examples/fan/canvas.lisp
;; ;; Fan © 2023 by Vito Van ;; is licensed under CC BY-NC-SA 4.0. ;; To view a copy of this license, visit ;; http://creativecommons.org/licenses/by-nc-sa/4.0/ ;; To obtain a commercial license, visit: ;; https://www.buymeacoffee.com/vitovan/e/119069 ;; (in-package #:calm) (defparameter *fan-version* "0.0.1") (setf *calm-window-width* 600) (setf *calm-window-height* 500) #-jscl (unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD")) (swank:create-server)) ;; reduce the delay (default is 42), make the fan more smooth #-jscl (setf *calm-delay* 10) #+jscl (setf *calm-fps* 0) (setf *calm-window-title* "Fan") (defparameter *fan-speed-level* 0) (defparameter *fan-speed-level-list* '(0 12 16 20)) (defparameter *fan-blade-angle-degree-default-list* '(0 90 180 270)) (defparameter *fan-blade-angle-degree-list* *fan-blade-angle-degree-default-list*) (defun on-fan-switch-click () (setf *calm-redraw* t) (let ((i (position *fan-speed-level* *fan-speed-level-list*))) (when (>= i 3) (setf i -1)) (setf *fan-speed-level* (nth (1+ i) *fan-speed-level-list*)))) (defun draw-blade (&optional (degree 0)) (c:save) (c:translate 300 170) (c:rotate (* degree (/ pi 180))) (c:move-to 0 -15) (c:line-to 0 -100) (c:curve-to 0 -110 100 -65 15 0) (c:stroke-preserve) (c:set-source-rgba (/ 12 255) (/ 55 255) (/ 132 255) 0.1) (c:fill-path) (c:restore)) (defun draw-switch () (c:new-path) (c:set-source-rgb (/ 12 255) (/ 55 255) (/ 132 255)) (c:set-line-width 3) (c:arc 550 50 15 0 (* 2 pi)) (if (c:in-fill *calm-state-mouse-x* *calm-state-mouse-y*) (progn (c:stroke-preserve) (c:fill-path) #-jscl (u:set-cursor :hand) (when *calm-state-mouse-just-clicked* (setf *calm-state-mouse-just-clicked* nil) (on-fan-switch-click))) (progn (c:stroke) #-jscl (u:set-cursor :arrow) ))) (defun rotate-blades () (when (> (apply #'max *fan-blade-angle-degree-list*) 360) (setf *fan-blade-angle-degree-list* *fan-blade-angle-degree-default-list*)) (if (= *fan-speed-level* 0) (progn (unless (equal *fan-blade-angle-degree-list* *fan-blade-angle-degree-default-list*) (setf *fan-blade-angle-degree-list* (mapcar #'(lambda (x) (+ x 3)) *fan-blade-angle-degree-list*)))) (progn (setf *fan-blade-angle-degree-list* (mapcar #'(lambda (x) (+ x *fan-speed-level*)) *fan-blade-angle-degree-list*))))) (defun draw-forever () (setf *calm-redraw* (or (> *fan-speed-level* 0) (not (= (car *fan-blade-angle-degree-list*) 0)))) (c:set-source-rgb (/ 12 255) (/ 55 255) (/ 132 255)) (c:new-path) (c:set-line-width 6) (c:set-line-cap :round) (c:arc 300 170 120 (* 1.25 pi) (* 3.2 pi)) (c:stroke) ;; (format t "X,Y: ~A,~A~%" *calm-state-mouse-x* *calm-state-mouse-y*) ;; neck (c:move-to 270 290) (c:line-to 255 380) (c:move-to 330 290) (c:line-to 345 380) ;; base (c:move-to 220 420) (c:line-to 380 420) (c:move-to 300 380) (c:curve-to 370 375 400 420 380 420) (c:move-to 280 380) (c:curve-to 220 380 200 420 220 420) (c:stroke) ;; blade (mapcar 'draw-blade *fan-blade-angle-degree-list*) ;; turbo (c:arc 300 170 10 0 (* 2 pi)) (c:stroke) ;; switch (draw-switch) ;; rotate (rotate-blades))
3,391
Common Lisp
.lisp
104
28.442308
126
0.617439
VitoVan/calm
101
3
8
GPL-2.0
9/19/2024, 11:25:29 AM (Europe/Amsterdam)
65104e141e9c4eeaf1804cd2ef450cd7b6142d0d62121284ffee84a9501018ae
2,211
[ -1 ]