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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,440 | editfns.lisp | spacebat_lice/src/editfns.lisp | (in-package "LICE")
(defvar *inhibit-field-text-motion* nil
"Non-nil means text motion commands don't notice fields.")
(defvar *buffer-access-fontify-functions* nil
"List of functions called by `buffer-substring' to fontify if necessary.
Each function is called with two arguments which specify the range
of the buffer being accessed.")
(defvar *buffer-access-fontified-property* nil
"Property which (if non-nil) indicates text has been fontified.
`buffer-substring' need not call the `buffer-access-fontify-functions'
functions if all the text being accessed has this property.")
(defvar *system-name* nil
"The host name of the machine Emacs is running on.")
(defvar *user-full-name* nil
"The full name of the user logged in.")
(defvar *user-login-name* nil
"The user's name, taken from environment variables if possible.")
(defvar *user-real-login-name* nil
"The user's name, based upon the real uid only.")
(defvar *operating-system-release* nil
"The release of the operating system Emacs is running on.")
(defun get-pos-property (position prop &optional (object (current-buffer)))
"Return the value of property PROP, in OBJECT at POSITION.
It's the value of PROP that a char inserted at POSITION would get.
OBJECT is optional and defaults to the current buffer.
If OBJECT is a buffer, then overlay properties are considered as well as
text properties.
If OBJECT is a window, then that window's buffer is used, but
window-specific overlays are considered only if they are associated
with OBJECT."
(when (typep object 'window)
(setf object (window-buffer object)))
(if (not (typep object 'buffer))
(get-text-property position prop object)
;;; XXX: handle overlays.
(let ((stickiness (text-property-stickiness prop position object)))
(cond
((eq stickiness 'after)
(get-text-property position prop object))
((eq stickiness 'before)
(get-text-property (1- position) prop object))
(t nil)))))
(defun find-field (pos merge-at-boundary &key beg-limit beg end-limit end (buf (current-buffer)))
"Find the field surrounding POS and return the beginning and end of
the field in a values list. If POS is nil, the value of point is used
instead. If BEG or END is nil then that boundary isn't calculated.
BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
results; they do not effect boundary behavior.
If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
position of a field, then the beginning of the previous field is
returned instead of the beginning of POS's field (since the end of a
field is actually also the beginning of the next input field, this
behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
true case, if two fields are separated by a field with the special
value `boundary', and POS lies within it, then the two separated
fields are considered to be adjacent, and POS between them, when
finding the beginning and ending of the \"merged\" field.
Either BEG or END may be 0, in which case the corresponding value
is not stored."
(let ((at-field-start nil)
(at-field-end nil)
before-field after-field)
(unless pos
(setf pos (pt)))
(setf after-field (get-char-property-and-overlay pos 'field buf nil)
before-field (if (> pos (begv buf))
(get-char-property-and-overlay (1- pos) 'field buf nil)
nil))
;; See if we need to handle the case where MERGE_AT_BOUNDARY is nil
;; and POS is at beginning of a field, which can also be interpreted
;; as the end of the previous field. Note that the case where if
;; MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
;; more natural one; then we avoid treating the beginning of a field
;; specially.
(unless merge-at-boundary
(let ((field (get-pos-property pos 'field buf)))
(when (not (eq field after-field))
(setf at-field-end t))
(when (not (eq field before-field))
(setf at-field-start t))
(when (and (null field)
at-field-start
at-field-end)
;; If an inserted char would have a nil field while the surrounding
;; text is non-nil, we're probably not looking at a
;; zero-length field, but instead at a non-nil field that's
;; not intended for editing (such as comint's prompts).
(setf at-field-end nil
at-field-start nil))))
;; Note about special `boundary' fields:
;; Consider the case where the point (`.') is between the fields `x' and `y':
;; xxxx.yyyy
;; In this situation, if merge_at_boundary is true, we consider the
;; `x' and `y' fields as forming one big merged field, and so the end
;; of the field is the end of `y'.
;; However, if `x' and `y' are separated by a special `boundary' field
;; (a field with a `field' char-property of 'boundary), then we ignore
;; this special field when merging adjacent fields. Here's the same
;; situation, but with a `boundary' field between the `x' and `y' fields:
;; xxx.BBBByyyy
;; Here, if point is at the end of `x', the beginning of `y', or
;; anywhere in-between (within the `boundary' field), we merge all
;; three fields and consider the beginning as being the beginning of
;; the `x' field, and the end as being the end of the `y' field. */
;; Return field boundary
(values (and beg
(if at-field-start
pos
(let ((p pos))
(if (and (null merge-at-boundary)
(eq before-field 'boundary))
(setf p (previous-single-char-property-change p 'field buf beg-limit))
(setf p (previous-single-char-property-change p 'field buf beg-limit)))
(or p
(begv buf)))))
(and end
(if at-field-end
pos
(progn
(when (and (null merge-at-boundary)
(eq after-field 'boundary))
(setf pos (next-single-char-property-change pos 'field buf end-limit)))
(setf pos (next-single-char-property-change pos 'field buf end-limit))
(or pos
(zv buf))))))))
(defun buffer-substring (start end &optional (buffer (current-buffer)))
"Return the contents of part of the current buffer as a string.
The two arguments START and END are character positions;
they can be in either order.
The string returned is multibyte if the buffer is multibyte.
This function copies the text properties of that part of the buffer
into the result string; if you don't want the text properties,
use `buffer-substring-no-properties' instead."
(multiple-value-setq (start end) (validate-region start end buffer))
(make-buffer-string start end t buffer))
(defun buffer-substring-no-properties (start end &optional (buffer (current-buffer)))
"Return the characters of part of the buffer, without the text properties.
The two arguments START and END are character positions;
they can be in either order."
(multiple-value-setq (start end) (validate-region start end buffer))
(make-buffer-string start end nil buffer))
(defun field-string (pos)
"Return the contents of the field surrounding POS as a string.
A field is a region of text with the same `field' property.
If POS is nil, the value of point is used for POS."
(multiple-value-bind (beg end) (find-field pos nil :beg t :end t)
(make-buffer-string beg end t)))
(defun field-beginning (&optional pos escape-from-edge limit)
"Return the beginning of the field surrounding POS.
A field is a region of text with the same `field' property.
If POS is nil, the value of point is used for POS.
If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
field, then the beginning of the *previous* field is returned.
If LIMIT is non-nil, it is a buffer position; if the beginning of the field
is before LIMIT, then LIMIT will be returned instead."
(declare (ignore escape-from-edge))
(multiple-value-bind (beg end) (find-field pos nil :beg-limit limit :beg t)
(declare (ignore end))
beg))
(defun field-end (&optional pos escape-from-edge limit)
"Return the end of the field surrounding POS.
A field is a region of text with the same `field' property.
If POS is nil, the value of point is used for POS.
If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
then the end of the *following* field is returned.
If LIMIT is non-nil, it is a buffer position; if the end of the field
is after LIMIT, then LIMIT will be returned instead."
(declare (ignore escape-from-edge))
(multiple-value-bind (beg end) (find-field pos nil :end-limit limit :end t)
(declare (ignore beg))
end))
(defun constrain-to-field (new-pos old-pos &optional escape-from-edge only-in-line inhibit-capture-property)
"Return the position closest to NEW-POS that is in the same field as OLD-POS.
A field is a region of text with the same `field' property.
If NEW-POS is nil, then the current point is used instead, and set to the
constrained position if that is different.
If OLD-POS is at the boundary of two fields, then the allowable
positions for NEW-POS depends on the value of the optional argument
ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
constrained to the field that has the same `field' char-property
as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
is non-nil, NEW-POS is constrained to the union of the two adjacent
fields. Additionally, if two fields are separated by another field with
the special value `boundary', then any point within this special field is
also considered to be `on the boundary'.
If the optional argument ONLY-IN-LINE is non-nil and constraining
NEW-POS would move it to a different line, NEW-POS is returned
unconstrained. This useful for commands that move by line, like
\\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
only in the case where they can still move to the right line.
If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
a non-nil property of that name, then any field boundaries are ignored.
Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil."
(let ((orig-point 0)
fwd prev-old prev-new)
(unless new-pos
;; Use the current point, and afterwards, set it.
(setf new-pos (pt)
orig-point new-pos))
(check-type new-pos number)
(check-type old-pos number)
(setf fwd (> new-pos old-pos)
prev-old (1- old-pos)
prev-new (1- new-pos))
(when (and (null *inhibit-field-text-motion*)
(/= new-pos old-pos)
(or (get-char-property new-pos 'field)
(get-char-property old-pos 'field)
;; To recognize field boundaries, we must also look at the
;; previous positions; we could use `get_pos_property'
;; instead, but in itself that would fail inside non-sticky
;; fields (like comint prompts).
(and (> new-pos (begv))
(get-char-property prev-new 'field))
(and (> old-pos (begv))
(get-char-property prev-old 'field)))
(or (null inhibit-capture-property)
(and (null (get-pos-property old-pos inhibit-capture-property nil))
(or (<= old-pos (begv))
(null (get-char-property old-pos inhibit-capture-property))
(null (get-char-property prev-old inhibit-capture-property))))))
;; It is possible that NEW_POS is not within the same field as
;; OLD_POS; try to move NEW_POS so that it is.
(let ((field-bound (if fwd
(field-end old-pos escape-from-edge new-pos)
(field-beginning old-pos escape-from-edge new-pos))))
(when (and
;; See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
;; other side of NEW_POS, which would mean that NEW_POS is
;; already acceptable, and it's not necessary to constrain it
;; to FIELD_BOUND.
(if (< field-bound new-pos) fwd (not fwd))
;; NEW_POS should be constrained, but only if either
;; ONLY_IN_LINE is nil (in which case any constraint is OK),
;; or NEW_POS and FIELD_BOUND are on the same line (in which
;; case the constraint is OK even if ONLY_IN_LINE is non-nil). */
(or (null only-in-line)
;; This is the ONLY_IN_LINE case, check that NEW_POS and
;; FIELD_BOUND are on the same line by seeing whether
;; there's an intervening newline or not.
(progn
(multiple-value-bind (p nfound)
(buffer-scan-newline (current-buffer) new-pos field-bound (if fwd -1 1))
(declare (ignore p))
(zerop nfound)))))
;; Constrain NEW_POS to FIELD_BOUND.
(setf new-pos field-bound))
(when (and orig-point
(/= new-pos orig-point))
(set-point new-pos))))
new-pos))
(defun npropertize (string &rest props)
"Same as propertize but don't make a copy of STRING."
(declare (type string string))
(let ((ps (make-instance 'pstring
:data string)))
(create-root-interval ps)
(add-text-properties 0 (pstring-length ps) props ps)
ps))
(defun propertize (string &rest props)
"Return a copy of STRING with text properties added.
First argument is the string to copy.
Remaining arguments form a sequence of PROPERTY VALUE pairs for text
properties to add to the result.
usage: (propertize STRING &rest PROPERTIES)"
(declare (type string string))
(apply #'npropertize (copy-seq string) props))
(defun delete-region (start end &optional (buffer (current-buffer)))
"Delete the text between point and mark.
expects two arguments, positions (integers or markers) specifying
the stretch to be deleted."
(multiple-value-setq (start end) (validate-region start end buffer))
(buffer-delete buffer start (- end start)))
(defun point (&aux (buffer (current-buffer)))
"Return the point in the current buffer."
(pt buffer))
(defun point-marker (&aux (buffer (current-buffer)))
"Return value of point, as a marker object."
(buffer-point buffer))
(defun point-min (&aux (buffer (current-buffer)))
"Return the minimum permissible value of point in the current buffer."
(declare (ignore buffer))
0)
(defun point-max (&aux (buffer (current-buffer)))
"Return the maximum permissible value of point in the current buffer."
(buffer-size buffer))
(defmacro save-current-buffer (&body body)
"Save the current buffer; execute BODY; restore the current buffer.
Executes BODY just like `progn'."
(let ((cb (gensym "CB")))
`(let ((,cb (current-buffer)))
(unwind-protect (progn ,@body)
(when (get-buffer ,cb)
(set-buffer cb))))))
(defmacro save-excursion (&body body)
"Save point, mark, and current buffer; execute BODY; restore those things.
Executes BODY just like `progn'.
The values of point, mark and the current buffer are restored
even in case of abnormal exit (throw or error).
*The state of activation of the mark is also restored.
*This construct does not save `deactivate-mark', and therefore
*functions that change the buffer will still cause deactivation
*of the mark at the end of the command. To prevent that, bind
*`deactivate-mark' with `let'."
(let ((cb (gensym "CB"))
(point (gensym "POINT"))
(mark (gensym "MARK")))
`(let ((,cb (current-buffer))
(,point (copy-marker (point-marker)))
(,mark (copy-marker (mark-marker))))
(unwind-protect (progn ,@body)
(when (get-buffer ,cb)
(set-buffer ,cb)
(setf (buffer-mark-marker ,cb) ,mark
(buffer-point ,cb) ,point))))))
(defun insert (&rest objects)
"Insert the arguments, either strings or characters, at point.
Point and before-insertion markers move forward to end up
after the inserted text.
Any other markers at the point of insertion remain before the text.
If the current buffer is multibyte, unibyte strings are converted
to multibyte for insertion (see `string-make-multibyte').
If the current buffer is unibyte, multibyte strings are converted
to unibyte for insertion (see `string-make-unibyte').
When operating on binary data, it may be necessary to preserve the
original bytes of a unibyte string when inserting it into a multibyte
buffer; to accomplish this, apply `string-as-multibyte' to the string
and insert the result."
(dolist (o objects)
(insert-move-point (current-buffer) o)))
(defun insert-buffer-substring (buffer &optional (start (point-min)) (end (point-max)))
"Insert before point a substring of the contents of buffer.
buffer may be a buffer or a buffer name.
Arguments start and end are character positions specifying the substring.
They default to the values of (point-min) and (point-max) in buffer."
(check-number-coerce-marker start)
(check-number-coerce-marker end)
(if (< end start)
(psetf start end
end start))
(let* ((buf (get-buffer buffer)))
(when (or (< start (buffer-min buf))
(> end (buffer-max buf)))
(signal 'args-out-of-range))
(insert (make-buffer-string start end t buf))))
(defun preceding-char ()
"Return the character preceding point.
At the beginning of the buffer or accessible region, return #\Nul."
(or (buffer-char-before (current-buffer) (pt))
#\Nul))
(defun following-char ()
"Return the character following point, as a number.
At the end of the buffer or accessible region, return #\Nul."
(if (>= (pt) (zv))
#\Nul ; XXX return nil?
(buffer-fetch-char (buffer-char-to-aref (current-buffer) (pt))
(current-buffer))))
(defun bolp ()
"Return t if point is at the beginning of a line."
(or (= (pt) (begv))
(char= (buffer-char-before (current-buffer) (pt)) #\Newline)))
(defun eolp ()
"Return t if point is at the end of a line.
`End of a line' includes point being at the end of the buffer."
(or (= (pt) (zv))
(char= (buffer-char-after (current-buffer) (pt)) #\Newline)))
(defun bobp (&optional (buffer (current-buffer)))
"Return T when the point is at the beginning of the buffer."
(= (begv buffer) (pt)))
(defun eobp (&optional (buffer (current-buffer)))
"Return T when the point is at the end of the buffer."
(= (zv buffer) (pt)))
(defun delete-and-extract-region (start end)
"Delete the text between start and end and return it."
(multiple-value-setq (start end) (validate-region start end))
(if (= start end)
""
(prog1
(make-buffer-string start end t)
(delete-region start end))))
(defun insert-char (character count &optional inherit)
"Insert COUNT copies of CHARACTER.
Point, and before-insertion markers, are relocated as in the function `insert'.
**The optional third arg INHERIT, if non-nil, says to inherit text properties
**from adjoining text, if those properties are sticky."
(declare (ignore inherit))
(check-type character character)
(check-type count number)
(unless (< count 0)
(dotimes (i count)
(insert character))))
(defun line-beginning-position (n)
"Return the character position of the first character on the current line.
With argument N not nil or 1, move forward N - 1 lines first.
If scan reaches end of buffer, return that position.
This function constrains the returned position to the current field
unless that would be on a different line than the original,
unconstrained result. If N is nil or 1, and a front-sticky field
starts at point, the scan stops as soon as it starts. To ignore field
boundaries bind `inhibit-field-text-motion' to t.
This function does not move point."
;; FIXME: inhibit-point-motion-hooks
(let ((pt (save-excursion
(forward-line (if n (1- n) 0))
(pt))))
(constrain-to-field pt (pt) (not (eql n 1)) t nil)))
(defun line-end-position (&optional (n 1))
"Return the character position of the last character on the current line.
With argument N not nil or 1, move forward N - 1 lines first.
If scan reaches end of buffer, return that position.
This function constrains the returned position to the current field
unless that would be on a different line than the original,
unconstrained result. If N is nil or 1, and a rear-sticky field ends
at point, the scan stops as soon as it starts. To ignore field
boundaries bind `inhibit-field-text-motion' to t.
This function does not move point."
(check-type n integer)
(setf n (- n (if (<= n 0) 1 0)))
(let* ((orig (pt))
(end-pos (find-before-next-newline orig nil n)))
(constrain-to-field end-pos orig nil t nil)))
(defun clip-to-bounds (lower num upper)
(max (min num upper) lower))
(defun string-to-char (string)
"Convert arg string to a character, the first character of that string.
A multibyte character is handled correctly."
(char string 0))
(defun char-to-string (char)
"Convert arg CHAR to a string containing that character.
usage: (char-to-string CHAR)"
(string char))
(defun buffer-string ()
(error "Unimplemented buffer-string"))
(defun field-string-no-properties ()
(error "Unimplemented field-string-no-properties"))
(defun delete-field ()
(error "Unimplemented delete-field"))
(defmacro save-current-buffer ()
(error "Unimplemented save-current-buffer"))
(defun bufsize ()
(error "Unimplemented bufsize"))
(defun point-min-marker ()
(error "Unimplemented point-min-marker"))
(defun point-max-marker ()
(error "Unimplemented point-max-marker"))
(defun gap-position ()
(error "Unimplemented gap-position"))
(defun gap-size ()
(error "Unimplemented gap-size"))
(defun position-bytes ()
(error "Unimplemented position-bytes"))
(defun byte-to-position ()
(error "Unimplemented byte-to-position"))
(defun previous-char ()
(error "Unimplemented previous-char"))
(defun insert-before-markers ()
(error "Unimplemented insert-before-markers"))
(defun insert-and-inherit ()
(error "Unimplemented insert-and-inherit"))
(defun insert-and-inherit-before-markers ()
(error "Unimplemented insert-and-inherit-before-markers"))
(defun user-login-name ()
(error "Unimplemented user-login-name"))
(defun user-real-login-name ()
(error "Unimplemented user-real-login-name"))
(defun user-uid ()
(error "Unimplemented user-uid"))
(defun user-real-uid ()
(error "Unimplemented user-real-uid"))
(defun user-full-name ()
(error "Unimplemented user-full-name"))
(defun emacs-pid ()
(error "Unimplemented emacs-pid"))
(defun current-time ()
(error "Unimplemented" current-time))
(defun format-time-string ()
(error "Unimplemented format-time-string"))
(defun float-time ()
(error "Unimplemented float-time"))
(defun decode-time ()
(error "Unimplemented decode-time"))
(defun encode-time ()
(error "Unimplemented encode-time"))
(defun current-time-string ()
(error "Unimplemented current-time-string"))
(defun current-time-zone ()
(error "Unimplemented current-time-zone"))
(defun set-time-zone-rule ()
(error "Unimplemented set-time-zone-rule"))
(defun system-name ()
(error "Unimplemented system-name"))
(defun message (string &rest arguments)
"Display a message at the bottom of the screen.
The message also goes into the `*Messages*' buffer.
\(In keyboard macros, that's all it does.)
Return the message.
The first argument is a format control string, and the rest are data
to be formatted under control of the string. See `format' for details.
Note: Use (message \"~s\" VALUE) to print the value of expressions and
variables to avoid accidentally interpreting `~' as format specifiers.
If the first argument is nil or the empty string, the function clears
any existing message; this lets the minibuffer contents show. See
also `current-message'."
(check-type string string)
;; FIXME: properly implement the echo area
(when (zerop (frame-minibuffers-active (selected-frame)))
(let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame))))
(msg (apply #'format nil string arguments)))
(erase-buffer minibuffer)
(buffer-insert minibuffer msg)
(with-current-buffer (get-buffer-create "*messages*")
(goto-char (point-max))
(insert msg #\Newline)))))
(defun message-box ()
(error "Unimplemented message-box"))
(defun message-or-box ()
(error "Unimplemented message-or-box"))
(defun current-message ()
"Return the string currently displayed in the echo area, or nil if none."
(let ((buf (frame-echo-area-current (selected-frame))))
(when buf
(make-buffer-string (begv buf) (zv buf) t buf))))
(defun compare-buffer-substrings ()
(error "Unimplemented compare-buffer-substrings"))
(defun subst-char-in-region (start end fromchar tochar &optional noundo)
"From START to END, replace FROMCHAR with TOCHAR each time it occurs.
If optional arg NOUNDO is non-nil, don't record this change for undo
and don't mark the buffer as really changed.
Both characters must have the same length of multi-byte form."
(declare (ignore noundo))
(check-number-coerce-marker start)
(check-number-coerce-marker end)
(check-type fromchar character)
(check-type tochar character)
(multiple-value-setq (start end) (validate-region start end))
;; FIXME: handle noundo
(let* ((buf (current-buffer))
(start-aref (buffer-char-to-aref buf start))
(end-aref (buffer-char-to-aref buf end)))
(if (or (< (gap-end buf)
start-aref)
(> (buffer-gap-start buf)
end-aref))
(nsubstitute tochar fromchar (buffer-data buf)
:start start-aref
:end end-aref)
(progn
(gap-move-to buf start-aref)
(nsubstitute tochar fromchar (buffer-data buf)
:start (buffer-char-to-aref buf start)
:end (buffer-char-to-aref buf end))))
nil))
(defun translate-region-internal ()
(error "Unimplemented translate-region-internal"))
(defun widen ()
(error "Unimplemented widen"))
(defun narrow-to-region ()
(error "Unimplemented narrow-to-region"))
(defun save-restriction ()
(error "Unimplemented save-restriction"))
(defun transpose-regions (startr1 endr1 startr2 endr2 &optional leave_markers)
"Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
The regions may not be overlapping, because the size of the buffer is
never changed in a transposition.
Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
any markers that happen to be located in the regions.
Transposing beyond buffer boundaries is an error."
(check-number-coerce-marker startr1)
(check-number-coerce-marker endr1)
(check-number-coerce-marker startr2)
(check-number-coerce-marker endr2)
(multiple-value-setq (startr1 endr1) (validate-region startr1 endr1))
(multiple-value-setq (startr2 endr2) (validate-region startr2 endr2))
(when (< startr2 startr1)
(psetf startr1 startr2
endr1 endr2
startr2 startr1
endr2 endr1))
;; no overlapping
(assert (<= endr1 startr2))
;; FIXME: The emacs version looks optimized for a bunch of
;; cases. But we're gonna cheap out
(let ((r1 (buffer-substring startr1 endr1))
(r2 (buffer-substring startr2 endr2)))
;; do the 2nd one first so the positions remain valid.
(delete-region startr2 endr2)
(set-point startr2)
(insert r1)
(delete-region startr1 endr1)
(set-point startr1)
(insert r2)))
(defun goto-char (position &aux (buffer (current-buffer)))
"Set point to POSITION, a number."
(check-number-coerce-marker position)
(when (and (>= position (begv buffer))
(<= position (zv buffer)))
(set-point position buffer)))
(defun char-after (&optional (pos (pt)))
"Return character in current buffer at position POS.
***POS is an integer or a marker.
***If POS is out of range, the value is nil."
(check-number-coerce-marker pos)
(buffer-char-after (current-buffer) pos))
(defun char-before (&optional (pos (pt)))
"Return character in current buffer preceding position POS.
***POS is an integer or a marker.
***If POS is out of range, the value is nil."
(check-number-coerce-marker pos)
(buffer-char-after (current-buffer) (1- pos)))
(defun substring-no-properties (string &optional (from 0) (to (length string)))
"Return a substring of string, without text properties.
It starts at index from and ending before to.
to may be nil or omitted; then the substring runs to the end of string.
If from is nil or omitted, the substring starts at the beginning of string.
If from or to is negative, it counts from the end.
With one argument, just copy string without its properties."
(subseq string from to))
(provide :lice-0.1/editfns)
| 28,898 | Common Lisp | .lisp | 618 | 41.982201 | 108 | 0.704296 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 142efab4147cad6f4c9b0a968099e006bb5e0b93ddc9231ea9b9cef612a933e1 | 18,440 | [
-1
] |
18,441 | custom.lisp | spacebat_lice/src/custom.lisp | (in-package "LICE")
;; FIXME: obviously this is incomplete
(defmacro defcustom (symbol value doc &rest args)
(declare (ignore args))
`(defvar ,symbol ,value ,doc))
;; FIXME: empty
(defmacro defgroup (name something docstring &rest stuff)
(declare (ignore name something docstring stuff))
)
;; FIXME: empty
(defmacro defface (name colors docstring &key group)
(declare (ignore name colors docstring group))
)
;; FIXME: this is incomplete
(defmacro defcustom-buffer-local (symbol value doc &rest args)
(declare (ignore args))
`(define-buffer-local ,symbol ,value ,doc))
| 588 | Common Lisp | .lisp | 17 | 32.411765 | 62 | 0.747795 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 12093367b3fb95e4f27f43860402427af46bf2d382f9bd25a26fb3311d85ee89 | 18,441 | [
-1
] |
18,442 | mcl-render.lisp | spacebat_lice/src/mcl-render.lisp | (in-package "LICE")
(defclass mcl-window (ccl:window)
())
(defclass mcl-frame (frame mcl-window)
((double-buffer :type (array character 1) :initarg :double-buffer :accessor frame-double-buffer :documentation
"The display double buffer. This structure is compared to
the characters we want to blit. Only differences are sent to the video
hardware.")
(2d-double-buffer :type (array character 2) :initarg :2d-double-buffer :accessor frame-2d-double-buffer :documentation
"Displaced from DISPLAY. This array is divided into rows and columns.")
(cursor :initform #(0 0) :accessor mcl-frame-cursor)
(font-width :initarg :font-width :accessor mcl-frame-font-width)
(font-height :initarg :font-height :accessor mcl-frame-font-height)
(font-ascent :initarg :font-ascent :accessor mcl-frame-font-ascent)))
(defmethod frame-start-render ((frame mcl-frame))
(declare (ignore frame))
)
(defmethod frame-end-render ((frame mcl-frame))
(declare (ignore frame))
(ccl:event-dispatch))
(defun window-move-cursor (window x y)
(declare (ignore window x y))
)
(defmethod frame-move-cursor ((frame mcl-frame) win x y)
;; (setf x (* x (mcl-frame-font-width frame))
;; y (+ (* y (mcl-frame-font-height frame)) 10))
;; (ccl:invert-rect frame x y (+ x (mcl-frame-font-width frame)) (+ y (mcl-frame-font-height frame)))
(setf (mcl-frame-cursor frame) (vector (+ (window-x win) x) (+ (window-y win) y)))
(window-move-cursor win x y))
(defun putch (ch x y window frame)
;; (0,0) is above the visible area of the window. so add 25 (experimentally determined).
;; (setf x (* x (mcl-frame-font-width frame))
;; y (+ (* y (mcl-frame-font-height frame)) 10))
;; (ccl:move-to (mcl-frame-window frame) x y)
;; (princ ch (mcl-frame-window frame))
(setf (aref (frame-2d-double-buffer frame) (+ y (window-y window)) (+ (window-x window) x)) ch)
)
(defun putstr (s x y w frame)
(loop for i from 0 below (length s)
for j from x by 1
;;if (char/= (aref (window-2d-display w) y j) (aref s i))
do (putch (char s i) j y w frame)))
(defun clear-line-between (w y start end frame)
"insert LEN spaces from START on line Y."
(window-move-cursor w start y)
;; FIXME: this could be done faster
(loop for i from start to end
do (putch #\Space i y w frame)))
(defun clear-to-eol (y start window frame)
(declare (type window window)
(type fixnum y start))
;; (let ((display (frame-2d-double-buffer frame))
;; (linear (frame-double-buffer frame)))
(clear-line-between window y start (1- (window-width window nil)) frame)
;; draw the seperator
(when (window-seperator window)
(putch #\| (+ (window-x window) (1- (window-width window t))) y window frame)))
(defun turn-on-attributes (buffer point)
(declare (ignore buffer point))
)
(defmethod frame-end-render ((frame mcl-frame))
(ccl:invalidate-view frame))
(defmethod window-render (w (frame mcl-frame))
"Render a window."
;; clear the window
;; (ccl:with-fore-color ccl:*white-color*
;; (ccl:paint-rect (mcl-frame-window frame) 0 0
;; (ccl:point-h (ccl:view-size (mcl-frame-window frame)))
;; (ccl:point-v (ccl:view-size (mcl-frame-window frame))))
;; (ccl:event-dispatch))
(let ((p (buffer-char-to-aref (window-buffer w) (marker-position (window-top w))))
;; current point in buffer buffer
(bp (marker-position (window-top w)))
(buf (window-buffer w))
;; The cursor point in the buffer. When the buffer isn't
;; current, then use the window's backup of the point.
(point (window-point w))
cursor-x
cursor-y
(cache-size (length (lc-cache (window-cache w))))
(linear (frame-double-buffer frame))
(display (frame-2d-double-buffer frame)))
(declare (ignore display linear))
;; clear the window
;; (ccl:erase-rect (mcl-frame-window frame) 0 0
;; (ccl:point-h (ccl:view-size (mcl-frame-window frame)))
;; (ccl:point-v (ccl:view-size (mcl-frame-window frame))))
;; Special case: when the buffer is empty
(if (= (buffer-size (window-buffer w)) 0)
(progn
(dotimes (y (window-height w nil))
(clear-to-eol y 0 w frame))
(setf cursor-x 0
cursor-y 0))
(let ((end (loop named row
for y below (window-height w nil)
for line from (window-top-line w) below cache-size
;; return the last line, so we can erase the rest
finally (return-from row y)
;; go to the next line
do (let* ((line-end (cache-item-end (item-in-cache w line)))
(line-start (cache-item-start (item-in-cache w line)))
(next-prop (next-single-property-change line-start :face (window-buffer w) line-end)))
(setf bp (cache-item-start (item-in-cache w line))
p (buffer-char-to-aref (window-buffer w) bp))
;; setup the display properties.
(turn-on-attributes (window-buffer w) bp)
(loop named col
for x below (window-width w nil) do
(progn
;; Skip the gap
(when (= p (buffer-gap-start buf))
(incf p (buffer-gap-size buf)))
;; Record point position on screen
(when (eq bp point)
(setf cursor-x x)
(setf cursor-y y))
(when (or (> bp line-end)
(>= p (length (buffer-data buf))))
;; Check if the rest of the line is blank
(clear-to-eol y x w frame)
(return-from col))
;; update attributes
(when (>= bp next-prop)
(turn-on-attributes (window-buffer w) bp))
(let ((ch (elt (buffer-data buf) p)))
;; Update display
(cond ((char= ch #\Newline)
(putch #\Space x y w frame))
(t
(putch ch x y w frame)))
;; go to the next character in the buffer
(incf p)
(incf bp))))))))
;; Check if the bottom of the window needs to be erased.
(when (< end (1- (window-height w nil)))
(loop for i from end below (window-height w nil) do
(clear-to-eol i 0 w frame)))))
;; Update the mode-line if it exists. FIXME: Not the right place
;; to update the mode-line.
(when (buffer-mode-line (window-buffer w))
(update-mode-line (window-buffer w))
(putstr (truncate-mode-line (window-buffer w) (window-width w nil))
0 (window-height w nil) w frame)
;; don't forget the seperator on the modeline line
(when (window-seperator w)
(putch #\| (+ (window-x w) (window-width w nil)) (window-height w nil) w frame)))
(reset-line-state w)
;; Set the cursor at the right spot
(values cursor-x cursor-y)))
(defvar *mcl-stackgroup* (ccl:make-stack-group "lice")
"")
(defun mcl-lice ()
"Boot lice on mcl"
(ccl:stack-group-preset *mcl-stackgroup* #'lice)
(funcall *mcl-stackgroup* nil))
(ccl:defrecord Event
(what integer)
(message longint)
(when longint)
(where point)
(modifiers integer))
(defvar *mcl-key-list* nil
"List of keys pressed.")
(defmethod ccl:view-key-event-handler :after ((w mcl-window) ch)
(declare (ignore ch))
(let* ((keystroke (ccl:keystroke-name (ccl:event-keystroke (ccl:rref ccl:*current-event* :event.message) (ccl:rref ccl:*current-event* :event.modifiers))))
(ch (if (listp keystroke)
(car (last keystroke))
keystroke))
(mods (and (listp keystroke)
(butlast keystroke))))
;;(format t "k: ~s ~s ~s~%" keystroke ch mods)
(setf *mcl-key-list* (nconc *mcl-key-list*
(list (make-key
:meta (and (find :meta mods) t)
:control (and (find :control mods) t)
:char ch))))
(funcall *mcl-stackgroup* nil)))
(defmethod ccl:view-draw-contents ((win frame))
(ccl:erase-rect win 0 0
(ccl:point-h (ccl:view-size win))
(ccl:point-v (ccl:view-size win)))
;; characters
(loop
for y from 0 below (array-dimension (frame-2d-double-buffer win) 0)
for i from (mcl-frame-font-ascent win) by (mcl-frame-font-height win) do
(loop
for x from 0 below (array-dimension (frame-2d-double-buffer win) 1)
for j from 0 by (mcl-frame-font-width win) do
(ccl:move-to win j i)
(princ (aref (frame-2d-double-buffer win) y x) win)))
;; point
(let ((x (* (elt (mcl-frame-cursor win) 0) (mcl-frame-font-width win)))
(y (* (elt (mcl-frame-cursor win) 1) (mcl-frame-font-height win))))
(ccl:invert-rect win x y (+ x (mcl-frame-font-width win)) (+ y (mcl-frame-font-height win)))))
(defmethod frame-read-event ((frame mcl-frame))
;; wait for more input
(unless *mcl-key-list*
(ccl:stack-group-return nil))
;; process the new input
(pop *mcl-key-list*))
(defun mcl-font-width (font-name font-size)
(multiple-value-bind (ascent descent maxwidth leading) (ccl::font-info (list font-name font-size))
(declare (ignore ascent descent leading))
maxwidth))
(defun mcl-font-height (font-name font-size)
(multiple-value-bind (ascent descent maxwidth leading) (ccl::font-info (list font-name font-size))
(declare (ignore maxwidth))
(+ ascent descent leading)))
(defun mcl-font-ascent (font-name font-size)
(multiple-value-bind (ascent descent maxwidth leading) (ccl::font-info (list font-name font-size))
(declare (ignore descent maxwidth leading))
ascent))
(defun make-default-mcl-frame (buffer)
(let* ((lines 25)
(height (1- lines))
(fw (mcl-font-width "Monaco" 12))
(fh (mcl-font-height "Monaco" 12))
(ascent (mcl-font-ascent "Monaco" 12))
(cols 80)
(l (make-array (* lines cols)
:element-type 'character))
(d (make-array (list lines cols)
:element-type 'character
:displaced-to l :displaced-index-offset 0))
(w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer))
(mb (make-minibuffer-window lines cols))
(frame (make-instance 'mcl-frame
:width cols
:height lines
:window-tree (list w mb)
:selected-window w
:minibuffer-window mb
:double-buffer l
:2d-double-buffer d
:font-height fh
:font-width fw
:font-ascent ascent
:view-size (ccl:make-point (* cols fw) (* lines fh))
:view-font '("Monaco" 12))))
(setf (window-frame w) frame
(window-frame mb) frame)
frame))
| 10,495 | Common Lisp | .lisp | 244 | 36.946721 | 157 | 0.628557 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3a6f960de30f9a0259033a916d5abee7ebd692116ed956786963d7e046cbea7a | 18,442 | [
-1
] |
18,443 | tty-render.lisp | spacebat_lice/src/tty-render.lisp | ;; TTY rendering routines
(in-package "LICE")
(defclass tty-frame (frame)
((double-buffer :type (array character 1) :initarg :double-buffer :accessor frame-double-buffer :documentation
"The display double buffer. This structure is compared to
the characters we want to blit. Only differences are sent to the video
hardware.")
(2d-double-buffer :type (array character 2) :initarg :2d-double-buffer :accessor frame-2d-double-buffer :documentation
"Displaced from DISPLAY. This array is divided into rows and columns.")))
(defmethod frame-start-render ((frame tty-frame))
)
(defmethod frame-end-render ((frame tty-frame))
(cl-ncurses::refresh))
(defun window-move-cursor (window x y)
(cl-ncurses::move (+ y (window-y window)) (+ x (window-x window))))
(defmethod frame-move-cursor ((frame tty-frame) win x y)
(window-move-cursor win x y))
(defun putch (ch x y window frame)
(window-move-cursor window x y)
(cl-ncurses::addch (char-int ch))
(setf (aref (frame-2d-double-buffer frame) (+ y (window-y window)) (+ x (window-x window))) ch))
(defun putstr (s x y w frame)
(loop for i from 0 below (length s)
for j from x by 1
;;if (char/= (aref (window-2d-display w) y j) (aref s i))
do (putch (aref s i) j y w frame)))
(defun line-height (buffer p)
"Return the height of the line starting at p."
(declare (ignore buffer p)))
(defun clear-line-between (w y start end frame)
"insert LEN spaces from START on line Y."
(window-move-cursor w start y)
;; FIXME: this could be done faster
(loop for i from start to end
do (putch #\Space i y w frame)))
;; Helper function for window-render
(defun clear-to-eol (y start window frame)
(declare (type window window)
(type fixnum y start))
(clear-line-between window y start (1- (window-width window nil)) frame)
;; draw the seperator
(when (window-seperator window)
(putch #\| (+ (window-x window) (1- (window-width window t))) y window frame)))
(defun turn-on-attributes (buffer point)
"Given the buffer and point, turn on the appropriate colors based on
the text properties present."
;; These are hardcoded for now
(case (get-text-property point :face buffer)
(:face-1
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 1)))
(:face-2
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 2)))
(:face-3
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 3)))
(:face-4
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 4)))
(:face-5
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 5)))
(:face-6
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 6)))
(:face-7
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 7)))
(:face-8
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 8)))
(t
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 1)))))
(defmethod window-render (w (frame tty-frame))
"Render a window."
(let ((p (buffer-char-to-aref (window-buffer w) (marker-position (window-top w))))
;; current point in buffer buffer
(bp (marker-position (window-top w)))
(buf (window-buffer w))
;; The cursor point in the buffer. When the buffer isn't
;; current, then use the window's backup of the point.
(point (window-point w))
cursor-x
cursor-y
(cache-size (length (lc-cache (window-cache w))))
;; (linear (frame-double-buffer frame))
;; (display (frame-2d-double-buffer frame))
)
;; rxvt draws black on black if i don't turn on a color
(cl-ncurses::attron (cl-ncurses::COLOR-PAIR 1))
;; Special case: when the buffer is empty
(if (= (buffer-size (window-buffer w)) 0)
(progn
(dotimes (y (window-height w nil))
(clear-to-eol y 0 w frame))
(setf cursor-x 0
cursor-y 0))
(let ((end (loop named row
for y below (window-height w nil)
for line from (window-top-line w) below cache-size
;; return the last line, so we can erase the rest
finally (return-from row y)
;; go to the next line
do (let* ((line-end (cache-item-end (item-in-cache w line)))
(line-start (cache-item-start (item-in-cache w line)))
(next-prop (next-single-property-change line-start :face (window-buffer w) line-end)))
(setf bp (cache-item-start (item-in-cache w line))
p (buffer-char-to-aref (window-buffer w) bp))
;; setup the display properties.
(turn-on-attributes (window-buffer w) bp)
(loop named col
for x below (window-width w nil) do
(progn
;; Skip the gap
(when (= p (buffer-gap-start buf))
(incf p (buffer-gap-size buf)))
;; Record point position on screen
(when (eq bp point)
(setf cursor-x x)
(setf cursor-y y))
(when (or (> bp line-end)
(>= p (length (buffer-data buf))))
;; gotta turn off attributes to do this
(cl-ncurses::attrset (cl-ncurses::COLOR-PAIR 1))
;; Check if the rest of the line is blank
(clear-to-eol y x w frame)
(return-from col))
;; update attributes
(when (>= bp next-prop)
(turn-on-attributes (window-buffer w) bp))
(let ((ch (elt (buffer-data buf) p)))
;; Update display
(cond ((char= ch #\Newline)
(putch #\Space x y w frame))
(t
(putch ch x y w frame)))
;; go to the next character in the buffer
(incf p)
(incf bp))))))))
;; Check if the bottom of the window needs to be erased.
(when (< end (1- (window-height w nil)))
(loop for i from end below (window-height w nil) do
(clear-to-eol i 0 w frame)))))
;; rxvt draws black on black if i don't turn on a color
(cl-ncurses::attroff (cl-ncurses::COLOR-PAIR 1))
;; Update the mode-line if it exists. FIXME: Not the right place
;; to update the mode-line.
(when (buffer-local '*mode-line-format* (window-buffer w))
(update-mode-line (window-buffer w))
;;(cl-ncurses::attron cl-ncurses::A_REVERSE)
(cl-ncurses::attron (cl-ncurses::COLOR-PAIR 2))
(putstr (truncate-mode-line (window-buffer w) (window-width w nil))
0 (window-height w nil) w frame)
(cl-ncurses::attroff (cl-ncurses::COLOR-PAIR 2))
;;(cl-ncurses::attroff cl-ncurses::A_REVERSE)
;; don't forget the seperator on the modeline line
(when (window-seperator w)
(putch #\| (+ (window-x w) (window-width w nil)) (window-height w nil) w frame)))
(reset-line-state w)
;; Set the cursor at the right spot
(values cursor-x cursor-y)))
;;; keyboard stuff
(defmethod frame-read-event ((frame tty-frame))
(when (listen *standard-input*)
(let ((ch (char-code (read-char)))
key meta control)
(dformat +debug-v+ "read: ~a~%" ch)
;; ESC mean Meta
(when (= ch +key-escape+)
(dformat +debug-v+ "meta~%")
(setf ch (char-code (read-char))
meta t))
;; the 8th bit could also mean meta
(when (= (logand ch 128) 128)
(decf ch 128)
(setf meta t))
;; <27 means Control
(when (< ch 27)
(incf ch 96)
(setf control t))
;; set key to the character
(setf key (case ch
(+key-backspace+
#\Backspace)
(+key-enter+
#\Return)
(+key-tab+
#\Tab)
(t
(code-char ch))))
(make-key
:char key
:control control
:meta meta))))
;;; some frame stuff
(defun init-tty-colors ()
(cl-ncurses::start-color)
(cl-ncurses::init-pair 1 cl-ncurses::COLOR_WHITE cl-ncurses::COLOR_BLACK)
(cl-ncurses::init-pair 2 cl-ncurses::COLOR_GREEN cl-ncurses::COLOR_BLUE)
(cl-ncurses::init-pair 3 cl-ncurses::COLOR_WHITE cl-ncurses::COLOR_BLACK)
(cl-ncurses::init-pair 4 cl-ncurses::COLOR_RED cl-ncurses::COLOR_BLACK)
(cl-ncurses::init-pair 5 cl-ncurses::COLOR_MAGENTA cl-ncurses::COLOR_GREEN)
(cl-ncurses::init-pair 6 cl-ncurses::COLOR_BLACK cl-ncurses::COLOR_BLUE)
(cl-ncurses::init-pair 7 cl-ncurses::COLOR_WHITE cl-ncurses::COLOR_CYAN)
(cl-ncurses::init-pair 8 cl-ncurses::COLOR_RED cl-ncurses::COLOR_MAGENTA))
;; (cl-ncurses::attron (cl-ncurses::COLOR-PAIR 1)))
(defun init-tty ()
(let ((scr (cl-ncurses::initscr)))
(init-tty-colors)
;;(cl-ncurses::raw)
(cl-ncurses::cbreak)
(cl-ncurses::meta scr 1)
(cl-ncurses::noecho)
(cl-ncurses::erase)
(cl-ncurses::scrollok scr 0)
(enable-sigint-handler)
(term-backup-settings)
(term-set-quit-char *quit-code*)))
(defun shutdown-tty ()
(term-restore-settings)
(cl-ncurses::endwin))
(defun make-default-tty-frame (buffer)
(let* ((lines cl-ncurses::*lines*)
(height (1- lines))
(cols (prog1 cl-ncurses::*cols*))
(l (make-array (* lines cols)
:element-type 'character))
(d (make-array (list lines cols)
:element-type 'character
:displaced-to l :displaced-index-offset 0))
(w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer))
(mb (make-minibuffer-window lines cols))
(frame (make-instance 'tty-frame
:width cols
:height lines
:window-tree (list w mb)
:selected-window w
:minibuffer-window mb
:double-buffer l
:2d-double-buffer d)))
(setf (window-frame w) frame
(window-frame mb) frame)
frame))
(defun make-test-frame (buffer)
"This can be used to create a frame configuration for testing."
(let* ((lines 20)
(height (1- lines))
(cols 78)
(l (make-array (* lines cols)
:element-type 'character
:initial-element #\Space))
(d (make-array (list lines cols)
:element-type 'character
:displaced-to l :displaced-index-offset 0))
(w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer))
(mb (make-minibuffer-window lines cols))
(frame (make-instance 'tty-frame
:width cols
:height lines
:window-tree (list w mb)
:selected-window w
:minibuffer-window mb
:double-buffer l
:2d-double-buffer d)))
(setf (window-frame w) frame
(window-frame mb) frame)
frame))
| 9,886 | Common Lisp | .lisp | 260 | 32.965385 | 121 | 0.648468 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7249f8860624c014b219bc78f0b04f945082756ef7c4ac161db73da0957e8859 | 18,443 | [
-1
] |
18,444 | major-mode.lisp | spacebat_lice/src/major-mode.lisp | ;;; Implement the major mode system
(in-package "LICE")
(defclass major-mode ()
((name :type string :initarg :name :accessor major-mode-name)
(map :type keymap :initarg :map :accessor major-mode-map)
(syntax :initarg :syntax-table :accessor major-mode-syntax-table)
(hook :initarg :hook :accessor major-mode-hook)
(init :initarg :init :accessor major-mode-init)
(inherit-map :type list :initarg :inherit-map :accessor major-mode-inherit-map)
(inherit-syntax :type list :initarg :inherit-syntax :accessor major-mode-inherit-syntax)
(inherit-init :type list :initarg :inherit-init :accessor major-mode-inherit-init))
(:default-initargs
:map (make-sparse-keymap)
:syntax-table *standard-syntax-table*
:inherit-map nil
:inherit-syntax nil
:inherit-init nil
:hook nil
:init nil)
(:documentation "A Major Mode class."))
(defun set-major-mode (mm)
"Set the current buffer's major mode."
(check-type mm symbol)
(let ((mode (symbol-value mm)))
;; Call All inherited init functions
(mapc 'set-major-mode (major-mode-inherit-init mode))
(when (major-mode-map mode)
(use-local-map (major-mode-map mode)))
(when (major-mode-syntax-table mode)
(set-syntax-table (major-mode-syntax-table mode)))
;; Now call this mm's init function
(when (major-mode-init mode)
(funcall (major-mode-init mode)))
;; Finally, set the mode and call the hook
(setf (buffer-major-mode (current-buffer)) mm)
(run-hooks (major-mode-hook mode))))
(provide :lice-0.1/major-mode)
| 1,554 | Common Lisp | .lisp | 37 | 37.864865 | 91 | 0.706623 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a08a32d932e43dcbf2f3d7e8af6c0ccfd0a0038874f2e8be114b729eb5c0fa09 | 18,444 | [
-1
] |
18,445 | files.lisp | spacebat_lice/src/files.lisp | (in-package :lice)
(defcustom *mode-require-final-newline* t
"Whether to add a newline at end of file, in certain major modes.
Those modes set `require-final-newline' to this value when you enable them.
They do so because they are often used for files that are supposed
to end in newlines, and the question is how to arrange that.
A value of t means do this only when the file is about to be saved.
A value of `visit' means do this right after the file is visited.
A value of `visit-save' means do it at both of those times.
Any other non-nil value means ask user whether to add a newline, when saving.
nil means do not add newlines. That is a risky choice in this variable
since this value is used for modes for files that ought to have final newlines.
So if you set this to nil, you must explicitly check and add
a final newline, whenever you save a file that really needs one."
:type '(choice (const :tag "When visiting" visit)
(const :tag "When saving" t)
(const :tag "When visiting or saving" visit-save)
(const :tag "Don't add newlines" nil)
(other :tag "Ask each time" ask))
:group 'editing-basics
:version "22.1")
(defcustom-buffer-local *require-final-newline* nil
"Whether to add a newline automatically at the end of the file.
A value of t means do this only when the file is about to be saved.
A value of `visit' means do this right after the file is visited.
A value of `visit-save' means do it at both of those times.
Any other non-nil value means ask user whether to add a newline, when saving.
nil means don't add newlines.
Certain major modes set this locally to the value obtained
from `mode-require-final-newline'."
:type '(choice (const :tag "When visiting" visit)
(const :tag "When saving" t)
(const :tag "When visiting or saving" visit-save)
(const :tag "Don't add newlines" nil)
(other :tag "Ask each time" ask))
:group 'editing-basics)
(defun format-filename (filename)
(declare (type pathname filename))
(format nil "~a~@[.~a~]"
(pathname-name filename)
(pathname-type filename)))
(defun slurp-file (filename)
"Return the contents of FILENAME as a string."
(declare (type pathname filename))
(with-open-file (in filename)
;; Note the 1+ is to leave a 1 character gap, because a buffer
;; can't have a 0 length gap.
(let* ((str (make-array (1+ (file-length in)) :element-type 'character)))
(read-sequence str in)
str)))
(defun make-file-buffer (filename)
"Assumes filename has been verified to exist and is a file."
;; load the file, put it in a buffer
(declare (type pathname filename))
(let* ((data (slurp-file filename))
(b (make-instance 'buffer
:file filename
:point (make-marker)
:mark (make-marker)
:data data
:name (format-filename filename)
;; 1- because the data has been allocated with 1 extra character
:gap-start (1- (length data))
:gap-size 1 ;;(length +other-buf+)
:major-mode '*fundamental-mode*)))
(set-marker (buffer-point b) 0 b)
(set-marker (mark-marker b) 0 b)
b))
(defun find-file-no-select (filename)
;; TODO: verify the file is a file (not a dir) and it exists, etc.
(let ((pn (parse-namestring filename)))
;; check that the directory exists
(unless (ensure-directories-exist pn)
(error "dir doesn't exist"))
(let ((b (get-buffer-create (format-filename pn))))
(setf (buffer-file b) pn)
(when (probe-file pn)
(setf (buffer-data b) (slurp-file pn)
(buffer-gap-start b) (1- (length (buffer-data b)))
(buffer-gap-size b) 1))
b)))
(defcommand find-file ((filename)
(:file "Find File: "))
""
(let ((b (find-file-no-select filename)))
(switch-to-buffer b)))
(defcommand save-buffer ()
(let ((buffer (current-buffer)))
(when (buffer-file buffer)
(if (buffer-modified-p buffer)
(with-open-file (out (buffer-file buffer)
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
;; write the data before the gap
(write-sequence (buffer-data buffer) out
:start (buffer-min buffer)
:end (buffer-gap-start buffer))
;; write the data after the gap
(write-sequence (buffer-data buffer) out
:start (gap-end buffer)
:end (length (buffer-data buffer)))
(setf (buffer-modified-p buffer) nil)
(message "Wrote ~a~%" (buffer-file (current-buffer))))
(message "(No changes need to be saved)")))))
(defun file-completions (base predicate other)
"Return a list of possible file completions given the base file, BASE. OTHER is not used."
(declare (ignore other))
;; FIXME: they need to be strings
(let ((tester (or predicate
(lambda (s)
(string= base s :end2 (min (length base)
(length s)))))))
(loop for elt in (mapcar 'princ-to-string (directory (merge-pathnames (make-pathname :name :wild) base)))
when (funcall tester elt)
collect elt)))
(defcommand load-file ((file)
(:file "Load file: "))
"Load the Lisp file named FILE."
(load file))
;;; auto save
(defun recent-auto-save-p ()
"Return t if current buffer has been auto-saved recently.
More precisely, if it has been auto-saved since last read from or saved
in the visited file. If the buffer has no visited file,
then any auto-save counts as \"recent\"."
;; FIXME: implement
nil)
(defun set-buffer-auto-saved ()
"Mark current buffer as auto-saved with its current text.
No auto-save file will be written until the buffer changes again."
(setf (buffer-auto-save-modified (current-buffer)) (buffer-modiff (current-buffer))))
;; FIXME: maybe this should be a slot in the buffer with the rest of the autosave slots
(define-buffer-local buffer-auto-save-file-name nil
"Name of file for auto-saving current buffer.
If it is nil, that means don't auto-save this buffer.")
(defcustom *delete-auto-save-files* t
"Non-nil means delete auto-save file when a buffer is saved or killed.
Note that the auto-save file will not be deleted if the buffer is killed
when it has unsaved changes."
:type 'boolean
:group 'auto-save)
(defun delete-auto-save-file-if-necessary (&optional force)
"Delete auto-save file for current buffer if `delete-auto-save-files' is t.
Normally delete only if the file was written by this Emacs since
the last real save, but optional arg FORCE non-nil means delete anyway."
(and buffer-auto-save-file-name *delete-auto-save-files*
(not (string= (buffer-file (current-buffer)) buffer-auto-save-file-name))
(or force (recent-auto-save-p))
(progn
(handler-case
(delete-file buffer-auto-save-file-name)
(file-error () nil))
(set-buffer-auto-saved))))
(defcommand save-buffers-kill-emacs ()
;; TODO: save-some-buffers
(kill-emacs))
;;; Key bindings
(define-key *ctl-x-map* "C-f" 'find-file)
(define-key *ctl-x-map* "C-r" 'find-file-read-only)
(define-key *ctl-x-map* "C-v" 'find-alternate-file)
(define-key *ctl-x-map* "C-s" 'save-buffer)
(define-key *ctl-x-map* "s" 'save-some-buffers)
(define-key *ctl-x-map* "C-w" 'write-file)
(define-key *ctl-x-map* "i" 'insert-file)
(define-key *esc-map* "~" 'not-modified)
(define-key *ctl-x-map* "C-d" 'list-directory)
(define-key *ctl-x-map* "C-c" 'save-buffers-kill-emacs)
(define-key *ctl-x-map* "C-q" 'toggle-read-only)
(define-key *ctl-x-4-map* "f" 'find-file-other-window)
(define-key *ctl-x-4-map* "r" 'find-file-read-only-other-window)
(define-key *ctl-x-4-map* "C-f" 'find-file-other-window)
(define-key *ctl-x-4-map* "b" 'switch-to-buffer-other-window)
(define-key *ctl-x-4-map* "C-o" 'display-buffer)
(define-key *ctl-x-5-map* "b" 'switch-to-buffer-other-frame)
(define-key *ctl-x-5-map* "f" 'find-file-other-frame)
(define-key *ctl-x-5-map* "C-f" 'find-file-other-frame)
(define-key *ctl-x-5-map* "r" 'find-file-read-only-other-frame)
(define-key *ctl-x-5-map* "C-o" 'display-buffer-other-frame)
(provide :lice-0.1/files)
| 8,070 | Common Lisp | .lisp | 180 | 40.522222 | 109 | 0.687738 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 606af3bd34e3b1cc159457a4cb4ae754755a34d31820c38af3d4c86e598e3a77 | 18,445 | [
-1
] |
18,446 | buffer-local.lisp | spacebat_lice/src/buffer-local.lisp | ;;; buffer local variables
(in-package "LICE")
(defstruct buffer-local-binding
symbol value local-p doc-string)
(defvar *global-buffer-locals* (make-hash-table)
"The default values of buffer locals and a hash table containing all possible buffer locals")
(defun buffer-local-exists-p (symbol)
(multiple-value-bind (v b) (gethash symbol *global-buffer-locals*)
(declare (ignore v))
b))
(defun get-buffer-local-create (symbol default-value &optional doc-string)
(if (buffer-local-exists-p symbol)
(gethash symbol *global-buffer-locals*)
(setf (gethash symbol *global-buffer-locals*)
(make-buffer-local-binding :symbol symbol
:value default-value
:doc-string doc-string))))
(defmacro define-buffer-local (symbol default-value &optional doc-string)
"buffer locals are data hooks you can use to store values per
buffer. Use them when building minor and major modes. You
generally want to define them with this so you can create a
docstring for them. there is also `get-buffer-local-create'."
`(progn
(when (boundp ',symbol)
(warn "Symbol ~s is already bound. Existing uses of symbol will not be buffer local." ',symbol)
(makunbound ',symbol))
(define-symbol-macro ,symbol (buffer-local ',symbol))
(get-buffer-local-create ',symbol ,default-value ,doc-string)))
(defun (setf buffer-local) (value symbol &optional (buffer (current-buffer)))
"Set the value of the buffer local in the current buffer."
;; create a global buffer local entry if needed.
(let ((global-binding (get-buffer-local-create symbol value)))
;; if the symbol becomes buffer local when set or it has a buffer
;; value
(if (or (buffer-local-binding-local-p global-binding)
(second (multiple-value-list
(gethash symbol (buffer-locals buffer)))))
;; set the buffer's value
(setf (gethash symbol (buffer-locals buffer)) value)
;; set the global value
(setf (buffer-local-binding-value global-binding) value))))
(defun buffer-local (symbol &optional (buffer (current-buffer)))
"Return the value of the buffer local symbol. If none exists
for the current buffer then use the global one. If that doesn't
exist, throw an error."
(multiple-value-bind (v b) (gethash symbol (buffer-locals buffer))
(if b
v
(multiple-value-bind (v b) (gethash symbol *global-buffer-locals*)
(if b
(buffer-local-binding-value v)
(error "No binding for buffer-local ~s" symbol))))))
(defun make-local-variable (symbol)
"Make VARIABLE have a separate value in the current buffer.
Other buffers will continue to share a common default value.
\(The buffer-local value of VARIABLE starts out as the same value
VARIABLE previously had. If VARIABLE was void, it remains void.\)
Return VARIABLE.
If the variable is already arranged to become local when set,
this function causes a local value to exist for this buffer,
just as setting the variable would do.
Unlike GNU/Emacs This function does not return
VARIABLE. See alse `(SETF MAKE-LOCAL-VARIABLE)'.
See also `make-variable-buffer-local' and `define-buffer-local'.
Do not use `make-local-variable' to make a hook variable buffer-local.
Instead, use `add-hook' and specify t for the LOCAL argument."
(setf (gethash symbol (buffer-locals (current-buffer))) (buffer-local symbol))
;; only setq and setf expand the symbol-macro properly, so we can't
;; return the symbol.
nil)
(defun (setf make-local-variable) (value symbol)
"Make the symbol local to the current buffer like
`make-local-variable' and also set its value in the buffer."
(setf (gethash symbol (buffer-locals (current-buffer))) value))
(defun make-variable-buffer-local (variable)
"Make VARIABLE become buffer-local whenever it is set.
At any time, the value for the current buffer is in effect,
unless the variable has never been set in this buffer,
in which case the default value is in effect.
Note that binding the variable with `let', or setting it while
a `let'-style binding made in this buffer is in effect,
does not make the variable buffer-local. Return VARIABLE.
In most cases it is better to use `make-local-variable',
which makes a variable local in just one buffer.
The function `default-value' gets the default value and `set-default' sets it."
(setf (buffer-local-binding-local-p (gethash variable *global-buffer-locals*)) t))
(defun default-value (symbol)
"Return SYMBOL's default value.
This is the value that is seen in buffers that do not have their own values
for this variable. The default value is meaningful for variables with
local bindings in certain buffers."
(buffer-local-binding-value (gethash symbol *global-buffer-locals*)))
(defun (setf default-value) (value symbol)
"Set symbol's default value to value. symbol and value are evaluated.
The default value is seen in buffers that do not have their own values
for this variable."
(setf (buffer-local-binding-value (gethash symbol *global-buffer-locals*)) value) )
(depricate set-default (setf default-value))
(defun set-default (symbol value)
"Set symbol's default value to value. symbol and value are evaluated.
The default value is seen in buffers that do not have their own values
for this variable."
(setf (default-value symbol) value))
(defmacro setq-default (var value)
"Set the default value of variable var to value."
`(setf (default-value ',var) ,value))
;;; Some built-in buffer local variables
(define-buffer-local *buffer-invisibility-spec* nil
"Invisibility spec of this buffer.
The default is t, which means that text is invisible
if it has a non-nil `invisible' property.
If the value is a list, a text character is invisible if its `invisible'
property is an element in that list.
If an element is a cons cell of the form (PROP . ELLIPSIS),
then characters with property value PROP are invisible,
and they have an ellipsis as well if ELLIPSIS is non-nil.")
(define-buffer-local *selective-display* nil
"Non-nil enables selective display.
An Integer N as value means display only lines
that start with less than n columns of space.
A value of t means that the character ^M makes itself and
all the rest of the line invisible; also, when saving the buffer
in a file, save the ^M as a newline.")
(define-buffer-local *mark-active* nil
"Non-nil means the mark and region are currently active in this buffer.")
| 6,493 | Common Lisp | .lisp | 125 | 48.192 | 102 | 0.742627 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 87fcd4c86f235d5dba88b217ad03d1e259bdc98357c77ed30f4e16a9392b1dbc | 18,446 | [
-1
] |
18,447 | main.lisp | spacebat_lice/src/main.lisp | (in-package "LICE")
;;
#+cmu (setf extensions:*gc-notify-after* (lambda (&rest r))
extensions:*gc-notify-before* (lambda (&rest r)))
(defun init-mode-line-format ()
(setf *default-mode-line-format*
(list "--:" ;; fake it for hype
(lambda (buffer)
(format nil "~C~C"
;; FIXME: add read-only stuff
(if (buffer-modified-p buffer)
#\* #\-)
(if (buffer-modified-p buffer)
#\* #\-)))
" "
(lambda (buffer)
(format nil "~12,,,a" (buffer-name buffer)))
" "
(lambda (buffer)
(format nil "(~a)"
(major-mode-name (symbol-value (buffer-major-mode buffer))))))))
(defun lice ()
"Run the lice environment."
(unwind-protect
(progn
(dformat +debug-v+ "-- Start lice~%")
#+(or cmu sbcl) (init-tty)
#+clisp (init-clisp)
(setf *buffer-list* nil)
#+movitz (init-commands)
(init-mode-line-format)
(make-default-buffers)
(set-buffer (get-buffer "*messages*"))
;; for the scratch buffer
(set-buffer (get-buffer "*scratch*"))
(insert *initial-scratch-message*)
;; FIXME: is this a hack?
(setf (buffer-modified-p (current-buffer)) nil
(buffer-undo-list (current-buffer)) nil)
(goto-char (point-min))
(set-major-mode '*lisp-interaction-mode*)
(init-command-arg-types)
(setf *frame-list* (list #+(or cmu sbcl) (make-default-tty-frame (get-buffer "*scratch*"))
#+clisp (make-default-clisp-frame (get-buffer "*scratch*"))
#+mcl (make-default-mcl-frame (get-buffer "*scratch*"))
#+movitz (make-default-movitz-frame (get-buffer "*scratch*")))
*selected-frame* (car *frame-list*)
*process-list* nil)
;;(make-global-keymaps)
(catch 'lice-quit
#+clisp
(ext:with-keyboard
(loop
(with-simple-restart (recursive-edit-top-level "Return to LiCE top level")
(recursive-edit))))
#-clisp
(loop
(with-simple-restart (recursive-edit-top-level "Return to LiCE top level")
(recursive-edit)))))
(progn
#+(or cmu sbcl) (shutdown-tty)
#+clisp (shutdown)
(dformat +debug-v+ "-- End lice~%"))))
#+movitz
(defun init-commands ()
"Our special wikked hack."
(macrolet ((create-cmd (name &rest args)
(let ((tmp (gensym)))
`(setf (gethash ',name *commands*)
(make-instance
'command
:name ',name
:args ',(delete nil (mapcar (lambda (a)
(when (listp a) (second a)))
args))
:doc nil
:fn (lambda ()
(let ((,tmp (list ,@(delete nil (mapcar (lambda (a)
(when (listp a)
`(funcall (gethash ,(second a) *command-arg-type-hash*) ,@(cddr a))))
args)))))
;; XXX: Is this a sick hack? We need to reset the
;; prefix-arg at the right time. After the command
;; is executed we can't because the universal
;; argument code sets the prefix-arg for the next
;; command. The Right spot seems to be to reset it
;; once a command is about to be executed, and
;; after the prefix arg has been gathered to be
;; used in the command. Which is right here.
(setf *prefix-arg* nil)
;; Note that we use the actual function. If the
;; function is redefined, the command will
;; continue to be defined and will call the
;; function declared above, not the redefined one.
(apply #',name ,tmp))))))))
(setf fundamental-mode
(make-instance 'major-mode
:name "Fundamental"
:map (make-hash-table)
:init-fn (lambda ()))
minibuffer-read-mode
(make-instance 'major-mode
:name "minibuffer mode"
:map (let ((m (make-sparse-keymap)))
(define-key m (make-instance 'key :char #\m :control t) 'exit-minibuffer)
(define-key m (make-instance 'key :char #\Newline) 'exit-minibuffer)
(define-key m (make-instance 'key :char #\j :control t) 'exit-minibuffer)
(define-key m (make-instance 'key :char #\p :meta t) 'previous-history-element)
(define-key m (make-instance 'key :char #\n :meta t) 'next-history-element)
(define-key m (make-instance 'key :char #\g :control t) 'abort-recursive-edit)
m)
:init-fn (lambda ()))
minibuffer-complete-mode
(make-instance 'major-mode
:name "minibuffer complete mode"
:map (let ((m (make-sparse-keymap)))
(define-key m (make-instance 'key :char #\m :control t) 'minibuffer-complete-and-exit)
(define-key m (make-instance 'key :char #\Newline) 'minibuffer-complete-and-exit)
(define-key m (make-instance 'key :char #\j :control t) 'minibuffer-complete-and-exit)
(define-key m (make-instance 'key :char #\p :meta t) 'previous-history-element)
(define-key m (make-instance 'key :char #\n :meta t) 'next-history-element)
(define-key m (make-instance 'key :char #\i :control t) 'minibuffer-complete)
(define-key m (make-instance 'key :char #\Tab) 'minibuffer-complete)
(define-key m (make-instance 'key :char #\g :control t) 'abort-recursive-edit)
m)
:init-fn (lambda ()))
lisp-interaction-mode
(make-instance 'major-mode :name "Lisp Interaction"
:map (let ((m (make-sparse-keymap)))
(define-key m (make-instance 'key :char #\j :control t) 'eval-print-last-sexp)
m)
:init-fn (lambda ()))
*universal-argument-map*
(let ((map (make-sparse-keymap)))
(define-key map t 'universal-argument-other-key)
(define-key map (kbd "C-u") 'universal-argument-more)
(define-key map (kbd "-") 'universal-argument-minus)
(define-key map (kbd "0") 'digit-argument)
(define-key map (kbd "1") 'digit-argument)
(define-key map (kbd "2") 'digit-argument)
(define-key map (kbd "3") 'digit-argument)
(define-key map (kbd "4") 'digit-argument)
(define-key map (kbd "5") 'digit-argument)
(define-key map (kbd "6") 'digit-argument)
(define-key map (kbd "7") 'digit-argument)
(define-key map (kbd "8") 'digit-argument)
(define-key map (kbd "9") 'digit-argument)
map))
(setf *mode-line-format* (list "--:" ;; fake it for hype
(lambda (buffer)
(format nil "~C~C"
;; FIXME: add read-only stuff
(if (buffer-modified-p buffer)
#\* #\-)
(if (buffer-modified-p buffer)
#\* #\-)))
" "
(lambda (buffer)
(format nil "~12,,,a" (buffer-name buffer)))
" "
(lambda (buffer)
(format nil "(~a)"
(major-mode-name (buffer-major-mode buffer))))))
(setf *commands* (make-hash-table :size 100))
(create-cmd forward-sexp)
(create-cmd backward-sexp)
(create-cmd eval-last-sexp)
(create-cmd eval-print-last-sexp)
(create-cmd lisp-interaction-mode)
(create-cmd ask-user)
(create-cmd exit-minibuffer)
(create-cmd abort-recursive-edit)
(create-cmd minibuffer-complete-and-exit)
(create-cmd next-history-element (n :prefix))
(create-cmd previous-history-element)
(create-cmd minibuffer-complete)
(create-cmd forward-char (n :prefix))
(create-cmd backward-char (n :prefix))
(create-cmd self-insert-command (arg :prefix))
(create-cmd newline)
(create-cmd next-line (n :prefix))
(create-cmd previous-line (n :prefix))
(create-cmd delete-backward-char)
(create-cmd delete-char)
(create-cmd beginning-of-line)
(create-cmd end-of-line)
(create-cmd erase-buffer)
(create-cmd execute-extended-command (n :prefix))
(create-cmd switch-to-buffer (buffer :buffer "Switch To Buffer: " (buffer-name (other-buffer (current-buffer)))))
(create-cmd save-buffers-kill-emacs ())
(create-cmd kill-buffer (buffer :buffer "Kill buffer: " (buffer-name (current-buffer)) t))
(create-cmd eval-expression (s :string "Eval: "))
(create-cmd exchange-point-and-mark)
(create-cmd set-mark-command)
(create-cmd scroll-up)
(create-cmd scroll-down)
(create-cmd end-of-buffer)
(create-cmd beginning-of-buffer)
(create-cmd split-window-vertically)
(create-cmd split-window-horizontally)
(create-cmd other-window)
(create-cmd switch-to-buffer-other-window (buffer :buffer "Switch to buffer in other window: " (buffer-name (other-buffer (current-buffer)))))
(create-cmd delete-other-windows)
(create-cmd keyboard-quit)
(create-cmd kill-ring-save)
(create-cmd kill-region (beg :region-beginning) (end :region-end))
(create-cmd kill-line)
(create-cmd yank)
(create-cmd yank-pop)
(create-cmd universal-argument)
(create-cmd universal-argument-more (arg :raw-prefix))
(create-cmd negative-argument (arg :raw-prefix))
(create-cmd digit-argument (arg :raw-prefix))
(create-cmd universal-argument-minus (arg :raw-prefix))
(create-cmd universal-argument-other-key (arg :raw-prefix))))
#+(or cmu sbcl)
(defun rl ()
(asdf:oos 'asdf:load-op :lice))
;;; The Deep Hack
;;(muerte.init::lice-genesis)
;; (defun foo ()
;; (let (a)
;; (labels ((do1 ()
;; ;; do stuff and then
;; (when <stuff>
;; (setf a <a struct>)))
;; (do2 ()
;; ;; do stuff and then call..
;; (do1)))
;; (do2)
;; a)))
(provide :lice-0.1/main)
| 9,384 | Common Lisp | .lisp | 232 | 33.827586 | 146 | 0.613475 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | eba47baaaf79f7b1e9584a5556863c1d033a73394039cdea54de4d710208ca18 | 18,447 | [
-1
] |
18,448 | insdel.lisp | spacebat_lice/src/insdel.lisp | ;;; buffer inserting, deleting, gap management, etc
(in-package "LICE")
;; (defun gap-close (buf)
;; "Move the gap to the end of the buffer."
;; (let ((gap-start (buffer-gap-start buf))
;; (gap-end (gap-end buf)))
;; (setf (buffer-gap-start buf) (- (length (buffer-data buf)) (buffer-gap-size buf)))
;; (replace (buffer-data buf) (buffer-data buf) :start1 gap-start :start2 gap-end)))
(defun grow-buffer-data (buf size)
"Grow the buffer data array to be SIZE. SIZE must be larger than before."
;; MOVITZ doesn't have adjust-array
;; ;; #\_ is used for debugging to represent the gap
;; (adjust-array (buffer-data buf) size :initial-element #\_ :fill-pointer t)
(let ((newbuf (make-array size :initial-element #\_;; :fill-pointer t
:element-type 'character)))
(replace newbuf (buffer-data buf))
(setf (buffer-data buf) newbuf)))
(defun gap-extend (buf size)
"Extend the gap by SIZE characters."
(let ((new-size (+ (length (buffer-data buf)) size))
(old-end (gap-end buf))
(old-size (buffer-size buf))
(data (buffer-data buf)))
(setf data (grow-buffer-data buf new-size))
(incf (buffer-gap-size buf) size)
(unless (= (buffer-gap-start buf) old-size)
(replace data data
:start1 (gap-end buf)
:start2 old-end))
;; for debugging, mark the gap
(fill-gap buf)))
;; (defun buffer-char-before-point (buf p)
;; "The character at the point P in buffer BUF. P is in char space."
;; (declare (type buffer buf)
;; (type integer p))
;; (let ((aref (buffer-char-to-aref buf p)))
;; (when (< aref (length (buffer-data buf)))
;; (aref (buffer-data buf) aref))))
(defgeneric buffer-insert (buffer object)
(:documentation "Insert OBJECT into BUFFER at the current point."))
(defmethod buffer-insert :after ((buf buffer) object)
"Any object insertion modifies the buffer."
(declare (ignore object))
(setf (buffer-modified-p buf) t))
(defmethod buffer-insert ((buf buffer) (char character))
"Insert a single character into buffer before point."
;; Resize the gap if needed
(if (<= (buffer-gap-size buf) 1)
(gap-extend buf 100))
;; Move the gap to the point
(unless (= (pt buf) (buffer-gap-start buf))
(gap-move-to buf (buffer-point-aref buf)))
(update-markers-ins buf (pt buf) 1)
;; undo
(record-insert (pt buf) 1 buf)
;; set the character
(setf (aref (buffer-data buf) (buffer-gap-start buf)) char)
;; move the gap forward
(incf (buffer-gap-start buf))
(decf (buffer-gap-size buf))
;; expand the buffer intervals
(offset-intervals buf (pt buf) 1))
(defmethod buffer-insert ((buf buffer) (string string))
;; resize
(when (<= (buffer-gap-size buf) (length string))
(gap-extend buf (+ (length string) 100)))
;; move the gap to the point
(unless (= (pt buf) (buffer-gap-start buf))
(gap-move-to buf (buffer-point-aref buf)))
(update-markers-ins buf (pt buf) (length string))
;; undo
(record-insert (pt buf) (length string) buf)
;; insert chars
(replace (buffer-data buf) string :start1 (buffer-gap-start buf))
(incf (buffer-gap-start buf) (length string))
(decf (buffer-gap-size buf) (length string))
;; expand the buffer intervals
(offset-intervals buf (pt buf) (length string)))
(defmethod buffer-insert ((buf buffer) (string pstring))
;; insert string
(buffer-insert buf (pstring-data string))
;; insert properties
(graft-intervals-into-buffer (intervals string)
(pt buf)
(pstring-length string)
buf
t))
(defgeneric insert-move-point (buffer object)
(:documentation "Insert OBJECT into BUFFER at the current point. Move the point
forward by its length."))
(defmethod insert-move-point ((buffer buffer) (object character))
(buffer-insert buffer object)
(incf (marker-position (buffer-point buffer))))
(defmethod insert-move-point ((buffer buffer) (object string))
(buffer-insert buffer object)
(incf (marker-position (buffer-point buffer)) (length object)))
(defmethod insert-move-point ((buffer buffer) (object pstring))
(buffer-insert buffer object)
(incf (marker-position (buffer-point buffer)) (pstring-length object)))
(defun buffer-delete (buf p length)
"Deletes chars from point to point + n. If N is negative, deletes backwards."
(cond ((< length 0)
(gap-move-to buf (buffer-char-to-aref buf p))
(let* ((new (max 0 (+ (buffer-gap-start buf) length)))
(capped-size (- (buffer-gap-start buf) new)))
(update-markers-del buf new capped-size)
(record-delete new (make-buffer-string new (+ new capped-size) t buf))
(adjust-intervals-for-deletion buf new capped-size)
(incf (buffer-gap-size buf) capped-size)
(setf (buffer-gap-start buf) new)))
((> length 0)
(unless (>= p (zv buf))
;; can't delete forward if we're at the end of the buffer.
(gap-move-to buf (buffer-char-to-aref buf p))
;; Make sure the gap size doesn't grow beyond the buffer size.
(let ((capped-size (- (min (+ (gap-end buf) length)
(length (buffer-data buf)))
(gap-end buf))))
(record-delete p (make-buffer-string p (+ p capped-size) t buf))
(incf (buffer-gap-size buf) capped-size)
(update-markers-del buf p capped-size)
(adjust-intervals-for-deletion buf p capped-size)))))
(setf (buffer-modified-p buf) t)
;; debuggning
(fill-gap buf))
(defun buffer-erase (&optional (buf (current-buffer)))
;; update properties
(record-delete (begv buf) (make-buffer-string (begv buf) (zv buf) t buf) buf)
(adjust-intervals-for-deletion buf 0 (buffer-size buf))
(update-markers-del buf 0 (buffer-size buf))
;; expand the gap to take up the whole buffer
(setf (buffer-gap-start buf) 0
(buffer-gap-size buf) (length (buffer-data buf))
(marker-position (buffer-point buf)) 0
(buffer-modified-p buf) t)
;; debugging
(fill-gap buf))
(defcommand erase-buffer ((&optional (buffer (current-buffer))))
"Delete the entire contents of the current buffer.
Any narrowing restriction in effect (see `narrow-to-region') is removed,
so the buffer is truly empty after this."
(buffer-erase buffer))
| 6,140 | Common Lisp | .lisp | 142 | 39.485915 | 89 | 0.679819 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ea0dfa1bf205b15717f29f87128cda65c38b073d1afeac703cbe2a1611b5eb8b | 18,448 | [
-1
] |
18,449 | window.lisp | spacebat_lice/src/window.lisp | (in-package "LICE")
(defvar *next-screen-context-lines* 2
"Number of lines of continuity when scrolling by screenfuls.")
(defvar *window-min-height* 4
"Delete any window less than this tall (including its mode line).")
(defvar *window-min-width* 10
"Delete any window less than this wide.")
(defmacro check-live-window (win)
"This macro rejects windows on the interior of the window tree as
\"dead\", which is what we want; this is an argument-checking macro, and
the user should never get access to interior windows.
A window of any sort, leaf or interior, is dead iff the buffer,
vchild, and hchild members are all nil."
`(and
(check-type ,win window)
(not (null (window-buffer ,win)))))
;; we just want a fast and easy dumping area for data. start and end
;; are inclusive.
(defstruct cache-item
(start 0 :type integer)
(end 0 :type integer))
(defun make-empty-cache-item-vector ()
;; (make-array 0 :element-type 'cache-item
;; :adjustable t
;; :fill-pointer 0)
())
(defun item-in-cache (window n)
"Return the Nth item in the cache or NIL if it doesn't exist."
(elt (lc-cache (window-cache window)) n))
;; (when (< n (length (lc-cache (window-cache window))))
;; (aref (lc-cache (window-cache window)) n)))
;; (defun update-window-display-arrays (window)
;; "Used to update the window display structures for window splits."
;; (let* ((rows (window-height window t))
;; (cols (window-width window t))
;; (l (make-array (* rows cols)
;; :element-type 'character))
;; (d (make-array (list rows cols)
;; :element-type 'character
;; :displaced-to l :displaced-index-offset 0)))
;; ;; FIXME: This forces needless redraw because the arrays are
;; ;; reset.
;; (setf (window-display window) l
;; (window-2d-display window) d)))
(defun make-window (&key x y cols rows buffer frame
(top (make-marker))
(bpoint (make-marker))
(bottom (make-marker))
(type 'window))
"Return a new window. This is handy for setting up all the pesky
display structures.
TYPE isn't used yet. it's just there for hype."
(let* ((w (make-instance type
:frame frame
:x x :y y :w cols :h rows
:line-state (make-array rows :element-type 'integer :initial-element -1)
:cache (make-instance 'line-cache :valid t)
:top-line 0
:bottom-line 0
:point-col 0
:point-line 0
:buffer buffer
:top top
:bottom bottom
:bpoint bpoint
:point-col 0
:point-line 0)))
(set-marker bpoint (pt buffer) buffer)
(set-marker top (begv buffer) buffer)
(set-marker bottom (begv buffer) buffer)
w))
(defun make-test-window (buffer)
(make-window :x 0 :y 0 :cols 60 :rows 20 :buffer buffer))
;;; Other non-display related functions
(defun window-height (&optional (w (selected-window)) (include-mode-line t))
"Return the height of the window. By default, the mode-line is not
included in the height."
;; if the mode-line is nil, then there is no modeline.
(if (or include-mode-line
(null (buffer-local '*mode-line-format* (window-buffer w))))
(slot-value w 'h)
(1- (slot-value w 'h))))
(defun window-width (&optional (w (selected-window)) (include-seperator t))
"Return the width of the window. By default, the vertical seperator,
for horizontal splits, is not included in the width."
;; if the mode-line is nil, then there is no modeline.
(if (or include-seperator
(not (window-seperator w)))
(slot-value w 'w)
(1- (slot-value w 'w))))
(defun selected-window ()
"Return the window that the cursor now appears in and commands apply to."
(frame-selected-window (selected-frame)))
;; *selected-window*)
(defun set-window-buffer (window buffer &optional keep-margins)
"Make WINDOW display BUFFER as its contents.
BUFFER can be a buffer or buffer name.
Optional third arg KEEP-MARGINS non-nil means that WINDOW's current
display margins, fringe widths, and scroll bar settings are maintained;
the default is to reset these from BUFFER's local settings or the frame
defaults."
;; this is redundant if buffer is a string, since its
;; looked up already.
(declare (type window window)
(type buffer buffer)
(type boolean keep-margins)
(ignore keep-margins))
(let ((buf (get-buffer buffer)))
(unless buf
(error "No buffer named ~a" buffer))
(unless (eq (window-buffer window) buf)
;; update buffer time stamps
(incf (buffer-display-count buf))
;; MOVITZ doesn't have get-universal-time
;; (setf (buffer-display-time buf) (get-universal-time))
;; update buffer list
(bring-buffer-to-front buf)
;; display stuff
(set-marker (window-top window) 0 buf)
(set-marker (window-bottom window) 100 buf)
(set-marker (window-bpoint window) (marker-position (buffer-point buf)) buf)
;; finally set the buffer
(setf (window-buffer window) buf)
;; TODO: run hooks
)))
(defgeneric cache-size (object))
(defmethod cache-size ((object line-cache))
(length (lc-cache object)))
(defmethod cache-size ((object window))
(cache-size (window-cache object)))
(defun reset-line-state (window)
(fill (window-line-state window) -1))
(defun window-reset-cache (window)
(with-slots (cache) window
(setf (lc-cache cache) nil
(lc-start cache) 0
(lc-end cache) 0
(lc-valid cache) t)))
(defun point-in-line-cache (line-cache p)
"Return the line in the cache that P is on. NIL if p is not in range"
(declare (type integer p))
(position-if (lambda (l)
(and (>= p (cache-item-start l))
(<= p (cache-item-end l))))
line-cache))
;;; Display related functions. Generate the line cache based on
;;; character cells, not pixels.
(defun add-line-to-cache (cache from to &optional at-beginning)
"Add a single line to the cache list. Return the new cache list."
(let ((line (make-cache-item :start from :end to)))
(if at-beginning
(cons line cache)
(nconc1 cache line))))
;; (progn
;; (grow-vector lines 1 line)
;; (replace lines lines :start1 1)
;; (setf (elt lines 0) line))
;; (vector-push-extend line lines))))
;; (defun generate-lines-region (cache buffer width from to)
;; "FROM must not be a newline (It should be the character after a new
;; line or the beginning of the buffer) and TO must be newline or the
;; end of the buffer."
;; (declare (type line-cache cache)
;; (type buffer buffer)
;; (type integer width from to))
;; (let ((lines (make-array 0 :element-type 'cache-item
;; :adjustable t
;; :fill-pointer 0))
;; (rplc-start (= (1+ to) (lc-start cache)))
;; (rplc-end (= (1- from) (lc-end cache)))
;; (empty-cache (= (length (lc-cache cache)) 0)))
;; (dformat +debug-vvv+ "generate-n-lines: ~a ~a~%" from to)
;; ;; Make sure either from-1 or to+1 is already in the cache, its
;; ;; the first one. A point cannot exist in 2 cache lines because
;; ;; points are inclusive.
;; (when (or rplc-start rplc-end empty-cache)
;; ;; search for newlines until we hit TO
;; (do ((last-p from (1+ p))
;; (p (buffer-scan-newline buffer from to 1)
;; (buffer-scan-newline buffer (1+ p) to 1))
;; (l 0 (1+ l)))
;; (nil)
;; ;; Break the buffer line into chunks that fit on one window line
;; (dformat +debug-vvv+ "last-p: ~a p:~a~%" last-p p)
;; (loop for i from last-p by width
;; do (vector-push-extend (make-cache-item :start i
;; :end (if (<= (+ i (1- width)) p)
;; (+ i (1- width))
;; p))
;; lines)
;; always (< (+ i (1- width)) p))
;; ;; Once we've processed the new line, check if we've run out of
;; ;; buffer to process.
;; (when (= p to)
;; (return)))
;; ;; Add these new items to the cache
;; (let ((carray (lc-cache cache)))
;; (adjust-array cache
;; (+ (length carray)
;; (length lines))
;; :initial-element (aref lines 0)
;; :fill-pointer (+ (length carray)
;; (length lines)))
;; (cond (rplc-start
;; ;; Put it at the beginning
;; (dformat +debug-vvv+ "rplc-start~%")
;; (setf (lc-start cache) from)
;; (replace carray carray :start1 (length lines))
;; (replace carray lines))
;; (rplc-end
;; (dformat +debug-vvv+ "rplc-end~%")
;; (setf (lc-end cache) to)
;; (replace carray lines :start1 (- (length carray)
;; (length lines))))
;; (empty-cache
;; (dformat +debug-vvv+ "empty-cache~%")
;; (setf (lc-start cache) from)
;; (setf (lc-end cache) to)
;; ;; FIXME: we could just use lines instead of copy them over, right?
;; (replace carray lines))))))
;; (dformat +debug-vvv+ "after gen-n-lines: ~a~%" (lc-cache cache)))
(defun generate-n-lines-forward (buffer width from n-lines)
"Return an array of cache-items for N-LINES lines in BUFFER rendered
with WIDTH columns starting at FROM. The array will have length at
least N-LINES."
(declare (type buffer buffer)
(type integer width from))
(let ((lines (make-empty-cache-item-vector))
(to (1- (buffer-size buffer))))
(dformat +debug-vvv+ "generate-n-lines: ~a ~a~%" from to)
;; search for newlines until we hit TO
(do ((last-p from (1+ p))
(p (buffer-scan-newline buffer from to 1)
(buffer-scan-newline buffer (1+ p) to 1))
(l 0 (1+ l)))
(nil)
;; Break the buffer line into chunks that fit on one window line
(dformat +debug-vvv+ "last-p: ~a p:~a~%" last-p p)
(loop for i from last-p by width
do (setf lines (add-line-to-cache lines i (if (<= (+ i (1- width)) p)
(+ i (1- width))
p)))
;; (vector-push-extend (make-cache-item :start i
;; :end (if (<= (+ i (1- width)) p)
;; (+ i (1- width))
;; p))
;; lines)
always (< (+ i (1- width)) p))
;; Once we've processed the new line, check if we've generated
;; enough lines. Return LINES we're done.
(when (or (>= (length lines) n-lines)
(>= p to))
(return lines)))))
(defun generate-n-lines-backward (buffer width from n-lines)
"Return an array of cache-items for N-LINES lines in BUFFER rendered
with WIDTH columns starting at FROM and going backward. The array will
have length at least N-LINES.
FROM is assumed to the char pos of the newline at the end of the
starting line."
(declare (type buffer buffer)
(type integer width from))
(let ((lines (make-empty-cache-item-vector))
(to 0))
(dformat +debug-vvv+ "generate-n-lines: ~a ~a~%" from to)
;; search for newlines until we hit TO.
(do ((last-p from p)
(p (buffer-scan-newline buffer (1- from) to -1)
(buffer-scan-newline buffer (1- p) to -1))
(l 0 (1+ l)))
(nil)
;; Break the buffer line into chunks that fit on one window line
(dformat +debug-vvv+ "last-p: ~a p:~a~%" last-p p)
;; unless we're at the beginning of the buffer, we want the char
;; after p because p will be a newline. last-p will be the
;; newline at the end of the line, 1+ p will be the beginning.
;;
;; this is a bit hairy because we're going backwards, but we go
;; through the line forward.
;;(let ((items (make-empty-cache-item-vector)))
(loop for i from (if (zerop p) 0 (1+ p)) by width
do (setf lines (add-line-to-cache lines
i
(if (<= (+ i (1- width)) last-p)
(+ i (1- width))
last-p)
t))
;; (vector-push-extend (make-cache-item :start i
;; :end (if (<= (+ i (1- width)) last-p)
;; (+ i (1- width))
;; last-p))
;; items)
always (< (+ i (1- width)) last-p))
;;(vector-append lines (nreverse items)))
;; Once we've processed the new line, check if we've generated
;; enough lines. Return LINES we're done.
(when (or (>= (length lines) n-lines)
(<= p to))
(return lines ;; (nreverse lines)
)))))
;; (defun update-cache (cache buffer width point n-many)
;; "Add N-MANY lines to the end of the line cache CACHE unless N-MANY
;; is negative. In that case add (abs n-many) to the beginning. This
;; function requires at least 1 line in the cache already.
;; Lines are WIDTH in length. BUFFER is the data for caching."
;; ;; Fill in above the cache
;; (dformat +debug-vv+ "update-cache: ~a~%" n-many)
;; (if (> n-many 0)
;; (let* ((end (1+ (lc-end cache)))
;; pt)
;; ;; Go forward
;; (when (< end (1- (buffer-size buffer)))
;; ;; Add cache entries
;; (setf pt (buffer-scan-newline buffer
;; end (1- (buffer-size buffer))
;; n-many))
;; (generate-lines-region cache buffer width end pt)))
;; ;; Go backward
;; (let* ((start (1- (lc-start cache)))
;; pt)
;; ;; We need this because start is a newline, which we want to skip over
;; (setf n-many (1- n-many))
;; (dformat +debug-vvv+ "backward: ~a ~a ~a~%"
;; start n-many (lc-cache cache))
;; (when (and (> start 0)
;; (/= n-many 0))
;; ;; Add cache entries
;; (setf pt (buffer-scan-newline buffer start 0 n-many))
;; (generate-lines-region cache buffer width (if (> pt 0) (1+ pt) pt) start)))))
(defun add-end-of-buffer (buffer lines)
"The point can be at (buffer-size buffer) but we only scan to
1- that. So if we're scanned to the end of the buffer properly
alter LINES to contain that point."
(let ((end (1- (buffer-size buffer)))
(last-elt (elt lines (1- (length lines)))))
(when (= (cache-item-end last-elt) end)
(if (char= (buffer-char-after buffer end) #\Newline)
(add-line-to-cache lines (buffer-size buffer) (buffer-size buffer))
(incf (cache-item-end last-elt))))))
(defun window-framer-from-top (window point &optional always-return-lines)
"Fill in window's line cache from WINDOW-TOP with a full window's
worth of lines and return T if POINT was in the line cache. otherwise
don't change anything and return nil."
(let* ((lines (generate-n-lines-forward (window-buffer window) (window-width window nil)
(marker-position (window-top window))
(window-height window nil))))
(add-end-of-buffer (window-buffer window) lines)
(when (or always-return-lines
(point-in-line-cache lines point))
lines)))
(defun window-framer-from-bottom (window point &optional always-return-lines)
"Fill in window's line cache from WINDOW-BOTTOM with a full window's
worth of lines and return T if POINT was in the line cache. otherwise
don't change anything and return nil."
(let* ((lines (generate-n-lines-backward (window-buffer window) (window-width window nil)
(marker-position (window-bottom window))
(window-height window nil))))
(add-end-of-buffer (window-buffer window) lines)
(when (or always-return-lines
(point-in-line-cache lines point))
lines)))
(defun window-framer-around-point (window point n-many)
"Fill in window's line cache going out from point with n-many lines
above WINDOW-POINT, or as many as possible if we hit the top of the window."
;; Add the line with the pointer on it
(let* ((max (1- (buffer-size (window-buffer window))))
(b (buffer-scan-newline (window-buffer window) point 0 0))
(e (buffer-scan-newline (window-buffer window) point max 1))
(lines-above (generate-n-lines-backward (window-buffer window) (window-width window nil)
e n-many))
(lines-below (when (< e max)
(generate-n-lines-forward (window-buffer window) (window-width window nil)
(1+ e)
(- (window-height window nil)
(min n-many
(length lines-above)))))))
(declare (ignore b))
(if lines-below
(add-end-of-buffer (window-buffer window) lines-below)
(add-end-of-buffer (window-buffer window) lines-above))
(when (or (point-in-line-cache lines-above point)
(point-in-line-cache lines-below point))
(if lines-below
(nconc lines-above lines-below)
;; (grow-vector lines-above (length lines-below) (elt lines-below 0))
;; (replace lines-above lines-below :start1 end))
lines-above))))
(defun window-framer (window point n-many)
"fill in window's line-cache."
;; first try the top/bottom markers. if point isn't in there then
;; center the window around point.
(let* ((bot (and (window-bottom-valid window)
(window-framer-from-bottom window point)))
(top (unless bot
(window-framer-from-top window point)))
(around (unless top
(window-framer-around-point window point n-many)))
(lines (or bot top around)))
(assert lines)
;; set the top marker
(setf (window-bottom-valid window) nil)
(cond (bot
(let* ((tl (max 0 (- (length lines) (window-height window nil))))
(bl (min (1- (length lines)) (+ tl (1- (window-height window nil))))))
(setf (marker-position (window-top window))
(cache-item-start (elt lines tl))
(window-top-line window) tl
(marker-position (window-bottom window)) (cache-item-end (elt lines bl)))))
(top
(let* ((tl (point-in-line-cache lines (marker-position (window-top window))))
(bl (min (1- (length lines)) (+ tl (1- (window-height window nil))))))
(setf (window-top-line window) tl
(marker-position (window-bottom window)) (cache-item-end (elt lines bl)))))
(around
(let* ((pl (point-in-line-cache lines point))
(tl (max 0 (- pl n-many)))
(bl (min (1- (length lines)) (+ tl (1- (window-height window nil))))))
(setf (marker-position (window-top window))
(cache-item-start (elt lines tl))
(window-top-line window) tl
(marker-position (window-bottom window)) (cache-item-end (elt lines bl))))))
;; fill in window's cache
(with-slots (cache) window
(setf (lc-cache cache) lines
(lc-start cache) (cache-item-start (elt lines 0))
(lc-end cache) (cache-item-end (elt lines (1- (length lines))))
(lc-valid cache) t))))
;; (defun window-framer (window point n-many)
;; "Decide what part of the buffer to display in window. Sets top,
;; bottom, point-col, and point-line in window. N-MANY is the number of
;; lines from point to the top of the window."
;; ;; Add the line with the pointer on it
;; (let ((b (buffer-scan-newline (window-buffer window) point 0 0))
;; (e (buffer-scan-newline (window-buffer window)
;; point (1- (buffer-size (window-buffer window))) 1)))
;; (dformat +debug-vv+ "point line: ~a ~a~%" b e)
;; (generate-lines-region window (if (= b 0) b (1+ b)) e))
;; ;; search up n-many the window height
;; (update-cache window (- n-many))
;; (dformat +debug-vvv+ "cache s/e: ~a ~a~%"
;; (lc-start (window-cache window))
;; (lc-end (window-cache window)))
;; ;; search down height - n-many + 1 (we've already generated the point's line)
;; (update-cache window (- (window-height window) n-many -1))
;; ;; Special case. if we got to the end of the buffer and it ends with
;; ;; a newline. Add an extra cache line for line after that which
;; ;; could contain the cursor.
;; (when (= (lc-end (window-cache window))
;; (1- (buffer-size (window-buffer window))))
;; (add-line-to-cache window
;; (buffer-size (window-buffer window))
;; (buffer-size (window-buffer window))
;; nil t nil))
;; ;; if we find window-top or window bottom in the cache then we
;; ;; should use it as the top/bottom and generate the remaining lines
;; (let ((wtop (point-window-line window (marker-position (window-top window))))
;; (pline (point-window-line window point))
;; (wbot (point-window-line window (marker-position (window-bottom window)))))
;; (dformat +debug-vvv+ "cache: ~a~%" (lc-cache (window-cache window)))
;; (dformat +debug-vv+ ">>>wtop: ~a ~a pline: ~a ~a wbot: ~a ~a~%"
;; wtop (marker-position (window-top window))
;; pline point
;; wbot (marker-position (window-bottom window)))
;; (cond ((and wtop
;; (<= wtop pline))
;; (dformat +debug-vv+ "wtop. ~a ~%" (cache-size window))
;; (let ((lines-left (- (window-height window)
;; (- (cache-size window) wtop))))
;; (when (> lines-left 0)
;; (update-cache window lines-left))
;; (dformat +debug-vvv+ "wtop cache: ~a~%" (lc-cache (window-cache window)))
;; (setf (window-top-line window) wtop
;; (marker-position (window-top window)) (cache-item-start
;; (aref (lc-cache (window-cache window)) wtop))
;; (window-bottom-line window) (min (1- (cache-size window))
;; (+ wtop (window-height window) -1))
;; (marker-position (window-bottom window)) (cache-item-end
;; (aref (lc-cache (window-cache window))
;; (window-bottom-line window))))))
;; ((and wbot
;; (>= wbot pline))
;; (dformat +debug-vv+ "wbot. ~a ~%" (cache-size window))
;; (let ((lines-left (- (window-height window) wbot 1)))
;; (when (> lines-left 0)
;; (update-cache window (- lines-left)))
;; (dformat +debug-vvv+ "wbot cache: ~a~%" (lc-cache (window-cache window)))
;; ;; we need to rescan bottom since lines may have been
;; ;; added above it, invalidating wbot
;; (setf wbot (point-window-line window (marker-position (window-bottom window)))
;; (window-bottom-line window) wbot
;; (marker-position (window-bottom window)) (cache-item-end (aref
;; (lc-cache (window-cache window))
;; wbot))
;; (window-top-line window) (max 0 (- wbot (window-height window) 1))
;; (marker-position (window-top window)) (cache-item-start (aref
;; (lc-cache (window-cache window))
;; (window-top-line window))))))
;; (t
;; (dformat +debug-vv+ "we need to scroll. ~a ~%" (cache-size window))
;; (setf (window-top-line window) (max 0 (- pline n-many))
;; (marker-position (window-top window)) (cache-item-start (aref (lc-cache (window-cache window))
;; (window-top-line window)))
;; (window-bottom-line window) (min
;; (1- (cache-size window))
;; (+ (window-top-line window) (window-height window) -1))
;; (marker-position (window-bottom window)) (cache-item-end
;; (aref (lc-cache (window-cache window))
;; (window-bottom-line window)))))))
;; (setf (window-point-line window) (point-window-line window point))
;; (dformat +debug-vv+ "<<<top: ~a ~a pt: ~a ~a bot: ~a ~a~%"
;; (window-top-line window) (marker-position (window-top window))
;; (window-point-line window) point
;; (window-bottom-line window) (marker-position (window-bottom window))))
(defun window-point (&optional window)
"Return current value of point in WINDOW. For a nonselected window,
this is the value point would have if that window were selected."
(if (eq window (selected-window))
(pt (window-buffer window))
(marker-position (window-bpoint window))))
(defun set-window-point (window pos)
(let ((mark (if (eq window (selected-window))
(buffer-point (window-buffer window))
(window-bpoint window))))
(if (and (<= pos (buffer-max (window-buffer window)))
(>= pos (buffer-min (window-buffer window))))
(setf (marker-position mark) pos)
(error "out of range"))))
(defun get-buffer-window (buffer &optional frame)
"Return a window currently displaying BUFFER, or nil if none.
If optional argument FRAME is `visible', search all visible frames.
If optional argument FRAME is 0, search all visible and iconified frames.
If FRAME is t, search all frames.
If FRAME is nil, search only the selected frame.
If FRAME is a frame, search only that frame."
;; TODO: honour FRAME
(setf frame (selected-frame)
buffer (get-buffer buffer))
(find buffer (frame-window-list frame) :key 'window-buffer))
(defun window-scroll-up (window n-lines)
"scroll the window up (go torwards the end of the buffer) LINES many
lines, moving the window point to be visible."
(let* ((len (+ (window-height window nil) n-lines))
(lines (generate-n-lines-forward (window-buffer window) (window-width window nil)
(marker-position (window-top window))
len)))
;; if there aren't n-lines left in the buffer then signal
;; an end-of-buffer error.
;; (unless (>= (length lines) n-lines)
;; (error "end of buffer"))
(setf (marker-position (window-top window)) (cache-item-start (elt lines
(1- (min (length lines)
n-lines)))))
;; FIXME: for now, set the point at the top of the window if it
;; isn't visible.
(when (or (< (window-point window) (marker-position (window-top window)))
(not (point-in-line-cache lines (window-point window))))
(set-window-point window (marker-position (window-top window))))))
(defun window-scroll-down (window n-lines)
"scroll the window down (go torwards the beginning of the buffer)
LINES many lines, moving the window point to be visible."
(let* ((len (+ (window-height window nil) n-lines))
;; FIXME: this is basically, gross.
(above (generate-n-lines-backward (window-buffer window) (window-width window nil)
(max (buffer-min (window-buffer window))
(1- (marker-position (window-top window))))
n-lines))
(lines (generate-n-lines-forward (window-buffer window) (window-width window nil)
(cache-item-start
(elt above (max 0 (- (length above) n-lines))))
len)))
;; if there aren't n-lines left in the buffer then signal
;; an end-of-buffer error.
;; (unless (>= (length above) n-lines)
;; (error "beginning of buffer"))
(setf (marker-position (window-top window)) (cache-item-start (elt lines 0)))
;; FIXME: for now, set the point at the bottom of the window if it
;; isn't visible.
(let ((eow (elt lines (1- (min (length lines)
(window-height window nil))))))
(when (or (> (window-point window) (cache-item-end eow))
(not (point-in-line-cache lines (window-point window))))
(set-window-point window (cache-item-start eow))))))
(defun window-save-point (window)
"Save WINDOW's buffer's point to WINDOW-BPOINT."
(setf (marker-position (window-bpoint window)) (pt (window-buffer window))))
(defun window-restore-point (window)
"Restore the WINDOW's buffer's point from WINDOW-BPOINT."
;; restore the point
(setf (marker-position (buffer-point (window-buffer window)))
(marker-position (window-bpoint window))))
(defun window-tree-find-if (fn tree &optional minibuf)
"depth first search the tree. Return the element that satisfies FN."
(cond ((listp tree)
(loop for i in tree
thereis (window-tree-find-if fn i minibuf)))
((typep tree 'minibuffer-window)
(when (and minibuf
(funcall fn tree))
tree))
(t
(when (funcall fn tree)
tree))))
(defcommand delete-other-windows ()
(let* ((frame (selected-frame))
(cw (selected-window))
(mb (window-tree-find-if (lambda (w)
(typep w 'minibuffer-window))
(frame-window-tree frame)
t)))
;; FIXME: This doesn't properly refresh and the window's display
;; arrays aren't resized.
(setf (window-x cw) 0
(window-y cw) 0
(window-seperator cw) nil
(slot-value cw 'w) (frame-width frame)
(slot-value cw 'h) (- (frame-height frame) (window-height mb t))
(frame-window-tree frame) (list cw mb))
;;(update-window-display-arrays cw)
))
(defun window-parent (window)
"Return the parent list in frame-window-tree for WINDOW."
(labels ((parent-of (tree parent window)
(cond ((listp tree)
(loop for i in tree
thereis (parent-of i tree window)))
(t
(when (eq tree window)
parent)))))
(parent-of (frame-window-tree (window-frame window)) nil window)))
(defun delete-window (&optional (window (selected-window)))
(check-type window window)
(when (or (typep window 'minibuffer-window)
(typep (frame-window-tree (window-frame window)) 'window))
(error "Attempt to delete minibuffer or sole ordinary window")))
(defun pos-visible-in-window-p (&optional (pos (pt)) (window (selected-window)) partially)
"Return non-nil if position POS is currently on the frame in WINDOW.
Return nil if that position is scrolled vertically out of view.
If a character is only partially visible, nil is returned, unless the
optional argument PARTIALLY is non-nil.
If POS is only out of view because of horizontal scrolling, return non-nil.
If POS is t, it specifies the position of the last visible glyph in WINDOW.
POS defaults to point in WINDOW; WINDOW defaults to the selected window.
If POS is visible, return t if PARTIALLY is nil; if PARTIALLY is non-nil,
return value is a list of 2 or 6 elements (X Y [RTOP RBOT ROWH VPOS]),
where X and Y are the pixel coordinates relative to the top left corner
of the window. The remaining elements are omitted if the character after
POS is fully visible; otherwise, RTOP and RBOT are the number of pixels
off-window at the top and bottom of the row, ROWH is the height of the
display row, and VPOS is the row number (0-based) containing POS."
(declare (ignore partially))
(check-type pos number)
(check-type window window)
;; FIXME: horizontal scrolling. and all the partial stuff aint there
(or (< pos (marker-position (window-top window)))
(> pos (marker-position (window-bottom window)))))
(defun select-window (window &optional norecord)
"Select WINDOW. Most editing will apply to WINDOW's buffer.
If WINDOW is not already selected, also make WINDOW's buffer current.
Also make WINDOW the frame's selected window.
Optional second arg NORECORD non-nil means
do not put this buffer at the front of the list of recently selected ones.
**Note that the main editor command loop
**selects the buffer of the selected window before each command."
(declare (ignore norecord))
(check-live-window window)
(when (eq window (selected-window))
(return-from select-window window))
(window-save-point (selected-window))
(setf *selected-window* window)
(let ((sf (selected-frame)))
(if (eq sf (window-frame window))
(progn
(setf (frame-selected-window (window-frame window)) window)
;; (select-frame (window-frame window))
)
(setf (frame-selected-window sf) window))
;; FIXME: get NORECORD working
(set-buffer (window-buffer window))
(window-restore-point window)
window))
(defun replace-window-in-frame-tree (window new)
(labels ((doit (tree window new)
(let ((p (position window tree)))
(if p
(setf (nth p tree) new)
(loop for w in tree
until (and (listp w)
(doit w window new)))))))
(doit (frame-window-tree (window-frame window))
window
new)))
(defun split-window-internal (&optional (window (selected-window)) size horflag)
(when (typep window 'minibuffer-window)
(error "Attempt to split minibuffer window"))
(when (null size)
(setf size (if horflag
(ceiling (window-width window t) 2)
(ceiling (window-height window t) 2))))
(let (new)
(if horflag
(progn
(when (< size *window-min-width*)
(error "Window width ~a too small (after splitting)" size))
;; will the other window be too big?
(when (> (+ size *window-min-width*)
(window-width window t))
(error "Window width ~a too small (after splitting)" (- (window-width window t) size)))
(setf new (make-window :x (+ (window-x window) size)
:y (window-y window)
:cols (- (window-width window t) size)
:rows (window-height window t)
:buffer (window-buffer window)
:frame (window-frame window))
(window-seperator new) (window-seperator window)
(window-seperator window) t
(slot-value window 'w) size)
;;(update-window-display-arrays window)
)
(progn
(when (< size *window-min-height*)
(error "Window height ~a too small (after splitting)" size))
;; will the other window be too big?
(when (> (+ size *window-min-height*)
(window-height window t))
(error "Window width ~a too small (after splitting)" (- (window-height window t) size)))
(setf new (make-window :x (window-x window)
:y (+ (window-y window) size)
:cols (window-width window t)
:rows (- (window-height window t) size)
:buffer (window-buffer window)
:frame (window-frame window))
(window-seperator new) (window-seperator window)
(slot-value window 'h) size)
;;(update-window-display-arrays window)
))
(replace-window-in-frame-tree window (list window new))
new))
(defun next-window (window &optional minibuf)
"Return next window after WINDOW in canonical ordering of windows.
FIXME: make this the same as Emacs' next-window."
(let* ((frame (window-frame window))
(tree (frame-window-tree frame))
bit
;; when we find WINDOW, set BIT to T and return the next window.
(w (window-tree-find-if (lambda (w)
(cond (bit w)
((eq w window)
(setf bit t)
nil)))
tree
(and minibuf (> (frame-minibuffers-active frame) 0)))))
;; if we didn't find the next one, maybe it's the first one
(if (not w)
(let ((other (window-tree-find-if #'identity tree)))
(unless (eq window other)
other))
w)))
(defun previous-window (&optional window minibuf all-frames)
"Return the window preceding WINDOW in canonical ordering of windows.
If omitted, WINDOW defaults to the selected window.
Optional second arg MINIBUF t means count the minibuffer window even
if not active. MINIBUF nil or omitted means count the minibuffer iff
it is active. MINIBUF neither t nor nil means not to count the
minibuffer even if it is active.
Several frames may share a single minibuffer; if the minibuffer
counts, all windows on all frames that share that minibuffer count
too. Therefore, `previous-window' can be used to iterate through
the set of windows even when the minibuffer is on another frame. If
the minibuffer does not count, only windows from WINDOW's frame count
Optional third arg ALL-FRAMES t means include windows on all frames.
ALL-FRAMES nil or omitted means cycle within the frames as specified
above. ALL-FRAMES = `visible' means include windows on all visible frames.
ALL-FRAMES = 0 means include windows on all visible and iconified frames.
If ALL-FRAMES is a frame, restrict search to windows on that frame.
Anything else means restrict to WINDOW's frame.
If you use consistent values for MINIBUF and ALL-FRAMES, you can use
`previous-window' to iterate through the entire cycle of acceptable
windows, eventually ending up back at the window you started with.
`next-window' traverses the same cycle, in the reverse order."
(declare (ignore window minibuf all-frames))
(error "unimplemented previous-window"))
(defcommand other-window ((arg &optional all-frames)
:prefix)
"Select the ARG'th different window on this frame.
All windows on current frame are arranged in a cyclic order.
This command selects the window ARG steps away in that order.
A negative ARG moves in the opposite order. The optional second
argument ALL-FRAMES has the same meaning as in `next-window', which see."
(declare (ignore all-frames))
(check-type arg number)
(let ((w (cond
((plusp arg)
(loop
for i from 1 to arg
for w = (next-window (selected-window) t) then (next-window w t)
finally (return w)))
((minusp arg)
(loop
for i from arg downto 1
for w = (previous-window (selected-window) t) then (previous-window w t)
finally (return w)))
(t (selected-window)))))
(when w
(select-window w))))
(defun display-buffer (buffer &optional not-this-window frame)
"Make BUFFER appear in some window but don't select it.
BUFFER can be a buffer or a buffer name.
If BUFFER is shown already in some window, just use that one,
unless the window is the selected window and the optional second
argument NOT-THIS-WINDOW is non-nil (interactively, with prefix arg).
**If `pop-up-frames' is non-nil, make a new frame if no window shows BUFFER.
**Returns the window displaying BUFFER.
**If `display-buffer-reuse-frames' is non-nil, and another frame is currently
**displaying BUFFER, then simply raise that frame."
(declare (ignore frame))
(setf buffer (get-buffer buffer))
(let* ((cw (selected-window))
(w (or (window-tree-find-if (lambda (w)
(and (not (and not-this-window
(eq w cw)))
(eq (window-buffer w) buffer)))
(frame-window-tree (selected-frame)))
(next-window cw)
(split-window-internal cw))))
(set-window-buffer w buffer)
(window-restore-point w)
w))
(defun other-buffer (&optional (buffer (current-buffer)) visible-ok frame)
"Return most recently selected buffer other than BUFFER.
Buffers not visible in windows are preferred to visible buffers,
unless optional second argument VISIBLE-OK is non-nil.
If the optional third argument FRAME is non-nil, use that frame's
buffer list instead of the selected frame's buffer list.
If no other buffer exists, the buffer `*scratch*' is returned.
If BUFFER is omitted or nil, some interesting buffer is returned."
(declare (ignore frame))
;; TODO: honour FRAME argument
(let* (vis
(match (loop for b in *buffer-list*
unless (or (eq b buffer)
(char= (char (buffer-name b) 0) #\Space))
if (and (not visible-ok)
(get-buffer-window b))
do (setf vis b)
else return b)))
(or match
vis
(get-buffer-create "*scratch*"))))
(defcommand kill-buffer ((buffer)
(:buffer "Kill buffer: " (buffer-name (current-buffer)) t))
"Kill the buffer BUFFER.
The argument may be a buffer or may be the name of a buffer.
defaults to the current buffer.
Value is t if the buffer is actually killed, nil if user says no.
The value of `kill-buffer-hook' (which may be local to that buffer),
if not void, is a list of functions to be called, with no arguments,
before the buffer is actually killed. The buffer to be killed is current
when the hook functions are called.
Any processes that have this buffer as the `process-buffer' are killed
with SIGHUP."
(let* ((target (get-buffer buffer))
(other (other-buffer target)))
(if target
(progn
;; all windows carrying the buffer need a new buffer
(loop for w in (frame-window-list (selected-frame))
do (when (eq (window-buffer w) target)
(set-window-buffer w other)))
(setf *buffer-list* (delete target *buffer-list*)))
(error "No such buffer ~a" buffer))))
(defun pop-to-buffer (buffer &optional other-window norecord)
"Select buffer BUFFER in some window, preferably a different one.
If `pop-up-windows' is non-nil, windows can be split to do this.
If optional second arg OTHER-WINDOW is non-nil, insist on finding another
window even if BUFFER is already visible in the selected window.
This uses the function `display-buffer' as a subroutine; see the documentation
of `display-buffer' for additional customization information.
**Optional third arg NORECORD non-nil means
**do not put this buffer at the front of the list of recently selected ones."
(declare (ignore norecord))
;; FIXME: honour NORECORD
(setf buffer (if buffer
(or (get-buffer buffer)
(progn
(get-buffer-create buffer)))
;; FIXME: (set-buffer-major-mode buffer)
(other-buffer (current-buffer))))
(select-window (display-buffer buffer other-window)))
(defun set-window-start (window pos &optional noforce)
"Make display in WINDOW start at position POS in WINDOW's buffer.
Return POS.
Optional third arg NOFORCE non-nil inhibits next redisplay
from overriding motion of point in order to display at this exact start."
)
(defun window-start (&optional (window (selected-window)))
"Return position at which display currently starts in WINDOW.
WINDOW defaults to the selected window.
This is updated by redisplay or by calling `set-window-start'."
(marker-position (window-top window)))
;;; Key bindings
(define-key *ctl-x-map* "1" 'delete-other-windows)
(define-key *ctl-x-map* "2" 'split-window)
(define-key *ctl-x-map* "0" 'delete-window)
(define-key *ctl-x-map* "o" 'other-window)
(define-key *ctl-x-map* "^" 'enlarge-window)
(define-key *ctl-x-map* "<" 'scroll-left)
(define-key *ctl-x-map* ">" 'scroll-right)
(define-key *global-map* "C-v" 'scroll-up)
(define-key *global-map* "M-C-v" 'scroll-other-window)
(define-key *global-map* "M-v" 'scroll-down)
(define-key *global-map* "C-l" 'recenter)
(define-key *global-map* "M-r" 'move-to-window-line)
(provide :lice-0.1/window)
| 40,879 | Common Lisp | .lisp | 912 | 40.945175 | 101 | 0.662251 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 096b1d542c7618132dde9aaace54c676a1383db978c965660691174ff519f9c9 | 18,449 | [
-1
] |
18,450 | clisp.lisp | spacebat_lice/src/clisp.lisp | (defpackage :lice
(:use :cl))
(labels ((cnl (file)
(compile-file file)
(load file)))
(cnl "wrappers")
(cnl "global")
(cnl "major-mode")
(cnl "buffer")
(cnl "window")
(cnl "frame")
(cnl "clisp-render")
(cnl "intervals")
(cnl "textprop")
(cnl "editfns")
(cnl "input")
(cnl "subr")
(cnl "debugger")
(cnl "recursive-edit")
(cnl "minibuffer")
(cnl "simple")
(cnl "wm")
(cnl "lisp-mode")
(cnl "search")
(cnl "syntax")
(cnl "files")
(cnl "main"))
| 498 | Common Lisp | .lisp | 27 | 15.296296 | 24 | 0.580851 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4ada1a7d25c7c40d79d344f4640cca5ec877d5a4cccb8b02aa0d801d83eec8e3 | 18,450 | [
-1
] |
18,451 | elisp.lisp | spacebat_lice/src/elisp.lisp | (cl:defpackage "ELISP"
(:nicknames "EL")
(:use "CL")
(:shadow cl:if cl:defun)
(:export #:if #:defun))
(in-package "ELISP")
(defmacro if (test pass &rest else)
"Elisp version of IF."
`(cl:if ,test
,pass
(progn
,@else)))
(cl:defun parse-interactive (thing)
(error "unimplemented parse-interactive"))
(defmacro defun (name lambda-list &body body)
"Parse an elisp style defun and convert it to a cl defun or lice defcommand."
(let ((doc (when (stringp (car body))
(pop body)))
(decls (loop while (eq (caar body) 'declare)
collect (pop body)))
(interactive (when (and (listp (car body))
(eq (caar body) 'interactive))
(pop body))))
(if interactive
`(defcommand ,name (,lambda-list
,@(parse-interactive (cdr interactive)))
,@(append (list doc) decls body))
`(cl:defun ,name ,@(append (list doc) decls body)))))
| 1,024 | Common Lisp | .lisp | 28 | 27.75 | 79 | 0.558022 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 03ce0e54dc5a757018e23b6d09d74b9870cd7c7febbee869935856046114dd18 | 18,451 | [
-1
] |
18,452 | load.lisp | spacebat_lice/src/load.lisp | (defpackage :lice
(:use :cl))
#+sbcl (require :sb-posix)
(require 'cl-ncurses)
(require 'cl-ppcre)
(labels ((cnl (file)
(load (compile-file file))))
(cnl "wrappers")
(cnl "global")
(cnl "custom")
(cnl "commands")
(cnl "keymap")
(cnl "major-mode")
(cnl "buffer")
(cnl "subr")
(cnl "files")
(cnl "intervals")
(cnl "textprop")
(cnl "editfns")
(cnl "window")
(cnl "frame")
(cnl "tty-render")
(cnl "syntax")
(cnl "debugger")
(cnl "recursive-edit")
(cnl "wm")
(cnl "minibuffer")
(cnl "simple")
(cnl "undo")
(cnl "indent")
(cnl "lisp-mode")
(cnl "search")
(cnl "help")
(cnl "debug")
(cnl "subprocesses")
(cnl "lisp-indent")
(cnl "input")
(cnl "main")
(cnl "casefiddle")
(cnl "paragraphs")
(cnl "text-mode")
(cnl "doctor")
)
| 798 | Common Lisp | .lisp | 43 | 15.674419 | 32 | 0.598667 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 30dc4cf727d2bd9e7e6e86fafde0fa67f8df0f4371fe25e49a262254b7c04eb1 | 18,452 | [
-1
] |
18,453 | clisp-render.lisp | spacebat_lice/src/clisp-render.lisp | ;; TTY rendering routines
(in-package :lice)
(defclass clisp-frame (frame)
((window-stream :type window-stream :initarg :window-stream :accessor frame-window-stream)
(double-buffer :type (array character 1) :initarg :double-buffer :accessor frame-double-buffer :documentation
"The display double buffer. This structure is compared to
the characters we want to blit. Only differences are sent to the video
hardware.")
(2d-double-buffer :type (array character 2) :initarg :2d-double-buffer :accessor frame-2d-double-buffer :documentation
"Displaced from DISPLAY. This array is divided into rows and columns.")))
(defmethod frame-start-render ((frame clisp-frame))
)
(defmethod frame-end-render ((frame clisp-frame))
;; (screen:window-refresh (frame-window-stream frame))
)
;; This has to be defined (it should be a generic function)
(defun window-move-cursor (window x y window-stream)
(screen:set-window-cursor-position window-stream (+ y (window-y window)) (+ x (window-x window))))
(defmethod frame-move-cursor ((frame clisp-frame) win x y)
(window-move-cursor win x y (frame-window-stream frame)))
(defun putch (ch x y window frame)
(when (char/= (aref (frame-2d-double-buffer frame) (+ y (window-y window)) (+ x (window-x window))) ch)
(window-move-cursor window x y (frame-window-stream frame))
(write-char ch (frame-window-stream frame))
(setf (aref (frame-2d-double-buffer frame) (+ y (window-y window)) (+ x (window-x window))) ch)))
(defun putstr (s x y w frame)
(loop for i from 0 below (length s)
for j from x by 1
do (putch (aref s i) j y w frame)))
(defun line-height (buffer p)
"Return the height of the line starting at p."
(declare (ignore buffer p)))
(defun clear-line-between (w y start end frame)
"insert LEN spaces from START on line Y."
(loop for i from start to end
do (putch #\Space i y w frame)))
;; Helper function for window-render
(defun clear-to-eol (y start window frame)
(declare (type window window)
(type fixnum y start))
(let ((display (frame-2d-double-buffer frame))
(linear (frame-double-buffer frame)))
(clear-line-between window y start (1- (window-width window nil)) frame)
;; draw the seperator
(when (window-seperator window)
(putch #\| (+ (window-x window) (1- (window-width window t))) y window frame))))
(defun turn-on-attributes (buffer point frame)
"Given the buffer and point, turn on the appropriate colors based on
the text properties present."
;; These are hardcoded for now
(if (get-text-property point :face buffer)
(screen:highlight-on (frame-window-stream frame))
(screen:highlight-off (frame-window-stream frame))))
(defmethod window-render (w (frame clisp-frame))
"Render a window."
(let ((p (buffer-char-to-aref (window-buffer w) (marker-position (window-top w))))
;; current point in buffer buffer
(bp (marker-position (window-top w)))
(buf (window-buffer w))
;; The cursor point in the buffer. When the buffer isn't
;; current, then use the window's backup of the point.
(point (window-point w))
cursor-x
cursor-y
(cache-size (length (lc-cache (window-cache w))))
(linear (frame-double-buffer frame))
(display (frame-2d-double-buffer frame)))
;; Special case: when the buffer is empty
(if (= (buffer-size (window-buffer w)) 0)
(progn
(dotimes (y (window-height w nil))
(clear-to-eol y 0 w frame))
(setf cursor-x 0
cursor-y 0))
(let ((end (loop named row
for y below (window-height w nil)
for line from (window-top-line w) below cache-size
;; return the last line, so we can erase the rest
finally (return-from row y)
;; go to the next line
do (let* ((line-end (cache-item-end (item-in-cache w line)))
(line-start (cache-item-start (item-in-cache w line)))
(next-prop (next-single-property-change line-start :face (window-buffer w) line-end)))
(setf bp (cache-item-start (item-in-cache w line))
p (buffer-char-to-aref (window-buffer w) bp))
;; setup the display properties.
(turn-on-attributes (window-buffer w) bp frame)
(loop named col
for x below (window-width w nil) do
(progn
;; Skip the gap
(when (= p (buffer-gap-start buf))
(incf p (buffer-gap-size buf)))
;; Record point position on screen
(when (eq bp point)
(setf cursor-x x)
(setf cursor-y y))
(when (or (> bp line-end)
(>= p (length (buffer-data buf))))
;; Check if the rest of the line is blank
(clear-to-eol y x w frame)
(return-from col))
;; update attributes
(when (>= bp next-prop)
(turn-on-attributes (window-buffer w) bp frame))
(let ((ch (elt (buffer-data buf) p)))
;; Update display
(cond ((char= ch #\Newline)
(putch #\Space x y w frame))
(t
(putch ch x y w frame)))
;; go to the next character in the buffer
(incf p)
(incf bp))))))))
;; Check if the bottom of the window needs to be erased.
(when (< end (1- (window-height w nil)))
(loop for i from end below (window-height w nil) do
(clear-to-eol i 0 w frame)))))
;; Update the mode-line if it exists. FIXME: Not the right place
;; to update the mode-line.
(when (buffer-local '*mode-line-format* (window-buffer w))
(update-mode-line (window-buffer w))
(putstr (truncate-mode-line (window-buffer w) (window-width w nil))
0 (window-height w nil) w frame)
;; don't forget the seperator on the modeline line
(when (window-seperator w)
(putch #\| (+ (window-x w) (window-width w nil)) (window-height w nil) w frame)))
(reset-line-state w)
;; Set the cursor at the right spot
(values cursor-x cursor-y)))
;;; keyboard stuff
(defmethod frame-read-event ((frame clisp-frame))
(let* ((input (read-char EXT:*KEYBOARD-INPUT*)) ;; (input (screen::read-keyboard-char (frame-window-stream frame)))
(ch (code-char (logand (char-code (or (ext:char-key input) (character input)))
(lognot 128))))
(meta (= (logand (char-code (or (ext:char-key input) (character input))) 128) 128)))
(when (and (characterp ch)
(char= ch #\Escape))
(setf input (read-char EXT:*KEYBOARD-INPUT*)
meta t))
(make-instance 'key
:char ch
:control (ext:char-bit input :control)
:meta (or meta
(ext:char-bit input :meta)))))
;;; some frame stuff
(defun init-clisp ()
)
(defun shutdown ()
(close (frame-window-stream (selected-frame))))
(defun make-default-clisp-frame (buffer)
(let ((ws (screen:make-window)))
(multiple-value-bind (lines cols) (screen:window-size ws)
(let* ((height (1- lines))
(l (make-array (* lines cols)
:element-type 'character))
(d (make-array (list lines cols)
:element-type 'character
:displaced-to l :displaced-index-offset 0))
(w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer))
(mb (make-minibuffer-window lines cols))
(frame (make-instance 'clisp-frame
:width cols
:height lines
:window-tree (list w mb)
:selected-window w
:minibuffer-window mb
:window-stream ws
:double-buffer l
:2d-double-buffer d)))
(setf (window-frame w) frame
(window-frame mb) frame)
frame))))
| 7,413 | Common Lisp | .lisp | 173 | 37.427746 | 121 | 0.656224 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ce0b95ad58d1752ff1fd67848de58f99b04e58c8104e75a27b6f60c18f7adca4 | 18,453 | [
-1
] |
18,454 | intervals.lisp | spacebat_lice/src/intervals.lisp | ;;; implentation of an interval tree
(in-package "LICE")
(defvar *text-property-default-nonsticky* nil
"Alist of properties vs the corresponding non-stickinesses.
Each element has the form (PROPERTY . NONSTICKINESS).
If a character in a buffer has PROPERTY, new text inserted adjacent to
the character doesn't inherit PROPERTY if NONSTICKINESS is non-nil,
inherits it if NONSTICKINESS is nil. The front-sticky and
rear-nonsticky properties of the character overrides NONSTICKINESS.")
(defvar *char-property-alias-alist* nil
"Alist of alternative properties for properties without a value.
Each element should look like (PROPERTY ALTERNATIVE1 ALTERNATIVE2...).
If a piece of text has no direct value for a particular property, then
this alist is consulted. If that property appears in the alist, then
the first non-nil value from the associated alternative properties is
returned.")
(defvar *default-text-properties* nil
"Property-list used as default values.
The value of a property in this list is seen as the value for every
character that does not have its own value for that property.")
(defmacro doplist ((sym val plist &optional ret) &body body)
"Loop through each symbol value pair in PLIST executing BODY."
(let ((csym (gensym)))
`(do* ((,csym ,plist (cddr ,csym)))
((endp ,csym) ,ret)
(let ((,sym (car ,csym))
(,val (cadr ,csym)))
,@body))))
(defun interval-has-object (interval)
(and (interval-parent interval)
(not (typep (interval-parent interval) 'interval))))
(defun interval-has-parent (interval)
(and (interval-parent interval)
(typep (interval-parent interval) 'interval)))
(defun check-total-length (interval)
(when (< (interval-length interval) 0)
(error "Interval length < 0 ~a" interval)))
(defun create-root-interval (object)
"Return a fresh interval for OBJECT."
(let ((i (make-interval :pt 0 :length 0 :parent object
:left nil :right nil :plist nil)))
(cond
((typep object 'buffer)
(setf (intervals object) i
;; XXX: are buffer-max buffer-min the right functions to use?
(interval-length i) (- (buffer-max object) (buffer-min object))
(interval-pt i) (buffer-min object)))
((typep object 'pstring)
(setf (intervals object) i
(interval-length i) (pstring-length object))))
i))
(defun plists-equal (p1 p2)
"Return 1 if the two properties lists are equal, 0 otherwise."
(when (= (length p1)
(length p2))
(doplist (sym val p1 t)
(unless (eql val (getf p2 sym))
(return-from plists-equal nil)))))
(defun intervals-equal (i1 i2)
"Return T if the two intervals have the same properties, NIL otherwise."
(plists-equal (interval-plist i1) (interval-plist i2)))
(defun lookup-char-property (plist prop textprop)
(let* ((val (getf plist prop))
(cat (getf plist 'category)))
(when val
(return-from lookup-char-property val))
;; This is what GNU emacs does...
(when (and (symbolp cat)
(get cat prop))
(return-from lookup-char-property (get cat prop)))
;; Check for alternative properties
(let ((tail (assoc prop *char-property-alias-alist*)))
(when tail
(or (find-if (lambda (p)
(getf plist p))
(cdr tail))
(and textprop
(consp *default-text-properties*)
(getf *default-text-properties* prop)))))))
(defun textget (plist sym)
"Get the value of property PROP from PLIST,
which is the plist of an interval.
We check for direct properties, for categories with property PROP,
and for PROP appearing on the default-text-properties list."
(lookup-char-property plist sym t))
(defun total-length (root)
"TOTAL_LENGTH"
(if root
(interval-length root)
0))
(defun left-total-length (root)
(if (interval-left root)
(interval-length (interval-left root))
0))
(defun right-total-length (root)
(if (interval-right root)
(interval-length (interval-right root))
0))
(defun interval-text-length (root)
"The size of text represented by this interval alone. LENGTH."
(if root
(- (total-length root)
(total-length (interval-right root))
(total-length (interval-left root)))
0))
(defun right-child-p (root)
(eq root (interval-right (interval-parent root))))
(defun left-child-p (root)
(eq root (interval-left (interval-parent root))))
(defun interval-past-top-p (interval)
"Return t if INTERVAL is not an interval. Used to check when we've
climbed past the root interval."
(not (typep (interval-parent interval) 'interval)))
(defun root-interval-p (i)
"Return true if i is the root interval node."
(or (null (interval-parent i))
(not (typep (interval-parent i) 'interval))))
(defun root-interval (interval)
"Return the root of interval."
(do ((i interval (interval-parent i)))
((root-interval-p i) i)))
(defun leaf-interval-p (i)
"Return T if this interval has no children."
(and (null (interval-left i))
(null (interval-right i))))
(defun only-interval-p (i)
"Return T if this interval is the only interval in the interval tree."
(and (root-interval-p i)
(leaf-interval-p i)))
(defun default-interval-p (i)
(or (null i)
(null (interval-plist i))))
(defun rotate-left (interval)
"Assuming that a right child exists, perform the following operation:
A B
/ \ / \
B => A
/ \ / \
c c
"
(let ((old-total (interval-length interval))
(b (interval-right interval))
i)
;; Change interval's parent to point b.
(unless (root-interval-p interval)
(if (left-child-p interval)
(setf (interval-left (interval-parent interval)) b)
(setf (interval-right (interval-parent interval)) b)))
(setf (interval-parent b) (interval-parent interval))
;; Make b the parent of a
(setf i (interval-left b)
(interval-left b) interval
(interval-parent interval) b)
;; make a point to c
(setf (interval-right interval) i)
(when i
(setf (interval-parent i) interval))
;; A's total length is decreased by the length of B and its left child.
(decf (interval-length interval) (- (interval-length b)
(right-total-length interval)))
(check-total-length interval)
;; B must have the same total length of A.
(setf (interval-length b) old-total)
(check-total-length b)
b))
(defun rotate-right (interval)
"Assuming that a left child exists, perform the following operation:
A B
/ \ / \
B => A
/ \ / \
c c
"
(let ((old-total (interval-length interval))
(b (interval-left interval))
i)
;; Change interval's parent to point b.
(unless (root-interval-p interval)
(if (left-child-p interval)
(setf (interval-left (interval-parent interval)) b)
(setf (interval-right (interval-parent interval)) b)))
(setf (interval-parent b) (interval-parent interval))
;; Make b the parent of a
(setf i (interval-right b)
(interval-right b) interval
(interval-parent interval) b)
;; make a point to c
(setf (interval-left interval) i)
(when i
(setf (interval-parent i) interval))
;; A's total length is decreased by the length of B and its left child.
(decf (interval-length interval) (- (interval-length b)
(left-total-length interval)))
(check-total-length interval)
;; B must have the same total length of A.
(setf (interval-length b) old-total)
(check-total-length b)
b))
(defun balance-an-interval (i)
(let (old-diff
new-diff)
(loop
(setf old-diff (- (left-total-length i) (right-total-length i)))
(cond ((> old-diff 0)
;; Since the left child is longer, there must be one.
(setf new-diff (+ (- (interval-length i)
(interval-length (interval-left i)))
(- (right-total-length (interval-left i))
(left-total-length (interval-left i)))))
(when (>= (abs new-diff) old-diff)
(return-from balance-an-interval i))
(setf i (rotate-right i))
(balance-an-interval (interval-right i)))
((< old-diff 0)
(setf new-diff (+ (- (interval-length i)
(interval-length (interval-right i)))
(- (left-total-length (interval-right i))
(right-total-length (interval-right i)))))
(when (>= (abs new-diff) (- old-diff))
(return-from balance-an-interval i))
(setf i (rotate-left i))
(balance-an-interval (interval-left i)))
(t (return-from balance-an-interval i))))))
(defun balance-intervals (tree)
"Balance the interval tree TREE. Balancing is by weight: the amount
of text."
(labels ((balance (tree)
(when (interval-left tree)
(balance (interval-left tree)))
(when (interval-right tree)
(balance (interval-right tree)))
(balance-an-interval tree)))
(when tree
(balance tree))))
(defun balance-possible-root-interval (interval)
(let ((has-parent nil)
parent)
(when (null (interval-parent interval))
(return-from balance-possible-root-interval interval))
(when (interval-has-object interval)
(setf parent (interval-parent interval)
has-parent t))
(setf interval (balance-intervals interval))
(when has-parent
(setf (intervals parent) interval))
interval))
(defun split-interval-left (interval offset)
(let* ((new-length offset)
(new (make-interval :pt (interval-pt interval)
:length offset
:parent interval)))
(incf (interval-pt interval) offset)
(if (interval-left interval)
(progn
(setf (interval-left new) (interval-left interval)
(interval-parent (interval-left new)) new
(interval-left interval) new
(interval-length new) (+ new-length (interval-length (interval-left new))))
(check-total-length new)
(balance-an-interval new))
(progn
(setf (interval-left interval) new
(interval-length new) new-length)
(check-total-length new)))
(balance-possible-root-interval interval)
new))
(defun split-interval-right (interval offset)
(let* ((position (interval-pt interval))
(new-length (- (interval-text-length interval) offset))
(new (make-interval :pt (+ position offset)
:length 0
:parent interval)))
(setf (interval-parent new) interval)
(if (interval-right interval)
(progn
(setf (interval-right new) (interval-right interval)
(interval-parent (interval-right interval)) new
(interval-right interval) new
(interval-length new) (+ new-length (interval-length (interval-right new))))
(check-total-length new)
(balance-an-interval new))
(progn
(setf (interval-right interval) new
(interval-length new) new-length)
(check-total-length new)))
(balance-possible-root-interval interval)
new))
(defun find-interval (tree position)
(let ((relative-position position))
(when (null tree)
(return-from find-interval nil))
(assert (<= relative-position (total-length tree)))
(balance-possible-root-interval tree)
(loop
(cond ((< relative-position (left-total-length tree))
(setf tree (interval-left tree)))
((and (interval-right tree)
(>= relative-position (- (total-length tree)
(right-total-length tree))))
(decf relative-position (- (total-length tree)
(right-total-length tree)))
(setf tree (interval-right tree)))
(t
(setf (interval-pt tree) (+ (- position relative-position)
(left-total-length tree)))
(return-from find-interval tree))))))
(defun next-interval (interval)
(unless (null interval)
(let ((i interval)
(next-position (+ (interval-pt interval)
(interval-text-length interval))))
(when (interval-right interval)
(setf i (interval-right i))
(while (interval-left i)
(setf i (interval-left i)))
(setf (interval-pt i) next-position)
(return-from next-interval i))
(loop until (interval-past-top-p i)
if (left-child-p i)
do (progn
(setf i (interval-parent i)
(interval-pt i) next-position)
(return-from next-interval i))
do (setf i (interval-parent i))))))
(defun previous-interval (interval)
(unless (null interval)
(let ((i interval))
(when (interval-left interval)
(setf i (interval-left i))
(while (interval-right i)
(setf i (interval-right i)))
(setf (interval-pt i) (- (interval-pt interval)
(interval-text-length i)))
(return-from previous-interval i))
(loop until (interval-past-top-p i)
if (right-child-p i)
do (progn
(setf i (interval-parent i)
(interval-pt i) (- (interval-pt interval)
(interval-text-length i)))
(return-from previous-interval i))
do (setf i (interval-parent i))))))
(defun delete-node (i)
;; Trivial cases
(when (null (interval-left i))
(return-from delete-node (interval-right i)))
(when (null (interval-right i))
(return-from delete-node (interval-left i)))
;; Meat
(let ((migrate (interval-left i))
(this (interval-right i))
(migrate-amt (interval-length (interval-left i))))
(while (interval-left this)
(setf this (interval-left this))
(incf (interval-length this) migrate-amt))
(check-total-length this)
(setf (interval-left this) migrate)
(setf (interval-parent migrate) this)
(interval-right i)))
(defun delete-interval (i)
(let ((amt (interval-text-length i))
parent)
(and (> amt 0)
(error "only used on zero length intervals."))
(when (root-interval-p i)
(let ((owner (interval-parent i)))
(setf parent (delete-node i))
(when (interval-parent parent)
(setf (interval-parent parent) owner))
(setf (intervals owner) parent)
(return-from delete-interval)))
(setf parent (interval-parent i))
(if (left-child-p i)
(progn
(setf (interval-left parent) (delete-node i))
(when (interval-left parent)
(setf (interval-parent (interval-left parent)) parent)))
(progn
(setf (interval-right parent) (delete-node i))
(when (interval-right parent)
(setf (interval-parent (interval-right parent)) parent))))))
(defun merge-interval-right (i)
(let ((absorb (interval-text-length i))
successor)
(decf (interval-length i) absorb)
(check-total-length i)
(when (interval-right i)
(setf successor (interval-right i))
(while (interval-left successor)
(incf (interval-length successor) absorb)
(check-total-length successor)
(setf successor (interval-left successor)))
(incf (interval-length successor) absorb)
(check-total-length successor)
(delete-interval i)
(return-from merge-interval-right successor))
(setf successor i)
(while (interval-parent successor)
(if (left-child-p successor)
(progn
(setf successor (interval-parent successor))
(delete-interval i)
(return-from merge-interval-right successor))
(progn
(setf successor (interval-parent successor))
(decf (interval-length successor) absorb)
(check-total-length successor))))
(error "merge-interval-right: gak")))
(defun merge-interval-left (i)
(let ((absorb (interval-text-length i))
predecessor)
(decf (interval-length i) absorb)
(check-total-length i)
(when (interval-left i)
(setf predecessor (interval-left i))
(while (interval-right predecessor)
(incf (interval-length predecessor) absorb)
(check-total-length predecessor)
(setf predecessor (interval-right predecessor)))
(incf (interval-length predecessor) absorb)
(check-total-length predecessor)
(delete-interval i)
(return-from merge-interval-left predecessor))
(setf predecessor i)
(while (interval-parent predecessor)
(when (interval-right predecessor)
(setf predecessor (interval-parent predecessor))
(delete-interval i)
(return-from merge-interval-left predecessor))
(setf predecessor (interval-parent predecessor))
(decf (interval-length predecessor) absorb)
(check-total-length predecessor)
)
(error "merge-interval-left: gak")))
(defun copy-properties (source target)
(when (and (default-interval-p source)
(default-interval-p target))
(return-from copy-properties))
(setf (interval-plist target) (copy-list (interval-plist source))))
(defun merge-properties (source target)
"/* Merge the properties of interval SOURCE into the properties of
interval TARGET. That is to say, each property in SOURCE is added to
TARGET if TARGET has no such property as yet. */"
(unless (and (default-interval-p source)
(default-interval-p target))
(doplist (sym val (interval-plist source))
(let ((found (getf (interval-plist target) sym)))
(unless found
(setf (getf (interval-plist target) sym) val))))))
(defun merge-properties-sticky (pleft pright)
"Any property might be front-sticky on the left, rear-sticky on the left,
front-sticky on the right, or rear-sticky on the right; the 16 combinations
can be arranged in a matrix with rows denoting the left conditions and
columns denoting the right conditions:
_ __ _
_ FR FR FR FR
FR__ 0 1 2 3
_FR 4 5 6 7
FR 8 9 A B
FR C D E F
left-props = '(front-sticky (p8 p9 pa pb pc pd pe pf)
rear-nonsticky (p4 p5 p6 p7 p8 p9 pa pb)
p0 L p1 L p2 L p3 L p4 L p5 L p6 L p7 L
p8 L p9 L pa L pb L pc L pd L pe L pf L)
right-props = '(front-sticky (p2 p3 p6 p7 pa pb pe pf)
rear-nonsticky (p1 p2 p5 p6 p9 pa pd pe)
p0 R p1 R p2 R p3 R p4 R p5 R p6 R p7 R
p8 R p9 R pa R pb R pc R pd R pe R pf R)
We inherit from whoever has a sticky side facing us. If both sides
do (cases 2, 3, E, and F), then we inherit from whichever side has a
non-nil value for the current property. If both sides do, then we take
from the left.
When we inherit a property, we get its stickiness as well as its value.
So, when we merge the above two lists, we expect to get this:
result = '(front-sticky (p6 p7 pa pb pc pd pe pf)
rear-nonsticky (p6 pa)
p0 L p1 L p2 L p3 L p6 R p7 R
pa R pb R pc L pd L pe L pf L)
The optimizable special cases are:
left rear-nonsticky = nil, right front-sticky = nil (inherit left)
left rear-nonsticky = t, right front-sticky = t (inherit right)
left rear-nonsticky = t, right front-sticky = nil (inherit none)"
(labels ((tmem (sym set)
;; Test for membership, allowing for t (actually any
;; non-cons) to mean the universal set."
(if (consp set)
(find sym set)
set)))
(let (props
front
rear
(lfront (getf pleft 'front-sticky))
(lrear (getf pleft 'rear-nonsticky))
(rfront (getf pright 'front-sticky))
(rrear (getf pright 'rear-nonsticky))
cat use-left use-right)
(doplist (sym rval pright)
(unless (or (eq sym 'rear-nonsticky)
(eq sym 'front-sticky))
;; Indicate whether the property is explicitly
;; defined on the left. (We know it is defined
;; explicitly on the right because otherwise we don't
;; get here.)
(let* ((lval (getf pleft sym))
;; Even if lrear or rfront say nothing about the
;; stickiness of SYM,
;; Vtext_property_default_nonsticky may give
;; default stickiness to SYM.
(tmp (assoc sym *text-property-default-nonsticky*)))
(setf use-left (and lval
(not (or (tmem sym lrear)
(and (consp tmp)
(cdr tmp)))))
use-right (or (tmem sym lrear)
(and (consp tmp)
(null (cdr tmp)))))
(when (and use-left
use-right)
(cond ((null lval)
(setf use-left nil))
((null rval)
(setf use-right nil))))
(cond (use-left
;; We build props as (value sym ...) rather than (sym value ...)
;; because we plan to nreverse it when we're done.
(setf (getf props sym) lval)
(when (tmem sym lfront)
(push sym front))
(when (tmem sym lrear)
(push sym rear)))
(use-right
(setf (getf props sym) rval)
(when (tmem sym rfront)
(push sym front))
(when (tmem sym rrear)
(push sym rear)))))))
;; Now go through each element of PLEFT.
(doplist (sym lval pleft)
(unless (or (eq sym 'rear-nonsticky)
(eq sym 'front-sticky))
;; If sym is in PRIGHT, we've already considered it.
(let* ((present (getf pright sym))
;; Even if lrear or rfront say nothing about the
;; stickiness of SYM,
;; Vtext_property_default_nonsticky may give
;; default stickiness to SYM.
(tmp (assoc sym *text-property-default-nonsticky*)))
;; XXX: if sym is set in pright to nil, its the same
;; as sym not being in the list.
(unless present
;; Since rval is known to be nil in this loop, the test simplifies.
(cond ((not (or (tmem sym lrear)
(and (consp tmp)
(cdr tmp))))
(setf (getf props sym) lval)
(when (tmem sym lfront)
(push sym front)))
((or (tmem sym rfront)
(and (consp tmp)
(null (cdr tmp))))
;; The value is nil, but we still inherit the stickiness
;; from the right.
(setf (getf props sym) lval)
(when (tmem sym rrear)
(push sym rear))))))))
(when rear
(setf (getf props 'rear-nonsticky) (nreverse rear)))
(setf cat (textget props 'category))
;; If we have inherited a front-stick category property that is t,
;; we don't need to set up a detailed one.
(when (and front
(not (and cat
(symbolp cat)
(eq (get cat 'front-sticky) t))))
(setf (getf props 'front-sticky) (nreverse front)))
props)))
(defun adjust-intervals-for-insertion (tree position length)
"Effect an adjustment corresponding to the addition of LENGTH characters
of text. Do this by finding the interval containing POSITION in the
interval tree TREE, and then adjusting all of its ancestors by adding
LENGTH to them.
If POSITION is the first character of an interval, meaning that point
is actually between the two intervals, make the new text belong to
the interval which is \"sticky\".
If both intervals are \"sticky\", then make them belong to the left-most
interval. Another possibility would be to create a new interval for
this text, and make it have the merged properties of both ends."
(let* ((parent (interval-parent tree))
(offset (if (typep parent 'buffer)
(buffer-min parent)
0))
i temp eobp)
;; If inserting at point-max of a buffer, that position will be out
;; of range. Remember that buffer positions are 1-based.
(when (>= position (+ (total-length tree) offset))
(setf position (+ (total-length tree) offset)
eobp t))
(setf i (find-interval tree position))
;; If in middle of an interval which is not sticky either way,
;; we must not just give its properties to the insertion.
;; So split this interval at the insertion point.
;; Originally, the if condition here was this:
;; (! (position == i->position || eobp)
;; && END_NONSTICKY_P (i)
;; && FRONT_NONSTICKY_P (i))
;; But, these macros are now unreliable because of introduction of
;; Vtext_property_default_nonsticky. So, we always check properties
;; one by one if POSITION is in middle of an interval.
(unless (or (= position (interval-pt i))
eobp)
(let* ((rear (getf (interval-plist i) 'rear-nonsticky))
(front (getf (interval-plist i) 'front-sticky))
(problem t))
(when (or (and (not (consp rear)) rear)
(and (not (consp front)) front))
;; All properties are nonsticky. We split the interval.
(setf problem nil))
;; Does any actual property pose an actual problem? We break
;; the loop if we find a nonsticky property.
(when problem
(setf problem (do* ((tail (interval-plist i) (cddr tail))
(prop (cdr tail) (cdr tail)))
((or (endp tail)
(and (not (and (consp front)
(not (find prop front))))
(or (and (consp rear)
(not (find prop rear)))
(let ((tmp (assoc prop *text-property-default-nonsticky*)))
(and (consp tmp) tmp)))))
tail))))
;; If any property is a real problem, split the interval.
(when problem
(setf temp (split-interval-right i (- position (interval-pt i))))
(copy-properties i temp)
(setf i temp))))
;; If we are positioned between intervals, check the stickiness of
;; both of them. We have to do this too, if we are at BEG or Z.
(if (or (= position (interval-pt i))
eobp)
(let ((prev (cond ((= position +beg+) nil)
(eobp i)
(t (previous-interval i)))))
(when eobp
(setf i nil))
;; Even if we are positioned between intervals, we default
;; to the left one if it exists. We extend it now and split
;; off a part later, if stickiness demands it.
(do ((tmp (or prev i) (when (interval-has-parent tmp)
(interval-parent tmp))))
((null tmp))
(incf (interval-length tmp) length)
;; CHECK_TOTAL_LENGTH (temp);
(setf tmp (balance-possible-root-interval tmp)))
;; If at least one interval has sticky properties, we check
;; the stickiness property by property.
;; Originally, the if condition here was this:
;; (END_NONSTICKY_P (prev) || FRONT_STICKY_P (i))
;; But, these macros are now unreliable because of introduction
;; of Vtext_property_default_nonsticky. So, we always have to
;; check stickiness of properties one by one. If cache of
;; stickiness is implemented in the future, we may be able to
;; use those macros again.
(let* ((pleft (when prev
(interval-plist prev)))
(pright (when i
(interval-plist i)))
(new-props (merge-properties-sticky pleft pright)))
(cond ((not prev)
;; /* i.e. position == BEG */
(unless (plists-equal (interval-plist i) new-props)
(setf i (split-interval-left i length)
(interval-plist i) new-props)))
((not (plists-equal (interval-plist prev) new-props))
(setf prev (split-interval-right prev (- position (interval-pt prev)))
(interval-plist prev) new-props)
(when (and i
(plists-equal (interval-plist prev) (interval-plist i)))
(merge-interval-right prev)))
((and (not prev)
(not (null (interval-plist i))))
;; Just split off a new interval at the left.
;; Since I wasn't front-sticky, the empty plist is ok.
(setf i (split-interval-left i length))))))
;; Otherwise just extend the interval.
(do ((tmp i (when (interval-has-parent tmp)
(interval-parent tmp))))
((null tmp))
(incf (interval-length tmp) length)
;; CHECK_TOTAL_LENGTH (temp);
(setf tmp (balance-possible-root-interval tmp))))
tree))
(defun interval-deletion-adjustment (tree from amount)
"Find the interval in TREE corresponding to the relative position
FROM and delete as much as possible of AMOUNT from that interval.
Return the amount actually deleted, and if the interval was
zeroed-out, delete that interval node from the tree.
Note that FROM is actually origin zero, aka relative to the
leftmost edge of tree. This is appropriate since we call ourselves
recursively on subtrees.
Do this by recursing down TREE to the interval in question, and
deleting the appropriate amount of text."
(let ((relative-position from))
(cond
((null tree)
0)
;; Left branch
((< relative-position (left-total-length tree))
(let ((subtract (interval-deletion-adjustment (interval-left tree)
relative-position
amount)))
(decf (interval-length tree) subtract)
;; CHECK_TOTAL_LENGTH
subtract))
;; Right branch
((>= relative-position (- (total-length tree)
(right-total-length tree)))
(decf relative-position (- (interval-length tree)
(right-total-length tree)))
(let ((subtract (interval-deletion-adjustment (interval-right tree)
relative-position
amount)))
(decf (interval-length tree) subtract)
;; CHECK_TOTAL_LENGTH
subtract))
;; This node
(t
;; How much can we delete from this interval?
(let ((my-amount (- (interval-length tree)
(right-total-length tree)
relative-position)))
(when (> amount my-amount)
(setf amount my-amount))
(decf (interval-length tree) amount)
;; CHECK_TOTAL_LENGTH
(when (zerop (total-length tree))
(delete-interval tree))
amount)))))
(defun adjust-intervals-for-deletion (buffer start length)
"Effect the adjustments necessary to the interval tree of BUFFER to
correspond to the deletion of LENGTH characters from that buffer
text. The deletion is effected at position START (which is a
buffer position, i.e. origin 1)."
(let ((left-to-delete length)
(tree (intervals buffer))
(offset (buffer-min buffer)))
(cond
((null tree))
((or (> start (+ offset (total-length tree)))
(> (+ start length) (+ offset (total-length tree))))
(error "gak ~a ~a ~a ~a" tree offset (total-length tree) length))
((= length (total-length tree))
(setf (intervals buffer) nil))
((only-interval-p tree)
(decf (interval-length tree) length)) ;; CHECK_TOTAL_LENGTH
(t
(when (> start (+ offset (total-length tree)))
(setf start (+ offset (total-length tree))))
(while (> left-to-delete 0)
(decf left-to-delete
(interval-deletion-adjustment tree (- start offset) left-to-delete))
(setf tree (intervals buffer))
(when (= left-to-delete (interval-length tree))
(setf (intervals buffer) nil)
(return)))))))
(defun interval-start-pos (source)
(if (or (null source)
(not (typep (interval-parent source) 'buffer)))
0
(buffer-min (interval-parent source))))
(defun reproduce-tree (source parent)
(let ((tree (copy-interval source)))
(setf (interval-plist tree) (copy-list (interval-plist source))
(interval-parent tree) parent)
(when (interval-left source)
(setf (interval-left tree) (reproduce-tree (interval-left source) tree)))
(when (interval-right source)
(setf (interval-right tree) (reproduce-tree (interval-right source) tree)))
tree))
(defun set-properties (properties interval object)
(when (typep object 'buffer)
;; record undo info
)
(setf (interval-plist interval) (copy-tree properties)))
(defun set-text-properties-1 (start end properties buffer i)
(let ((len (- end start))
(prev-changed nil)
unchanged)
(when (zerop len)
(return-from set-text-properties-1))
(when (minusp len)
(incf start len)
(setf len (abs len)))
(when (null i)
(setf i (find-interval (intervals buffer) start)))
(when (/= (interval-pt i) start)
(setf unchanged i
i (split-interval-right unchanged (- start (interval-pt unchanged))))
(when (> (interval-text-length i) len)
(copy-properties unchanged i)
(setf i (split-interval-left i len))
(set-properties properties i buffer)
(return-from set-text-properties-1))
(set-properties properties i buffer)
(when (= (interval-text-length i) len)
(return-from set-text-properties-1))
(setf prev-changed i)
(decf len (interval-text-length i))
(setf i (next-interval i)))
(while (> len 0)
(when (null i)
(error "borked."))
(when (>= (interval-text-length i) len)
(when (> (interval-text-length i) len)
(setf i (split-interval-left i len)))
(set-properties properties i buffer)
(when prev-changed
(merge-interval-left i))
(return-from set-text-properties-1))
(decf len (interval-text-length i))
;; We have to call set_properties even if we are going
;; to merge the intervals, so as to make the undo
;; records and cause redisplay to happen.
(set-properties properties i buffer)
(if (null prev-changed)
(setf prev-changed i)
(setf prev-changed (merge-interval-left i)
i prev-changed))
(setf i (next-interval i)))))
(defun graft-intervals-into-buffer (source position length buffer inherit)
"Insert the intervals of SOURCE into BUFFER at POSITION.
LENGTH is the length of the text in SOURCE.
The `position' field of the SOURCE intervals is assumed to be
consistent with its parent; therefore, SOURCE must be an
interval tree made with copy_interval or must be the whole
tree of a buffer or a string.
This is used in insdel.c when inserting Lisp_Strings into the
buffer. The text corresponding to SOURCE is already in the buffer
when this is called. The intervals of new tree are a copy of those
belonging to the string being inserted; intervals are never
shared.
If the inserted text had no intervals associated, and we don't
want to inherit the surrounding text's properties, this function
simply returns -- offset_intervals should handle placing the
text in the correct interval, depending on the sticky bits.
If the inserted text had properties (intervals), then there are two
cases -- either insertion happened in the middle of some interval,
or between two intervals.
If the text goes into the middle of an interval, then new
intervals are created in the middle with only the properties of
the new text, *unless* the macro MERGE_INSERTIONS is true, in
which case the new text has the union of its properties and those
of the text into which it was inserted.
If the text goes between two intervals, then if neither interval
had its appropriate sticky property set (front_sticky, rear_sticky),
the new text has only its properties. If one of the sticky properties
is set, then the new text \"sticks\" to that region and its properties
depend on merging as above. If both the preceding and succeeding
intervals to the new text are \"sticky\", then the new text retains
only its properties, as if neither sticky property were set. Perhaps
we should consider merging all three sets of properties onto the new
text..."
(let ((tree (intervals buffer))
over-used
under over this prev)
;; /* If the new text has no properties, then with inheritance it
;; becomes part of whatever interval it was inserted into.
;; To prevent inheritance, we must clear out the properties
;; of the newly inserted text. */
(when (null source)
(when (and (not inherit)
tree
(> length 0))
;; XSETBUFFER (buf, buffer);
(set-text-properties-1 position (+ position length) nil buffer 0))
(when (intervals buffer)
(setf (intervals buffer) (balance-an-interval (intervals buffer))))
(return-from graft-intervals-into-buffer))
(cond ((null tree)
;; /* The inserted text constitutes the whole buffer, so
;; simply copy over the interval structure. */
(when (= (- (buffer-size buffer) (buffer-min buffer))
(total-length source))
(setf (intervals buffer) (reproduce-tree source buffer)
(interval-pt (intervals buffer)) (buffer-min buffer))
(return-from graft-intervals-into-buffer))
;; /* Create an interval tree in which to place a copy
;; of the intervals of the inserted string. */
(setf tree (create-root-interval buffer)))
((= (total-length tree)
(total-length source))
;; /* If the buffer contains only the new string, but
;; there was already some interval tree there, then it may be
;; some zero length intervals. Eventually, do something clever
;; about inserting properly. For now, just waste the old intervals. */
(setf (intervals buffer) (reproduce-tree source (interval-parent tree))
(interval-pt (intervals buffer)) (buffer-min buffer))
(return-from graft-intervals-into-buffer))
((zerop (total-length tree))
(error "bork")))
(setf under (find-interval tree position)
this under
over (find-interval source (interval-start-pos source)))
(if (> position (interval-pt under))
(let ((end-unchanged (split-interval-left this (- position (interval-pt under)))))
(copy-properties under end-unchanged)
(setf (interval-pt under) position))
(setf prev (previous-interval under)))
(setf over-used 0)
(while over
(if (< (- (interval-text-length over) over-used)
(interval-text-length under))
(progn
(setf this (split-interval-left under (- (interval-text-length over)
over-used)))
(copy-properties under this))
(setf this under))
;; /* THIS is now the interval to copy or merge into.
;; OVER covers all of it. */
(if inherit
(merge-properties over this)
(copy-properties over this))
;; /* If THIS and OVER end at the same place,
;; advance OVER to a new source interval. */
(if (= (interval-text-length this)
(- (interval-text-length over) over-used))
(progn
(setf over (next-interval over)
over-used 0))
;; /* Otherwise just record that more of OVER has been used. */
(incf over-used (interval-text-length this)))
;; /* Always advance to a new target interval. */
(setf under (next-interval this)))
(when (intervals buffer)
(setf (intervals buffer) (balance-an-interval (intervals buffer))))))
(defun offset-intervals (buffer start length)
"Make the adjustments necessary to the interval tree of BUFFER to
represent an addition or deletion of LENGTH characters starting
at position START. Addition or deletion is indicated by the sign
of LENGTH."
(unless (or (null (intervals buffer))
(zerop length))
(if (> length 0)
(adjust-intervals-for-insertion (intervals buffer) start length)
(adjust-intervals-for-deletion buffer (+ start length) (- length)))))
(provide :lice-0.1/intervals)
| 37,771 | Common Lisp | .lisp | 945 | 34.966138 | 83 | 0.671639 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fcd90ae0a5d71c8b68cf86d145f2bd756c7e2f9af7418a73e80c4b675ab3eeaa | 18,454 | [
-1
] |
18,455 | data-types.lisp | spacebat_lice/src/data-types.lisp | ;;; declare all our data types
(in-package "LICE")
;;; Markers
(deftype marker-insertion-type () '(member :before :after))
(defclass marker ()
((position :type integer :initform 0 :accessor marker-position)
(buffer #|:type (or buffer null)|# :initform nil :accessor marker-buffer)
(insertion-type :type marker-insertion-type :initform :after :accessor marker-insertion-type))
(:documentation "A Marker"))
(defmethod print-object ((obj marker) stream)
(print-unreadable-object (obj stream :type t :identity t)
(format stream "~a" (marker-position obj))))
;;; Intervals
;; interval node is a list: (key left right &rest plist)
(defstruct (interval
(:print-function (lambda (i s d)
(declare (ignore d))
(format s "#S(interval ~s ~s ~s | ~s ~s)"
(interval-pt i)
(interval-length i)
(interval-plist i)
(interval-left i)
(interval-right i)))))
(pt nil)
(length nil)
(left nil)
(right nil)
(parent nil #|:type (or null pstring buffer interval)|#)
(plist nil :type list))
;; MOVITZ's defstruct doesn't create copy-interval
#+movitz
(defun copy-interval (interval)
(make-interval :pt (interval-pt interval)
:length (interval-length interval)
:left (interval-left interval)
:right (interval-right interval)
:parent (interval-parent interval)
:plist (interval-plist interval)))
;;; Buffers
(defclass pstring ()
((data :type string :initarg :data :accessor pstring-data)
(intervals #|:type (or null interval)|# :initform nil :initarg :intervals :accessor intervals))
(:documentation "The lice string implementation."))
(defmethod print-object ((obj pstring) stream)
(print-unreadable-object (obj stream :type t :identity t)
(format stream "~s" (pstring-data obj))))
(defun pstring-length (ps)
"Return the length of the string in PS"
(declare (type pstring ps))
(length (pstring-data ps)))
(defclass base-buffer ()
((file :type (or null pathname) :initarg :file :accessor buffer-file)
(name :type string :initarg :name :accessor buffer-name)
(mode-line-string :type string :initform "" :accessor buffer-mode-line-string)
(modified-p :type boolean :initform nil)
(read-only :type boolean :initform nil)
(tick :type integer :initform 0 :accessor buffer-modified-tick :documentation
"The buffer's tick counter. It is incremented for each change
in text.")
(display-count :type integer :initform 0 :accessor buffer-display-count :documentation
"The buffer's display counter. It is incremented each time it
is displayed in a window.")
(display-time :type integer :initform 0 :accessor buffer-display-time :documentation
"The last time the buffer was switched to in a window.")
(major-mode #|:type major-mode|# :initarg :major-mode :accessor buffer-major-mode)
(local-map :initform nil :initarg :local-map :accessor buffer-local-map :documentation
"The keymap local to the buffer. This overrides major mode bindings.")
(syntax-table :initform nil :initarg :syntax-table :accessor buffer-syntax-table)
(locals-variables :type hash-table :initform (make-hash-table) :accessor buffer-local-variables)
(locals :type hash-table :initform (make-hash-table) :accessor buffer-locals))
(:documentation "A Buffer."))
;; undo structures used to record types of undo information. This is
;; an alternative to the cons cells gnu emacs uses which I find
;; obscure.
(defstruct undo-entry-insertion
beg end)
(defstruct undo-entry-delete
text position)
(defstruct undo-entry-modified
time)
(defstruct undo-entry-property
prop value beg end)
(defstruct undo-entry-apply
function args)
(defstruct undo-entry-selective
delta beg end function args)
(defstruct undo-entry-marker
marker distance)
(defclass buffer (base-buffer)
((point #|:type marker|# :initarg :point :accessor buffer-point)
(mark #|:type marker|# :initarg :mark :accessor buffer-mark-marker)
;; A string containing the raw buffer
(data :type (array character 1) :initarg :data :accessor buffer-data)
(intervals #|:type (or null interval)|# :initform nil :initarg :intervals :accessor intervals)
(gap-start :type integer :initarg :gap-start :accessor buffer-gap-start)
(gap-size :type integer :initarg :gap-size :accessor buffer-gap-size)
(markers :type list :initform '() :accessor buffer-markers)
(auto-save-modified :type integer :initform 0 :accessor buffer-auto-save-modified)
(modiff :type integer :initform 0 :accessor buffer-modiff)
;;(syntax-table :initform *standard-syntax-table* :accessor buffer-syntax-table)
(undo-list :initform '() :accessor buffer-undo-list
:documentation "List of undo entries in current buffer.
Recent changes come first; older changes follow newer.
An entry (BEG . END) represents an insertion which begins at
position BEG and ends at position END.
An entry (TEXT . POSITION) represents the deletion of the string TEXT
from (abs POSITION). If POSITION is positive, point was at the front
of the text being deleted; if negative, point was at the end.
An entry (t HIGH . LOW) indicates that the buffer previously had
\"unmodified\" status. HIGH and LOW are the high and low 16-bit portions
of the visited file's modification time, as of that time. If the
modification time of the most recent save is different, this entry is
obsolete.
An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
was modified between BEG and END. PROPERTY is the property name,
and VALUE is the old value.
An entry (apply FUN-NAME . ARGS) means undo the change with
\(apply FUN-NAME ARGS).
An entry (apply DELTA BEG END FUN-NAME . ARGS) supports selective undo
in the active region. BEG and END is the range affected by this entry
and DELTA is the number of bytes added or deleted in that range by
this change.
An entry (MARKER . DISTANCE) indicates that the marker MARKER
was adjusted in position by the offset DISTANCE (an integer).
An entry of the form POSITION indicates that point was at the buffer
location given by the integer. Undoing an entry of this form places
point at POSITION.
nil marks undo boundaries. The undo command treats the changes
between two undo boundaries as a single step to be undone.
If the value of the variable is t, undo information is not recorded.
"))
(:documentation "A text Buffer."))
(defmethod print-object ((obj buffer) stream)
(print-unreadable-object (obj stream :type t :identity t)
(format stream "~a" (buffer-name obj))))
(defvar *current-buffer* nil
"When this buffer is non-nil, it contains the current buffer. Calls
to `current-buffer' return this buffer. Otherwise, `current-buffer'
returns the current frames's current window's buffer.
This variable should never be set using `setq' or `setf'. Bind it with
`let' for as long as it needs to be set.")
(defun current-buffer ()
"Return the current buffer."
*current-buffer*)
;;; Windows
;; start and end are inclusive and are buffer points
(defclass line-cache ()
((start :type integer :initform 0 :initarg :start :accessor lc-start)
(end :type integer :initform 0 :initarg :end :accessor lc-end)
(valid :type boolean :initform nil :initarg :valid :accessor lc-valid)
(cache :type list ;;(array cache-item 1)
:initform nil ;; (make-array 0 :element-type 'cache-item
;; :adjustable t
;; :fill-pointer 0)
:initarg :cache :accessor lc-cache)))
(defclass window ()
((frame :initarg :frame :accessor window-frame)
(x :type integer :initarg :x :accessor window-x)
(y :type integer :initarg :y :accessor window-y)
(w :type integer :initarg :w :documentation
"The width of the window's contents.")
(h :type integer :initarg :h :documentation
"The total height of the window, including the mode-line.")
(seperator :type boolean :initform nil :accessor window-seperator :documentation
"T when the window is to draw a vertical seperator. used in horizontal splits.")
(line-state :type (array integer 1) :initarg :line-state :accessor window-line-state)
(cache :type line-cache :initarg :cache :accessor window-cache)
;; Indices into cache (inclusive) that describe the range of the
;; cache that will be displayed.
(top-line :type integer :initarg :top-line :accessor window-top-line)
(bottom-line :type integer :initarg :bottom-line :accessor window-bottom-line)
(point-col :type integer :initarg :point-col :accessor window-point-col)
(point-line :type integer :initarg :point-line :accessor window-point-line)
;; The rest refer to points in the buffer
(buffer :type buffer :initarg :buffer :accessor window-buffer)
(bpoint :type marker :initarg :bpoint :accessor window-bpoint :documentation
"A marker marking where in the text the window point is.")
(top :type marker :initarg :top :accessor window-top :documentation
"The point in buffer that is the first character displayed in the window")
(bottom :type marker :initarg :bottom :accessor window-bottom :documentation
"The point in buffer that is the last character displayed
in the window. This should only be used if bottom-valid is T.")
(bottom-valid :type boolean :initform nil :accessor window-bottom-valid :documentation
"When this is T then bottom should be used to
calculate the visible contents of the window. This is used when
scrolling up (towards the beginning of the buffer)."))
(:documentation "A Lice Window."))
(defclass minibuffer-window (window)
())
(defvar *selected-window* nil
"The window that the cursor now appears in and commands apply to.")
;;; frames
(defclass frame ()
((window-tree :type (or list window) :initarg :window-tree :accessor frame-window-tree)
(width :type fixnum :initarg :width :accessor frame-width)
(height :type fixnum :initarg :height :accessor frame-height)
(minibuffer-window :type window :initarg :minibuffer-window :accessor frame-minibuffer-window)
(minibuffers-active :type fixnum :initform 0 :initarg minibuffers-active :accessor frame-minibuffers-active)
;; echo-area-current is the buffer that holds the current (desired) echo area message,
;; or nil if none is desired right now.
;; echo-area-prev is the buffer that holds the previously displayed echo area message,
;; or nil to indicate no message. This is normally what's on the screen now.
;; These two can point to the same buffer. That happens when the last
;; message output by the user (or made by echoing) has been displayed.
(echo-area-current :initarg echo-area-current :accessor frame-echo-area-current)
(echo-area-prev :initarg echo-area-current :accessor frame-echo-area-prev)
(selected-window :type window :initarg :selected-window :accessor frame-selected-window))
(:documentation "A Lice frame is super cool."))
;; XXX: This is only temporary
(defvar *selected-frame* nil
"The frame that accepts input.")
;;; Events
(defvar *last-point-position* nil
"The value of point when the last command was started.")
(defvar *last-point-position-buffer* nil
"The buffer that was current when the last command was started.")
(defvar *last-point-position-window* nil
"The window that was selected when the last command was started.")
(defvar *current-event* nil
"The current event being processed.")
| 11,525 | Common Lisp | .lisp | 220 | 48.213636 | 111 | 0.72972 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | adb341f6bc6e3e438fb17cefb4e611f14ba53602dc3fa7c385799fe086a98076 | 18,455 | [
-1
] |
18,456 | charset.lisp | spacebat_lice/src/charset.lisp | (in-package "LICE")
(defun define-charset ()
(error "unimplemented define-charset"))
(defun generic-character-list ()
(error "unimplemented generic-character-list"))
(defun get-unused-iso-final-char ()
(error "unimplemented get-unused-iso-final-char"))
(defun declare-equiv-charset ()
(error "unimplemented declare-equiv-charset"))
(defun find-charset-region ()
(error "unimplemented find-charset-region"))
(defun find-charset-string ()
(error "unimplemented find-charset-string"))
(defun make-char-internal ()
(error "unimplemented make-char-internal"))
(defun split-char ()
(error "unimplemented split-char"))
(defun char-charset ()
(error "unimplemented char-charset"))
(defun charset-after (&optional (pos (pt)))
"Return charset of a character in the current buffer at position POS.
If POS is nil, it defauls to the current point.
If POS is out of range, the value is nil."
(error "unimplemented charset-after"))
(defun iso-charset ()
(error "unimplemented iso-charset"))
(defun char-valid-p ()
(error "unimplemented char-valid-p"))
(defun unibyte-char-to-multibyte ()
(error "unimplemented unibyte-char-to-multibyte"))
(defun multibyte-char-to-unibyte ()
(error "unimplemented multibyte-char-to-unibyte"))
(defun char-bytes ()
(error "unimplemented char-bytes"))
(defun char-width ()
(error "unimplemented char-width"))
(defun string-width ()
(error "unimplemented" string-width))
(defun char-direction ()
(error "unimplemented char-direction"))
;; (defun string ()
;; (error (format nil "unimplemented ~a"))
(defun setup-special-charsets ()
(error "unimplemented setup-special-charsets"))
| 1,657 | Common Lisp | .lisp | 44 | 35.295455 | 71 | 0.744507 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 89b3b823ea7c68287409a6b50cdd4a0d88e346b7a4427067fee068f7f1494c5c | 18,456 | [
-1
] |
18,457 | help.lisp | spacebat_lice/src/help.lisp | ;;; Documentation and help related commands
(in-package "LICE")
(defcommand describe-symbol ()
"Display the full documentation of a symbol."
(let* ((pkgs (mapcar (lambda (p)
(cons (package-name p) p))
(list-all-packages)))
(pkg (cdr (find (completing-read "Package: " pkgs) pkgs :key 'car :test 'string-equal)))
(symbols (loop for s being each present-symbol of pkg
collect s))
(symbol (find-symbol (string-upcase (completing-read "Symbol: " symbols)) pkg)))
(with-current-buffer (get-buffer-create "*Help*")
(erase-buffer)
(insert (with-output-to-string (out)
(describe symbol out)))
(pop-to-buffer (current-buffer)))))
(provide :lice-0.1/help)
| 778 | Common Lisp | .lisp | 17 | 37.058824 | 98 | 0.607662 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 164f43f6adb6354f1897141ffbf510e272f1e661101b9493fcc1c1c9ed718b9f | 18,457 | [
-1
] |
18,458 | frame.lisp | spacebat_lice/src/frame.lisp | (in-package :lice)
(defvar *frame-list* nil
"List of frames lice frames.")
(defun set-frame-minibuffer (frame minibuffer)
"Make MINIBUFFER the minibuffer for FRAME."
(setf (window-buffer (frame-minibuffer-window frame)) minibuffer))
(defun resize-window (window amount &optional (dir :height))
"grow or shrink window, resizing dependant windows as well."
(declare (ignore window amount dir))
;; (let* ((frame (frame-window-tree (frame-for-window window)))
;; (sibling (tree-sibling frame window)))
;; )
)
(defun selected-frame ()
"Return the frame that is now selected."
*selected-frame*)
(defun active-minibuffer-window ()
"Return the currently active minibuffer window or nil if there isn't
one."
(let ((frame (selected-frame)))
(unless (zerop (frame-minibuffers-active frame))
(frame-minibuffer-window frame))))
(defun frame-window-list (frame &optional minibuf)
"Return the list of windows in FRAME. If MINIBUF is true then include the minibuffer window."
;; (declare (type frame frame))
;; FIXME: The reason we need to pass MB into flatten is because movitz can't "lend optional right now"
(labels ((flatten (tree mb)
(if (atom tree)
(unless (and (typep tree 'minibuffer-window)
(not mb))
(list tree))
(nconc (flatten (first tree) mb)
(flatten (second tree) mb)))))
(flatten (frame-window-tree frame) minibuf)))
(defun framep (object)
"Return non-nil if OBJECT is a frame.
Value is t for a termcap frame (a character-only terminal),
`x' for an Emacs frame that is really an X window,
`w32' for an Emacs frame that is a window on MS-Windows display,
`mac' for an Emacs frame on a Macintosh display,
`pc' for a direct-write MS-DOS frame.
See also `frame-live-p'."
(typep object 'frame))
(defun frame-live-p ()
(error "unimplemented frame-live-p"))
(defun make-terminal-frame ()
(error "unimplemented make-terminal-frame"))
(defun handle-switch-frame ()
(error "unimplemented handle-switch-frame"))
(defun select-frame (frame)
"Select the frame FRAME.
Subsequent editing commands apply to its selected window.
The selection of FRAME lasts until the next time the user does
something to select a different frame, or until the next time this
function is called. If you are using a window system, the previously
selected frame may be restored as the selected frame after return to
the command loop, because it still may have the window system's input
focus. On a text-only terminal, the next redisplay will display FRAME.
This function returns FRAME, or nil if FRAME has been deleted."
(declare (ignore frame))
(error "unimplemented select-frame"))
(defun frame-root-window ()
(error "unimplemented frame-root-window"))
(defun frame-first-window ()
(error "unimplemented frame-first-window"))
(depricate set-frame-selected-window (setf frame-selected-window))
(defun set-frame-selected-window (frame window)
"Set the selected window of frame object frame to window.
Return window.
If frame is nil, the selected frame is used.
If frame is the selected frame, this makes window the selected window."
(setf (frame-selected-window (or frame (selected-frame))) window))
(defun frame-list ()
"Return a list of all frames."
(copy-list *frame-list*))
(defun next-frame ()
(error "unimplemented next-frame"))
(defun previous-frame ()
(error "unimplemented previous-frame"))
(defun delete-frame ()
(error "unimplemented delete-frame"))
(defun mouse-position ()
(error "unimplemented mouse-position"))
(defun mouse-pixel-position ()
(error "unimplemented mouse-pixel-position"))
(defun set-mouse-position ()
(error "unimplemented set-mouse-position"))
(defun set-mouse-pixel-position ()
(error "unimplemented set-mouse-pixel-position"))
(defun make-frame-visible ()
(error "unimplemented make-frame-visible"))
(defun make-frame-invisible ()
(error "unimplemented make-frame-invisible"))
(defun iconify-frame ()
(error "unimplemented iconify-frame"))
(defun frame-visible-p ()
(error "unimplemented frame-visible-p"))
(defun visible-frame-list ()
(error "unimplemented visible-frame-list"))
(defun raise-frame ()
(error "unimplemented raise-frame"))
(defun lower-frame ()
(error "unimplemented lower-frame"))
(defun redirect-frame-focus ()
(error "unimplemented redirect-frame-focus"))
(defun frame-focus ()
(error "unimplemented frame-focus"))
(defun frame-parameters ()
(error "unimplemented frame-parameters"))
(defun frame-parameter ()
(error "unimplemented frame-parameter"))
(defun modify-frame-parameters ()
(error "unimplemented modify-frame-parameters"))
(defun frame-char-height ()
(error "unimplemented frame-char-height"))
(defun frame-char-width ()
(error "unimplemented frame-char-width"))
(defun frame-pixel-height ()
(error "unimplemented frame-pixel-height"))
(defun frame-pixel-width ()
(error "unimplemented frame-pixel-width"))
(defun set-frame-height ()
(error "unimplemented set-frame-height"))
(defun set-frame-width ()
(error "unimplemented set-frame-width"))
(defun set-frame-size ()
(error "unimplemented set-frame-size"))
(defun set-frame-position ()
(error "unimplemented set-frame-position"))
;; (defun x-get-resource ()
;; (error "unimplemented"))
;; (defun x-parse-geometry ()
;; (error "unimplemented"))
(provide :lice-0.1/frame)
| 5,387 | Common Lisp | .lisp | 134 | 37.544776 | 104 | 0.740684 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9a613e37cbe3f4d5f516f74491e2c36a0fbe279f3693f7c2e8cf600e5730f686 | 18,458 | [
-1
] |
18,459 | textprop.lisp | spacebat_lice/src/textprop.lisp | (in-package "LICE")
(defvar *inhibit-point-motion-hooks* nil
"If non-nil, don't run `point-left' and `point-entered' text properties.
This also inhibits the use of the `intangible' text property.")
;; This function is not translated well
(defun validate-interval-range (object begin end force)
(let (i searchpos)
;; /* If we are asked for a point, but from a subr which operates
;; on a range, then return nothing. */
;; if (EQ (*begin, *end) && begin != end)
;; return NULL_INTERVAL;
(when (> begin end)
(psetf begin end
end begin))
(etypecase object
(buffer
(when (not (and (<= (buffer-min object) begin)
(<= begin end)
(<= end (buffer-max object))))
(signal 'args-out-of-range))
(setf i (intervals object))
(when (= (buffer-min object) (buffer-max object))
(return-from validate-interval-range (values nil begin end)))
(setf searchpos begin))
(pstring
(let ((len (length (pstring-data object))))
(when (not (and (<= 0 begin)
(<= begin end)
(<= end len)))
(signal 'args-out-of-range))
(setf i (intervals object))
(when (zerop len)
(return-from validate-interval-range (values nil begin end)))
(setf searchpos begin)))
(string
(return-from validate-interval-range
(values nil (max 0 begin) (min (length object) end)))))
(if i
(values (find-interval i searchpos) begin end)
(if force
(values (create-root-interval object) begin end)
(values i begin end)))))
(defun validate-plist (list)
"/* Validate LIST as a property list. If LIST is not a list, then
make one consisting of (LIST nil). Otherwise, verify that LIST is
even numbered and thus suitable as a plist. */"
(cond ((null list) nil)
((consp list)
(if (oddp (length list))
(error "odd length property list")
list))
(t (list (list list nil)))))
(defun set-text-properties (start end properties &optional (object (current-buffer)))
(let ((start-bk start)
(end-bk end)
i)
(setf properties (validate-plist properties))
;; If we want no properties for a whole string, get rid of its
;; intervals.
(when (and (null properties)
(typep object 'pstring)
(zerop start)
(= end (length (pstring-data object))))
(when (null (intervals object))
(return-from set-text-properties t))
(setf (intervals object) nil)
(return-from set-text-properties t))
(multiple-value-setq (i start end)
(validate-interval-range object start end nil))
(when (null i)
(when (null properties)
(return-from set-text-properties nil))
;; /* Restore the original START and END values because
;; validate_interval_range increments them for strings. */
(setf start start-bk
end end-bk)
(multiple-value-setq (i start end)
(validate-interval-range object start end t))
;; /* This can return if start == end. */
(when (null i)
(return-from set-text-properties nil)))
;; TODO: add this
;; (when (typep object 'buffer)
;; ;; modify_region (XBUFFER (object), XINT (start), XINT (end));
(set-text-properties-1 start end properties object i)
;; if (BUFFERP (object) && !NILP (signal_after_change_p))
;; signal_after_change (XINT (start), XINT (end) - XINT (start),
;; XINT (end) - XINT (start));
t))
(defun add-properties (plist i object)
"Add the properties in plist to interval I. OBJECT should be the
string of buffer containing the interval."
(declare (ignore object))
(let ((changed nil))
(doplist (sym val plist changed)
(let ((found (getf (interval-plist i) sym)))
(if found
(progn
;; record-property-change
(when (not (eql found val))
(setf (getf (interval-plist i) sym) val
changed t)))
(progn
;; record-property-change
(setf (getf (interval-plist i) sym) val
changed t)))))))
(defun interval-has-all-properties (plist i)
"/* Return nonzero if interval I has all the properties, with the same
values, of list PLIST. */"
(doplist (sym val plist t)
(let ((found (getf (interval-plist i) sym)))
(if found
(when (not (eql found val))
(return-from interval-has-all-properties nil))
(return-from interval-has-all-properties nil)))))
(defun add-text-properties (start end properties &optional (object (current-buffer)))
"Add properties to the text from START to END. The third argument
PROPERTIES is a property list specifying the property values to add.
If the optional fourth argument OBJECT is a buffer (or nil, which
means the current buffer), START and END are buffer positions
(integers or markers). If OBJECT is a string, START and END are
0-based indices into it. Return t if any property value actually
changed, nil otherwise."
(let ((len (- end start))
(modified 0)
i unchanged)
(setf properties (validate-plist properties))
(when (null properties)
(return-from add-text-properties nil))
(multiple-value-setq (i start end) (validate-interval-range object start end t))
(when (null i)
(return-from add-text-properties nil))
;; If we're not starting on an interval boundary, we have to split
;; this interval.
(when (/= (interval-pt i) start)
(if (interval-has-all-properties properties i)
(let ((got (- (interval-text-length i) (- start (interval-pt i)))))
(when (>= got len)
(return-from add-text-properties nil))
(decf len got)
(setf i (next-interval i)))
(progn
(setf unchanged i)
(setf i (split-interval-right unchanged (- start (interval-pt unchanged))))
(copy-properties unchanged i))))
;; if (BUFFERP (object))
;; modify_region (XBUFFER (object), XINT (start), XINT (end));
;; We are at the beginning of interval I, with LEN chars to scan.
(loop
(when (null i)
(error "BORK."))
(when (>= (interval-text-length i) len)
(when (interval-has-all-properties properties i)
(return-from add-text-properties modified))
(when (= (interval-text-length i) len)
(add-properties properties i object)
(return-from add-text-properties t))
(setf unchanged i
i (split-interval-left unchanged len))
(copy-properties unchanged i)
(add-properties properties i object)
(return-from add-text-properties t))
(decf len (interval-text-length i))
(setf modified (add-properties properties i object)
i (next-interval i)))))
(defun put-text-property (start end property value object)
"Set one property of the text from START to END. The third and
fourth arguments PROPERTY and VALUE specify the property to add. If
the optional fifth argument OBJECT is a buffer (or nil, which means
the current buffer), START and END are buffer positions (integers or
markers). If OBJECT is a string, START and END are 0-based indices
into it."
(add-text-properties start end (list property value) object))
(defun remove-properties (plist list i object)
(declare (ignore object))
(doplist (sym val plist)
(declare (ignore val))
(remf sym (interval-plist i)))
(dolist (sym list)
(remf sym (interval-plist i))))
(defun remove-text-properties (start end properties &optional (object (current-buffer)))
"Remove some properties from text from START to END. The third
argument PROPERTIES is a property list whose property names specify
the properties to remove. \(The values stored in PROPERTIES are
ignored.) If the optional fourth argument OBJECT is a buffer (or nil,
which means the current buffer), START and END are buffer positions
(integers or markers). If OBJECT is a string, START and END are
0-based indices into it. Return t if any property was actually
removed, nil otherwise.
Use set-text-properties if you want to remove all text properties."
(let (i unchanged len (modified nil))
(multiple-value-setq (i start end)
(validate-interval-range object start end nil))
(when (null i)
(return-from remove-text-properties nil))
(setf len (- end start))
(when (/= (interval-pt i) start)
(if (not (interval-has-all-properties properties i))
(let ((got (- (interval-text-length i) (- start (interval-pt i)))))
(when (>= got len)
(return-from remove-text-properties nil))
(decf len got)
(setf i (next-interval i)))
(progn
(setf unchanged i
i (split-interval-right unchanged (- start (interval-pt unchanged))))
(copy-properties unchanged i))))
(loop
(unless i
(error "BORK."))
(when (>= (interval-text-length i) len)
(unless (interval-has-all-properties properties i)
(return-from remove-text-properties modified))
(when (= (interval-text-length i) len)
(remove-properties properties nil i object)
(return-from remove-text-properties t))
(setf unchanged i
i (split-interval-left i len))
(copy-properties unchanged i)
(remove-properties properties nil i object)
(return-from remove-text-properties t))
(decf len (interval-text-length i))
(setf modified (remove-properties properties nil i object)
i (next-interval i)))))
(defun text-properties-at (position &optional (object (current-buffer)))
(multiple-value-bind (i position) (validate-interval-range object position position t)
(unless (null i)
;; If POSITION is at the end of the interval,
;; it means it's the end of OBJECT.
;; There are no properties at the very end,
;; since no character follows.
(unless (= position (+ (interval-text-length i) (interval-pt i)))
(interval-plist i)))))
(defun get-text-property (position prop &optional (object (current-buffer)))
(getf (text-properties-at position object) prop))
(defun get-char-property-and-overlay (position prop object overlay)
(declare (ignore overlay))
(get-text-property position prop object))
(defun get-char-property (position prop &optional (object (current-buffer)))
(get-char-property-and-overlay position prop object 0))
(defun previous-property-change (position &optional (object (current-buffer)) limit)
"Return the position of previous property change.
Scans characters backwards from POSITION in OBJECT till it finds
a change in some text property, then returns the position of the change.
If the optional second argument OBJECT is a buffer (or nil, which means
the current buffer), POSITION is a buffer position (integer or marker).
If OBJECT is a string, POSITION is a 0-based index into it.
Return nil if the property is constant all the way to the start of OBJECT.
If the value is non-nil, it is a position less than POSITION, never equal.
If the optional third argument LIMIT is non-nil, don't search
back past position LIMIT; return LIMIT if nothing is found until LIMIT."
(let (i previous)
(multiple-value-setq (i position) (validate-interval-range object position position nil))
(unless i
(return-from previous-property-change limit))
(when (= (interval-pt i) position)
(setf i (previous-interval i)))
(setf previous (previous-interval i))
(while (and previous
(intervals-equal previous i)
(or (null limit)
(> (+ (interval-pt previous)
(interval-text-length previous))
limit)))
(setf previous (previous-interval previous)))
;; FIXME: this code needs cleaning
(when (null previous)
(return-from previous-property-change limit))
(setf limit (or limit
(cond ((typep object 'pstring) 0)
((typep object 'buffer) (buffer-min object)))))
(when (<= (+ (interval-pt previous) (interval-text-length previous))
limit)
(return-from previous-property-change limit))
(+ (interval-pt previous) (interval-text-length previous))))
(defun next-property-change (position &optional object limit)
"Return the position of next property change.
Scans characters forward from POSITION in OBJECT till it finds
a change in some text property, then returns the position of the change.
If the optional second argument OBJECT is a buffer (or nil, which means
the current buffer), POSITION is a buffer position (integer or marker).
If OBJECT is a string, POSITION is a 0-based index into it.
Return nil if the property is constant all the way to the end of OBJECT.
If the value is non-nil, it is a position greater than POSITION, never equal.
If the optional third argument LIMIT is non-nil, don't search
past position LIMIT; return LIMIT if nothing is found before LIMIT."
(let (i next)
(multiple-value-setq (i position) (validate-interval-range object position position nil))
(when (eq limit t)
(setf next (if (null i)
i
(next-interval i)))
(setf position (if (null next)
(cond ((typep object 'pstring) (pstring-length object))
((typep object 'buffer) (buffer-max object)))
(interval-pt next)))
(return-from next-property-change position))
(when (null i)
(return-from next-property-change limit))
(setf next (next-interval i))
(while (and next
(intervals-equal i next)
(or (null limit)
(< (interval-pt next)
limit)))
(setf next (next-interval next)))
(when (null next)
(return-from next-property-change limit))
(when (null limit)
(setf limit (cond ((typep object 'pstring) (pstring-length object))
((typep object 'buffer) (buffer-max object)))))
(unless (< (interval-pt next) limit)
(return-from next-property-change limit))
;; FIXME: This is silly code.
(setf position (interval-pt next))
position))
(defun next-char-property-change (position &optional limit (buffer (current-buffer)))
"Return the position of next text property or overlay change.
This scans characters forward in the current buffer from POSITION till
it finds a change in some text property, or the beginning or end of an
overlay, and returns the position of that.
If none is found, the function returns (point-max).
If the optional third argument LIMIT is non-nil, don't search
past position LIMIT; return LIMIT if nothing is found before LIMIT."
;; temp = Fnext_overlay_change (position);
(next-property-change position buffer (or limit (buffer-max buffer))))
(defun next-single-property-change (position prop &optional (object (current-buffer)) limit)
(let (i next here-val)
(multiple-value-setq (i position)
(validate-interval-range object position position nil))
(when (null i)
(return-from next-single-property-change limit))
(setf here-val (getf (interval-plist i) prop)
next (next-interval i))
;; walk the intervals til we find one with a different plist val
;; for prop.
(while (and next
(eql here-val (getf (interval-plist next) prop))
(or (null limit)
(< (interval-pt next) limit)))
(setf next (next-interval next)))
;; FIXME: this code should be cleaned.
(when (null next)
(return-from next-single-property-change limit))
(setf limit (or limit
(cond ((typep object 'pstring) (pstring-length object))
((typep object 'buffer) (buffer-max object)))))
(when (>= (interval-pt next) limit)
(return-from next-single-property-change limit))
(interval-pt next)))
(defun previous-single-property-change (position prop &optional (object (current-buffer)) limit)
(let (i previous here-val)
(multiple-value-setq (i position) (validate-interval-range object position position nil))
(when (and i
(= (interval-pt i) position))
(setf i (previous-interval i)))
(unless i
(return-from previous-single-property-change limit))
(setf here-val (getf (interval-plist i) prop)
previous (previous-interval i))
(while (and previous
(eql here-val (getf (interval-plist previous) prop))
(or (null limit)
(> (+ (interval-pt previous) (interval-text-length previous))
limit)))
(setf previous (previous-interval previous)))
;; FIXME: this code should be cleaned.
(when (null previous)
(return-from previous-single-property-change limit))
(setf limit (or limit
(cond ((typep object 'pstring) 0)
((typep object 'buffer) (buffer-min object)))))
(when (<= (+ (interval-pt previous) (interval-text-length previous))
limit)
(return-from previous-single-property-change limit))
(+ (interval-pt previous) (interval-text-length previous))))
(defun previous-char-property-change (position &optional limit (buffer (current-buffer)))
"Return the position of previous text property or overlay change.
Scans characters backward in the current buffer from POSITION till it
finds a change in some text property, or the beginning or end of an
overlay, and returns the position of that.
If none is found, the function returns (point-max).
If the optional third argument LIMIT is non-nil, don't search
past position LIMIT; return LIMIT if nothing is found before LIMIT."
(previous-property-change position buffer (or limit (buffer-min buffer))))
(defun next-single-char-property-change (position prop &optional (object (current-buffer)) limit)
"/* Return the position of next text property or overlay change for a specific property.
Scans characters forward from POSITION till it finds
a change in the PROP property, then returns the position of the change.
If the optional third argument OBJECT is a buffer (or nil, which means
the current buffer), POSITION is a buffer position (integer or marker).
If OBJECT is a string, POSITION is a 0-based index into it.
The property values are compared with `eql' by default.
If the property is constant all the way to the end of OBJECT, return the
last valid position in OBJECT.
If the optional fourth argument LIMIT is non-nil, don't search
past position LIMIT; return LIMIT if nothing is found before LIMIT. */"
(if (typep object 'pstring)
(progn
(setf position (next-single-property-change position prop object limit))
(unless position
(if (null limit)
(setf position (pstring-length object))
(setf position limit))))
(let ((initial-value (get-char-property position prop object))
value)
;; (when (and (typep object 'buffer)
;; (not (eq object (current-buffer))))
;; (
(when (null limit)
(setf limit (buffer-max object)))
(loop
(setf position (next-char-property-change position limit object))
(when (>= position limit)
(return limit))
(setf value (get-char-property position prop object))
(unless (eq value initial-value)
(return position))))))
(defun previous-single-char-property-change (position prop &optional (object (current-buffer)) limit)
(cond ((typep object 'pstring)
(setf position (previous-single-property-change position prop object limit))
(when (null position)
(setf position (or limit
(pstring-length object)))))
(t
(unless limit
(setf limit (buffer-min object)))
(if (<= position limit)
(setf position limit)
(let ((initial-value (get-char-property (1- position) prop object))
value)
(loop
(setf position (previous-char-property-change position limit object))
(when (<= position limit)
(return limit))
(setf value (get-char-property (1- position) prop object))
(unless (eq value initial-value)
(return position))))))))
(defun text-property-stickiness (prop pos &optional (buffer (current-buffer)))
"Return the direction from which the text-property PROP would be
inherited by any new text inserted at POS: AFTER if it would be
inherited from the char after POS, BEFORE if it would be inherited from
the char before POS, and NIL if from neither.
BUFFER can be either a buffer or nil (meaning current buffer)."
(labels ((tmem (sym set)
;; Test for membership, allowing for t (actually any
;; non-cons) to mean the universal set."
(if (consp set)
(find sym set)
set)))
(let ((is-rear-sticky t)
(is-front-sticky nil)
prev-pos front-sticky)
(when (> pos (begv buffer))
;; Consider previous character.
(setf prev-pos (1- pos))
(let ((rear-non-sticky (get-text-property prev-pos 'rear-nonsticky buffer)))
(when (tmem prop rear-non-sticky)
;; PROP is rear-non-sticky
(setf is-rear-sticky nil))))
;; Consider following character.
(setf front-sticky (get-text-property pos 'front-sticky buffer))
(when (or (eq front-sticky t)
(and (consp front-sticky)
(find prop front-sticky)))
;; PROP is inherited from after
(setf is-front-sticky t))
;; return the symbol
(cond
;; Simple cases, where the properties are consistent.
((and is-rear-sticky
(not is-front-sticky))
'before)
((and (not is-rear-sticky)
is-front-sticky)
'after)
((and (not is-rear-sticky)
(not is-front-sticky))
nil)
((or (= pos (begv buffer))
(null (get-text-property prev-pos prop buffer)))
'after)
(t
'before)))))
(defun remove-list-of-text-properties (start end list-of-properties &optional object)
"Remove some properties from text from START to END.
The third argument LIST-OF-PROPERTIES is a list of property names to remove.
If the optional fourth argument OBJECT is a buffer (or nil, which means
the current buffer), START and END are buffer positions (integers or
markers). If OBJECT is a string, START and END are 0-based indices into it.
Return t if any property was actually removed, nil otherwise."
(declare (ignore start and list-of-properties object))
(error "unimplemented remove-list-of-text-properties"))
(provide :lice-0.1/textprop)
| 21,918 | Common Lisp | .lisp | 494 | 39.172065 | 101 | 0.687123 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b953518753f502a566702e6feb02f71aef93269580d2963de37ccd7b18472ce0 | 18,459 | [
-1
] |
18,460 | undo.lisp | spacebat_lice/src/undo.lisp | ;;; undo code from undo.c
(in-package "LICE")
(defvar *last-undo-buffer* nil
"Last buffer for which undo information was recorded.")
;; FIXME: a global used in these functions is probably bad wrt concurrency
(defvar *pending-boundary* nil
"The first time a command records something for undo.
it also allocates the undo-boundary object
which will be added to the list at the end of the command.
This ensures we can't run out of space while trying to make
an undo-boundary.")
(defun undo-boundary (&optional (buffer (current-buffer)))
"Mark a boundary between units of undo.
An undo command will stop at this point,
but another undo command will undo to the previous boundary."
(when (eq (buffer-undo-list buffer) t)
(return-from undo-boundary nil))
(when (car (buffer-undo-list buffer))
;; One way or another, cons nil onto the front of the undo list.
(if *pending-boundary*
;; If we have preallocated the cons cell to use here, use that one. ; why the little dance? -sabetts
(setf (cdr *pending-boundary*) (buffer-undo-list buffer)
(buffer-undo-list buffer) *pending-boundary*
*pending-boundary* nil)
(push nil (buffer-undo-list buffer)))
nil))
(defun ensure-pending-boundary ()
"Allocate a cons cell to be the undo boundary after this command."
(when (null *pending-boundary*)
(setf *pending-boundary* (cons nil nil))))
(defun ensure-last-undo-buffer (&optional (buffer (current-buffer)))
(unless (eq buffer *last-undo-buffer*)
(undo-boundary buffer))
(setf *last-undo-buffer* buffer))
(defun record-point (pt &optional (buffer (current-buffer)))
"Record point as it was at beginning of this command (if necessary)
And prepare the undo info for recording a change.
PT is the position of point that will naturally occur as a result of the
undo record that will be added just after this command terminates."
(let (at-boundary)
(ensure-pending-boundary)
(ensure-last-undo-buffer buffer)
(if (consp (buffer-undo-list buffer))
;; Set AT_BOUNDARY to 1 only when we have nothing other than
;; marker adjustment before undo boundary.
(setf at-boundary (loop
for elt in (buffer-undo-list buffer)
while (typep elt 'undo-entry-marker)
finally (return (null elt))))
(setf at-boundary t))
;; FIXME
;; if (MODIFF <= SAVE_MODIFF)
;; record_first_change ();
(when (and at-boundary
;; If we're called from batch mode, this could be nil.
(eq buffer *last-point-position-buffer*))
;; If we have switched windows, use the point value
;; from the window we are in.
(unless (eq *last-point-position-window* (selected-window))
(setf *last-point-position* (marker-position (window-point (selected-window)))))
(when (/= *last-point-position* pt)
(push *last-point-position* (buffer-undo-list buffer))))))
(defun record-insert (beg length &optional (buffer (current-buffer)))
"Record an insertion that just happened or is about to happen, for
LENGTH characters at position BEG. (It is possible to record an
insertion before or after the fact because we don't need to record
the contents.)"
(when (eq (buffer-undo-list buffer) t)
(return-from record-insert nil))
(record-point beg buffer)
;; If this is following another insertion and consecutive with it
;; in the buffer, combine the two.
(when (consp (buffer-undo-list buffer))
(let ((elt (car (buffer-undo-list buffer))))
(when (and (typep elt 'undo-entry-insertion)
(= (undo-entry-insertion-end elt) beg))
(setf (undo-entry-insertion-end elt) (+ beg length))
(return-from record-insert nil))))
(push (make-undo-entry-insertion :beg beg :end (+ beg length)) (buffer-undo-list buffer)))
(defun record-delete (beg string &optional (buffer (current-buffer)))
"Record that a deletion is about to take place, of the
characters in STRING, at location BEG."
(when (eq (buffer-undo-list buffer) t)
(return-from record-delete nil))
(if (= (point) (+ beg (length string)))
(progn
(setf beg (- beg))
(record-point (point)))
(record-point beg))
(push (make-undo-entry-delete :position beg :text string)
(buffer-undo-list buffer)))
(defun record-marker-adjustment (marker adjustment &optional (buffer (current-buffer)))
"Record the fact that MARKER is about to be adjusted by ADJUSTMENT.
This is done only when a marker points within text being deleted,
because that's the only case where an automatic marker adjustment
won't be inverted automatically by undoing the buffer modification."
(when (eq (buffer-undo-list buffer) t)
(return-from record-marker-adjustment nil))
(unless *pending-boundary*
(setf *pending-boundary* (cons nil nil)))
(unless (eq buffer *last-undo-buffer*)
(undo-boundary buffer))
(setf *last-undo-buffer* buffer)
(push (make-undo-entry-marker :marker marker :adjustment adjustment)
(buffer-undo-list buffer)))
(defun record-change (beg length &optional (buffer (current-buffer)))
"Record that a replacement is about to take place,
for LENGTH characters at location BEG.
The replacement must not change the number of characters."
(record-delete beg (buffer-substring beg (+ beg length) buffer))
(record-insert beg length))
(defun record-first-change (&optional (buffer (current-buffer)))
"Record that an unmodified buffer is about to be changed.
Record the file modification date so that when undoing this entry
we can tell whether it is obsolete because the file was saved again."
(when (eq (buffer-undo-list buffer) t)
(return-from record-first-change nil))
(unless (eq buffer *last-undo-buffer*)
(undo-boundary buffer))
(setf *last-undo-buffer* buffer)
;; FIXME
;; if (base_buffer->base_buffer)
;; base_buffer = base_buffer->base_buffer;
;; FIXME: implement modtime
(push (make-undo-entry-modified :time nil)
(buffer-undo-list buffer)))
(defun record-property-change (beg length prop value buffer)
"Record a change in property PROP (whose old value was VAL)
for LENGTH characters starting at position BEG in BUFFER."
(let (boundary)
(when (eq (buffer-undo-list buffer) t)
(return-from record-property-change nil))
(ensure-pending-boundary)
(unless (eq buffer *last-undo-buffer*)
(setf boundary t))
(setf *last-undo-buffer* buffer)
(when boundary
(undo-boundary buffer))
;; FIXME
;; if (MODIFF <= SAVE_MODIFF)
;; record_first_change ();
(push (make-undo-entry-property :prop prop :value value :beg beg :end (+ beg length))
(buffer-undo-list buffer))))
(defgeneric primitive-undo-elt (undo-elt)
)
(defmethod primitive-undo-elt ((elt integer))
"Handle an integer by setting point to that value."
(set-point (clip-to-bounds (begv) elt (zv))))
(defmethod primitive-undo-elt ((elt undo-entry-insertion))
(when (or (< (undo-entry-insertion-beg elt) (begv))
(> (undo-entry-insertion-end elt) (zv)))
(error "Changes to be undone are outside visible portion of buffer"))
(goto-char (undo-entry-insertion-beg elt))
(delete-region (undo-entry-insertion-beg elt)
(undo-entry-insertion-end elt)))
(defmethod primitive-undo-elt ((elt undo-entry-delete))
(let ((pos (undo-entry-delete-position elt))
(text (undo-entry-delete-text elt)))
(if (minusp pos)
(progn
(when (or (< (- pos) (begv))
(> (- pos) (zv)))
(error "Changes to be undone are outside visible portion of buffer"))
(set-point (- pos))
(insert text))
(progn
(when (or (< pos (begv))
(> pos (zv)))
(error "Changes to be undone are outside visible portion of buffer"))
(set-point pos)
(insert text)
(set-point pos)))))
(defmethod primitive-undo-elt ((undo-elt undo-entry-modified))
(error "unimplented"))
(defmethod primitive-undo-elt ((elt undo-entry-property))
(put-text-property (undo-entry-property-beg elt)
(undo-entry-property-end elt)
(undo-entry-property-prop elt)
(undo-entry-property-value elt)
nil))
(defmethod primitive-undo-elt ((undo-elt undo-entry-apply))
(error "unimplented"))
(defmethod primitive-undo-elt ((undo-elt undo-entry-selective))
(error "unimplented"))
(defmethod primitive-undo-elt ((elt undo-entry-marker))
(let ((marker (undo-entry-marker-marker elt)))
(when (marker-buffer marker)
(set-marker marker (- (marker-position marker)
(undo-entry-marker-distance elt))
(marker-buffer marker)))))
(defun primitive-undo (n list)
"Undo N records from the front of the list LIST.
Return what remains of the list."
(check-type n integer)
(let ( ;; Don't let `intangible' properties interfere with undo.
(*inhibit-point-motion-hooks* t)
;; In a writable buffer, enable undoing read-only text that is so
;; because of text properties.
(*inhibit-read-only* t))
(dotimes (arg n)
(while (consp list)
(let ((elt (pop list)))
;; Exit inner loop at undo boundary.
(when (null elt)
(return nil))
(primitive-undo-elt elt))))
;; Make sure an apply entry produces at least one undo entry,
;; so the test in `undo' for continuing an undo series
;; will work right.
list))
| 9,667 | Common Lisp | .lisp | 210 | 39.880952 | 108 | 0.671832 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0929ad0d70828a815a3f50db13579c126b5a5a0e603745d5e0fe05d9e51bbb35 | 18,460 | [
-1
] |
18,461 | dired.lisp | spacebat_lice/src/dired.lisp | ;;; Lisp functions for making directory listings.
(in-package "LICE")
(defvar completion-ignored-extensions nil
"Completion ignores file names ending in any string in this list.
It does not ignore them if all possible completions end in one of
these strings or when displaying a list of completions.
It ignores directory names if they match any string in this list which
ends in a slash.")
(defun directory-files ()
(error "unimplemented directory-files"))
(defun directory-files-and-attributes ()
(error "unimplemented directory-files-and-attributes"))
(defun file-name-completion ()
(error "unimplemented file-name-completion"))
(defun file-name-all-completions ()
(error "unimplemented file-name-all-completions"))
(defun file-attributes ()
(error "unimplemented file-attributes"))
(defun file-attributes-lessp ()
(error "unimplemented file-attributes-lessp"))
| 886 | Common Lisp | .lisp | 20 | 42.2 | 70 | 0.787879 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 051ef578087a2cb72271b061a65f8bd209034d461b67f2a2b47098216e8415c1 | 18,461 | [
-1
] |
18,462 | wm.lisp | spacebat_lice/src/wm.lisp | ;;; window configuration code
(in-package "LICE")
(defstruct window-bk
"A structure that stores the vital data needed to restore a window."
x y w h seperator top bpoint buffer)
(defstruct frame-bk
current-window
window-tree)
(defun current-window-configuration (&optional (frame (selected-frame)))
"Return the vital components of the window configuration of FRAME."
(let ((frame frame)
cw)
(labels ((bk-window (window)
(with-slots (x y w h seperator top bpoint buffer) window
(let ((bk (make-window-bk :x x
:y y
:w w
:h h
:seperator seperator
:top (copy-marker top)
:bpoint (copy-marker bpoint)
:buffer buffer)))
;; record the current window
(when (eq window (frame-selected-window frame))
(setf cw bk))
bk)))
(dup-tree (tree)
(cond ((typep tree 'window)
(bk-window tree))
(t (list (dup-tree (first tree))
(dup-tree (second tree)))))))
(make-frame-bk :window-tree (dup-tree (first (frame-window-tree frame)))
:current-window cw))))
(defun set-window-configuration (configuration &optional (frame (selected-frame)))
"CONFIGURATION must have been generated from FRAME. Otherwise, Bad Things could happen."
(let ((frame frame)
cw)
(labels ((restore-window (bk)
(let ((w (make-window :frame frame
:x (window-bk-x bk)
:y (window-bk-y bk)
:cols (window-bk-w bk)
:rows (window-bk-h bk)
:buffer (window-bk-buffer bk)
:top (window-bk-top bk)
:bpoint (window-bk-bpoint bk))))
(unless (get-buffer (window-bk-buffer bk))
;; default to scratch for deleted buffers
(let ((scratch (get-buffer-create "*scratch*")))
(setf (window-buffer w) scratch
(window-top w) (set-marker (make-marker) 0 scratch)
(window-bpoint w) (set-marker (make-marker) 0 scratch))))
(setf (window-seperator w) (window-bk-seperator bk))
(when (eq bk (frame-bk-current-window configuration))
(setf cw w))
w))
(restore-tree (tree)
(cond ((typep tree 'window-bk)
(restore-window tree))
(t (list (restore-tree (first tree))
(restore-tree (second tree)))))))
(setf (frame-window-tree frame) (cons (restore-tree (frame-bk-window-tree configuration))
(cdr (frame-window-tree frame)))
(frame-selected-window frame) cw)
(set-buffer (window-buffer cw)))))
(defmacro save-window-excursion (&body body)
"Execute body, preserving window sizes and contents.
Restore which buffer appears in which window, where display starts,
and the value of point and mark for each window.
Also restore the choice of selected window.
Also restore which buffer is current.
**Does not restore the value of point in current buffer."
(let ((wc (gensym "WINDOW-CONFIGURATION")))
`(let ((,wc (current-window-configuration)))
(unwind-protect
(progn
,@body)
(set-window-configuration ,wc)))))
(provide :lice-0.1/wm)
| 3,462 | Common Lisp | .lisp | 79 | 32.379747 | 95 | 0.568249 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e6d49ceac360eefc89b1c7f3ad61d096868193d444a87b6b8a95683363941a4b | 18,462 | [
-1
] |
18,463 | minibuffer.lisp | spacebat_lice/src/minibuffer.lisp | (in-package "LICE")
(defvar *history-length* 30
"Maximum length for history lists before truncation takes place.
A number means that length; t means infinite. Truncation takes place
just after a new element is inserted. Setting the :HISTORY-LENGTH
property of a history variable overrides this default.")
(defvar *minibuffer-text-before-history* nil
"Text that was in this minibuffer before any history commands.
This is nil if there have not yet been any history commands
in this use of the minibuffer.")
(defvar *minibuffer-local-map*
(let ((m (make-sparse-keymap)))
(define-key m (make-key :char #\m :control t) 'exit-minibuffer)
(define-key m (make-key :char #\Newline) 'exit-minibuffer)
(define-key m (make-key :char #\Return) 'exit-minibuffer)
(define-key m (make-key :char #\j :control t) 'exit-minibuffer)
(define-key m (make-key :char #\p :meta t) 'previous-history-element)
(define-key m (make-key :char #\n :meta t) 'next-history-element)
(define-key m (make-key :char #\g :control t) 'abort-recursive-edit)
m)
"Default keymap to use when reading from the minibuffer.")
(defvar *minibuffer-local-completion-map*
(let ((m (make-sparse-keymap)))
(define-key m (make-key :char #\i :control t) 'minibuffer-complete)
(define-key m (make-key :char #\Tab) 'minibuffer-complete)
(setf (keymap-parent m) *minibuffer-local-map*)
m)
"Local keymap for minibuffer input with completion.")
(defvar *minibuffer-local-must-match-map*
(let ((m (make-sparse-keymap)))
(define-key m (make-key :char #\m :control t) 'minibuffer-complete-and-exit)
(define-key m (make-key :char #\Newline) 'minibuffer-complete-and-exit)
(define-key m (make-key :char #\Return) 'minibuffer-complete-and-exit)
(define-key m (make-key :char #\j :control t) 'minibuffer-complete-and-exit)
(setf (keymap-parent m) *minibuffer-local-completion-map*)
m)
"Local keymap for minibuffer input with completion, for exact match.")
(defvar *minibuffer-read-mode*
(make-instance 'major-mode
:name "minibuffer mode"
:map *minibuffer-local-map*))
(defvar *minibuffer-complete-mode*
(make-instance 'major-mode
:name "minibuffer mode"
:map *minibuffer-local-completion-map*))
(defvar *minibuffer-must-match-mode*
(make-instance 'major-mode
:name "minibuffer mode"
:map *minibuffer-local-must-match-map*))
(defvar *minibuffer-completion-table* nil
"Alist or obarray used for completion in the minibuffer.
This becomes the ALIST argument to `try-completion' and `all-completions'.
The value can also be a list of strings or a hash table.
The value may alternatively be a function, which is given three arguments:
STRING, the current buffer contents;
PREDICATE, the predicate for filtering possible matches;
CODE, which says what kind of things to do.
CODE can be nil, t or `lambda'.
nil means to return the best completion of STRING, or nil if there is none.
t means to return a list of all possible completions of STRING.
`lambda' means to return t if STRING is a valid completion as it stands.")
(defvar *minibuffer-history* nil
"Default minibuffer history list.
This is used for all minibuffer input
except when an alternate history list is specified.")
;; FIXME: this should be a minibuffer-mode slot?
(defvar *minibuffer-history-position* nil
"Current position of redoing in the history list.")
;; FIXME: this should be a minibuffer-mode slot?
(defvar *minibuffer-history-variable* '*minibuffer-history*
"History list symbol to add minibuffer values to.
Each string of minibuffer input, as it appears on exit from the minibuffer,
is added with
** (set minibuffer-history-variable
** (cons STRING (symbol-value minibuffer-history-variable)))")
;; FIXME: this should be a minibuffer-mode slot?
(defvar *minibuffer-completion-predicate* nil
"Within call to `completing-read', this holds the PREDICATE argument.")
(defvar *minibuffer-list* nil
"List of buffers for use as minibuffers.
The first element of the list is used for the outermost minibuffer
invocation, the next element is used for a recursive minibuffer
invocation, etc. The list is extended at the end as deeper
minibuffer recursions are encountered.")
(defun minibufferp (&optional (buffer (current-buffer)))
"Return t if BUFFER is a minibuffer.
No argument or nil as argument means use current buffer as BUFFER.
BUFFER can be a buffer or a buffer name."
(and (find buffer *minibuffer-list*) t))
(defun make-minibuffer (map)
"Return a fresh minibuffer with major mode, MAJOR-MODE."
;; FIXME: Emacs prefixes it with a space so it doesn't show up in
;; buffer listings. How are we gonna do this?
(let ((mb (get-buffer-create (generate-new-buffer-name " *minibuffer*"))))
(setf (buffer-local-map mb) map
(buffer-local '*mode-line-format* mb) nil)
mb))
(defun make-minibuffer-window (height cols)
(let* ((w (make-instance 'minibuffer-window
:x 0 :y (- height 1) :w cols :h 1
:line-state (make-array 1 :fill-pointer 1
:element-type 'integer :initial-element -1)
:cache (make-instance 'line-cache :valid t)
:top-line 0
:bottom-line 0
:point-col 0
:point-line 0
:buffer (make-minibuffer *minibuffer-local-map*)
:top (make-marker)
:bottom (make-marker)
:bpoint (make-marker)
:point-col 0
:point-line 0)))
(set-marker (window-top w) 0 (window-buffer w))
(set-marker (window-bottom w) 0 (window-buffer w))
w))
;; (defun clear-minibuffer ()
;; "Erase the contents of the minibuffer when it isn't active."
;; (let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame)))))
;; (erase-buffer minibuffer)))
(defun minibuffer-window (&optional (frame (selected-frame)))
"Return the window used now for minibuffers.
If the optional argument FRAME is specified, return the minibuffer window
used by that frame."
(frame-minibuffer-window frame))
(defun clear-minibuffer ()
"Erase the text in the minibuffer, unless it's active."
(when (zerop (frame-minibuffers-active (selected-frame)))
(erase-buffer (window-buffer (frame-minibuffer-window (selected-frame))))))
(defun show-minibuffer-prompt (frame prompt)
"Show PROMPT in the minibuffer. Flip a bit in FRAME to allow
switching to the minibuffer."
(declare (type string prompt)
(ignore frame))
(let ((minibuffer (window-buffer (frame-minibuffer-window (selected-frame))))
(field (npropertize prompt 'field 't 'front-sticky t 'rear-nonsticky t)))
(dformat +debug-v+ "~a~%" field)
(erase-buffer minibuffer)
(buffer-insert minibuffer field)))
(defun minibuffer-prompt-end (&optional (minibuf (current-buffer)))
"Return the buffer position of the end of the minibuffer prompt.
Return (point-min) if current buffer is not a mini-buffer."
(let ((beg (begv minibuf)))
(multiple-value-bind (start end) (find-field beg nil :beg t :end t :buf minibuf)
(dformat +debug-v+ "exit-mb: ~a ~a ~a~%" start end (buffer-size minibuf))
(if (and (= end (zv minibuf))
(null (get-char-property beg 'field minibuf)))
beg
end))))
(defun minibuffer-contents (&optional (minibuf (current-buffer)))
"Return the user input in a minbuffer as a string.
If MINIBUF is omitted, default to the current buffer.
MINIBUF must be a minibuffer."
(buffer-substring (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
(defun minibuffer-contents-no-properties (&optional (minibuf (current-buffer)))
"Return the user input in a minbuffer as a string.
If MINIBUF is omitted, default to the current buffer.
MINIBUF must be a minibuffer."
(buffer-substring-no-properties (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
(defun minibuffer-completion-contents (&optional (minibuf (current-buffer)))
"Return the user input in a minibuffer before point as a string.
That is what completion commands operate on.
The current buffer must be a minibuffer."
;; FIXME: the emacs source produces an error when the pt is not at
;; the end. I Don't know why, though.
(buffer-substring (minibuffer-prompt-end minibuf) (zv minibuf) minibuf))
(defun delete-minibuffer-contents (&optional (minibuf (current-buffer)))
"Delete all user input in a minibuffer.
MINIBUF must be a minibuffer."
(let ((end (minibuffer-prompt-end minibuf)))
(when (< end (zv minibuf))
(delete-region end (zv minibuf)))))
(defun setup-minibuffer-for-read (map prompt initial-contents history)
(save-window-excursion
;; Create a new minibuffer
(let* ((frame (selected-frame))
(*minibuffer-history-variable* history)
(*minibuffer-history-position* 0)
(*minibuffer-text-before-history* nil)
(old-minibuffer (window-buffer (frame-minibuffer-window frame)))
(new-minibuffer (make-minibuffer map)))
(window-save-point (selected-window))
;; attach it to the current frame
(set-window-buffer (frame-minibuffer-window frame) new-minibuffer)
(select-window (frame-minibuffer-window frame))
;; Show the prompt
(show-minibuffer-prompt frame prompt)
;; move to the end of input
(setf (marker-position (buffer-point new-minibuffer)) (buffer-size new-minibuffer))
(when initial-contents (insert initial-contents))
;; enter recursive edit
(dformat +debug-v+ "ya ohoe~%")
(incf (frame-minibuffers-active frame))
(unwind-protect
(progn
(recursive-edit)
(let* ((val (minibuffer-contents new-minibuffer))
(hist-string (when (> (length val) 0)
val)))
(when (and *minibuffer-history-variable* hist-string)
(let ((hist-val (symbol-value *minibuffer-history-variable*)))
;; If the caller wanted to save the value read on a history list,
;; then do so if the value is not already the front of the list.
(when (or (null hist-val)
(and (consp hist-val)
(not (equal hist-string (car hist-val)))))
(push hist-string hist-val)
(setf (symbol-value *minibuffer-history-variable*) hist-val))
;; truncate if requested
(let ((len (or (get *minibuffer-history-variable* :history-length)
*history-length*)))
(when (integerp len)
(if (< len 0)
(setf (symbol-value *minibuffer-history-variable*) nil)
(let ((tmp (nthcdr len hist-val)))
(when tmp
(rplacd tmp nil))))))))
;; return the value
val))
;; Restore the buffer
(dformat +debug-v+ "minibuffer~%")
(set-window-buffer (frame-minibuffer-window frame) old-minibuffer)
(kill-buffer new-minibuffer)
(decf (frame-minibuffers-active frame))))))
(defun test-completion (string alist &optional predicate)
"Return non-nil if string is a valid completion.
Takes the same arguments as `all-completions' and `try-completion'.
If alist is a function, it is called with three arguments:
the values string, predicate and `lambda'."
(let ((matches (all-completions string alist predicate)))
(and (= (length matches) 1)
(string= (first matches) string))))
(defcommand minibuffer-complete-and-exit ()
"If the minibuffer contents is a valid completion then exit.
Otherwise try to complete it. If completion leads to a valid completion,
a repetition of this command will exit."
(let ((str (minibuffer-contents)))
(if (test-completion str *minibuffer-completion-table* *minibuffer-completion-predicate*)
(throw 'exit nil)
(minibuffer-complete))))
(defun read-from-minibuffer (prompt &key initial-contents keymap read (history '*minibuffer-history*) default-value)
"Read a string from the minibuffer, prompting with string PROMPT.
The optional second arg INITIAL-CONTENTS is an obsolete alternative to
DEFAULT-VALUE. It normally should be nil in new code, except when
HISTORY is a cons. It is discussed in more detail below.
Third arg KEYMAP is a keymap to use whilst reading;
if omitted or nil, the default is `minibuffer-local-map'.
If fourth arg READ is non-nil, then interpret the result as a Lisp object
and return that object:
in other words, do `(car (read-from-string INPUT-STRING))'
Fifth arg HISTORY, if non-nil, specifies a history list and optionally
the initial position in the list. It can be a symbol, which is the
history list variable to use, or it can be a cons cell
(HISTVAR . HISTPOS). In that case, HISTVAR is the history list variable
to use, and HISTPOS is the initial position for use by the minibuffer
history commands. For consistency, you should also specify that
element of the history as the value of INITIAL-CONTENTS. Positions
are counted starting from 1 at the beginning of the list.
Sixth arg DEFAULT-VALUE is the default value. If non-nil, it is available
for history commands; but, unless READ is non-nil, `read-from-minibuffer'
does NOT return DEFAULT-VALUE if the user enters empty input! It returns
the empty string.
Seventh arg INHERIT-INPUT-METHOD, if non-nil, means the minibuffer inherits
the current input method and the setting of `enable-multibyte-characters'.
Eight arg KEEP-ALL, if non-nil, says to put all inputs in the history list,
even empty or duplicate inputs.
If the variable `minibuffer-allow-text-properties' is non-nil,
then the string which is returned includes whatever text properties
were present in the minibuffer. Otherwise the value has no text properties.
The remainder of this documentation string describes the
INITIAL-CONTENTS argument in more detail. It is only relevant when
studying existing code, or when HISTORY is a cons. If non-nil,
INITIAL-CONTENTS is a string to be inserted into the minibuffer before
reading input. Normally, point is put at the end of that string.
However, if INITIAL-CONTENTS is \(STRING . POSITION), the initial
input is STRING, but point is placed at _one-indexed_ position
POSITION in the minibuffer. Any integer value less than or equal to
one puts point at the beginning of the string. *Note* that this
behavior differs from the way such arguments are used in `completing-read'
and some related functions, which use zero-indexing for POSITION."
(declare (ignore default-value read keymap))
(setup-minibuffer-for-read (or keymap *minibuffer-local-map*) prompt initial-contents history))
(defun tree-find (tree obj &key (test #'eq))
"find OBJ in TREE. Return the OBJ or nil."
(cond ((typep tree obj)
(when (funcall test tree obj)
tree))
(t (or (tree-find (car tree) obj :test test)
(tree-find (cdr tree) obj :test test)))))
(defun tree-sibling (tree obj &key (test #'eq))
"Return the OBJ's sibling in tree or nil."
(declare (type (or list window) tree))
(cond ((typep tree obj)
nil)
((funcall test obj (car tree))
(cdr tree))
((funcall test obj (cdr tree))
(car tree))
(t (or (tree-sibling (car tree) obj :test test)
(tree-sibling (cdr tree) obj :test test)))))
(defun frame-for-window (window)
"Return the frame that holds WINDOW."
(find-if (lambda (f)
(tree-find (frame-window-tree f) window)) *frame-list*))
(defcommand ask-user ()
""
(message "user typed: ~a" (read-from-minibuffer "input: ")))
(defcommand exit-minibuffer ()
""
(dformat +debug-v+ "exit-minibuffer~%")
(throw 'exit nil))
(defcommand abort-recursive-edit ()
(throw 'exit t))
(defgeneric all-completions (string alist &optional predicate hide-spaces)
(:documentation "Return a list of possible matches."))
(defmethod all-completions (string (alist list) &optional predicate hide-spaces)
(declare (ignore hide-spaces))
(let ((tester (or predicate
(lambda (s)
(string= string s :end2 (min (length string)
(length s)))))))
(loop for elt in alist
for i = (cond ((consp elt)
(car elt))
((symbolp elt)
;; FIXME: this is a hack. isn't there a
;; global that decides whether they're
;; printed upcase or not?
(string-downcase (symbol-name elt)))
(t elt))
when (funcall tester i)
collect i)))
(defmethod all-completions (string (fn function) &optional predicate hide-spaces)
(declare (ignore hide-spaces))
(funcall fn string predicate nil))
(defun try-completion (string alist &optional predicate)
(labels ((all-are-good (match strings)
(loop for i in strings
never (string/= match i :end2 (min (length match)
(length i))))))
(let* ((possibles (all-completions string alist predicate))
(match (make-array 100 ; MOVITZ: the match can't be more than 100 chars
:element-type 'character
:fill-pointer 0
;; :adjustable t
)))
;; FIXME: this dubplicates effort since the first (length string)
;; chars will be the same.
(when possibles
(loop for i from 0 below (length (first possibles))
do (vector-push-extend (char (first possibles) i) match)
unless (all-are-good match possibles)
do (progn
(decf (fill-pointer match))
(return)))
match))))
(define-condition history-end (lice-condition)
() (:documentation "raised when at the end of the history"))
(define-condition history-beginning (lice-condition)
() (:documentation "raised when at the begining of the history"))
(defcommand next-history-element ((&optional n)
:prefix)
(let ((narg (- *minibuffer-history-position* n))
(minimum 0)
elt)
(when (and (zerop *minibuffer-history-position*)
(null *minibuffer-text-before-history*))
(setf *minibuffer-text-before-history*
(minibuffer-contents-no-properties)))
(when (< narg minimum)
(signal 'history-end #|"End of history; no next item"|#))
(when (> narg (length (symbol-value *minibuffer-history-variable*)))
(signal 'history-beginning #|"Beginning of history; no preceding item"|#))
(goto-char (point-max))
(delete-minibuffer-contents)
(setf *minibuffer-history-position* narg)
(cond ((= narg 0)
(setf elt (or *minibuffer-text-before-history* "")
*minibuffer-text-before-history* nil))
(t
(setf elt (nth (1- *minibuffer-history-position*)
(symbol-value *minibuffer-history-variable*)))))
(insert
;; (if (and (eq minibuffer-history-sexp-flag (minibuffer-depth))
;; (not minibuffer-returned-to-present))
;; (let ((*print-level* nil))
;; (prin1-to-string elt))
elt)
(goto-char (point-max))))
(defcommand previous-history-element ()
(next-history-element -1))
(defcommand minibuffer-complete ()
(let* ((txt (minibuffer-contents))
(match (try-completion txt *minibuffer-completion-table*)))
(dformat +debug-v+ "txt: ~a match: ~a~%" txt match)
(when match
(if (= (length match)
(length txt))
;; no new text was added, so list the possibilities
(let* ((txt (minibuffer-contents))
(strings (all-completions txt *minibuffer-completion-table*)))
(with-current-buffer (get-buffer-create "*Completions*")
(erase-buffer)
(insert (format nil "Here are the completions.~%"))
(loop for c in strings
do (insert (format nil "~a~%" c)))
(goto-char (point-min))
(display-buffer (current-buffer))))
(progn
(goto-char (point-max))
(insert (subseq match (length txt))))))))
(defun completing-read (prompt table &key predicate require-match
initial-input (history '*minibuffer-history*) def)
"Read a string in the minibuffer, with completion.
PROMPT is a string to prompt with; normally it ends in a colon and a space.
TABLE is an alist whose elements' cars are strings, or an obarray.
TABLE can also be a function to do the completion itself.
PREDICATE limits completion to a subset of TABLE.
See `try-completion' and `all-completions' for more details
on completion, TABLE, and PREDICATE.
If REQUIRE-MATCH is non-nil, the user is not allowed to exit unless
the input is (or completes to) an element of TABLE or is null.
If it is also not t, Return does not exit if it does non-null completion.
If the input is null, `completing-read' returns an empty string,
regardless of the value of REQUIRE-MATCH.
If INITIAL-INPUT is non-nil, insert it in the minibuffer initially.
If it is (STRING . POSITION), the initial input
is STRING, but point is placed POSITION characters into the string.
This feature is deprecated--it is best to pass nil for INITIAL.
HISTORY, if non-nil, specifies a history list
and optionally the initial position in the list.
It can be a symbol, which is the history list variable to use,
or it can be a cons cell (HISTVAR . HISTPOS).
In that case, HISTVAR is the history list variable to use,
and HISTPOS is the initial position (the position in the list
which INITIAL-INPUT corresponds to).
Positions are counted starting from 1 at the beginning of the list.
DEF, if non-nil, is the default value."
(declare (ignore def))
(let ((*minibuffer-completion-table* table)
(*minibuffer-completion-predicate* predicate))
(setup-minibuffer-for-read (if require-match
*minibuffer-local-must-match-map*
*minibuffer-local-completion-map*)
prompt initial-input history)))
;; (defun y-or-n-p (prompt)
;; "Ask user a \"y or n\" question. Return t if answer is \"y\".
;; Takes one argument, which is the string to display to ask the question.
;; It should end in a space; `y-or-n-p' adds `(y or n) ' to it.
;; No confirmation of the answer is requested; a single character is enough.
;; Also accepts Space to mean yes, or Delete to mean no. (Actually, it uses
;; the bindings in `query-replace-map'; see the documentation of that variable
;; for more information. In this case, the useful bindings are `act', `skip',
;; `recenter', and `quit'.)
;; Under a windowing system a dialog box will be used if `last-nonmenu-event'
;; is nil and `use-dialog-box' is non-nil."
;; ;; FIXME: This needs to be redone when the ECHO AREA works.
;; (string-equal "y" (read-from-minibuffer (concatenate 'string prompt "(y on n)"))))
(provide :lice-0.1/minibuffer)
| 22,187 | Common Lisp | .lisp | 459 | 43.923747 | 116 | 0.709928 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 95f90bb86300b49e14b3b56c4f6e7a82cfd7d9030915b9f6a996d99ade97c03a | 18,463 | [
-1
] |
18,464 | callproc.lisp | spacebat_lice/src/callproc.lisp | ;; Synchronous subprocess invocation for GNU Emacs.
(in-package "LICE")
;; FIXME: Fill these with real values
(defvar shell-file-name nil
"*File name to load inferior shells from.
Initialized from the SHELL environment variable, or to a system-dependent
default if SHELL is not set.")
(defvar exec-path nil
"*List of directories to search programs to run in subprocesses.
Each element is a string (directory name) or nil (try default directory).")
(defvar exec-suffixes nil
"*List of suffixes to try to find executable file names.
Each element is a string.")
Vexec_suffixes = Qnil;
(defvar exec-directory nil
"Directory for executables for Emacs to invoke.
More generally, this includes any architecture-dependent files
that are built and installed from the Emacs distribution.")
(defvar data-directory nil
"Directory of machine-independent files that come with GNU Emacs.
These are files intended for Emacs to use while it runs.")
(defvar doc-directory nil
"Directory containing the DOC file that comes with GNU Emacs.
This is usually the same as `data-directory'.")
(defvar configure-info-directory nil
"For internal use by the build procedure only.
This is the name of the directory in which the build procedure installed
Emacs's info files; the default value for `Info-default-directory-list'
includes this.")
(defvar shared-game-score-directory nil
"Directory of score files for games which come with GNU Emacs.
If this variable is nil, then Emacs is unable to use a shared directory.")
(defvar temp-file-name-pattern nil
"Pattern for making names for temporary files.
This is used by `call-process-region'.")
(defvar process-environment nil
"List of environment variables for subprocesses to inherit.
Each element should be a string of the form ENVVARNAME=VALUE.
If multiple entries define the same variable, the first one always
takes precedence.
The environment which Emacs inherits is placed in this variable
when Emacs starts.
Non-ASCII characters are encoded according to the initial value of
`locale-coding-system', i.e. the elements must normally be decoded for use.
See `setenv' and `getenv'.")
| 2,123 | Common Lisp | .lisp | 45 | 45.866667 | 75 | 0.807841 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b756d8c17e392b856aada98ace2ef283153631a102e8d06efffef0249f0ff7e7 | 18,464 | [
-1
] |
18,465 | search.lisp | spacebat_lice/src/search.lisp | (in-package "LICE")
;; because gnu emacs' match-data is not reentrant we create this
;; structure that is returned for all searching functions. It is
;; passed into the match-data related functions.
(defstruct match-data
obj start end reg-starts reg-ends)
(defvar *match-data* nil
"store the match data for searches.")
(defvar *with-match-data* nil
"Set to true when inside a match-data block. If this is NIL
during one of the searches, a warning is signaled because it's
not thread safe. But, lots of code uses the search functions so
it's useful, at least now to be compatible with gnu emacs, even
if it's not thread safe. Never set this variable directly.")
(defmacro with-match-data (&body body)
`(let ((*with-match-data* t)
(*match-data* nil))
,@body))
(defun match-end (idx &optional (data *match-data*))
"Return position of start of text matched by last search.
SUBEXP, a number, specifies which parenthesized expression in the last
regexp.
Value is nil if SUBEXPth pair didn't match, or there were less than
SUBEXP pairs.
Zero means the entire text matched by the whole regexp or whole string."
(if (zerop idx)
(match-data-end data)
(aref (match-data-reg-ends data) (1- idx))))
(defun match-beginning (idx &optional (data *match-data*))
"Return position of start of text matched by last search.
SUBEXP, a number, specifies which parenthesized expression in the last
regexp.
Value is nil if SUBEXPth pair didn't match, or there were less than
SUBEXP pairs.
Zero means the entire text matched by the whole regexp or whole string."
(if (zerop idx)
(match-data-start data)
(aref (match-data-reg-starts data) (1- idx))))
(defun match-string (num &optional string)
"Return string of text matched by last search.
NUM specifies which parenthesized expression in the last regexp.
Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
Zero means the entire text matched by the whole regexp or whole string.
STRING should be given if the last search was by `string-match' on STRING."
(if (match-beginning num)
(if string
(substring string (match-beginning num) (match-end num))
(buffer-substring (match-beginning num) (match-end num)))))
(defun replace-match (newtext &optional fixedcase literal string subexp)
"Replace text matched by last search with NEWTEXT.
Leave point at the end of the replacement text.
If second arg FIXEDCASE is non-nil, do not alter case of replacement text.
Otherwise maybe capitalize the whole text, or maybe just word initials,
based on the replaced text.
If the replaced text has only capital letters
and has at least one multiletter word, convert NEWTEXT to all caps.
Otherwise if all words are capitalized in the replaced text,
capitalize each word in NEWTEXT.
If third arg LITERAL is non-nil, insert NEWTEXT literally.
Otherwise treat `\\' as special:
`\\&' in NEWTEXT means substitute original matched text.
`\\N' means substitute what matched the Nth `\\(...\\)'.
If Nth parens didn't match, substitute nothing.
`\\\\' means insert one `\\'.
Case conversion does not apply to these substitutions.
FIXEDCASE and LITERAL are optional arguments.
The optional fourth argument STRING can be a string to modify.
This is meaningful when the previous match was done against STRING,
using `string-match'. When used this way, `replace-match'
creates and returns a new string made by copying STRING and replacing
the part of STRING that was matched.
The optional fifth argument SUBEXP specifies a subexpression;
it says to replace just that subexpression with NEWTEXT,
rather than replacing the entire matched text.
This is, in a vague sense, the inverse of using `\\N' in NEWTEXT;
`\\N' copies subexp N into NEWTEXT, but using N as SUBEXP puts
NEWTEXT in place of subexp N.
This is useful only after a regular expression search or match,
since only regular expressions have distinguished subexpressions."
(declare (ignore newtext fixedcase literal string subexp))
(error "unimplemented replace-match"))
(defun match-string-no-properties (num &optional string)
"Return string of text matched by last search, without text properties.
NUM specifies which parenthesized expression in the last regexp.
Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
Zero means the entire text matched by the whole regexp or whole string.
STRING should be given if the last search was by `string-match' on STRING."
(if (match-beginning num)
(if string
(substring-no-properties string (match-beginning num)
(match-end num))
(buffer-substring-no-properties (match-beginning num)
(match-end num)))))
;; FIXME: needs a formatter and the search string
(define-condition search-failed (lice-condition)
() (:documentation "raised when a search failed to match"))
(define-condition thread-unsafe (style-warning)
() (:documentation "Raised when a search is not threadsafe. See also `*with-match-data*'"))
(defun check-search-thread-safe ()
"Report a warning if the search is unsafe for threads."
(unless *with-match-data*
(signal 'thread-unsafe)))
(defun string-search-command (string bound error count direction)
(check-search-thread-safe)
(gap-move-to (current-buffer) (buffer-point-aref (current-buffer)))
;; normalize vars
(setf count (* count direction)
bound (if (minusp count)
(if bound (max bound (begv)) (begv))
(if bound (min bound (zv)) (zv))))
(let* ((buffer (current-buffer))
pos
(start-aref (buffer-point-aref buffer))
(bound-aref (buffer-char-to-aref buffer bound))
(n (if (minusp count)
(loop for i from 0 below (- count)
do (setf pos (search string (buffer-data buffer) :from-end t :end2 start-aref :start2 bound-aref))
while pos
count i)
(loop for i from 0 below count
do (setf pos (search string (buffer-data buffer) :start2 start-aref :end2 bound-aref))
while pos
count i))))
(if (/= n (abs count))
(cond
((eq error t)
(signal 'search-failed))
((null error)
nil)
(bound
(set-point bound buffer)
nil)
(t nil))
(progn
(if (minusp count)
(set-point (+ (buffer-aref-to-char buffer pos) (length string)))
(set-point (buffer-aref-to-char buffer pos)))
(values (pt)
(setf *match-data*
(make-match-data :obj buffer
:start (buffer-aref-to-char buffer pos)
:end (+ (buffer-aref-to-char buffer pos) (length string))
:reg-starts #()
:reg-ends #())))))))
(defun search-forward (string &key bound (error t) (count 1))
"Search forward from point for string.
Set point to the end of the occurrence found, and return point.
An optional second argument bounds the search; it is a buffer position.
The match found must not extend after that position. nil is equivalent
to (point-max).
Optional third argument, if t, means if fail just return nil (no error).
If not nil and not t, move to limit of search and return nil.
Optional fourth argument is repeat count--search for successive occurrences.
Search case-sensitivity is determined by the value of the variable
`case-fold-search', which see.
See also the functions `match-beginning', `match-end' and `replace-match'."
(string-search-command string bound error count 1))
(defun search-backward (string &key bound (error t) (count 1))
"Search backward from point for STRING.
Set point to the beginning of the occurrence found, and return point.
An optional second argument bounds the search; it is a buffer position.
The match found must not extend before that position.
Optional third argument, if t, means if fail just return nil (no error).
If not nil and not t, position at limit of search and return nil.
Optional fourth argument is repeat count--search for successive occurrences.
Search case-sensitivity is determined by the value of the variable
`case-fold-search', which see.
See also the functions `match-beginning', `match-end' and `replace-match'."
(string-search-command string bound error count -1))
(defvar *regexp-cache* (make-memoize-state :test 'string=))
;; TODO: create compiler-macros for regex functions so the regexps can
;; be compiled at compile time.
(defun looking-at (regexp &optional (buffer (current-buffer)))
"Return the match-data if text after point matches regular expression regexp."
(check-type regexp string)
(check-search-thread-safe)
;; get the gap outta the way. It sucks we have to do this. Really we
;; should modify ppcre to generate scanner functions that hop the
;; gap. Meantime...
(when (< (buffer-char-to-aref buffer (pt buffer))
(buffer-gap-start buffer))
(gap-move-to-point buffer))
(multiple-value-bind (start end reg-starts reg-ends)
(ppcre:scan (memoize *regexp-cache* regexp (ppcre:create-scanner regexp :multi-line-mode t)) (buffer-data buffer)
:start (buffer-char-to-aref buffer (pt buffer))
:real-start-pos 0)
(when (and start
(= start (buffer-char-to-aref buffer (pt buffer))))
(values t
(setf *match-data*
(make-match-data :obj buffer
:start (buffer-aref-to-char buffer start)
:end (buffer-aref-to-char buffer end)
:reg-starts (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-starts)
:reg-ends (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-ends)))))))
(defun re-search-forward (regexp &key (bound (zv)) (error t) count &aux (buffer (current-buffer)))
"Search forward from point for regular expression regexp.
Set point to the end of the occurrence found, and return match-data structure.
BOUND bounds the search; it is a buffer position.
The match found must not extend after that position.
ERROR, if nil, means if fail just return nil (no error).
If not nil and not t, move to limit of search and return nil.
COUNT is repeat count--search for successive occurrences.
See also the functions `match-beginning', `match-end', `match-string',
and `replace-match'."
(declare (ignore count))
(check-search-thread-safe)
(when (< (buffer-char-to-aref buffer (pt buffer))
(buffer-gap-start buffer))
(gap-move-to-point buffer))
(multiple-value-bind (start end reg-starts reg-ends)
(ppcre:scan (memoize *regexp-cache* regexp (ppcre:create-scanner regexp :multi-line-mode t)) (buffer-data buffer)
:start (buffer-char-to-aref buffer (pt buffer))
:end (buffer-char-to-aref buffer bound)
:real-start-pos 0)
(cond (start
(set-point (buffer-aref-to-char buffer end) buffer)
(values (pt)
(setf *match-data*
(make-match-data :obj buffer
:start (buffer-aref-to-char buffer start)
:end (buffer-aref-to-char buffer end)
:reg-starts (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-starts)
:reg-ends (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-ends)))))
((eq error t)
(signal 'search-failed))
((null error)
nil)
(bound
(set-point bound buffer)
nil)
(t nil))))
(defun re-search-backward (regexp &key (bound (begv)) (error t) count &aux (buffer (current-buffer)))
"Search backward from point for match for regular expression regexp.
Set point to the beginning of the match, and return match-data.
The match found is the one starting last in the buffer
and yet ending before the origin of the search.
BOUND bounds the search; it is a buffer position.
The match found must start at or after that position.
ERROR, if nil, means if fail just return nil (no error).
If not nil and not t, move to limit of search and return nil.
COUNT is repeat count--search for successive occurrences.
See also the functions `match-beginning', `match-end', `match-string',
and `replace-match'."
(declare (ignore count))
(check-search-thread-safe)
;;(message "re-search-backward ~s ~d" regexp (point))
(when (> (buffer-gap-start buffer)
(buffer-char-to-aref buffer (pt buffer)))
(gap-move-to buffer (buffer-char-to-aref buffer (1+ (pt buffer)))))
;; start search from point and keep walking back til we match something
(let* ((start-aref (buffer-char-to-aref buffer (pt buffer)))
(pt-aref start-aref)
(stop (buffer-char-to-aref buffer bound))
(scanner (memoize *regexp-cache* regexp (ppcre:create-scanner regexp :multi-line-mode t))))
(loop
(multiple-value-bind (start end reg-starts reg-ends)
(ppcre:scan scanner (buffer-data buffer) :start start-aref :end pt-aref :real-start-pos 0)
(when start
(set-point (buffer-aref-to-char buffer start) buffer)
(return (values (pt)
(setf *match-data*
(make-match-data :obj buffer
:start (buffer-aref-to-char buffer start)
:end (buffer-aref-to-char buffer end)
:reg-starts (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-starts)
:reg-ends (map 'vector (lambda (n)
(buffer-aref-to-char buffer n))
reg-ends))))))
(dec-aref start-aref buffer)
(when (< start-aref stop)
(cond ((eq error t)
;; FIXME: we need a search condition
(signal 'search-failed))
((null error)
(return nil))
(t
(when bound
(set-point bound buffer))
(return nil))))))))
(defun string-match (regexp string &key (start 0) (end (length string)))
"Return index of start of first match for regexp in string and match-data, or nil.
Matching ignores case if `case-fold-search' is non-nil.
START, start search at that index in string.
END, end search at that index in string.
**For index of first char beyond the match, do (match-end 0).
**`match-end' and `match-beginning' also give indices of substrings
**matched by parenthesis constructs in the pattern.
You can use the function `match-string' to extract the substrings
matched by the parenthesis constructions in regexp."
(check-search-thread-safe)
(multiple-value-bind (start end reg-starts reg-ends)
(ppcre:scan (memoize *regexp-cache* regexp (ppcre:create-scanner regexp :multi-line-mode t))
string :start start :end end)
(when start
(values start
(setf *match-data*
(make-match-data :obj string
:start start
:end end
:reg-starts reg-starts
:reg-ends reg-ends))))))
(defun regexp-quote (string)
"Return a regexp string which matches exactly STRING and nothing else."
(check-type string string)
(coerce
(loop for c across string
when (find c "[*.\\?+^$" :test 'char=)
collect #\\
collect c)
'string))
(defun wordify (string)
"Given a string of words separated by word delimiters,
compute a regexp that matches those exact words
separated by arbitrary punctuation."
(error "unimplemented wordify"))
(defun word-search-forward (string &key (bound (begv)) (error t) count &aux (buffer (current-buffer)))
(error "unimplemented word-search-forward"))
(defun scan-buffer (buffer target start end count)
"Search for COUNT instances of the character TARGET between START and END.
If COUNT is positive, search forwards; END must be >= START.
If COUNT is negative, search backwards for the -COUNTth instance;
END must be <= START.
If COUNT is zero, do anything you please; run rogue, for all I care.
If END is NIL, use BEGV or ZV instead, as appropriate for the
direction indicated by COUNT.
If we find COUNT instances, return the
position past the COUNTth match and 0. Note that for reverse motion
this is not the same as the usual convention for Emacs motion commands.
If we don't find COUNT instances before reaching END, return END
and the number of TARGETs left unfound."
(let ((shortage (abs count))
last)
(if (> count 0)
(setf end (or end (zv buffer)))
(setf end (or end (begv buffer))))
(setf start (buffer-char-to-aref buffer start)
end (buffer-char-to-aref buffer end))
(loop while (and (> count 0)
(/= start end)) do
(setf start
(if (< start (buffer-gap-start buffer))
(or (position target (buffer-data buffer) :start start :end (min end (buffer-gap-start buffer)))
(and (> end (gap-end buffer))
(position target (buffer-data buffer) :start (gap-end buffer) :end end)))
(position target (buffer-data buffer) :start start :end end)))
(if start
(setf start (1+ start)
last start
count (1- count)
shortage (1- shortage))
(setf start end)))
(loop while (and (< count 0)
(/= start end)) do
(setf start
(if (> start (buffer-gap-start buffer))
(or (position target (buffer-data buffer) :start (max end (gap-end buffer)) :end start :from-end t)
(and (< end (buffer-gap-start buffer))
(position target (buffer-data buffer) :start end :end (buffer-gap-start buffer) :from-end t)))
(position target (buffer-data buffer) :start end :end start :from-end t)))
(if start
(setf last (+ start 1) ; match emacs functionality
count (1+ count)
shortage (1- shortage))
(setf start end)))
(if (zerop count)
(values (and last (buffer-aref-to-char buffer last)) 0)
(values (buffer-aref-to-char buffer end) shortage))))
(defun find-before-next-newline (from to cnt)
"Like find_next_newline, but returns position before the newline,
not after, and only search up to TO. This isn't just
find_next_newline (...)-1, because you might hit TO."
(multiple-value-bind (pos shortage) (scan-buffer (current-buffer) #\Newline from to cnt)
(when (zerop shortage)
(decf pos))
pos))
(defun buffer-scan-newline (buf start limit count)
"Search BUF for COUNT newlines with a limiting point at LIMIT,
starting at START. Returns the point of the last newline or limit and
number of newlines found. START and LIMIT are inclusive."
(declare (type buffer buf)
(type integer start limit count))
(labels ((buffer-scan-bk (buf start limit count)
"count is always >=0. start >= limit."
(let* ((start-aref (buffer-char-to-aref buf start))
(limit-aref (buffer-char-to-aref buf limit))
(ceiling (if (>= start-aref (gap-end buf))
(max limit-aref (gap-end buf))
limit-aref))
(i 0)
;; :END is not inclusive but START is.
(start (1+ start-aref))
p)
(loop
;; Always search at least once
(setf p (position #\Newline (buffer-data buf)
:start ceiling :end start :from-end t))
(if p
(progn
;; Move start. Note that start isn't set to (1+ p)
;; because we don't want to search p again.
(setf start p)
;; Count the newline
(incf i)
;; Have we found enough newlines?
(when (>= i count)
(return-from buffer-scan-bk (values (buffer-aref-to-char buf p)
i))))
;; Check if we've searched up to the limit
(if (= ceiling limit-aref)
(return-from buffer-scan-bk (values limit i))
;; if not, skip past the gap
(progn
(setf ceiling limit-aref)
(setf start (buffer-gap-start buf))))))))
(buffer-scan-fw (buf start limit count)
"count is always >=0. start >= limit."
(let* ((start-aref (buffer-char-to-aref buf start))
(limit-aref (1+ (buffer-char-to-aref buf limit)))
(ceiling (if (< start (buffer-gap-start buf))
(min limit-aref (buffer-gap-start buf))
limit-aref))
(i 0)
(start start-aref)
p)
(loop
;; Always search at least once
(setf p (position #\Newline (buffer-data buf) :start start :end ceiling))
(if p
(progn
;; Move start. We don't want to search p again, thus the 1+.
(setf start (1+ p))
;; Count the newline
(incf i)
;; Have we found enough newlines?
(when (>= i count)
(return-from buffer-scan-fw (values (buffer-aref-to-char buf p)
i))))
;; Check if we've searched up to the limit
(if (= ceiling limit-aref)
(return-from buffer-scan-fw (values limit i))
;; if not, skip past the gap
(progn
(setf ceiling limit-aref)
(setf start (gap-end buf)))))))))
;; make sure start and limit are within the bounds
(setf start (max 0 (min start (1- (buffer-size buf))))
limit (max 0 (min limit (1- (buffer-size buf)))))
;; the search always fails on an empty buffer
(when (= (buffer-size buf) 0)
(return-from buffer-scan-newline (values limit 0)))
(cond ((> count 0)
(dformat +debug-vv+ "scan-fw ~a ~a ~a~%" start limit count)
(buffer-scan-fw buf start limit count))
((< count 0)
(dformat +debug-vv+ "scan-bk ~a ~a ~a~%" start limit count)
(buffer-scan-bk buf start limit (abs count)))
;; 0 means the newline before the beginning of the current
;; line. We need to handle the case where we are on a newline.
(t
(dformat +debug-vv+ "scan-0 ~a ~a ~a~%" start limit count)
(if (char= (buffer-char-after buf start) #\Newline)
(buffer-scan-bk buf start limit 2)
(buffer-scan-bk buf start limit 1))))))
| 23,361 | Common Lisp | .lisp | 474 | 39.833333 | 122 | 0.625826 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 893f8747c59284ec65766b17db522acbe27d7775a86beee46234073e1e782b55 | 18,465 | [
-1
] |
18,466 | recursive-edit.lisp | spacebat_lice/src/recursive-edit.lisp | ;;; Implement the recursive edit.
(in-package "LICE")
(defvar *recursive-edit-depth* 0
"The current recursive-edit depth.")
;; TODO: Restore the window/buffer layout
(defun recursive-edit ()
(let* ((*recursive-edit-depth* (1+ *recursive-edit-depth*))
;; reset the command keys for the recursive edit
(*this-command-keys* nil)
;; restore the last command
(*last-command* *last-command*)
(ret (catch 'exit
(with-lice-debugger
(command-loop)))))
;; return the ret val.
(dformat +debug-v+ "ret ~a~%" ret)
(when ret
(signal 'quit))))
(provide :lice-0.1/recursive-edit)
| 636 | Common Lisp | .lisp | 19 | 28.684211 | 61 | 0.647635 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f86111dfc048c683ebd7f77990f1833276386c711c2a5f5d10da863c63467f6d | 18,466 | [
-1
] |
18,467 | all.lisp | spacebat_lice/src/all.lisp | (provide :lice-0.1/all :load-priority -1)
(defpackage :lice
(:use :cl))
(require :lice-0.1/wrappers)
(require :lice-0.1/global)
(require :lice-0.1/major-mode)
(require :lice-0.1/buffer)
(require :lice-0.1/window)
(require :lice-0.1/frame)
(require :lice-0.1/movitz-render)
(require :lice-0.1/intervals)
(require :lice-0.1/textprop)
(require :lice-0.1/editfns)
(require :lice-0.1/input)
(require :lice-0.1/recursive-edit)
(require :lice-0.1/minibuffer)
(require :lice-0.1/subr)
(require :lice-0.1/simple)
;; ;; (require :lice-0.1/debug)
;; ;; (require :lice-0.1/files)
;; ;; (require :lice-0.1/help)
(require :lice-0.1/wm)
(require :lice-0.1/lisp-mode)
(require :lice-0.1/main)
;; (progn
;; (movitz-compile-file #p"losp/lice-0.1/wrappers.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/global.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/major-mode.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/buffer.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/window.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/frame.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/movitz-render.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/intervals.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/textprop.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/editfns.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/input.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/recursive-edit.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/minibuffer.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/subr.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/simple.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/wm.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/lisp-mode.lisp" :load-priority -1)
;; (movitz-compile-file #p"losp/lice-0.1/main.lisp" :load-priority -1))
| 2,075 | Common Lisp | .lisp | 43 | 46.953488 | 82 | 0.695695 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0346268cc7b18247068ba1fd657246e312a2b603aaed3ad0c1123ff27c137e7f | 18,467 | [
-1
] |
18,468 | fns.lisp | spacebat_lice/src/fns.lisp | ;;; fns.lisp --- compatibility function from emacs
(in-package "LICE")
(defun concat (&rest strings)
"Concatenate all the arguments and make the result a string.
The result is a string whose elements are the elements of all the arguments.
Each argument must be a string."
(apply 'concatenate 'string strings))
(defun cdr-safe (object)
"Return the cdr of OBJECT if it is a cons cell, or else nil."
(when (consp object)
(cdr object)))
;; XXX: get rid of this function and all callers
(defun assq (prop list)
"Return non-nil if key is `eq' to the car of an element of list.
The value is actually the first element of list whose car is key.
Elements of list that are not conses are ignored."
(assoc prop (remove-if 'listp list)))
(depricate substring subseq)
(defun substring (string from &optional (to (length string)))
"Return a substring of string, starting at index from and ending before to.
to may be nil or omitted; then the substring runs to the end of string.
from and to start at 0. If either is negative, it counts from the end.
This function allows vectors as well as strings."
(when (< from 0)
(setf from (max 0 (+ (length string) from))))
(when (< to 0)
(setf to (max 0 (+ (length string) to))))
(subseq string from to))
(depricate memq member)
(defun memq (elt list)
"Return non-nil if ELT is an element of LIST.
Comparison done with `eq'. The value is actually the tail of LIST
whose car is ELT."
(member elt list :test 'eq))
(depricate put (setf get))
(defun put (symbol propname value)
"Store SYMBOL's PROPNAME property with value VALUE.
It can be retrieved with `(get SYMBOL PROPNAME)'."
(setf (get symbol propname) value))
(defun featurep (feature &optional subfeature)
"Returns t if FEATURE is present in this Emacs.
Use this to conditionalize execution of lisp code based on the
presence or absence of Emacs or environment extensions.
Use `provide' to declare that a feature is available. This function
looks at the value of the variable `features'. The optional argument
SUBFEATURE can be used to check a specific subfeature of FEATURE."
(and (find feature *features*) t))
| 2,150 | Common Lisp | .lisp | 47 | 43.595745 | 77 | 0.748686 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 700f8a6c4a00c9328866c8d2937ddc7e3bbbf88c6174e419e5fe82007956e483 | 18,468 | [
-1
] |
18,469 | cmds.lisp | spacebat_lice/src/cmds.lisp | ;;; Simple built-in editing commands.
(in-package "LICE")
(defun forward-point (n)
"Return buffer position N characters after (before if N negative) point."
(check-type n integer)
(+ (pt) n))
(defcommand forward-char ((&optional (n 1))
:prefix)
"Move the point forward N characters in the current buffer."
(incf (marker-position (buffer-point (current-buffer))) n)
(cond ((< (pt) (begv))
(set-point (begv))
(signal 'beginning-of-buffer))
((> (pt) (zv))
(set-point (zv))
(signal 'end-of-buffer))))
(defcommand backward-char ((&optional (n 1))
:prefix)
(forward-char (- n)))
(defun forward-line (n)
"Move n lines forward (backward if n is negative).
Precisely, if point is on line I, move to the start of line I + n.
If there isn't room, go as far as possible (no error).
Returns the count of lines left to move. If moving forward,
that is n - number of lines moved; if backward, n + number moved.
With positive n, a non-empty line at the end counts as one line
successfully moved (for the return value)."
(cond ((and (> n 0)
(= (pt) (zv)))
(signal 'end-of-buffer))
((and (< n 0)
(= (pt) (begv)))
(signal 'beginning-of-buffer)))
(if (> n 0)
(multiple-value-bind (p lines) (buffer-scan-newline (current-buffer)
(pt)
(1- (buffer-size (current-buffer)))
n)
;; Increment p by one so the point is at the beginning of the
;; line.
(when (or (char= (buffer-char-after (current-buffer) p) #\Newline)
(= p (1- (buffer-size (current-buffer)))))
(incf p))
(set-point p)
(when (zerop lines)
(signal 'end-of-buffer))
(- n lines))
(if (and (= n 0)
(not (buffer-char-before (current-buffer) (pt))))
0
;; A little mess to figure out how many newlines to search
;; for to give the proper output.
(let ((lines (if (and (buffer-char-after (current-buffer) (pt))
(char= (buffer-char-after (current-buffer) (pt)) #\Newline))
(- n 2)
(1- n))))
(multiple-value-bind (p flines)
(buffer-scan-newline (current-buffer)
(pt) (begv)
lines)
(when (and (char= (buffer-char-after (current-buffer) p) #\Newline)
(= flines (- lines)))
(incf p))
(set-point p)
(when (and (< n 0)
(zerop flines))
(signal 'beginning-of-buffer))
(+ n flines))))))
(defun beginning_of_line ()
(error "unimplemented beginning_of_line"))
(defun end_of_line ()
(error "unimplemented end_of_line"))
(defcommand delete-char ()
"Delete the following N characters."
(buffer-delete (current-buffer) (pt) 1))
(defcommand delete-backward-char ()
"Delete the previous N characters."
(buffer-delete (current-buffer) (pt) -1))
(defcommand self-insert-command ((arg)
:prefix)
"Insert the character you type.
Whichever character you type to run this command is inserted."
(dformat +debug-v+ "currentb: ~a ~a~%" (current-buffer) *current-buffer*)
(if (>= arg 2)
(insert-move-point (current-buffer) (make-string arg :initial-element (key-char *current-event*)))
(when (> arg 0)
(insert-move-point (current-buffer) (key-char *current-event*)))))
;;; Key bindings
(define-key *global-map* "C-i" 'self-insert-command)
(loop for i in '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j
#\k #\l #\m #\n #\o #\p #\q #\r #\s #\t
#\u #\v #\w #\x #\y #\z
#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J
#\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T
#\U #\V #\W #\X #\Y #\Z
#\Space #\! #\" #\# #\$ #\% #\& #\' #\(
#\) #\* #\+ #\, #\- #\. #\/ #\: #\; #\<
#\= #\> #\? #\@ #\[ #\\ #\] #\^ #\_ #\`
#\| #\} #\~ #\{)
do (define-key *global-map* (make-key :char i) 'self-insert-command))
(define-key *global-map* "C-a" 'beginning-of-line)
(define-key *global-map* "C-b" 'backward-char)
(define-key *global-map* "C-d" 'delete-char)
(define-key *global-map* "C-e" 'end-of-line)
(define-key *global-map* "C-f" 'forward-char)
(define-key *global-map* "DEL" 'delete-backward-char) | 4,648 | Common Lisp | .lisp | 107 | 33.588785 | 104 | 0.515901 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fa5330b987f349d221b8962c9d9912b958e35d30dc23918d4be2990a48f1bdc8 | 18,469 | [
-1
] |
18,470 | indent.lisp | spacebat_lice/src/indent.lisp | ;;; Indentation functions
(in-package "LICE")
(define-buffer-local indent-tabs-mode t
"*Indentation can insert tabs if this is non-nil.
Setting this variable automatically makes it local to the current buffer.")
(define-buffer-local *indent-line-function* 'indent-relative
"Function to indent the current line.
This function will be called with no arguments.
If it is called somewhere where auto-indentation cannot be done
\(f.ex. inside a string), the function should simply return `noindent'.
Setting this function is all you need to make TAB indent appropriately.
Don't rebind TAB unless you really need to.")
(defun position-indentation (pos-aref buffer)
;; XXX: just cheap out on this puppy
(let ((column 0))
(loop
(inc-aref pos-aref buffer)
(when (>= pos-aref (zv-aref buffer))
(return column))
(let ((c (buffer-fetch-char pos-aref buffer)))
(cond ((char= c #\Space)
(incf column))
((char= c #\Tab)
;; FIXME: tab width
(incf column))
(t
;; categories?
(return column)))))))
(defun current-indentation (&aux (buffer (current-buffer)))
"Return the indentation of the current line.
This is the horizontal position of the character
following any initial whitespace."
(let ((pt (buffer-scan-newline buffer (pt buffer) (begv buffer) -1)))
(position-indentation (buffer-char-to-aref buffer pt) buffer)))
;; (defun current-column ()
;; "Return the current column that the current buffer's point is on."
;; (let ((bol (buffer-beginning-of-line)))
;; (- (point) bol)))
(defun current-column (&aux (buffer (current-buffer)))
"Return the horizontal position of point. Beginning of line is column 0.
This is calculated by adding together the widths of all the displayed
representations of the character between the start of the previous line
and point (eg. control characters will have a width of 2 or 4, tabs
will have a variable width).
Ignores finite width of frame, which means that this function may return
values greater than (frame-width).
Whether the line is visible (if `selective-display' is t) has no effect;
however, ^M is treated as end of line when `selective-display' is t.
Text that has an invisible property is considered as having width 0, unless
`buffer-invisibility-spec' specifies that it is replaced by an ellipsis."
(let ((pos-aref (buffer-char-to-aref buffer (pt buffer)))
(column 0)
c)
(loop
(dec-aref pos-aref buffer)
(when (< pos-aref (begv-aref buffer))
(return column))
(setf c (buffer-fetch-char pos-aref buffer))
(cond ((char= c #\Newline)
(return column))
((char= c #\Tab)
;; TODO: tabs are > 1 column
(incf column))
;; FIXME: what about control chars?
(t (incf column))))))
(defun indent-to (column &optional (minimum 0))
"Indent from point with tabs and spaces until COLUMN is reached.
Optional second argument MINIMUM says always do at least MINIMUM spaces
even if that goes past COLUMN; by default, MINIMUM is zero."
(check-type column number)
(check-type minimum number)
(let* ((fromcol (current-column))
(mincol (+ fromcol minimum)))
(when (< mincol column)
(setf mincol column))
(when (= fromcol mincol)
(return-from indent-to mincol))
;; TODO: use tabs to indent
(insert-char #\Space column t)
;; TODO: cache the last known column
mincol))
(defcommand move-to-column ((column &optional force)
:prefix)
"Move point to column COLUMN in the current line.
Interactively, COLUMN is the value of prefix numeric argument.
The column of a character is calculated by adding together the widths
as displayed of the previous characters in the line.
This function ignores line-continuation;
there is no upper limit on the column number a character can have
and horizontal scrolling has no effect.
If specified column is within a character, point goes after that character.
If it's past end of line, point goes to end of line.
Optional second argument FORCE non-nil means if COLUMN is in the
middle of a tab character, change it to spaces.
In addition, if FORCE is t, and the line is too short to reach
COLUMN, add spaces/tabs to get there.
The return value is the current column."
(let* ((buffer (current-buffer))
(col (current-column))
(pos (point buffer))
(pos-aref (buffer-char-to-aref buffer pos))
(end (zv buffer)))
;; If we're starting past the desired column, back up to beginning
;; of line and scan from there.
(when (> col column)
(setf end pos
pos (buffer-beginning-of-line)
pos-aref (buffer-char-to-aref buffer pos)
col 0))
;; FIXME: this assumes each character is 1 column
(while (and (< col column)
(< pos end))
(let ((c (buffer-fetch-char pos-aref buffer)))
(when (char= c #\Newline)
(return nil))
(incf col)
(inc-both pos pos-aref buffer)))
(set-point pos buffer)
(when (and force
(< col column))
(setf col column)
(indent-to col))
col))
(defcommand indent-relative ((&optional unindented-ok)
:raw-prefix)
"Space out to under next indent point in previous nonblank line.
An indent point is a non-whitespace character following whitespace.
The following line shows the indentation points in this line.
^ ^ ^ ^ ^ ^ ^ ^ ^
If the previous nonblank line has no indent points beyond the
column point starts at, `tab-to-tab-stop' is done instead, unless
this command is invoked with a numeric argument, in which case it
does nothing.
See also `indent-relative-maybe'."
;; FIXME: abbrev mode
;; (if (and abbrev-mode
;; (eq (char-syntax (preceding-char)) :word-constituent))
;; (expand-abbrev))
(let ((start-column (current-column))
indent)
(save-excursion
(beginning-of-line)
(if (re-search-backward "\\n[^\\n]" :error nil) ;; XXX used to be "^[^\n]"
(let ((end (save-excursion (forward-line 1) (point))))
(move-to-column start-column)
;; Is start-column inside a tab on this line?
(if (> (current-column) start-column)
(backward-char 1))
(or (looking-at "[ \\t]")
unindented-ok
(skip-chars-forward (coerce '(#\^ #\Space #\Tab) 'string) end))
(skip-whitespace-forward end)
(or (= (point) end) (setq indent (current-column))))))
(if indent
(let ((opoint (point-marker)))
(indent-to indent 0)
(if (> opoint (point))
(goto-char opoint))
(set-marker opoint nil))
;; FIXME: implement and uncomment
;; (tab-to-tab-stop)
)))
(defvar *indent-region-function* 'lisp-indent-region
"Short cut function to indent region using `indent-according-to-mode'.
A value of nil means really run `indent-according-to-mode' on each line.")
(defcommand indent-region ((start end &optional column)
:region-beginning :region-end :raw-prefix)
"Indent each nonblank line in the region.
A numeric prefix argument specifies a column: indent each line to that column.
With no prefix argument, the command chooses one of these methods and
indents all the lines with it:
1) If `fill-prefix' is non-nil, insert `fill-prefix' at the
beginning of each line in the region that does not already begin
with it.
2) If `indent-region-function' is non-nil, call that function
to indent the region.
3) Indent each line as specified by the variable `indent-line-function'.
Called from a program, START and END specify the region to indent.
If the third argument COLUMN is an integer, it specifies the
column to indent to; if it is nil, use one of the three methods above."
(message "guuh ~s ~s" column *prefix-arg*)
(if (null column)
(if *fill-prefix*
(save-excursion
(goto-char end)
(setq end (point-marker))
(goto-char start)
(let ((regexp (regexp-quote *fill-prefix*)))
(while (< (point) (marker-position end))
(or (looking-at regexp)
(and (bolp) (eolp))
(insert *fill-prefix*))
(forward-line 1))))
(if *indent-region-function*
(funcall *indent-region-function* start end)
(save-excursion
(setq end (copy-marker end))
(goto-char start)
(while (< (point) (marker-position end))
(or (and (bolp) (eolp))
(funcall *indent-line-function*))
(forward-line 1))
(set-marker end nil))))
(progn
(setq column (prefix-numeric-value column))
(save-excursion
(goto-char end)
(setq end (point-marker))
(goto-char start)
(or (bolp) (forward-line 1))
(while (< (point) (marker-position end))
(delete-region (point) (progn (skip-whitespace-forward) (point)))
(or (eolp)
(indent-to column 0))
(forward-line 1))
(set-marker end nil)))))
(defun vertical-motion (lines &optional (window (selected-window)))
"Move point to start of the screen line LINES lines down.
If LINES is negative, this means moving up.
This function is an ordinary cursor motion function
which calculates the new position based on how text would be displayed.
The new position may be the start of a line,
or just the start of a continuation line.
The function returns number of screen lines moved over;
that usually equals LINES, but may be closer to zero
if beginning or end of buffer was reached.
The optional second argument WINDOW specifies the window to use for
parameters such as width, horizontal scrolling, and so on.
The default is to use the selected window's parameters.
`vertical-motion' always uses the current buffer,
regardless of which buffer is displayed in WINDOW.
This is consistent with other cursor motion functions
and makes it possible to use `vertical-motion' in any buffer,
whether or not it is currently displayed in some window."
(declare (ignore lines window))
;; FIXME: its cheap but it works, for now. It all assumes there
;; aren't pictures or variable width fonts, etc.
(let* ((total lines)
(old-pt (pt))
(win (selected-window))
(width (window-width win nil))
(buf (current-buffer)))
;; go to the beginning of the line
(decf old-pt (mod (current-column) width))
(while (and (< old-pt (zv))
(> lines 0))
(setf old-pt (1+ (buffer-scan-newline buf old-pt (+ old-pt width) 1)))
(decf lines))
(while (and (> old-pt (begv))
(< lines 0))
(setf old-pt (buffer-scan-newline buf old-pt (- old-pt width) -2))
;; go past the newline except at the beginning of the buffer
(unless (= old-pt (begv))
(incf old-pt))
(incf lines))
(set-point (max (begv) (min (zv) old-pt)))
(- total lines)))
(defun indent-line-to (column)
"Indent current line to COLUMN.
This function removes or adds spaces and tabs at beginning of line
only if necessary. It leaves point at end of indentation."
(back-to-indentation)
(let ((cur-col (current-column)))
(cond ((< cur-col column)
(if (>= (- column (* (/ cur-col tab-width) tab-width)) tab-width)
(delete-region (point)
(progn (skip-chars-backward " ") (point))))
(indent-to column))
((> cur-col column) ; too far right (after tab?)
(delete-region (progn (move-to-column column t) (point))
(progn (back-to-indentation) (point)))))))
(defun current-left-margin ()
"Return the left margin to use for this line.
This is the value of the buffer-local variable `left-margin' plus the value
of the `left-margin' text-property at the start of the line."
(save-excursion
(back-to-indentation)
(max 0
(+ left-margin (or (get-text-property
(if (and (eobp) (not (bobp)))
(1- (point)) (point))
'left-margin) 0)))))
(defcommand move-to-left-margin ((&optional (n 1) (force t))
:prefix)
"Move to the left margin of the current line.
With optional argument, move forward N-1 lines first.
The column moved to is the one given by the `current-left-margin' function.
If the line's indentation appears to be wrong, and this command is called
interactively or with optional argument FORCE, it will be fixed."
;;(interactive (list (prefix-numeric-value current-prefix-arg) t))
(check-type n integer)
(beginning-of-line n)
(skip-chars-forward " \t")
(if (minibufferp (current-buffer))
(if (save-excursion (beginning-of-line) (bobp))
(goto-char (minibuffer-prompt-end))
(beginning-of-line))
(let ((lm (current-left-margin))
(cc (current-column)))
(cond ((> cc lm)
(if (> (move-to-column lm force) lm)
;; If lm is in a tab and we are not forcing, move before tab
(backward-char 1)))
((and force (< cc lm))
(indent-to-left-margin))))))
;; This used to be the default indent-line-function,
;; used in Fundamental Mode, Text Mode, etc.
(defun indent-to-left-margin ()
"Indent current line to the column given by `current-left-margin'."
(indent-line-to (current-left-margin)))
(defcommand beginning-of-line-text ((&optional n)
:prefix)
"Move to the beginning of the text on this line.
With optional argument, move forward N-1 lines first.
From the beginning of the line, moves past the left-margin indentation, the
fill-prefix, and any indentation used for centering or right-justifying the
line, but does not move past any whitespace that was explicitly inserted
\(such as a tab used to indent the first line of a paragraph)."
(beginning-of-line n)
(skip-chars-forward " \t")
;; Skip over fill-prefix.
(if (and *fill-prefix*
(not (string-equal *fill-prefix* "")))
(if (equal *fill-prefix*
(buffer-substring
(point) (min (point-max) (+ (length *fill-prefix*) (point)))))
(forward-char (length *fill-prefix*)))
(if (and adaptive-fill-mode adaptive-fill-regexp
(looking-at adaptive-fill-regexp))
(goto-char (match-end 0))))
;; Skip centering or flushright indentation
(if (memq (current-justification) '(center right))
(skip-chars-forward " \t")))
| 14,440 | Common Lisp | .lisp | 333 | 37.642643 | 80 | 0.665813 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 3adf5ed183dd817dbf461089c9c5d2ae5415ba6bef618c27bd73448e31171f30 | 18,470 | [
-1
] |
18,471 | render.lisp | spacebat_lice/src/render.lisp | ;;; frame rendering routines
(in-package "LICE")
;; The defmethods are found in the *-render.lisp files
(defgeneric frame-start-render (frame)
(:documentation "Do any setup we need before we beginning rendering the frame."))
(defgeneric frame-end-render (frame)
(:documentation "Do any cleanup or refreshing after the frame is rendered."))
;; the defmethods are found in the *-render.lisp files
(defgeneric window-render (window frame)
(:documentation "Render the window in the given frame."))
(defgeneric frame-read-event (frame)
(:documentation "Read a keyboard event for the specified frame."))
(defgeneric frame-move-cursor (frame window x y)
(:documentation "Move the cursor to the X,Y location in WINDOW on the frame, FRAME."))
(defun frame-render (frame)
"Render a frame."
(let (cursor-x cursor-y win)
(labels ((render (tree)
(cond ((null tree) nil)
((atom tree)
;; reset the cache
(window-reset-cache tree)
;; Figure out what part to display
(window-framer tree
(window-point tree)
(truncate (window-height tree nil) 2))
(dformat +debug-vvv+ "after framer: ~a~%"
(lc-cache (window-cache tree)))
;; display it
(multiple-value-bind (x y) (window-render tree frame)
(when (eq tree (frame-selected-window frame))
(setf win tree cursor-x x cursor-y y))))
(t (cons (render (car tree))
(render (cdr tree)))))))
(frame-start-render frame)
(render (frame-window-tree frame))
(when (and win cursor-x cursor-y)
(frame-move-cursor frame win cursor-x cursor-y))
(frame-end-render frame))))
| 1,651 | Common Lisp | .lisp | 39 | 37.076923 | 88 | 0.676012 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9dfc246bd58f10f1da4997aae31c9ba4cacc4553ba4e588dc73716c03c7b48c9 | 18,471 | [
-1
] |
18,472 | subprocesses.lisp | spacebat_lice/src/subprocesses.lisp | ;;; handle subprocesses and threads
(in-package "LICE")
(defclass base-process ()
((input-stream :initarg :error-stream :accessor process-input-stream)
(output-stream :initarg :output-stream :accessor process-output-stream)
(error-stream :initarg :error-stream :accessor process-error-stream)
(name :initarg :name :accessor process-name)
(filter :initarg :filter :initform nil :accessor process-filter)
(sentinel :initarg :sentinel :initform nil :accessor process-sentinel)))
(defclass subprocess (base-process)
((process :initarg :internal-process :accessor subprocess-internal-process)))
(defclass thread-process (base-process)
((thread :initarg :thread :accessor thread-process-thread)))
(defclass stream-process (base-process)
()
(:documentation "No process or thread is attached to this
process. It's just a stream whose filter function gets called
when input exists. An eof would presumably call the sentinel and
clean this process up.
This is how network streams can be handled like gnu emacs does."))
(defclass user-process (base-process)
()
(:documentation "When we call the filter and sentinel functions
is decided by calling a function. I'm gonna try implementing an irc mode with this."))
(defclass base-buffer-process-mixin ()
((buffer :initarg :buffer :accessor process-buffer)
(mark :initarg :mark :accessor process-mark)))
(defclass buffer-subprocess (base-buffer-process-mixin subprocess)
())
(defclass buffer-thread-process (base-buffer-process-mixin thread-process)
())
(defclass buffer-stream-process (base-buffer-process-mixin stream-process)
())
(defvar *process-list* nil
"")
(defmethod initialize-instance :after ((instance base-process) &rest initargs &key &allow-other-keys)
"Keep track of the instances in our list."
(declare (ignore initargs))
(push instance *process-list*))
(defun subprocess-alive-p (subproc)
(internal-process-alive-p (subprocess-internal-process subproc)))
(defun process-activity-p (process)
(or (and (process-output-stream process)
(listen (process-output-stream process)))
(and (process-error-stream process)
(listen (process-error-stream process)))
;; if the process quit, we need to clean things up
(and (typep process 'subprocess)
(not (subprocess-alive-p process)))))
(defun poll-processes (&aux (process-list *process-list*))
"Return the list of processes that need processing."
(loop for p in process-list
when (process-activity-p p)
collect p))
(defun process-ready-streams (process)
(let (streams)
(and (process-output-stream process)
(listen (process-output-stream process))
(push (process-output-stream process) streams))
(and (process-error-stream process)
(listen (process-error-stream process))
(push (process-error-stream process) streams))
streams))
(defgeneric dispatch-process (process)
(:documentation "Call the filter and sentinel functions on process, if needed."))
(defmethod dispatch-process :around ((process base-process))
"Handle calling the filter functions."
(let ((streams (process-ready-streams process)))
(when streams
(if (process-filter process)
(if (process-buffer process)
(with-current-buffer (process-buffer process)
;; TODO: set the point to the process mark
(funcall (process-filter process) process))
;; FIXME: which buffer should be current if the process has no buffer?
(funcall (process-filter process) process))
;; or discard the data
(mapc 'clear-input streams))))
(call-next-method))
(defmethod dispatch-process ((process subprocess))
"call the sentinel. FIXME: this isn't quite right. we wanna call
the sentinel when its status has changed which includes other
states."
(unless (subprocess-alive-p process)
(unwind-protect
(and (process-sentinel process)
(funcall (process-sentinel process) process))
;; its dead. clean it up.
(setf *process-list* (remove process *process-list*)))))
(defmethod dispatch-process ((process thread-process))
(unless (thread-alive-p (thread-process-thread process))
(unwind-protect
(and (process-sentinel process)
(funcall (process-sentinel process) process))
;; its dead. clean it up.
(setf *process-list* (remove process *process-list*)))))
(defmethod dispatch-process ((process stream-process))
;; FIXME: We maybe want something more flexible than just checking
;; the state of the stream.
(unless (open-stream-p (process-output-stream process))
(unwind-protect
(and (process-sentinel process)
(funcall (process-sentinel process) process))
;; its dead. clean it up.
(setf *process-list* (remove process *process-list*)))))
(defun dispatch-processes (process-list)
"Call whatever handler function is hooked up to the process"
(mapc 'dispatch-process process-list))
(defun default-buffer-process-filter (process)
"The default process filter function. Read input from streams
and insert it into the process' buffer. Or discard it if buffer
is nil."
(when (process-buffer process)
;; TODO: If the other process is spitting stuff out as fast as
;; possible is this gonna spin til the program calms down? We
;; don't want that I don't think. -sabetts
(while (listen (process-output-stream process))
(insert (read-line (process-output-stream process)) #\Newline))
;; handle error output too
(while (listen (process-error-stream process))
(insert (read-line (process-error-stream process)) #\Newline))))
(defun handle-subprocess-state-change (internal-proc)
(let ((process (find internal-proc *process-list*
:key 'subprocess-internal-process)))
(when process
(when (process-sentinel process)
(funcall (process-sentinel process)))
;; assume the process is killed for now
(setf *process-list* (remove process *process-list*)))))
(defun default-buffer-process-sentinel (process)
(declare (ignore process))
;; uh wuddo we do here?
)
(defun start-process (name buffer program &rest program-args)
"Start a program in a subprocess. Return the process object for it.
name is name for process. It is modified if necessary to make it unique.
buffer is the buffer (or buffer name) to associate with the process.
Process output goes at end of that buffer, unless you specify
an output stream or filter function to handle the output.
buffer may be also nil, meaning that this process is not associated
with any buffer.
program is the program file name. It is searched for in PATH.
Remaining arguments are strings to give program as arguments."
(let* ((buf (and buffer (get-buffer-create buffer)))
(mark (and buf (copy-marker (point-marker buf)))))
(multiple-value-bind (proc input output error) (run-program program program-args)
(make-instance 'buffer-subprocess
:internal-process proc
:input-stream input
:output-stream output
:error-stream error
:filter 'default-buffer-process-filter
:sentinel 'default-buffer-process-sentinel
:name name
:buffer buf
:mark mark))))
(defun open-network-stream (name buffer host service)
"Open a TCP connection for a service to a host.
Returns a subprocess-object to represent the connection.
Input and output work as for subprocesses; `delete-process' closes it.
Args are name buffer host service.
name is name for process. It is modified if necessary to make it unique.
buffer is the buffer (or buffer name) to associate with the process.
Process output goes at end of that buffer, unless you specify
an output stream or filter function to handle the output.
buffer may be also nil, meaning that this process is not associated
with any buffer.
host is name of the host to connect to, or its IP address.
service is name of the service desired, or an integer specifying
a port number to connect to."
(declare (ignore name buffer host service))
;; TODO: implement
(error "unimplemented open-network-stream")
)
(defvar *shell-file-name* (getenv "SHELL")
"File name to load inferior shells from.
Initialized from the SHELL environment variable.")
(defvar *shell-command-switch* "-c"
"Switch used to have the shell execute its command line argument.")
(defcommand shell-command ((command)
(:string "Shell Command: "))
(let ((buf (get-buffer-create "*Async Shell Command*")))
(erase-buffer buf)
(display-buffer buf)
(start-process "Shell Command" "*Async Shell Command*"
*shell-file-name*
*shell-command-switch*
command)))
(defgeneric kill-process (process)
(:documentation "Kill process process. May be process or name of one.
See function `interrupt-process' for more details on usage."))
(defmethod kill-process ((process subprocess))
;; send the QUIT signal
(internal-process-kill (subprocess-internal-process process)))
(defmethod kill-process ((obj thread-process))
(kill-thread (thread-process-thread obj)))
(defgeneric delete-process (process)
(:documentation "Delete process: kill it and forget about it immediately.
process may be a process, a buffer, the name of a process or buffer, or
nil, indicating the current buffer's process."))
;; (defmethod delete-process ((proces subprocess))
;; ;; TODO
;; )
;; (defmethod delete-process ((obj buffer))
;; ;; TODO
;; )
;; (defmethod delete-process ((obj string))
;; ;; TODO
;; )
;; (defmethod delete-process ((process thread-process))
;; ;; TODO
;; )
;; (defmethod delete-process ((process null))
;; ;; TODO
;; )
| 9,577 | Common Lisp | .lisp | 215 | 41.013953 | 101 | 0.736503 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a8e8ced0e5694109501aadecd4990f34ce9513378b536e1912f0cc1feeb7f0ca | 18,472 | [
-1
] |
18,473 | commands.lisp | spacebat_lice/src/commands.lisp | ;; Command related functions
(in-package "LICE")
(defclass command ()
((name :type symbol :initarg :name :accessor command-name)
(args :type list :initarg :args :accessor command-args)
(fn :type function :initarg :fn :accessor command-fn)
(doc :type (or null string) :initarg :doc :accessor command-doc))
(:documentation "An interactive command."))
(defvar *commands* (make-hash-table)
"A hash table of interactive commands")
(defmacro defcommand (name (&optional args &rest interactive-args) &body body)
"Create an interactive command named NAME."
(let ((tmp (gensym)))
`(progn
(defun ,name ,args
,@body)
(setf (gethash ',name *commands*)
(make-instance
'command
:name ',name
:args ',interactive-args
:doc ,(when (typep (first body) 'string) (first body))
:fn #',name)))))
(defgeneric lookup-command (name)
(:documentation "lookup the command named NAME."))
(defmethod lookup-command ((name symbol))
(gethash name *commands*))
(defmethod lookup-command ((name string))
;; FIXME: this can fill the keyword package with lots of junk
;; symbols.
(gethash (intern (string-upcase name) "KEYWORD") *commands*))
(defvar *command-arg-type-hash* (make-hash-table)
"A hash table of symbols. each symbol is an interactive argument
type whose value is a function that is called to gather input from the
user (or somewhere else) and return the result. For instance,
:BUFFER's value is read-buffer which prompts the user for a buffer and
returns it.
This variable is here to allow modules to add new argument types easily.")
(defvar mark-even-if-inactive nil
"*Non-nil means you can use the mark even when inactive.
This option makes a difference in Transient Mark mode.
When the option is non-nil, deactivation of the mark
turns off region highlighting, but commands that use the mark
behave as if the mark were still active.")
| 1,927 | Common Lisp | .lisp | 44 | 40.272727 | 78 | 0.726108 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 75b0a0d9b06c7121d991d7720fc2926fd5c4f9e1cd0da297c7e938171f23c6bc | 18,473 | [
-1
] |
18,474 | echo-area.lisp | spacebat_lice/src/echo-area.lisp | ;;; echo area related function. this stuff is in xdisp.c in emacs
(in-package "LICE")
(defun ensure-echo-area-buffers ()
"Make sure echo area buffers in `echo_buffers' are live.
If they aren't, make new ones."
(unless (and (bufferp (frame-echo-area-current (selected-frame)))
(buffer-live-p (frame-echo-area-current (selected-frame))))
(let ((buf (get-buffer-create " *Echo Area 0*")))
(setf (frame-echo-area-current (selected-frame)) buf
(buffer-local 'truncate-lines buf) nil)))
;; bleh, duplicate code
(unless (and (bufferp (frame-echo-area-pren (selected-frame)))
(buffer-live-p (frame-echo-area-prev (selected-frame))))
(let ((buf (get-buffer-create " *Echo Area 1*")))
(setf (frame-echo-area-prev (selected-frame)) buf
(buffer-local 'truncate-lines buf) nil))))
| 855 | Common Lisp | .lisp | 16 | 47 | 74 | 0.653524 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5382859551721b103a93ee0d54337392e0ccfcebc75f1c7e28542358e96ac0df | 18,474 | [
-1
] |
18,475 | wrappers.lisp | spacebat_lice/src/wrappers.lisp | ;;; A collection of wrappers around extended functionality that may be
;;; different across CL implementations.
;;; To add support for a new CL implementation, an entry in each of
;;; these functions must be made for it.
;; don't print the unable to optimize notes
#+sbcl (declaim (sb-ext:muffle-conditions sb-ext:compiler-note))
(in-package "LICE")
;;; Weak Pointers
(defun weak-pointer-p (wp)
#+clisp (ext:weak-pointer-p (wp))
#-(or clisp) (declare (ignore wp)))
(defun make-weak-pointer (data)
#+clisp (ext:make-weak-pointer data)
#+cmu (extensions:make-weak-pointer data)
#+sbcl (sb-ext:make-weak-pointer data)
#+(or movitz mcl) data)
(defun weak-pointer-value (wp)
#+clisp (ext:weak-pointer-value wp)
#+cmu (extensions:weak-pointer-value wp)
#+sbcl (sb-ext:weak-pointer-value wp)
#+(or movitz mcl) (values wp t))
;;; Some wrappers for access to filesystem things. file type, file
;;; size, ownership, modification date, mode, etc
(defun file-stats (pathname)
"Return some file stats"
#+sbcl
(let ((stat (sb-posix:lstat pathname)))
(values (sb-posix:stat-mode stat)
(sb-posix:stat-size stat)
(sb-posix:stat-uid stat)
(sb-posix:stat-gid stat)
(sb-posix:stat-mtime stat)))
#+clisp
(let ((stat (sys::file-stat pathname)))
(values (butlast (sys::file-stat-mode stat))
(sys::file-stat-size stat)
(sys::file-stat-uid stat)
(sys::file-stat-gid stat)
(sys::file-stat-mtime stat)))
#-(or sbcl clisp)
(error "Not implemented"))
;;; subprocesses
(defun run-program (program args &key (output :stream) (error :stream) (input :stream) (sentinel nil))
#+sbcl (let ((p (sb-ext:run-program program args :output output :error error :input input :status-hook sentinel)))
(values p
(sb-ext:process-input p)
(sb-ext:process-output p)
(sb-ext:process-error p)))
#-sbcl (error "Not implemented"))
(defun internal-process-alive-p (process)
#+sbcl (sb-ext:process-alive-p process)
#-sbcl (error "Not implemented"))
(defun internal-process-kill (process &optional (signal 3))
#+sbcl (sb-ext:process-kill process signal)
#-(or sbcl) (error "Not implemented"))
;;; threads
(defun make-thread (function)
#+sbcl (sb-thread:make-thread function)
#-(or sbcl) (error "Not implemented"))
(defun thread-alive-p (thread)
#+sbcl (sb-thread:thread-alive-p thread)
#-(or sbcl) (error "Not implemented"))
(defun kill-thread (thread)
#+sbcl (sb-thread:terminate-thread thread)
#-(or sbcl) (error "Not implemented"))
(defun make-mutex ()
#+sbcl (sb-thread:make-mutex)
#-(or sbcl) (error "Not implemented"))
(defmacro with-mutex ((mutex) &body body)
#+sbcl `(sb-thread:with-mutex (,mutex) ,@body)
#-(or sbcl) (error "Not implemented"))
;;; environment
(defun getenv (var)
"Return the value of the environment variable."
#+clisp (ext:getenv (string var))
#+sbcl (sb-posix:getenv (string var))
#-(or clisp sbcl)
(error "Not implemented"))
;;; debugger
(defun backtrace-as-string (&optional (depth most-positive-fixnum))
(with-output-to-string (s)
#+sbcl (sb-debug:backtrace depth s)
#-(or sbcl)
(error "Not implemented")))
;;; terminal manipulation
;;; SIGINT error. we setup our own error handler.
(define-condition user-break (simple-condition)
())
#+sbcl
(defun sbcl-sigint-handler (&rest junk)
(declare (ignore junk))
(flet ((break-it ()
(with-simple-restart (continue "continue from break")
(invoke-debugger (make-condition 'user-break
:format-control "User break")))))
(sb-thread:interrupt-thread (sb-thread::foreground-thread) #'break-it)))
(defun enable-sigint-handler ()
#+sbcl (sb-unix::enable-interrupt sb-unix::sigint #'sbcl-sigint-handler)
#-(or sbcl) (error "not implemented"))
(defvar *old-term-settings* nil)
(defun term-backup-settings ()
#+sbcl
(setf *old-term-settings* (sb-posix:tcgetattr 0))
#-(or sbcl) (error "not implemented"))
(defun term-restore-settings ()
#+sbcl
(sb-posix:tcsetattr 0 0 *old-term-settings*)
#-(or sbcl) (error "not implemented"))
(defun term-set-quit-char (code)
#+sbcl
(let ((attr (sb-posix:tcgetattr 0))
;; according to termios.h VINTR is 8
(vintr 8))
(setf (aref (sb-posix:termios-cc attr) vintr) code)
(sb-posix:tcsetattr 0 0 attr))
#-(or sbcl) (error "not implemented"))
;;; two way streams
(provide :lice-0.1/wrappers)
| 4,454 | Common Lisp | .lisp | 118 | 34 | 116 | 0.683659 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fe914a2e484534b83c265d36f30bc6f7b07d64cc9df7c76886ce3876891df0cf | 18,475 | [
-1
] |
18,476 | callint.lisp | spacebat_lice/src/callint.lisp | ;;; Call a Lisp function interactively.
(in-package #:lice)
(defvar *prefix-arg* nil
"The value of the prefix argument for the next editing command.
It may be a number, or the symbol `-' for just a minus sign as arg,
or a list whose car is a number for just one or more C-u's
or nil if no argument has been specified.
You cannot examine this variable to find the argument for this command
since it has been set to nil by the time you can look.
Instead, you should use the variable `current-prefix-arg', although
normally commands can get this prefix argument with (interactive \"P\").")
(defvar *last-prefix-arg* nil
"The value of the prefix argument for the previous editing command.
See `prefix-arg' for the meaning of the value.")
(defvar *current-prefix-arg* nil
"The value of the prefix argument for this editing command.
It may be a number, or the symbol `-' for just a minus sign as arg,
or a list whose car is a number for just one or more C-u's
or nil if no argument has been specified.
This is what `(interactive \"P\")' returns.")
(defvar *command-history* nil
"List of recent commands that read arguments from terminal.
Each command is represented as a form to evaluate.")
(defun call-interactively (function &optional record-flag (keys *this-command-keys*))
"Call FUNCTION, reading args according to its interactive calling specs.
Return the value FUNCTION returns.
The function contains a specification of how to do the argument reading.
In the case of user-defined functions, this is specified by placing a call
to the function `interactive' at the top level of the function body.
See `interactive'.
Optional second arg RECORD-FLAG non-nil
means unconditionally put this command in the command-history.
Otherwise, this is done only if an arg is read using the minibuffer.
Optional third arg KEYS, if given, specifies the sequence of events to
supply, as a vector, if the command inquires which events were used to
invoke it. If KEYS is omitted or nil, the return value of
`*this-command-keys-vector*' is used."
;;(setf function (lookup-command function))
(check-type function command)
(let ((args (mapcar (lambda (a)
(if (listp a)
(apply (gethash (first a) *command-arg-type-hash*) (cdr a))
(funcall (gethash a *command-arg-type-hash*))))
(command-args function))))
;; XXX: Is this a sick hack? We need to reset the
;; prefix-arg at the right time. After the command
;; is executed we can't because the universal
;; argument code sets the prefix-arg for the next
;; command. The Right spot seems to be to reset it
;; once a command is about to be executed, and
;; after the prefix arg has been gathered to be
;; used in the command. Which is right here.
(setf *prefix-arg* nil)
;; Note that we use the actual function. If the
;; function is redefined, the command will
;; continue to be defined and will call the
;; function declared above, not the redefined one.
(apply (command-fn function) args)))
(defun prefix-numeric-value (prefix)
"Return numeric meaning of raw prefix argument RAW.
A raw prefix argument is what you get from :raw-prefix.
Its numeric meaning is what you would get from :prefix."
;; TODO
(cond ((null prefix)
1)
((eq prefix '-)
-1)
((and (consp prefix)
(integerp (car prefix)))
(car prefix))
((integerp prefix)
prefix)
(t 1)))
| 3,475 | Common Lisp | .lisp | 73 | 43.753425 | 87 | 0.72368 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e1b53ac61f1ff52b6d83e708f1496dea0d911d32dc438968299f7fd893a3c633 | 18,476 | [
-1
] |
18,477 | lisp-indent.lisp | spacebat_lice/src/lisp/lisp-indent.lisp | ;;; lisp-indent.lisp --- enhanced lisp-indent mode
;; to implement: backward-up-list concat downcase intern-soft match-beginning parse-partial-sexp regexp-opt skip-chars-forward substring
;;; Commentary:
;; This package supplies a single entry point, common-lisp-indent-function,
;; which performs indentation in the preferred style for Common Lisp code.
;; To enable it:
;;
;; (setq lisp-indent-function 'common-lisp-indent-function)
;;>> TODO
;; :foo
;; bar
;; :baz
;; zap
;; &key (like &body)??
;; &rest 1 in lambda-lists doesn't work
;; -- really want (foo bar
;; baz)
;; not (foo bar
;; baz)
;; Need something better than &rest for such cases
;;; Code:
(in-package "LICE")
;; (defgroup lisp-indent nil
;; "Indentation in Lisp."
;; :group 'lisp)
(defcustom lisp-indent-maximum-backtracking 3
"*Maximum depth to backtrack out from a sublist for structured indentation.
If this variable is 0, no backtracking will occur and forms such as `flet'
may not be correctly indented."
:type 'integer
:group 'lisp-indent)
(defcustom lisp-tag-indentation 1
"*Indentation of tags relative to containing list.
This variable is used by the function `lisp-indent-tagbody'."
:type 'integer
:group 'lisp-indent)
(defcustom lisp-tag-body-indentation 3
"*Indentation of non-tagged lines relative to containing list.
This variable is used by the function `lisp-indent-tagbody' to indent normal
lines (lines without tags).
The indentation is relative to the indentation of the parenthesis enclosing
the special form. If the value is t, the body of tags will be indented
as a block at the same indentation as the first s-expression following
the tag. In this case, any forms before the first tag are indented
by `lisp-body-indent'."
:type 'integer
:group 'lisp-indent)
(defcustom lisp-backquote-indentation t
"*Whether or not to indent backquoted lists as code.
If nil, indent backquoted lists as data, i.e., like quoted lists."
:type 'boolean
:group 'lisp-indent)
(defcustom lisp-loop-keyword-indentation 3
"*Indentation of loop keywords in extended loop forms."
:type 'integer
:group 'lisp-indent)
(defcustom lisp-loop-forms-indentation 5
"*Indentation of forms in extended loop forms."
:type 'integer
:group 'lisp-indent)
(defcustom lisp-simple-loop-indentation 3
"*Indentation of forms in simple loop forms."
:type 'integer
:group 'lisp-indent)
(defvar lisp-indent-error-function)
(defvar lisp-indent-defun-method '(4 &lambda &body))
(defvar lisp-body-indent 2
"Number of columns to indent the second line of a `(def...)' form.")
(defun extended-loop-p (loop-start)
"True if an extended loop form starts at LOOP-START."
(handler-case
(save-excursion
(goto-char loop-start)
(forward-char 1)
(forward-sexp 2)
(backward-sexp 1)
(looking-at "\\w"))
(error () t)))
(defun common-lisp-loop-part-indentation (indent-point state)
"Compute the indentation of loop form constituents."
(let* ((loop-indentation (save-excursion
(goto-char (parse-state-prev-level-start state))
(current-column))))
(goto-char indent-point)
(beginning-of-line)
(cond ((not (extended-loop-p (parse-state-prev-level-start state)))
(+ loop-indentation lisp-simple-loop-indentation))
((looking-at "^\\s*(:?\\w+|;)")
(+ loop-indentation lisp-loop-keyword-indentation))
(t
(+ loop-indentation lisp-loop-forms-indentation)))))
;;;###autoload
(defun common-lisp-indent-function (indent-point state)
(if (save-excursion (goto-char (parse-state-prev-level-start state))
(looking-at "\\([Ll][Oo][Oo][Pp]"))
(common-lisp-loop-part-indentation indent-point state)
(common-lisp-indent-function-1 indent-point state)))
(defun common-lisp-indent-function-1 (indent-point state)
(with-match-data
(let ((normal-indent (current-column)))
;; Walk up list levels until we see something
;; which does special things with subforms.
(let ((depth 0)
;; Path describes the position of point in terms of
;; list-structure with respect to containing lists.
;; `foo' has a path of (0 4 1) in `((a b c (d foo) f) g)'
(path ())
;; set non-nil when somebody works out the indentation to use
calculated
;; If non-nil, this is an indentation to use
;; if nothing else specifies it more firmly.
tentative-calculated
(last-point indent-point)
;; the position of the open-paren of the innermost containing list
(containing-form-start (parse-state-prev-level-start state))
;; the column of the above
sexp-column)
(message "hey ~d" containing-form-start)
;; Move to start of innermost containing list
(goto-char containing-form-start)
(setq sexp-column (current-column))
;; Look over successively less-deep containing forms
(while (and (not calculated)
(< depth lisp-indent-maximum-backtracking))
(let ((containing-sexp (point)))
(forward-char 1)
;;(message "first one!")
(parse-partial-sexp (point) indent-point :target-depth 1 :stop-before t)
;; Move to the car of the relevant containing form
(let (tem function method tentative-defun)
(if (not (looking-at "\\w|\\s"))
;; This form doesn't seem to start with a symbol
(setq function nil method nil)
(progn
(setq tem (point))
(forward-sexp 1)
(setq function (string-upcase (buffer-substring-no-properties
tem (point))))
(message "name is ~a" function)
(goto-char tem)
(setq tem (intern-soft function)
method (get tem 'common-lisp-indent-function))
(cond ((and (null method)
(string-match ":[^:]+" function))
;; The pleblisp package feature
(setq function (subseq function
(1+ (match-beginning 0)))
method (get (intern-soft function)
'common-lisp-indent-function)))
((and (null method))
;; backwards compatibility
(setq method (get tem 'lisp-indent-function))))))
(let ((n 0))
;; How far into the containing form is the current form?
(if (< (point) indent-point)
(while (handler-case
(progn
(forward-sexp 1)
(if (>= (point) indent-point)
nil
(progn
;;(message "second one!")
(parse-partial-sexp (point)
indent-point :target-depth 1 :stop-before t)
(setq n (1+ n))
t)))
(error () nil))))
(setq path (cons n path)))
;; backwards compatibility.
(cond ((null function))
((null method)
(when (null (cdr path))
;; (package prefix was stripped off above)
(cond ((string-match "\\`def"
function)
(setq tentative-defun t))
((string-match
;; eval-when-compile ;;(regexp-opt '("with" "without" "do"))
"\\`\\(with\\|without\\|do\\)-"
function)
(setq method '(&lambda &body))))))
;; backwards compatibility. Bletch.
((eq method 'defun)
(setq method lisp-indent-defun-method)))
(cond ((and (or (eq (char-after (1- containing-sexp)) #\')
(and (not lisp-backquote-indentation)
(eq (char-after (1- containing-sexp)) #\`)))
(not (eq (char-after (- containing-sexp 2)) #\#)))
;; No indentation for "'(...)" elements
(setq calculated (1+ sexp-column)))
((or (eq (char-after (1- containing-sexp)) #\,)
(and (eq (char-after (1- containing-sexp)) #\@)
(eq (char-after (- containing-sexp 2)) #\,)))
;; ",(...)" or ",@(...)"
(setq calculated normal-indent))
((eq (char-after (1- containing-sexp)) #\#)
;; "#(...)"
(setq calculated (1+ sexp-column)))
((null method)
;; If this looks like a call to a `def...' form,
;; think about indenting it as one, but do it
;; tentatively for cases like
;; (flet ((defunp ()
;; nil)))
;; Set both normal-indent and tentative-calculated.
;; The latter ensures this value gets used
;; if there are no relevant containing constructs.
;; The former ensures this value gets used
;; if there is a relevant containing construct
;; but we are nested within the structure levels
;; that it specifies indentation for.
(if tentative-defun
(setq tentative-calculated
(common-lisp-indent-call-method
function lisp-indent-defun-method
path state indent-point
sexp-column normal-indent)
normal-indent tentative-calculated)))
((integerp method)
;; convenient top-level hack.
;; (also compatible with lisp-indent-function)
;; The number specifies how many `distinguished'
;; forms there are before the body starts
;; Equivalent to (4 4 ... &body)
(setq calculated (cond ((cdr path)
normal-indent)
((<= (car path) method)
;; `distinguished' form
(list (+ sexp-column 4)
containing-form-start))
((= (car path) (1+ method))
;; first body form.
(+ sexp-column lisp-body-indent))
(t
;; other body form
normal-indent))))
(t
(setq calculated
(common-lisp-indent-call-method
function method path state indent-point
sexp-column normal-indent)))))
(goto-char containing-sexp)
(setq last-point containing-sexp)
(unless calculated
(handler-case
(progn (backward-up-list 1)
(setq depth (1+ depth)))
(error () (setq depth lisp-indent-maximum-backtracking))))))
(or calculated tentative-calculated)))))
(defun common-lisp-indent-call-method (function method path state indent-point
sexp-column normal-indent)
(let ((lisp-indent-error-function function))
(if (symbolp method)
(funcall method
path state indent-point
sexp-column normal-indent)
(lisp-indent-259 method path state indent-point
sexp-column normal-indent))))
(defun lisp-indent-report-bad-format (m)
(error "~s has a badly-formed ~s property: ~s"
;; Love those free variable references!!
lisp-indent-error-function 'common-lisp-indent-function m))
;; Blame the crufty control structure on dynamic scoping
;; -- not on me!
(defun lisp-indent-259 (method path state indent-point
sexp-column normal-indent)
(catch 'exit
(let ((p path)
(containing-form-start (parse-state-prev-level-start state))
n tem tail)
;; Isn't tail-recursion wonderful?
(while p
;; This while loop is for destructuring.
;; p is set to (cdr p) each iteration.
(if (not (consp method)) (lisp-indent-report-bad-format method))
(setq n (1- (car p))
p (cdr p)
tail nil)
(while n
;; This while loop is for advancing along a method
;; until the relevant (possibly &rest/&body) pattern
;; is reached.
;; n is set to (1- n) and method to (cdr method)
;; each iteration.
(setq tem (car method))
(or (eq tem 'nil) ;default indentation
(eq tem '&lambda) ;lambda list
(and (eq tem '&body) (null (cdr method)))
(and (eq tem '&rest)
(consp (cdr method))
(null (cddr method)))
(integerp tem) ;explicit indentation specified
(and (consp tem) ;destructuring
(eq (car tem) '&whole)
(or (symbolp (cadr tem))
(integerp (cadr tem))))
(and (symbolp tem) ;a function to call to do the work.
(null (cdr method)))
(lisp-indent-report-bad-format method))
(cond ((and tail (not (consp tem)))
;; indent tail of &rest in same way as first elt of rest
(throw 'exit normal-indent))
((eq tem '&body)
;; &body means (&rest <lisp-body-indent>)
(throw 'exit
(if (and (= n 0) ;first body form
(null p)) ;not in subforms
(+ sexp-column
lisp-body-indent)
normal-indent)))
((eq tem '&rest)
;; this pattern holds for all remaining forms
(setq tail (> n 0)
n 0
method (cdr method)))
((> n 0)
;; try next element of pattern
(setq n (1- n)
method (cdr method))
(if (< n 0)
;; Too few elements in pattern.
(throw 'exit normal-indent)))
((eq tem 'nil)
(throw 'exit (list normal-indent containing-form-start)))
((eq tem '&lambda)
(throw 'exit
(cond ((null p)
(list (+ sexp-column 4) containing-form-start))
((null (cdr p))
(+ sexp-column 1))
(t normal-indent))))
((integerp tem)
(throw 'exit
(if (null p) ;not in subforms
(list (+ sexp-column tem) containing-form-start)
normal-indent)))
((symbolp tem) ;a function to call
(throw 'exit
(funcall tem path state indent-point
sexp-column normal-indent)))
(t
;; must be a destructing frob
(if (not (null p))
;; descend
(setq method (cddr tem)
n nil)
(progn
(setq tem (cadr tem))
(throw 'exit
(cond (tail
normal-indent)
((eq tem 'nil)
(list normal-indent
containing-form-start))
((integerp tem)
(list (+ sexp-column tem)
containing-form-start))
(t
(funcall tem path state indent-point
sexp-column normal-indent)))))))))))))
(defun lisp-indent-tagbody (path state indent-point sexp-column normal-indent)
(if (not (null (cdr path)))
normal-indent
(save-excursion
(goto-char indent-point)
(beginning-of-line)
(skip-whitespace-forward)
(list (cond ((looking-at "\\w|\\w") ;; used to be symbol constituent \\s_
;; a tagbody tag
(+ sexp-column lisp-tag-indentation))
((integerp lisp-tag-body-indentation)
(+ sexp-column lisp-tag-body-indentation))
((eq lisp-tag-body-indentation 't)
(handler-case
(progn (backward-sexp 1) (current-column))
(error () (1+ sexp-column))))
(t (+ sexp-column lisp-body-indent)))
; (cond ((integerp lisp-tag-body-indentation)
; (+ sexp-column lisp-tag-body-indentation))
; ((eq lisp-tag-body-indentation 't)
; normal-indent)
; (t
; (+ sexp-column lisp-body-indent)))
(parse-state-prev-level-start state)
))))
(defun lisp-indent-do (path state indent-point sexp-column normal-indent)
(if (>= (car path) 3)
(let ((lisp-tag-body-indentation lisp-body-indent))
(funcall (function lisp-indent-tagbody)
path state indent-point sexp-column normal-indent))
(funcall (function lisp-indent-259)
'((&whole nil &rest
;; the following causes weird indentation
;;(&whole 1 1 2 nil)
)
(&whole nil &rest 1))
path state indent-point sexp-column normal-indent)))
(defun lisp-indent-defmethod (path state indent-point sexp-column
normal-indent)
"Indentation function defmethod."
(lisp-indent-259 (if (and (>= (car path) 3)
(null (cdr path))
(save-excursion (goto-char (parse-state-prev-level-start state))
(forward-char 1)
(forward-sexp 3)
(backward-sexp)
(looking-at ":|\\w+")))
'(4 4 (&whole 4 &rest 4) &body)
(get 'defun 'common-lisp-indent-function))
path state indent-point sexp-column normal-indent))
(defun lisp-indent-function-lambda-hack (path state indent-point
sexp-column normal-indent)
(declare (ignore state indent-point))
;; indent (function (lambda () <newline> <body-forms>)) kludgily.
(if (or (cdr path) ; wtf?
(> (car path) 3))
;; line up under previous body form
normal-indent
;; line up under function rather than under lambda in order to
;; conserve horizontal space. (Which is what #' is for.)
(handler-case
(save-excursion
(backward-up-list 2)
(forward-char 1)
(if (looking-at "(lisp:+)?function(\\W|\\W)") ; XXX: used to be symbol constituent \\S_
(+ lisp-body-indent -1 (current-column))
(+ sexp-column lisp-body-indent)))
(error () (+ sexp-column lisp-body-indent)))))
(let ((l '((block 1)
(case (4 &rest (&whole 2 &rest 1)))
(ccase . case) (ecase . case)
(typecase . case) (etypecase . case) (ctypecase . case)
(catch 1)
(cond (&rest (&whole 2 &rest 1)))
(defvar (4 2 2))
(defclass (6 4 (&whole 2 &rest 1) (&whole 2 &rest 1)))
(defconstant . defvar)
(defcustom (4 2 2 2))
(defparameter . defvar)
(defconst . defcustom)
(define-condition . defclass)
(define-modify-macro (4 &lambda &body))
(defsetf (4 &lambda 4 &body))
(defun (4 &lambda &body))
(define-setf-method . defun)
(define-setf-expander . defun)
(defmacro . defun) (defsubst . defun) (deftype . defun)
(defmethod lisp-indent-defmethod)
(defpackage (4 2))
(defstruct ((&whole 4 &rest (&whole 2 &rest 1))
&rest (&whole 2 &rest 1)))
(destructuring-bind
((&whole 6 &rest 1) 4 &body))
(do lisp-indent-do)
(do* . do)
(dolist ((&whole 4 2 1) &body))
(dotimes . dolist)
(eval-when 1)
(flet ((&whole 4 &rest (&whole 1 &lambda &body)) &body))
(labels . flet)
(macrolet . flet)
(generic-flet . flet) (generic-labels . flet)
(handler-case (4 &rest (&whole 2 &lambda &body)))
(restart-case . handler-case)
;; `else-body' style
(if (nil nil &body))
;; single-else style (then and else equally indented)
(if (&rest nil))
(lambda (&lambda &rest lisp-indent-function-lambda-hack))
(let ((&whole 4 &rest (&whole 1 1 2)) &body))
(let* . let)
(compiler-let . let) ;barf
(handler-bind . let) (restart-bind . let)
(locally 1)
;(loop lisp-indent-loop)
(:method (&lambda &body)) ; in `defgeneric'
(multiple-value-bind ((&whole 6 &rest 1) 4 &body))
(multiple-value-call (4 &body))
(multiple-value-prog1 1)
(multiple-value-setq (4 2))
(multiple-value-setf . multiple-value-setq)
(pprint-logical-block (4 2))
(print-unreadable-object ((&whole 4 1 &rest 1) &body))
;; Combines the worst features of BLOCK, LET and TAGBODY
(prog (&lambda &rest lisp-indent-tagbody))
(prog* . prog)
(prog1 1)
(prog2 2)
(progn 0)
(progv (4 4 &body))
(return 0)
(return-from (nil &body))
(symbol-macrolet . let)
(tagbody lisp-indent-tagbody)
(throw 1)
(unless 1)
(unwind-protect (5 &body))
(when 1)
(with-accessors . multiple-value-bind)
(with-condition-restarts . multiple-value-bind)
(with-output-to-string (4 2))
(with-slots . multiple-value-bind)
(with-standard-io-syntax (2)))))
(dolist (el l)
(setf (get (car el) 'common-lisp-indent-function)
(if (symbolp (cdr el))
(get (cdr el) 'common-lisp-indent-function)
(car (cdr el))))))
;(defun foo (x)
; (tagbody
; foo
; (bar)
; baz
; (when (losing)
; (with-big-loser
; (yow)
; ((lambda ()
; foo)
; big)))
; (flet ((foo (bar baz zap)
; (zip))
; (zot ()
; quux))
; (do ()
; ((lose)
; (foo 1))
; (quux)
; foo
; (lose))
; (cond ((x)
; (win 1 2
; (foo)))
; (t
; (lose
; 3))))))
;(put 'while 'common-lisp-indent-function 1)
;(put 'defwrapper'common-lisp-indent-function ...)
;(put 'def 'common-lisp-indent-function ...)
;(put 'defflavor 'common-lisp-indent-function ...)
;(put 'defsubst 'common-lisp-indent-function ...)
;(put 'with-restart 'common-lisp-indent-function '((1 4 ((* 1))) (2 &body)))
;(put 'restart-case 'common-lisp-indent-function '((1 4) (* 2 ((0 1) (* 1)))))
;(put 'define-condition 'common-lisp-indent-function '((1 6) (2 6 ((&whole 1))) (3 4 ((&whole 1))) (4 &body)))
;(put 'with-condition-handler 'common-lisp-indent-function '((1 4 ((* 1))) (2 &body)))
;(put 'condition-case 'common-lisp-indent-function '((1 4) (* 2 ((0 1) (1 3) (2 &body)))))
;(put 'defclass 'common-lisp-indent-function '((&whole 2 &rest (&whole 2 &rest 1) &rest (&whole 2 &rest 1)))
;(put 'defgeneric 'common-lisp-indent-function 'defun)
;;; arch-tag: 7914d50f-92ec-4476-93fc-0f043a380e03
;;; cl-indent.el ends here
| 23,811 | Common Lisp | .lisp | 549 | 31.879781 | 136 | 0.528357 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c0a2e99d30d1098cf9cd7d7011e108a0f304395657f32bb371f12d16a5c70537 | 18,477 | [
-1
] |
18,478 | paren.lisp | spacebat_lice/src/lisp/paren.lisp | ;;; paren.el --- highlight matching paren
;; Copyright (C) 1993, 1996, 2001, 2002, 2003, 2004,
;; 2005, 2006 Free Software Foundation, Inc.
;; Author: [email protected]
;; Maintainer: FSF
;; Keywords: languages, faces
;; This file is part of GNU Emacs.
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; Put this into your ~/.emacs:
;; (show-paren-mode t)
;; It will display highlighting on whatever paren matches the one
;; before or after point.
;;; Code:
(in-package "LICE")
(defgroup paren-showing nil
"Showing (un)matching of parens and expressions."
:prefix "show-paren-"
:group 'paren-matching)
;; This is the overlay used to highlight the matching paren.
(defvar show-paren-overlay nil)
;; This is the overlay used to highlight the closeparen right before point.
(defvar show-paren-overlay-1 nil)
(defcustom show-paren-style 'parenthesis
"*Style used when showing a matching paren.
Valid styles are `parenthesis' (meaning show the matching paren),
`expression' (meaning show the entire expression enclosed by the paren) and
`mixed' (meaning show the matching paren if it is visible, and the expression
otherwise)."
:type '(choice (const parenthesis) (const expression) (const mixed))
:group 'paren-showing)
(defcustom show-paren-delay
(if (featurep 'lisp-float-type) (/ (float 1) (float 8)) 1)
"*Time in seconds to delay before showing a matching paren."
:type '(number :tag "seconds")
:group 'paren-showing)
(defcustom show-paren-priority 1000
"*Priority of paren highlighting overlays."
:type 'integer
:group 'paren-showing
:version "21.1")
(defcustom show-paren-ring-bell-on-mismatch nil
"*If non-nil, beep if mismatched paren is detected."
:type 'boolean
:group 'paren-showing
:version "20.3")
(defgroup paren-showing-faces nil
"Group for faces of Show Paren mode."
:group 'paren-showing
:group 'faces
:version "22.1")
(defface show-paren-match
'((((class color) (background light))
:background "turquoise") ; looks OK on tty (becomes cyan)
(((class color) (background dark))
:background "steelblue3") ; looks OK on tty (becomes blue)
(((background dark))
:background "grey50")
(t
:background "gray"))
"Show Paren mode face used for a matching paren."
:group 'paren-showing-faces)
;; backward-compatibility alias
(put 'show-paren-match-face 'face-alias 'show-paren-match)
(defface show-paren-mismatch
'((((class color)) (:foreground "white" :background "purple"))
(t (:inverse-video t)))
"Show Paren mode face used for a mismatching paren."
:group 'paren-showing-faces)
;; backward-compatibility alias
(put 'show-paren-mismatch-face 'face-alias 'show-paren-mismatch)
(defvar show-paren-highlight-openparen t
"*Non-nil turns on openparen highlighting when matching forward.")
(defvar show-paren-idle-timer nil)
;;;###autoload
(define-minor-mode (show-paren-mode
"Toggle Show Paren mode.
With prefix ARG, turn Show Paren mode on if and only if ARG is positive.
Returns the new status of Show Paren mode (non-nil means on).
When Show Paren mode is enabled, any matching parenthesis is highlighted
in `show-paren-style' after `show-paren-delay' seconds of Emacs idle time."
:global t :group 'paren-showing)
;; Enable or disable the mechanism.
;; First get rid of the old idle timer.
(if show-paren-idle-timer
(cancel-timer show-paren-idle-timer))
(setq show-paren-idle-timer nil)
;; If show-paren-mode is enabled in some buffer now,
;; set up a new timer.
(when (memq t (mapcar (lambda (buffer)
(with-current-buffer buffer
show-paren-mode))
(buffer-list)))
(setq show-paren-idle-timer (run-with-idle-timer
show-paren-delay t
'show-paren-function)))
(unless show-paren-mode
(and show-paren-overlay
(eq (overlay-buffer show-paren-overlay) (current-buffer))
(delete-overlay show-paren-overlay))
(and show-paren-overlay-1
(eq (overlay-buffer show-paren-overlay-1) (current-buffer))
(delete-overlay show-paren-overlay-1))))
;; Find the place to show, if there is one,
;; and show it until input arrives.
(defun show-paren-function ()
(el:if show-paren-mode
(let ((oldpos (point))
(dir (cond ((eq (syntax-class (syntax-after (1- (point)))) 5) -1)
((eq (syntax-class (syntax-after (point))) 4) 1)))
pos mismatch face)
;;
;; Find the other end of the sexp.
(when dir
(save-excursion
(save-restriction
;; Determine the range within which to look for a match.
(when blink-matching-paren-distance
(narrow-to-region
(max (point-min) (- (point) blink-matching-paren-distance))
(min (point-max) (+ (point) blink-matching-paren-distance))))
;; Scan across one sexp within that range.
;; Errors or nil mean there is a mismatch.
(condition-case ()
(setq pos (scan-sexps (point) dir))
(error (setq pos t mismatch t)))
;; Move back the other way and verify we get back to the
;; starting point. If not, these two parens don't really match.
;; Maybe the one at point is escaped and doesn't really count.
(when (integerp pos)
(unless (condition-case ()
(eq (point) (scan-sexps pos (- dir)))
(error nil))
(setq pos nil)))
;; If found a "matching" paren, see if it is the right
;; kind of paren to match the one we started at.
(when (integerp pos)
(let ((beg (min pos oldpos)) (end (max pos oldpos)))
(unless (eq (syntax-class (syntax-after beg)) 8)
(setq mismatch
(not (or (eq (char-before end)
;; This can give nil.
(cdr (syntax-after beg)))
(eq (char-after beg)
;; This can give nil.
(cdr (syntax-after (1- end))))
;; The cdr might hold a new paren-class
;; info rather than a matching-char info,
;; in which case the two CDRs should match.
(eq (cdr (syntax-after (1- end)))
(cdr (syntax-after beg))))))))))))
;;
;; Highlight the other end of the sexp, or unhighlight if none.
(el:if (not pos)
(progn
;; If not at a paren that has a match,
;; turn off any previous paren highlighting.
(and show-paren-overlay (overlay-buffer show-paren-overlay)
(delete-overlay show-paren-overlay))
(and show-paren-overlay-1 (overlay-buffer show-paren-overlay-1)
(delete-overlay show-paren-overlay-1)))
;;
;; Use the correct face.
(el:if mismatch
(progn
(el:if show-paren-ring-bell-on-mismatch
(beep))
(setq face 'show-paren-mismatch))
(setq face 'show-paren-match))
;;
;; If matching backwards, highlight the closeparen
;; before point as well as its matching open.
;; If matching forward, and the openparen is unbalanced,
;; highlight the paren at point to indicate misbalance.
;; Otherwise, turn off any such highlighting.
(el:if (and (not show-paren-highlight-openparen) (= dir 1) (integerp pos))
(when (and show-paren-overlay-1
(overlay-buffer show-paren-overlay-1))
(delete-overlay show-paren-overlay-1))
(let ((from (el:if (= dir 1)
(point)
(forward-point -1)))
(to (el:if (= dir 1)
(forward-point 1)
(point))))
(el:if show-paren-overlay-1
(move-overlay show-paren-overlay-1 from to (current-buffer))
(setq show-paren-overlay-1 (make-overlay from to)))
;; Always set the overlay face, since it varies.
(overlay-put show-paren-overlay-1 'priority show-paren-priority)
(overlay-put show-paren-overlay-1 'face face)))
;;
;; Turn on highlighting for the matching paren, if found.
;; If it's an unmatched paren, turn off any such highlighting.
(unless (integerp pos)
(delete-overlay show-paren-overlay))
(let ((to (el:if (or (eq show-paren-style 'expression)
(and (eq show-paren-style 'mixed)
(not (pos-visible-in-window-p pos))))
(point)
pos))
(from (el:if (or (eq show-paren-style 'expression)
(and (eq show-paren-style 'mixed)
(not (pos-visible-in-window-p pos))))
pos
(save-excursion
(goto-char pos)
(forward-point (- dir))))))
(el:if show-paren-overlay
(move-overlay show-paren-overlay from to (current-buffer))
(setq show-paren-overlay (make-overlay from to))))
;;
;; Always set the overlay face, since it varies.
(overlay-put show-paren-overlay 'priority show-paren-priority)
(overlay-put show-paren-overlay 'face face)))
;; show-paren-mode is nil in this buffer.
(and show-paren-overlay
(delete-overlay show-paren-overlay))
(and show-paren-overlay-1
(delete-overlay show-paren-overlay-1))))
(provide 'paren)
;;; paren.el ends here
| 9,537 | Common Lisp | .lisp | 233 | 35.905579 | 78 | 0.675722 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a148e59b6bea694205cf191c1c0eb607be8d62029779be8f5443dd221761a1c6 | 18,478 | [
-1
] |
18,479 | subr.lisp | spacebat_lice/src/lisp/subr.lisp | ;;; subr.lice --- basic lisp subroutines for Emacs
(in-package "LICE")
;;; Argument types
(defun interactive (&rest prompts)
"Read input from the minibuffer and return it in a list."
(loop for p in prompts
collect (read-from-minibuffer p)))
(defvar *extended-command-history* nil)
(defun read-command (prompt)
"Read the name of a command and return as a symbol.
Prompt with prompt. By default, return default-value."
(let (cmds)
(maphash (lambda (k v)
(declare (ignore v))
(push k cmds))
*commands*)
(dformat +debug-v+ "commands: ~s~%" cmds)
;; Sadly, a cheap hack
(find (completing-read prompt cmds :history '*extended-command-history*)
cmds :test #'string-equal :key #'symbol-name)))
(defun read-buffer (prompt &optional def require-match)
"Read the name of a buffer and return as a string.
Prompt with prompt.
Optional second arg def is value to return if user enters an empty line.
*If optional third arg require-match is non-nil,
* only existing buffer names are allowed."
(declare (ignore require-match))
(let* ((bufs (mapcar (lambda (b)
(cons (buffer-name b) b))
*buffer-list*))
(b (completing-read (if def
(format nil "~a(default ~a) " prompt def)
prompt)
bufs)))
(if (zerop (length b))
def
b)))
(defun read-file-name (prompt &key dir default-filename mustmatch initial predicate)
"Read file name, prompting with prompt and completing in directory dir.
Value is not expanded---you must call `expand-file-name' yourself.
Default name to default-filename if user exits the minibuffer with
the same non-empty string that was inserted by this function.
(If default-filename is omitted, the visited file name is used,
except that if initial is specified, that combined with dir is used.)
If the user exits with an empty minibuffer, this function returns
an empty string. (This can only happen if the user erased the
pre-inserted contents or if `insert-default-directory' is nil.)
Fourth arg mustmatch non-nil means require existing file's name.
Non-nil and non-t means also require confirmation after completion.
Fifth arg initial specifies text to start with.
If optional sixth arg predicate is non-nil, possible completions and
the resulting file name must satisfy (funcall predicate NAME).
dir should be an absolute directory name. It defaults to the value of
`:default-directory'.
If this command was invoked with the mouse, use a file dialog box if
`use-dialog-box' is non-nil, and the window system or X toolkit in use
provides a file dialog box.
See also `read-file-name-completion-ignore-case'
and `read-file-name-function'."
(declare (ignore predicate initial mustmatch default-filename dir))
(completing-read prompt #'file-completions :initial-input (princ-to-string *default-directory*)))
(defun read-string (prompt &optional initial-input history default-value)
"Read a string from the minibuffer, prompting with string prompt.
If non-nil, second arg initial-input is a string to insert before reading.
This argument has been superseded by default-value and should normally
be nil in new code. It behaves as in `read-from-minibuffer'. See the
documentation string of that function for details.
The third arg history, if non-nil, specifies a history list
and optionally the initial position in the list.
See `read-from-minibuffer' for details of history argument.
Fourth arg default-value is the default value. If non-nil, it is used
for history commands, and as the value to return if the user enters
the empty string.
**Fifth arg inherit-input-method, if non-nil, means the minibuffer inherits
the current input method and the setting of `enable-multibyte-characters'."
(read-from-minibuffer prompt :initial-contents initial-input :history history :default-value default-value))
(defun region-limit (beginningp)
"Return the start or end position of the region.
BEGINNINGP non-zero means return the start.
If there is no region active, signal an error."
(if beginningp
(min (point) (mark))
(max (point) (mark))))
(defun region-beginning ()
"Return position of beginning of region, as an integer."
(region-limit t))
(defun region-end ()
"Return position of end of region, as an integer."
(region-limit nil))
(defun add-command-arg-type (type fn)
"TYPE is a symbol. Add it to the hash table of command types and link it to FN, a function or function symbol."
(setf (gethash type *command-arg-type-hash*) fn))
(defun init-command-arg-types ()
"populate the hash table with some defaults"
;; Reset the hash table. FIXME: should we do this?
(setf *command-arg-type-hash* (make-hash-table))
(add-command-arg-type :buffer 'read-buffer)
(add-command-arg-type :file 'read-file-name)
(add-command-arg-type :string 'read-from-minibuffer)
(add-command-arg-type :command 'read-command)
(add-command-arg-type :prefix 'prefix-arg)
(add-command-arg-type :raw-prefix 'raw-prefix-arg)
(add-command-arg-type :region-beginning 'region-beginning)
(add-command-arg-type :region-end 'region-end))
(defun get-buffer-window-list (buffer &optional minibuf frame)
"Return list of all windows displaying BUFFER, or nil if none.
BUFFER can be a buffer or a buffer name.
See `walk-windows' for the meaning of MINIBUF and FRAME."
(let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
(mapc (lambda (window)
(if (eq (window-buffer window) buffer)
(push window windows)))
(frame-window-list frame minibuf))
windows))
;; FIXME: this isn't complete.
(defmacro defalias (from-symbol to-symbol)
"Set symbol's function definition to definition, and return definition."
`(define-symbol-macro ,from-symbol ,to-symbol))
(defun intern-soft (name &optional (package *package*))
(find-symbol name package))
;;; reading from the buffer
(defun read-from-buffer (&aux (buffer (current-buffer)))
"Read 1 sexp from the buffer at the current point, moving the point to the end of what was read"
(when (< (buffer-char-to-aref buffer (point buffer))
(buffer-gap-start buffer))
(gap-move-to-point buffer))
(multiple-value-bind (obj pos)
(read-from-string (buffer-data buffer) t nil
:start (buffer-char-to-aref buffer (point buffer)))
(set-point (buffer-aref-to-char buffer pos))
obj))
(defcommand eval-region ((start end &optional print-flag (read-function 'read-from-string))
:region-beginning :region-end)
"Execute the region as Lisp code.
When called from programs, expects two arguments,
giving starting and ending indices in the current buffer
of the text to be executed.
Programs can pass third argument PRINTFLAG which controls output:
A value of nil means discard it; anything else is stream for printing it.
Also the fourth argument READ-FUNCTION, if non-nil, is used
instead of `read' to read each expression. It gets one argument
which is the input stream for reading characters.
This function does not move point."
(let* ((stdout (make-string-output-stream))
(*standard-output* stdout)
(*error-output* stdout)
(*debug-io* stdout)
(string (buffer-substring-no-properties start end))
(pos 0)
last obj)
(loop
(setf last obj)
(multiple-value-setq (obj pos) (funcall read-function string nil string :start pos))
(when (eq obj string)
(cond ((eq print-flag t)
(message "~s" last)))
(return-from eval-region last)))))
(defun sit-for (seconds &optional nodisp)
"Perform redisplay, then wait for seconds seconds or until input is available.
seconds may be a floating-point value, meaning that you can wait for a
fraction of a second.
(Not all operating systems support waiting for a fraction of a second.)
Optional arg nodisp non-nil means don't redisplay, just wait for input.
Redisplay is preempted as always if input arrives, and does not happen
if input is available before it starts.
Value is t if waited the full time with no input arriving."
(unless nodisp
(frame-render (selected-frame)))
;; FIXME: poll for input
(sleep seconds)
t
;; (let ((event (wait-for-event seconds)))
;; (if event
;; (progn
;; (push event *unread-command-events*)
;; nil)
;; t))
)
;;; Matching and match data
(defun match-string (num &optional string)
"Return string of text matched by last search.
NUM specifies which parenthesized expression in the last regexp.
Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
Zero means the entire text matched by the whole regexp or whole string.
STRING should be given if the last search was by `string-match' on STRING."
(if (match-beginning num)
(if string
(substring string (match-beginning num) (match-end num))
(buffer-substring (match-beginning num) (match-end num)))))
(defun match-string-no-properties (num &optional string)
"Return string of text matched by last search, without text properties.
NUM specifies which parenthesized expression in the last regexp.
Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
Zero means the entire text matched by the whole regexp or whole string.
STRING should be given if the last search was by `string-match' on STRING."
(if (match-beginning num)
(if string
(substring-no-properties string (match-beginning num)
(match-end num))
(buffer-substring-no-properties (match-beginning num)
(match-end num)))))
(defun force-mode-line-update (&optional all)
"Force redisplay of the current buffer's mode line and header line.
With optional non-nil ALL, force redisplay of all mode lines and
header lines. This function also forces recomputation of the
menu bar menus and the frame title."
(declare (ignore all))
(error "unimplemented force-mode-line-update")
;; (if all (save-excursion (set-buffer (other-buffer))))
;; (set-buffer-modified-p (buffer-modified-p))
)
(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
"Register a new minor mode.
This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
TOGGLE is a symbol which is the name of a buffer-local variable that
is toggled on or off to say whether the minor mode is active or not.
NAME specifies what will appear in the mode line when the minor mode
is active. NAME should be either a string starting with a space, or a
symbol whose value is such a string.
Optional KEYMAP is the keymap for the minor mode that will be added
to `*minor-mode-map-list*'.
Optional AFTER specifies that TOGGLE should be added after AFTER
in `*minor-mode-list*'.
Optional TOGGLE-FUN is an interactive function to toggle the mode.
It defaults to (and should by convention be) TOGGLE.
If TOGGLE has a non-nil `:included' property, an entry for the mode is
included in the mode-line minor mode menu.
If TOGGLE has a `:menu-tag', that is used for the menu item's label."
(unless (memq toggle minor-mode-list)
(push toggle minor-mode-list))
(unless toggle-fun (setq toggle-fun toggle))
(unless (eq toggle-fun toggle)
(setf (get toggle :minor-mode-function) toggle-fun))
;; Add the name to the *minor-mode-list*.
(when name
(let ((existing (find toggle *minor-mode-list* :key 'first)))
(if existing
(setf (cdr existing) (list name))
(let ((found (member after *minor-mode-list* :key 'first)))
(if found
(let ((rest (cdr found)))
(setf (cdr found) nil)
(nconc found (list (list toggle name)) rest))
(push (cons (list toggle name)
*minor-mode-list*) *minor-mode-list*))))))
;; FIXME: when menu support is added, use this code
;; ;; Add the toggle to the minor-modes menu if requested.
;; (when (get toggle :included)
;; (define-key mode-line-mode-menu
;; (vector toggle)
;; (list 'menu-item
;; (concat
;; (or (get toggle :menu-tag)
;; (if (stringp name) name (symbol-name toggle)))
;; (let ((mode-name (if (symbolp name) (symbol-value name))))
;; (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
;; (concat " (" (match-string 0 mode-name) ")"))))
;; toggle-fun
;; :button (cons :toggle toggle))))
;; Add the map to the *minor-mode-map-list*.
(when keymap
(let ((existing (find toggle *minor-mode-map-list* :key 'minor-mode-map-variable)))
(if existing
(setf (minor-mode-map-keymap existing) keymap)
(let ((found (member after *minor-mode-map-list* :key 'minor-mode-map-variable)))
(if found
(let ((rest (cdr found)))
(setf (cdr found) nil)
(nconc found (list (make-minor-mode-map :variable toggle :keymap keymap)) rest))
(push (make-minor-mode-map :variable toggle :keymap keymap)
*minor-mode-map-list*)))))))
(defun replace-regexp-in-string (regexp rep string &optional
fixedcase literal subexp start)
"Replace all matches for REGEXP with REP in STRING.
Return a new string containing the replacements.
Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
arguments with the same names of function `replace-match'. If START
is non-nil, start replacements at that index in STRING.
REP is either a string used as the NEWTEXT arg of `replace-match' or a
function. If it is a function, it is called with the actual text of each
match, and its value is used as the replacement text. When REP is called,
the match-data are the result of matching REGEXP against a substring
of STRING.
To replace only the first match (if any), make REGEXP match up to \\'
and replace a sub-expression, e.g.
(replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
=> \" bar foo\"
"
;; To avoid excessive consing from multiple matches in long strings,
;; don't just call `replace-match' continually. Walk down the
;; string looking for matches of REGEXP and building up a (reversed)
;; list MATCHES. This comprises segments of STRING which weren't
;; matched interspersed with replacements for segments that were.
;; [For a `large' number of replacements it's more efficient to
;; operate in a temporary buffer; we can't tell from the function's
;; args whether to choose the buffer-based implementation, though it
;; might be reasonable to do so for long enough STRING.]
(let ((l (length string))
(start (or start 0))
matches str mb me)
(with-match-data
(while (and (< start l) (string-match regexp string start))
(setq mb (match-beginning 0)
me (match-end 0))
;; If we matched the empty string, make sure we advance by one char
(when (= me mb) (setq me (min l (1+ mb))))
;; Generate a replacement for the matched substring.
;; Operate only on the substring to minimize string consing.
;; Set up match data for the substring for replacement;
;; presumably this is likely to be faster than munging the
;; match data directly in Lisp.
(string-match regexp (setq str (substring string mb me)))
(setq matches
(cons (replace-match (if (stringp rep)
rep
(funcall rep (match-string 0 str)))
fixedcase literal str subexp)
(cons (substring string start mb) ; unmatched prefix
matches)))
(setq start me))
;; Reconstruct a string from the pieces.
(setq matches (cons (substring string start l) matches)) ; leftover
(apply #'concat (nreverse matches)))))
;;;; Key binding commands.
(defcommand global-set-key ((key command)
(:key "Set key globally: ")
(:command "Set key ~a to command: "))
"Give KEY a global binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a key sequence; noninteractively, it is a string or vector
of characters or event types, and non-ASCII characters with codes
above 127 (such as ISO Latin-1) can be included if you use a vector.
Note that if KEY has a local binding in the current buffer,
that local binding will continue to shadow any global binding
that you make with this function."
;;(interactive "KSet key globally: \nCSet key %s to command: ")
(or (vectorp key) (stringp key) (symbolp key) (clickp key)
(signal 'wrong-type-argument :type (list 'arrayp key)))
(define-key (current-global-map) key command))
(defcommand local-set-key ((key command)
(:key "Set key locally: ")
(:command "Set key ~a locally to command: "))
"Give KEY a local binding as COMMAND.
COMMAND is the command definition to use; usually it is
a symbol naming an interactively-callable function.
KEY is a key sequence; noninteractively, it is a string or vector
of characters or event types, and non-ASCII characters with codes
above 127 (such as ISO Latin-1) can be included if you use a vector.
The binding goes in the current buffer's local map,
which in most cases is shared with all other buffers in the same major mode."
;;(interactive "KSet key locally: \nCSet key %s locally to command: ")
(let ((map (current-local-map)))
(or map
(use-local-map (setq map (make-sparse-keymap))))
(or (vectorp key) (stringp key)
(signal 'wrong-type-argument (list 'arrayp key)))
(define-key map key command)))
(defun global-unset-key (key)
"Remove global binding of KEY.
KEY is a string or vector representing a sequence of keystrokes."
(interactive "kUnset key globally: ")
(global-set-key key nil))
(defun local-unset-key (key)
"Remove local binding of KEY.
KEY is a string or vector representing a sequence of keystrokes."
(interactive "kUnset key locally: ")
(if (current-local-map)
(local-set-key key nil))
nil)
;;;; substitute-key-definition and its subroutines.
(defvar key-substitution-in-progress nil
"Used internally by `substitute-key-definition'.")
(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
"Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
In other words, OLDDEF is replaced with NEWDEF where ever it appears.
Alternatively, if optional fourth argument OLDMAP is specified, we redefine
in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
If you don't specify OLDMAP, you can usually get the same results
in a cleaner way with command remapping, like this:
\(define-key KEYMAP [remap OLDDEF] NEWDEF)
\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
;; Don't document PREFIX in the doc string because we don't want to
;; advertise it. It's meant for recursive calls only. Here's its
;; meaning
;; If optional argument PREFIX is specified, it should be a key
;; prefix, a string. Redefined bindings will then be bound to the
;; original key, with PREFIX added at the front.
(or prefix (setq prefix ""))
(let* ((scan (or oldmap keymap))
(prefix1 (vconcat prefix [nil]))
(key-substitution-in-progress
(cons scan key-substitution-in-progress)))
;; Scan OLDMAP, finding each char or event-symbol that
;; has any definition, and act on it with hack-key.
(map-keymap
(lambda (char defn)
(aset prefix1 (length prefix) char)
(substitute-key-definition-key defn olddef newdef prefix1 keymap))
scan)))
(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
(let (inner-def skipped menu-item)
;; Find the actual command name within the binding.
(el:if (eq (car-safe defn) 'menu-item)
(setq menu-item defn defn (nth 2 defn))
;; Skip past menu-prompt.
(while (stringp (car-safe defn))
(push (pop defn) skipped))
;; Skip past cached key-equivalence data for menu items.
(if (consp (car-safe defn))
(setq defn (cdr defn))))
(el:if (or (eq defn olddef)
;; Compare with equal if definition is a key sequence.
;; That is useful for operating on function-key-map.
(and (or (stringp defn) (vectorp defn))
(equal defn olddef)))
(define-key keymap prefix
(if menu-item
(let ((copy (copy-sequence menu-item)))
(setcar (nthcdr 2 copy) newdef)
copy)
(nconc (nreverse skipped) newdef)))
;; Look past a symbol that names a keymap.
(setq inner-def
(or (indirect-function defn t) defn))
;; For nested keymaps, we use `inner-def' rather than `defn' so as to
;; avoid autoloading a keymap. This is mostly done to preserve the
;; original non-autoloading behavior of pre-map-keymap times.
(if (and (keymapp inner-def)
;; Avoid recursively scanning
;; where KEYMAP does not have a submap.
(let ((elt (lookup-key keymap prefix)))
(or (null elt) (natnump elt) (keymapp elt)))
;; Avoid recursively rescanning keymap being scanned.
(not (memq inner-def key-substitution-in-progress)))
;; If this one isn't being scanned already, scan it now.
(substitute-key-definition olddef newdef keymap inner-def prefix)))))
(provide :lice-0.1/subr)
| 21,155 | Common Lisp | .lisp | 438 | 44.182648 | 113 | 0.713995 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8a984074d8cb5d904650a8b2b856e724b7a695ca42abc490c2a4a934df4ad33b | 18,479 | [
-1
] |
18,480 | bindings.lisp | spacebat_lice/src/lisp/bindings.lisp | ;;; bindings.el --- define standard key bindings and some variables
;; Copyright (C) 1985, 1986, 1987, 1992, 1993, 1994, 1995, 1996, 1999,
;; 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
;; Maintainer: FSF
;; Keywords: internal
;; This file is part of GNU Emacs.
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
;;; Special formatting conventions are used in this file!
;;;
;;; A backslash-newline is used at the beginning of a documentation string
;;; when that string should be stored in the file etc/DOCnnn, not in core.
;;;
;;; Such strings read into Lisp as numbers (during the pure-loading phase).
;;;
;;; But you must obey certain rules to make sure the string is understood
;;; and goes into etc/DOCnnn properly.
;;;
;;; The doc string must appear in the standard place in a call to
;;; defun, autoload, defvar or defconst. No Lisp macros are recognized.
;;; The open-paren starting the definition must appear in column 0.
;;;
;;; In defvar and defconst, there is an additional rule:
;;; The double-quote that starts the string must be on the same
;;; line as the defvar or defconst.
;;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
;;; Code:
(in-package "LICE")
(defun make-mode-line-mouse-map (mouse function) "\
Return a keymap with single entry for mouse key MOUSE on the mode line.
MOUSE is defined to run function FUNCTION with no args in the buffer
corresponding to the mode line clicked."
(let ((map (make-sparse-keymap)))
(define-key map (vector 'mode-line mouse) function)
map))
(defcommand mode-line-toggle-read-only ((event)
:event)
"Like `toggle-read-only', for the mode-line."
;;(interactive "e")
(save-selected-window
(select-window (posn-window (event-start event)))
(toggle-read-only)
(force-mode-line-update)))
(defcommand mode-line-toggle-modified ((event)
:event)
"Toggle the buffer-modified flag from the mode-line."
;;(interactive "e")
(save-selected-window
(select-window (posn-window (event-start event)))
(set-buffer-modified-p (not (buffer-modified-p)))
(force-mode-line-update)))
(defcommand mode-line-widen ((event)
:event)
"Widen a buffer from the mode-line."
(save-selected-window
(select-window (posn-window (event-start event)))
(widen)
(force-mode-line-update)))
(defcommand mode-line-abbrev-mode ((event)
:event)
"Turn off `abbrev-mode' from the mode-line."
;;(interactive "e")
(save-selected-window
(select-window (posn-window (event-start event)))
(abbrev-mode)
(force-mode-line-update)))
(defcommand mode-line-auto-fill-mode ((event)
:event)
"Turn off `auto-fill-mode' from the mode-line."
;;(interactive "e")
(save-selected-window
(select-window (posn-window (event-start event)))
(auto-fill-mode)
(force-mode-line-update)))
;; FIXME: when we figure out charsets and stuff, maybe uncomment this -sabetts
;; FIXME: interactive lambdas are impossible in LICE
;; (defvar mode-line-input-method-map
;; (let ((map (make-sparse-keymap)))
;; (define-key map (make-click :where :mode-line :button :mouse-2)
;; (lambda (e)
;; (interactive "e")
;; (save-selected-window
;; (select-window
;; (posn-window (event-start e)))
;; (toggle-input-method)
;; (force-mode-line-update))))
;; (define-key map (make-click :where :mode-line :button :mouse-3)
;; (lambda (e)
;; (interactive "e")
;; (save-selected-window
;; (select-window
;; (posn-window (event-start e)))
;; (describe-current-input-method))))
;; (purecopy map)))
;;
;; ;; FIXME: interactive lambdas are impossible in LICE
;; (defvar mode-line-coding-system-map
;; (let ((map (make-sparse-keymap)))
;; (define-key map (make-click :where :mode-line :button :mouse-1)
;; (lambda (e)
;; (interactive "e")
;; (save-selected-window
;; (select-window (posn-window (event-start e)))
;; (when (and enable-multibyte-characters
;; buffer-file-coding-system)
;; (describe-coding-system buffer-file-coding-system)))))
;; (purecopy map))
;; "Local keymap for the coding-system part of the mode line.")
;;
;;
;; (defcommand mode-line-change-eol ((event)
;; :event)
;; "Cycle through the various possible kinds of end-of-line styles."
;; ;;(interactive "e")
;; (save-selected-window
;; (select-window (posn-window (event-start event)))
;; (let ((eol (coding-system-eol-type buffer-file-coding-system)))
;; (set-buffer-file-coding-system
;; (cond ((eq eol 0) 'dos) ((eq eol 1) 'mac) (t 'unix))))))
;;
;; (defvar mode-line-eol-desc-cache nil)
;;
;; (defun mode-line-eol-desc ()
;; (let* ((eol (coding-system-eol-type buffer-file-coding-system))
;; (mnemonic (coding-system-eol-type-mnemonic buffer-file-coding-system))
;; (desc (assq eol mode-line-eol-desc-cache)))
;; (el:if (and desc (eq (cadr desc) mnemonic))
;; (cddr desc)
;; (if desc (setq mode-line-eol-desc-cache nil)) ;Flush the cache if stale.
;; (setq desc
;; (propertize
;; mnemonic
;; 'help-echo (format nil "~a end-of-line; mouse-1 to cycle"
;; (if (eq eol 0) "Unix-style LF"
;; (if (eq eol 1) "Dos-style CRLF"
;; (if (eq eol 2) "Mac-style CR"
;; "Undecided"))))
;; 'keymap
;; ;;(eval-when-compile
;; #.(let ((map (make-sparse-keymap)))
;; (define-key map [mode-line mouse-1] 'mode-line-change-eol)
;; map)
;; 'mouse-face 'mode-line-highlight))
;; (push (cons eol (cons mnemonic desc)) mode-line-eol-desc-cache)
;; desc)))
;;
;; (defvar mode-line-mule-info
;; `(""
;; (current-input-method
;; (:propertize ("" current-input-method-title)
;; help-echo (concat
;; "Input method: "
;; current-input-method
;; ". mouse-2: disable, mouse-3: describe")
;; local-map ,mode-line-input-method-map
;; mouse-face mode-line-highlight))
;; ,(propertize
;; "%z"
;; 'help-echo
;; #'(lambda (window object point)
;; (with-current-buffer (window-buffer window)
;; ;; Don't show this tip if the coding system is nil,
;; ;; it reads like a bug, and is not useful anyway.
;; (when buffer-file-coding-system
;; (if enable-multibyte-characters
;; (concat (symbol-name buffer-file-coding-system)
;; " buffer; mouse-1: describe coding system")
;; (concat "Unibyte " (symbol-name buffer-file-coding-system)
;; " buffer")))))
;; 'mouse-face 'mode-line-highlight
;; 'local-map mode-line-coding-system-map)
;; (:eval (mode-line-eol-desc)))
;; "Mode-line control for displaying information of multilingual environment.
;; Normally it displays current input method (if any activated) and
;; mnemonics of the following coding systems:
;; coding system for saving or writing the current buffer
;; coding system for keyboard input (if Emacs is running on terminal)
;; coding system for terminal output (if Emacs is running on terminal)"
;; ;; Currently not:
;; ;; coding system for decoding output of buffer process (if any)
;; ;; coding system for encoding text to send to buffer process (if any)."
;; )
;;
;; (make-variable-buffer-local 'mode-line-mule-info)
(defvar mode-line-frame-identification '("-%F ")
"Mode-line control to describe the current frame.")
(define-buffer-local mode-line-process nil "\
Mode-line control for displaying info on process status.
Normally nil in most modes, since there is no process to display.")
(make-variable-buffer-local 'mode-line-process)
(define-buffer-local mode-line-modified
(list (propertize
"%1*"
'help-echo (purecopy (lambda (window object point)
(format nil "~sead-only: mouse-1 toggles"
(save-selected-window
(select-window window)
(if (buffer-read-only)
"R"
"Not r")))))
'local-map (purecopy (make-mode-line-mouse-map
'mouse-1
#'mode-line-toggle-read-only))
'mouse-face 'mode-line-highlight)
(propertize
"%1+"
'help-echo (purecopy (lambda (window object point)
(format nil "~sodified: mouse-1 toggles"
(save-selected-window
(select-window window)
(if (buffer-modified-p)
"M"
"Not m")))))
'local-map (purecopy (make-mode-line-mouse-map
'mouse-1 #'mode-line-toggle-modified))
'mouse-face 'mode-line-highlight))
"Mode-line control for displaying whether current buffer is modified.")
(make-variable-buffer-local 'mode-line-modified)
;; Actual initialization is below.
(defvar mode-line-position nil
"Mode-line control for displaying the position in the buffer.
Normally displays the buffer percentage and, optionally, the
buffer size, the line number and the column number.")
(defvar mode-line-modes nil
"Mode-line control for displaying major and minor modes.")
(defvar mode-line-major-mode-keymap
(let ((map (make-sparse-keymap)))
(define-key map (make-click :where :mode-line :button :down-mouse-1) 'mouse-major-mode-menu)
(define-key map (make-click :where :mode-line :button :mouse-2) 'describe-mode)
(define-key map (make-click :where :mode-line :button :down-mouse-3) 'mode-line-mode-menu-1)
map) "\
Keymap to display on major mode.")
(defvar mode-line-minor-mode-keymap
(let ((map (make-sparse-keymap)))
(define-key map (make-click :where :mode-line :button :mouse-2) 'mode-line-minor-mode-help)
(define-key map (make-click :where :mode-line :button :down-mouse-3) 'mode-line-mode-menu-1)
(define-key map (make-click :where :header-line :button :down-mouse-3) 'mode-line-mode-menu-1)
map) "\
Keymap to display on minor modes.")
;; FIXME: When our modeline formatting is up to snuff, uncomment -sabetts
;; (let* ((help-echo
;; ;; The multi-line message doesn't work terribly well on the
;; ;; bottom mode line... Better ideas?
;; ;; "\
;; ;; mouse-1: select window, mouse-2: delete others, mouse-3: delete,
;; ;; drag-mouse-1: resize, C-mouse-2: split horizontally"
;; "mouse-1: select (drag to resize), mouse-2: delete others, mouse-3: delete this")
;; (dashes (propertize "--" 'help-echo help-echo))
;; (standard-mode-line-format
;; (list
;; "%e"
;; (propertize "-" 'help-echo help-echo)
;; 'mode-line-mule-info
;; 'mode-line-modified
;; 'mode-line-frame-identification
;; 'mode-line-buffer-identification
;; (propertize " " 'help-echo help-echo)
;; 'mode-line-position
;; '(vc-mode vc-mode)
;; (propertize " " 'help-echo help-echo)
;; 'mode-line-modes
;; `(which-func-mode ("" which-func-format ,dashes))
;; `(global-mode-string (,dashes global-mode-string))
;; (propertize "-%-" 'help-echo help-echo)))
;; (standard-mode-line-modes
;; (list
;; (propertize "%[(" 'help-echo help-echo)
;; `(:propertize ("" mode-name)
;; help-echo "mouse-1: major mode, mouse-2: major mode help, mouse-3: toggle minor modes"
;; mouse-face mode-line-highlight
;; local-map ,mode-line-major-mode-keymap)
;; '("" mode-line-process)
;; `(:propertize ("" minor-mode-alist)
;; mouse-face mode-line-highlight
;; help-echo "mouse-2: minor mode help, mouse-3: toggle minor modes"
;; local-map ,mode-line-minor-mode-keymap)
;; (propertize "%n" 'help-echo "mouse-2: widen"
;; 'mouse-face 'mode-line-highlight
;; 'local-map (make-mode-line-mouse-map
;; 'mouse-2 #'mode-line-widen))
;; (propertize ")%]--" 'help-echo help-echo)))
;; (standard-mode-line-position
;; `((-3 ,(propertize "%p" 'help-echo help-echo))
;; (size-indication-mode
;; (8 ,(propertize " of %I" 'help-echo help-echo)))
;; (line-number-mode
;; ((column-number-mode
;; (10 ,(propertize " (%l,%c)" 'help-echo help-echo))
;; (6 ,(propertize " L%l" 'help-echo help-echo))))
;; ((column-number-mode
;; (5 ,(propertize " C%c" 'help-echo help-echo))))))))
;;
;; (setq-default *mode-line-format* standard-mode-line-format)
;; (setf (get '*mode-line-format* 'standard-value)
;; (list `(quote ,standard-mode-line-format)))
;;
;; (setq-default mode-line-modes standard-mode-line-modes)
;; (setf (get 'mode-line-modes 'standard-value)
;; (list `(quote ,standard-mode-line-modes)))
;;
;; (setq-default mode-line-position standard-mode-line-position)
;; (setf (get 'mode-line-position 'standard-value)
;; (list `(quote ,standard-mode-line-position))))
(defvar mode-line-buffer-identification-keymap nil "\
Keymap for what is displayed by `mode-line-buffer-identification'.")
;; Add menu of buffer operations to the buffer identification part
;; of the mode line.or header line.
;
(let ((map (make-sparse-keymap)))
;; Bind down- events so that the global keymap won't ``shine
;; through''.
(define-key map (make-click :where :mode-line :button :mouse-1) 'mode-line-previous-buffer)
(define-key map (make-click :where :header-line :button :down-mouse-1) 'ignore)
(define-key map (make-click :where :header-line :button :mouse-1) 'mode-line-previous-buffer)
(define-key map (make-click :where :header-line :button :down-mouse-3) 'ignore)
(define-key map (make-click :where :mode-line :button :mouse-3) 'mode-line-next-buffer)
(define-key map (make-click :where :header-line :button :down-mouse-3) 'ignore)
(define-key map (make-click :where :header-line :button :mouse-3) 'mode-line-next-buffer)
(setq mode-line-buffer-identification-keymap map))
(defun propertized-buffer-identification (fmt)
"Return a list suitable for `mode-line-buffer-identification'.
FMT is a format specifier such as \"%12b\". This function adds
text properties for face, help-echo, and local-map to it."
(list (propertize fmt
'face 'mode-line-buffer-id
'help-echo
(purecopy "mouse-1: previous buffer, mouse-3: next buffer")
'mouse-face 'mode-line-highlight
'local-map mode-line-buffer-identification-keymap)))
(define-buffer-local mode-line-buffer-identification (propertized-buffer-identification "%12b") "\
Mode-line control for identifying the buffer being displayed.
Its default value is (\"%12b\") with some text properties added.
Major modes that edit things other than ordinary files may change this
\(e.g. Info, Dired,...)")
(make-variable-buffer-local 'mode-line-buffer-identification)
(defcommand unbury-buffer () "\
Switch to the last buffer in the buffer list."
(switch-to-buffer (last-buffer)))
(defcommand mode-line-unbury-buffer ((event)
:event) "\
Call `unbury-buffer' in this window."
(save-selected-window
(select-window (posn-window (event-start event)))
(unbury-buffer)))
(defcommand mode-line-bury-buffer ((event)
:event)"\
Like `bury-buffer', but temporarily select EVENT's window."
(save-selected-window
(select-window (posn-window (event-start event)))
(bury-buffer)))
(defcommand mode-line-other-buffer () "\
Switch to the most recently selected buffer other than the current one."
(switch-to-buffer (other-buffer)))
(defcommand mode-line-next-buffer ((event)
:event)
"Like `next-buffer', but temporarily select EVENT's window."
(save-selected-window
(select-window (posn-window (event-start event)))
(next-buffer)))
(defcommand mode-line-previous-buffer ((event)
:event)
"Like `previous-buffer', but temporarily select EVENT's window."
(save-selected-window
(select-window (posn-window (event-start event)))
(previous-buffer)))
(defvar mode-line-mode-menu (make-sparse-keymap "Minor Modes") "\
Menu of mode operations in the mode line.")
(defcommand mode-line-mode-menu-1 ((event)
:event)
(save-selected-window
(select-window (posn-window (event-start event)))
(let* ((selection (mode-line-mode-menu event))
(binding (and selection (lookup-key mode-line-mode-menu
(vector (car selection))))))
(if binding
(call-interactively binding)))))
(defmacro bound-and-true-p (var)
"Return the value of symbol VAR if it is bound, else nil."
`(and (boundp (quote ,var)) ,var))
;; FIXME: when menu stuff is added uncomment this
;; (define-key mode-line-mode-menu [overwrite-mode]
;; `(menu-item ,(purecopy "Overwrite (Ovwrt)") overwrite-mode
;; :button (:toggle . overwrite-mode)))
;; (define-key mode-line-mode-menu [outline-minor-mode]
;; `(menu-item ,(purecopy "Outline (Outl)") outline-minor-mode
;; :button (:toggle . (bound-and-true-p outline-minor-mode))))
;; (define-key mode-line-mode-menu [line-number-mode]
;; `(menu-item ,(purecopy "Line number") line-number-mode
;; :button (:toggle . line-number-mode)))
;; (define-key mode-line-mode-menu [highlight-changes-mode]
;; `(menu-item ,(purecopy "Highlight changes (Chg)") highlight-changes-mode
;; :button (:toggle . (bound-and-true-p highlight-changes-mode))))
;; (define-key mode-line-mode-menu [hide-ifdef-mode]
;; `(menu-item ,(purecopy "Hide ifdef (Ifdef)") hide-ifdef-mode
;; :button (:toggle . (bound-and-true-p hide-ifdef-mode))))
;; (define-key mode-line-mode-menu [glasses-mode]
;; `(menu-item ,(purecopy "Glasses (o^o)") glasses-mode
;; :button (:toggle . (bound-and-true-p glasses-mode))))
;; (define-key mode-line-mode-menu [font-lock-mode]
;; `(menu-item ,(purecopy "Font Lock") font-lock-mode
;; :button (:toggle . font-lock-mode)))
;; (define-key mode-line-mode-menu [flyspell-mode]
;; `(menu-item ,(purecopy "Flyspell (Fly)") flyspell-mode
;; :button (:toggle . (bound-and-true-p flyspell-mode))))
;; (define-key mode-line-mode-menu [column-number-mode]
;; `(menu-item ,(purecopy "Column number") column-number-mode
;; :button (:toggle . column-number-mode)))
;; (define-key mode-line-mode-menu [auto-revert-tail-mode]
;; `(menu-item ,(purecopy "Auto revert tail (Tail)") auto-revert-tail-mode
;; :button (:toggle . (bound-and-true-p auto-revert-tail-mode))))
;; (define-key mode-line-mode-menu [auto-revert-mode]
;; `(menu-item ,(purecopy "Auto revert (ARev)") auto-revert-mode
;; :button (:toggle . (bound-and-true-p auto-revert-mode))))
;; (define-key mode-line-mode-menu [auto-fill-mode]
;; `(menu-item ,(purecopy "Auto fill (Fill)") auto-fill-mode
;; :button (:toggle . auto-fill-function)))
;; (define-key mode-line-mode-menu [abbrev-mode]
;; `(menu-item ,(purecopy "Abbrev (Abbrev)") abbrev-mode
;; :button (:toggle . abbrev-mode)))
(defun mode-line-mode-menu (event)
(interactive "@e")
(x-popup-menu event mode-line-mode-menu))
(defun mode-line-minor-mode-help (event)
"Describe minor mode for EVENT occured on minor modes area of the mode line."
(interactive "@e")
(let ((indicator (car (nth 4 (car (cdr event))))))
(describe-minor-mode-from-indicator indicator)))
(defvar minor-mode-alist nil "\
Alist saying how to show minor modes in the mode line.
Each element looks like (VARIABLE STRING);
STRING is included in the mode line iff VARIABLE's value is non-nil.
Actually, STRING need not be a string; any possible mode-line element
is okay. See `mode-line-format'.")
;; Don't use purecopy here--some people want to change these strings.
(setq minor-mode-alist
(list
(list 'abbrev-mode " Abbrev")
'(overwrite-mode overwrite-mode)
(list 'auto-fill-function " Fill")
;; not really a minor mode...
'(defining-kbd-macro " Def")))
;; These variables are used by autoloadable packages.
;; They are defined here so that they do not get overridden
;; by the loading of those packages.
;; Names in directory that end in one of these
;; are ignored in completion,
;; making it more likely you will get a unique match.
(setq completion-ignored-extensions
(append
(cond ((memq system-type '(ms-dos windows-nt))
'(".o" "~" ".bin" ".bak" ".obj" ".map" ".ico" ".pif" ".lnk"
".a" ".ln" ".blg" ".bbl" ".dll" ".drv" ".vxd" ".386"))
((eq system-type 'vax-vms)
'(".obj" ".exe" ".bin" ".lbin" ".sbin"
".brn" ".rnt" ".lni"
".olb" ".tlb" ".mlb" ".hlb"))
(t
'(".o" "~" ".bin" ".lbin" ".so"
".a" ".ln" ".blg" ".bbl")))
'(".elc" ".lof"
".glo" ".idx" ".lot"
;; TeX-related
".dvi" ".fmt" ".tfm" ".pdf"
;; Java compiled
".class"
;; CLISP
".fas" ".lib" ".mem"
;; CMUCL
".x86f" ".sparcf"
;; Other CL implementations (Allegro, LispWorks, OpenMCL)
".fasl" ".ufsl" ".fsl" ".dxl" ".pfsl" ".dfsl"
;; Libtool
".lo" ".la"
;; Gettext
".gmo" ".mo"
;; Texinfo-related
;; This used to contain .log, but that's commonly used for log
;; files you do want to see, not just TeX stuff. -- fx
".toc" ".aux"
".cp" ".fn" ".ky" ".pg" ".tp" ".vr"
".cps" ".fns" ".kys" ".pgs" ".tps" ".vrs"
;; Python byte-compiled
".pyc" ".pyo")))
;; Suffixes used for executables.
(setq exec-suffixes
(cond
((memq system-type '(ms-dos windows-nt))
'(".exe" ".com" ".bat" ".cmd" ".btm" ""))
(t
'(""))))
;; Packages should add to this list appropriately when they are
;; loaded, rather than listing everything here.
(setq debug-ignored-errors
'(beginning-of-line beginning-of-buffer end-of-line
end-of-buffer end-of-file buffer-read-only
file-supersession
"^Previous command was not a yank$"
"^Minibuffer window is not active$"
"^No previous history search regexp$"
"^No later matching history item$"
"^No earlier matching history item$"
"^End of history; no default available$"
"^End of history; no next item$"
"^Beginning of history; no preceding item$"
"^No recursive edit is in progress$"
"^Changes to be undone are outside visible portion of buffer$"
"^No undo information in this buffer$"
"^No further undo information"
"^Save not confirmed$"
"^Recover-file cancelled\\.$"
"^Cannot switch buffers in a dedicated window$"
))
(make-variable-buffer-local 'indent-tabs-mode)
;; We have base64 and md5 functions built in now.
(provide 'base64)
(provide 'md5)
(provide 'overlay) ;;'(display syntax-table field))
(provide 'text-properties) ;; '(display syntax-table field point-entered))
(define-key *esc-map* "TAB" 'complete-symbol)
(defcommand complete-symbol ((arg)
:raw-prefix) "\
Perform tags completion on the text around point.
Completes to the set of names listed in the current tags table.
The string to complete is chosen in the same way as the default
for \\[find-tag] (which see).
With a prefix argument, this command does completion within
the collection of symbols listed in the index of the manual for the
language you are using."
(if arg
(info-complete-symbol)
(if (fboundp 'complete-tag)
(complete-tag)
;; Don't autoload etags if we have no tags table.
(error (substitute-command-keys
"No tags table loaded; use \\[visit-tags-table] to load one")))))
;; Reduce total amount of space we must allocate during this function
;; that we will not need to keep permanently.
(garbage-collect)
;; FIXME: figure out how cl charset stuff works and uncomment this code -sabetts
;; Make all multibyte characters self-insert.
;; (let ((l (generic-character-list))
;; (table (nth 1 *global-map*)))
;; (while l
;; (set-char-table-default table (car l) 'self-insert-command)
;; (setq l (cdr l))))
(setq help-event-list '(help f1))
(make-variable-buffer-local '*minor-mode-overriding-map-list*)
;; From frame.c
(global-set-key :switch-frame 'handle-switch-frame)
(global-set-key :select-window 'handle-select-window)
;; FIXME: Do those 3 events really ever reach the *global-map* ?
;; It seems that they can't because they're handled via
;; special-event-map which is used at very low-level. -stef
(global-set-key :delete-frame 'handle-delete-frame)
(global-set-key :iconify-frame 'ignore-event)
(global-set-key :make-frame-visible 'ignore-event)
;These commands are defined in editfns.c
;but they are not assigned to keys there.
(setf (get 'narrow-to-region 'disabled) t)
(define-key *ctl-x-map* "n n" 'narrow-to-region)
(define-key *ctl-x-map* "n w" 'widen)
;; (define-key *ctl-x-map* "n" 'narrow-to-region)
;; (define-key *ctl-x-map* "w" 'widen)
;; Quitting
(define-key *global-map* "ESC ESC ESC" 'keyboard-escape-quit)
(define-key *global-map* "C-g" 'keyboard-quit)
(define-key *global-map* "C-j" 'newline-and-indent)
(define-key *global-map* "C-m" 'newline)
(define-key *global-map* "C-o" 'open-line)
(define-key *esc-map* "C-o" 'split-line)
(define-key *global-map* "C-q" 'quoted-insert)
(define-key *esc-map* "^" 'delete-indentation)
(define-key *esc-map* "\\" 'delete-horizontal-space)
(define-key *esc-map* "m" 'back-to-indentation)
(define-key *ctl-x-map* "C-o" 'delete-blank-lines)
(define-key *esc-map* " " 'just-one-space)
(define-key *esc-map* "z" 'zap-to-char)
(define-key *esc-map* "=" 'count-lines-region)
(define-key *ctl-x-map* "=" 'what-cursor-position)
(define-key *esc-map* ":" 'eval-expression)
;; Define ESC ESC : like ESC : for people who type ESC ESC out of habit.
(define-key *esc-map* (kbd "M-:") 'eval-expression)
;; Changed from C-x ESC so that function keys work following C-x.
(define-key *ctl-x-map* "\e\e" 'repeat-complex-command)
;; New binding analogous to M-:.
(define-key *ctl-x-map* "\M-:" 'repeat-complex-command)
(define-key *ctl-x-map* "u" 'advertised-undo)
;; Many people are used to typing C-/ on X terminals and getting C-_.
(define-key *global-map* "C-/" 'undo)
(define-key *global-map* "C-_" 'undo)
;; Richard said that we should not use C-x <uppercase letter> and I have
;; no idea whereas to bind it. Any suggestion welcome. -stef
;; (define-key *ctl-x-map* "U" 'undo-only)
(define-key *esc-map* "!" 'shell-command)
(define-key *esc-map* "|" 'shell-command-on-region)
(define-key *global-map* "C-x right" 'next-buffer)
(define-key *global-map* "C-x C-right" 'next-buffer)
(define-key *global-map* "C-x left" 'previous-buffer)
(define-key *global-map* "C-x C-left" 'previous-buffer)
(let ((map *minibuffer-local-map*))
(define-key map "M-n" 'next-history-element)
(define-key map :next 'next-history-element)
(define-key map :down 'next-history-element)
(define-key map "M-p" 'previous-history-element)
(define-key map :prior 'previous-history-element)
(define-key map :up 'previous-history-element)
(define-key map "M-s" 'next-matching-history-element)
(define-key map "M-r" 'previous-matching-history-element)
;; Override the global binding (which calls indent-relative via
;; indent-for-tab-command). The alignment that indent-relative tries to
;; do doesn't make much sense here since the prompt messes it up.
(define-key map "TAB" 'self-insert-command))
(define-key *global-map* "C-u" 'universal-argument)
(loop for i from 0 to 9 do
(define-key *esc-map* (format nil "~d" i) 'digit-argument))
(define-key *esc-map* "-" 'negative-argument)
;; Define control-digits.
(loop for i from 0 to 9 do
(define-key *global-map* (format nil "C-~d" i) 'digit-argument))
(define-key *global-map* "C--" 'negative-argument)
;; Define control-meta-digits.
(loop for i from 0 to 9 do
(define-key *esc-map* (format nil "C-~d" i) 'digit-argument))
(define-key *global-map* "C-M--" 'negative-argument)
(define-key *global-map* "C-k" 'kill-line)
(define-key *global-map* "C-w" 'kill-region)
(define-key *esc-map* "w" 'kill-ring-save)
(define-key *esc-map* "C-w" 'append-next-kill)
(define-key *global-map* "C-y" 'yank)
(define-key *esc-map* "y" 'yank-pop)
;; (define-key *ctl-x-map* "a" 'append-to-buffer)
(define-key *global-map* "C-@" 'set-mark-command)
;; Many people are used to typing C-SPC and getting C-@.
(define-key *global-map* "C-SPC" 'set-mark-command)
(define-key *ctl-x-map* "C-x" 'exchange-point-and-mark)
(define-key *ctl-x-map* "C-@" 'pop-global-mark)
(define-key *ctl-x-map* "C-SPC" 'pop-global-mark)
(define-key *global-map* "C-n" 'next-line)
(define-key *global-map* "C-p" 'previous-line)
(define-key *ctl-x-map* "C-n" 'set-goal-column)
(define-key *global-map* "C-a" 'move-beginning-of-line)
(define-key *global-map* "C-e" 'move-end-of-line)
(define-key *esc-map* "g" (make-sparse-keymap))
(define-key *esc-map* "g M-g" 'goto-line)
(define-key *esc-map* "g g" 'goto-line)
(define-key *esc-map* "g n" 'next-error)
(define-key *esc-map* "g M-n" 'next-error)
(define-key *ctl-x-map* "`" 'next-error)
(define-key *esc-map* "g p" 'previous-error)
(define-key *esc-map* "g M-p" 'previous-error)
;;(defun function-key-error ()
;; (interactive)
;; (error "That function key is not bound to anything"))
(define-key *global-map* :menu 'execute-extended-command)
(define-key *global-map* :find 'search-forward)
;; Don't do this. We define <delete> in *function-key-map* instead.
;(define-key *global-map* [delete] 'backward-delete-char)
;; natural bindings for terminal keycaps --- defined in X keysym order
(define-key *global-map* "C-S-backspace" 'kill-whole-line)
(define-key *global-map* "home" 'move-beginning-of-line)
(define-key *global-map* "C-home" 'beginning-of-buffer)
(define-key *global-map* "M-home" 'beginning-of-buffer-other-window)
(define-key *esc-map* "home" 'beginning-of-buffer-other-window)
(define-key *global-map* "left" 'backward-char)
(define-key *global-map* "up" 'previous-line)
(define-key *global-map* "right" 'forward-char)
(define-key *global-map* "down" 'next-line)
(define-key *global-map* "prior" 'scroll-down)
(define-key *global-map* "next" 'scroll-up)
(define-key *global-map* "C-up" 'backward-paragraph)
(define-key *global-map* "C-down" 'forward-paragraph)
(define-key *global-map* "C-prior" 'scroll-right)
(setf (get 'scroll-left 'disabled) t)
(define-key *global-map* "C-next" 'scroll-left)
(define-key *global-map* "M-next" 'scroll-other-window)
(define-key *esc-map* "next" 'scroll-other-window)
(define-key *global-map* "M-prior" 'scroll-other-window-down)
(define-key *esc-map* "prior" 'scroll-other-window-down)
(define-key *esc-map* "?\C-\S-v" 'scroll-other-window-down)
(define-key *global-map* "end" 'move-end-of-line)
(define-key *global-map* "C-end" 'end-of-buffer)
(define-key *global-map* "M-end" 'end-of-buffer-other-window)
(define-key *esc-map* "end" 'end-of-buffer-other-window)
(define-key *global-map* "begin" 'beginning-of-buffer)
(define-key *global-map* "M-begin" 'beginning-of-buffer-other-window)
(define-key *esc-map* "begin" 'beginning-of-buffer-other-window)
;; (define-key *global-map* "select" 'function-key-error)
;; (define-key *global-map* "print" 'function-key-error)
(define-key *global-map* "execute" 'execute-extended-command)
(define-key *global-map* "insert" 'overwrite-mode)
(define-key *global-map* "C-insert" 'kill-ring-save)
(define-key *global-map* "S-insert" 'yank)
;; `insertchar' is what term.c produces. Should we change term.c
;; to produce `insert' instead?
(define-key *global-map* "insertchar" 'overwrite-mode)
(define-key *global-map* "C-insertchar" 'kill-ring-save)
(define-key *global-map* "S-insertchar" 'yank)
(define-key *global-map* "undo" 'undo)
(define-key *global-map* "redo" 'repeat-complex-command)
(define-key *global-map* "again" 'repeat-complex-command) ; Sun keyboard
(define-key *global-map* "open" 'find-file) ; Sun
;; The following wouldn't work to interrupt running code since C-g is
;; treated specially in the event loop.
;; (define-key *global-map* "stop" 'keyboard-quit) ; Sun
;; (define-key *global-map* "clearline" 'function-key-error)
(define-key *global-map* "insertline" 'open-line)
(define-key *global-map* "deleteline" 'kill-line)
(define-key *global-map* "deletechar" 'delete-char)
;; (define-key *global-map* "backtab" 'function-key-error)
;; (define-key *global-map* "f1" 'function-key-error)
;; (define-key *global-map* "f2" 'function-key-error)
;; (define-key *global-map* "f3" 'function-key-error)
;; (define-key *global-map* "f4" 'function-key-error)
;; (define-key *global-map* "f5" 'function-key-error)
;; (define-key *global-map* "f6" 'function-key-error)
;; (define-key *global-map* "f7" 'function-key-error)
;; (define-key *global-map* "f8" 'function-key-error)
;; (define-key *global-map* "f9" 'function-key-error)
;; (define-key *global-map* "f10" 'function-key-error)
;; (define-key *global-map* "f11" 'function-key-error)
;; (define-key *global-map* "f12" 'function-key-error)
;; (define-key *global-map* "f13" 'function-key-error)
;; (define-key *global-map* "f14" 'function-key-error)
;; (define-key *global-map* "f15" 'function-key-error)
;; (define-key *global-map* "f16" 'function-key-error)
;; (define-key *global-map* "f17" 'function-key-error)
;; (define-key *global-map* "f18" 'function-key-error)
;; (define-key *global-map* "f19" 'function-key-error)
;; (define-key *global-map* "f20" 'function-key-error)
;; (define-key *global-map* "f21" 'function-key-error)
;; (define-key *global-map* "f22" 'function-key-error)
;; (define-key *global-map* "f23" 'function-key-error)
;; (define-key *global-map* "f24" 'function-key-error)
;; (define-key *global-map* "f25" 'function-key-error)
;; (define-key *global-map* "f26" 'function-key-error)
;; (define-key *global-map* "f27" 'function-key-error)
;; (define-key *global-map* "f28" 'function-key-error)
;; (define-key *global-map* "f29" 'function-key-error)
;; (define-key *global-map* "f30" 'function-key-error)
;; (define-key *global-map* "f31" 'function-key-error)
;; (define-key *global-map* "f32" 'function-key-error)
;; (define-key *global-map* "f33" 'function-key-error)
;; (define-key *global-map* "f34" 'function-key-error)
;; (define-key *global-map* "f35" 'function-key-error)
;; (define-key *global-map* "kp-backtab" 'function-key-error)
;; (define-key *global-map* "kp-space" 'function-key-error)
;; (define-key *global-map* "kp-tab" 'function-key-error)
;; (define-key *global-map* "kp-enter" 'function-key-error)
;; (define-key *global-map* "kp-f1" 'function-key-error)
;; (define-key *global-map* "kp-f2" 'function-key-error)
;; (define-key *global-map* "kp-f3" 'function-key-error)
;; (define-key *global-map* "kp-f4" 'function-key-error)
;; (define-key *global-map* "kp-multiply" 'function-key-error)
;; (define-key *global-map* "kp-add" 'function-key-error)
;; (define-key *global-map* "kp-separator" 'function-key-error)
;; (define-key *global-map* "kp-subtract" 'function-key-error)
;; (define-key *global-map* "kp-decimal" 'function-key-error)
;; (define-key *global-map* "kp-divide" 'function-key-error)
;; (define-key *global-map* "kp-0" 'function-key-error)
;; (define-key *global-map* "kp-1" 'function-key-error)
;; (define-key *global-map* "kp-2" 'function-key-error)
;; (define-key *global-map* "kp-3" 'function-key-error)
;; (define-key *global-map* "kp-4" 'function-key-error)
;; (define-key *global-map* "kp-5" 'recenter)
;; (define-key *global-map* "kp-6" 'function-key-error)
;; (define-key *global-map* "kp-7" 'function-key-error)
;; (define-key *global-map* "kp-8" 'function-key-error)
;; (define-key *global-map* "kp-9" 'function-key-error)
;; (define-key *global-map* "kp-equal" 'function-key-error)
;; X11R6 distinguishes these keys from the non-kp keys.
;; Make them behave like the non-kp keys unless otherwise bound.
(define-key *function-key-map* "kp-home" "home")
(define-key *function-key-map* "kp-left" "left")
(define-key *function-key-map* "kp-up" "up")
(define-key *function-key-map* "kp-right" "right")
(define-key *function-key-map* "kp-down" "down")
(define-key *function-key-map* "kp-prior" "prior")
(define-key *function-key-map* "kp-next" "next")
(define-key *function-key-map* "M-kp-next" "M-next")
(define-key *function-key-map* "kp-end" "end")
(define-key *function-key-map* "kp-begin" "begin")
(define-key *function-key-map* "kp-insert" "insert")
(define-key *function-key-map* "backspace" "?\C-?")
(define-key *function-key-map* "delete" "?\C-?")
(define-key *function-key-map* "kp-delete" "?\C-?")
(define-key *function-key-map* "S-kp-end" "S-end")
(define-key *function-key-map* "S-kp-down" "S-down")
(define-key *function-key-map* "S-kp-next" "S-next")
(define-key *function-key-map* "S-kp-left" "S-left")
(define-key *function-key-map* "S-kp-right" "S-right")
(define-key *function-key-map* "S-kp-home" "S-home")
(define-key *function-key-map* "S-kp-up" "S-up")
(define-key *function-key-map* "S-kp-prior" "S-prior")
(define-key *function-key-map* "C-S-kp-end" "C-S-end")
(define-key *function-key-map* "C-S-kp-down" "C-S-down")
(define-key *function-key-map* "C-S-kp-next" "C-S-next")
(define-key *function-key-map* "C-S-kp-left" "C-S-left")
(define-key *function-key-map* "C-S-kp-right" "C-S-right")
(define-key *function-key-map* "C-S-kp-home" "C-S-home")
(define-key *function-key-map* "C-S-kp-up" "C-S-up")
(define-key *function-key-map* "C-S-kp-prior" "C-S-prior")
;; Don't bind shifted keypad numeric keys, they reportedly
;; interfere with the feature of some keyboards to produce
;; numbers when NumLock is off.
;(define-key *function-key-map* "S-kp-1" "S-end")
;(define-key *function-key-map* "S-kp-2" "S-down")
;(define-key *function-key-map* "S-kp-3" "S-next")
;(define-key *function-key-map* "S-kp-4" "S-left")
;(define-key *function-key-map* "S-kp-6" "S-right")
;(define-key *function-key-map* "S-kp-7" "S-home")
;(define-key *function-key-map* "S-kp-8" "S-up")
;(define-key *function-key-map* "S-kp-9" "S-prior")
(define-key *function-key-map* "C-S-kp-1" "C-S-end")
(define-key *function-key-map* "C-S-kp-2" "C-S-down")
(define-key *function-key-map* "C-S-kp-3" "C-S-next")
(define-key *function-key-map* "C-S-kp-4" "C-S-left")
(define-key *function-key-map* "C-S-kp-6" "C-S-right")
(define-key *function-key-map* "C-S-kp-7" "C-S-home")
(define-key *function-key-map* "C-S-kp-8" "C-S-up")
(define-key *function-key-map* "C-S-kp-9" "C-S-prior")
(define-key *global-map* "mouse-movement" 'ignore)
(define-key *global-map* "C-t" 'transpose-chars)
(define-key *esc-map* "t" 'transpose-words)
(define-key *esc-map* "C-t" 'transpose-sexps)
(define-key *ctl-x-map* "C-t" 'transpose-lines)
(define-key *esc-map* ";" 'comment-dwim)
(define-key *esc-map* "j" 'indent-new-comment-line)
(define-key *esc-map* "C-j" 'indent-new-comment-line)
(define-key *ctl-x-map* ";" 'comment-set-column)
(define-key *ctl-x-map* "f" 'set-fill-column)
(define-key *ctl-x-map* "$" 'set-selective-display)
(define-key *esc-map* "@" 'mark-word)
(define-key *esc-map* "f" 'forward-word)
(define-key *esc-map* "b" 'backward-word)
(define-key *esc-map* "d" 'kill-word)
(define-key *esc-map* "\177" 'backward-kill-word)
(define-key *esc-map* "<" 'beginning-of-buffer)
(define-key *esc-map* ">" 'end-of-buffer)
(define-key *ctl-x-map* "h" 'mark-whole-buffer)
(define-key *esc-map* "\\" 'delete-horizontal-space)
(defvar mode-specific-command-prefix (make-sparse-keymap))
(defvar mode-specific-map mode-specific-command-prefix
"Keymap for characters following C-c.")
(define-key *global-map* "C-c" 'mode-specific-command-prefix)
(global-set-key "M-right" 'forward-word)
(define-key *esc-map* "right" 'forward-word)
(global-set-key "M-left" 'backward-word)
(define-key *esc-map* "left" 'backward-word)
;; [email protected] says these bindings are standard on PC editors.
(global-set-key "C-right" 'forward-word)
(global-set-key "C-left" 'backward-word)
;; This is not quite compatible, but at least is analogous
(global-set-key "C-delete" 'backward-kill-word)
(global-set-key "C-backspace" 'kill-word)
;; This is "move to the clipboard", or as close as we come.
(global-set-key "S-delete" 'kill-region)
(global-set-key "C-M-left" 'backward-sexp)
(define-key *esc-map* "C-left" 'backward-sexp)
(global-set-key "C-M-right" 'forward-sexp)
(define-key *esc-map* "C-right" 'forward-sexp)
(global-set-key "C-M-up" 'backward-up-list)
(define-key *esc-map* "C-up" 'backward-up-list)
(global-set-key "C-M-down" 'down-list)
(define-key *esc-map* "C-down" 'down-list)
(global-set-key "C-M-home" 'beginning-of-defun)
(define-key *esc-map* "C-home" 'beginning-of-defun)
(global-set-key "C-M-end" 'end-of-defun)
(define-key *esc-map* "C-end" 'end-of-defun)
(define-key *esc-map* "C-f" 'forward-sexp)
(define-key *esc-map* "C-b" 'backward-sexp)
(define-key *esc-map* "C-u" 'backward-up-list)
(define-key *esc-map* "C-@" 'mark-sexp)
(define-key *esc-map* "C-SPC" 'mark-sexp)
(define-key *esc-map* "C-d" 'down-list)
(define-key *esc-map* "C-k" 'kill-sexp)
;;; These are dangerous in various situations,
;;; so let's not encourage anyone to use them.
;;;(define-key *global-map* "C-M-delete" 'backward-kill-sexp)
;;;(define-key *global-map* "C-M-backspace" 'backward-kill-sexp)
(define-key *esc-map* "C-delete" 'backward-kill-sexp)
(define-key *esc-map* "C-backspace" 'backward-kill-sexp)
(define-key *esc-map* "C-n" 'forward-list)
(define-key *esc-map* "C-p" 'backward-list)
(define-key *esc-map* "C-a" 'beginning-of-defun)
(define-key *esc-map* "C-e" 'end-of-defun)
(define-key *esc-map* "C-h" 'mark-defun)
(define-key *ctl-x-map* "n d" 'narrow-to-defun)
(define-key *esc-map* "(" 'insert-parentheses)
(define-key *esc-map* ")" 'move-past-close-and-reindent)
(define-key *ctl-x-map* "C-e" 'eval-last-sexp)
(define-key *ctl-x-map* "m" 'compose-mail)
(define-key *ctl-x-4-map* "m" 'compose-mail-other-window)
(define-key *ctl-x-5-map* "m" 'compose-mail-other-frame)
(define-key *ctl-x-map* "r C-@" 'point-to-register)
(define-key *ctl-x-map* "r C-SPC" 'point-to-register)
(define-key *ctl-x-map* "r SPC" 'point-to-register)
(define-key *ctl-x-map* "r j" 'jump-to-register)
(define-key *ctl-x-map* "r s" 'copy-to-register)
(define-key *ctl-x-map* "r x" 'copy-to-register)
(define-key *ctl-x-map* "r i" 'insert-register)
(define-key *ctl-x-map* "r g" 'insert-register)
(define-key *ctl-x-map* "r r" 'copy-rectangle-to-register)
(define-key *ctl-x-map* "r n" 'number-to-register)
(define-key *ctl-x-map* "r +" 'increment-register)
(define-key *ctl-x-map* "r c" 'clear-rectangle)
(define-key *ctl-x-map* "r k" 'kill-rectangle)
(define-key *ctl-x-map* "r d" 'delete-rectangle)
(define-key *ctl-x-map* "r y" 'yank-rectangle)
(define-key *ctl-x-map* "r o" 'open-rectangle)
(define-key *ctl-x-map* "r t" 'string-rectangle)
(define-key *ctl-x-map* "r w" 'window-configuration-to-register)
(define-key *ctl-x-map* "r f" 'frame-configuration-to-register)
;; ;; These key bindings are deprecated; use the above C-x r map instead.
;; ;; We use these aliases so \[...] will show the C-x r bindings instead.
;; (defalias 'point-to-register-compatibility-binding 'point-to-register)
;; (defalias 'jump-to-register-compatibility-binding 'jump-to-register)
;; (defalias 'copy-to-register-compatibility-binding 'copy-to-register)
;; (defalias 'insert-register-compatibility-binding 'insert-register)
;; (define-key *ctl-x-map* "/" 'point-to-register-compatibility-binding)
;; (define-key *ctl-x-map* "j" 'jump-to-register-compatibility-binding)
;; (define-key *ctl-x-map* "x" 'copy-to-register-compatibility-binding)
;; (define-key *ctl-x-map* "g" 'insert-register-compatibility-binding)
;; (define-key *ctl-x-map* "r" 'copy-rectangle-to-register)
(define-key *esc-map* "q" 'fill-paragraph)
;; (define-key *esc-map* "g" 'fill-region)
(define-key *ctl-x-map* "." 'set-fill-prefix)
(define-key *esc-map* "{" 'backward-paragraph)
(define-key *esc-map* "}" 'forward-paragraph)
(define-key *esc-map* "h" 'mark-paragraph)
(define-key *esc-map* "a" 'backward-sentence)
(define-key *esc-map* "e" 'forward-sentence)
(define-key *esc-map* "k" 'kill-sentence)
(define-key *ctl-x-map* "DEL" 'backward-kill-sentence)
(define-key *ctl-x-map* "[" 'backward-page)
(define-key *ctl-x-map* "]" 'forward-page)
(define-key *ctl-x-map* "C-p" 'mark-page)
(define-key *ctl-x-map* "l" 'count-lines-page)
(define-key *ctl-x-map* "n p" 'narrow-to-page)
;; (define-key *ctl-x-map* "p" 'narrow-to-page)
(define-key *ctl-x-map* "a l" 'add-mode-abbrev)
(define-key *ctl-x-map* "a C-a" 'add-mode-abbrev)
(define-key *ctl-x-map* "a g" 'add-global-abbrev)
(define-key *ctl-x-map* "a +" 'add-mode-abbrev)
(define-key *ctl-x-map* "a i g" 'inverse-add-global-abbrev)
(define-key *ctl-x-map* "a i l" 'inverse-add-mode-abbrev)
;; (define-key *ctl-x-map* "a\C-h" 'inverse-add-global-abbrev)
(define-key *ctl-x-map* "a -" 'inverse-add-global-abbrev)
(define-key *ctl-x-map* "a e" 'expand-abbrev)
(define-key *ctl-x-map* "a '" 'expand-abbrev)
;; (define-key *ctl-x-map* "\C-a" 'add-mode-abbrev)
;; (define-key *ctl-x-map* "\+" 'add-global-abbrev)
;; (define-key *ctl-x-map* "\C-h" 'inverse-add-mode-abbrev)
;; (define-key *ctl-x-map* "\-" 'inverse-add-global-abbrev)
(define-key *esc-map* "'" 'abbrev-prefix-mark)
(define-key *ctl-x-map* "'" 'expand-abbrev)
(define-key *ctl-x-map* "z" 'repeat)
(define-key *ctl-x-4-map* "c" 'clone-indirect-buffer-other-window)
;; Don't look for autoload cookies in this file.
;; Local Variables:
;; no-update-autoloads: t
;; End:
;; arch-tag: 23b5c7e6-e47b-49ed-8c6c-ed213c5fffe0
;;; bindings.el ends here
| 45,906 | Common Lisp | .lisp | 975 | 44.821538 | 98 | 0.6751 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9eedbc5a337333caf312881a40b37e117bb504224f37f2949faf2148e2a2b2af | 18,480 | [
-1
] |
18,481 | simple.lisp | spacebat_lice/src/lisp/simple.lisp | (in-package "LICE")
(defvar *kill-ring* nil
"The kill ring.")
(defvar *kill-ring-max* 60
"Maximum length of kill ring before oldest elements are thrown away.")
(defvar *kill-ring-yank-pointer* nil
"The tail of the kill ring whose car is the last thing yanked.")
(defcustom *eval-expression-print-level* 4
"Value for `print-level' while printing value in `eval-expression'.
A value of nil means no limit."
:group 'lisp
:type '(choice (const :tag "No Limit" nil) integer)
:version "21.1")
(defcustom *eval-expression-print-length* 12
"Value for `print-length' while printing value in `eval-expression'.
A value of nil means no limit."
:group 'lisp
:type '(choice (const :tag "No Limit" nil) integer)
:version "21.1")
(defcustom *eval-expression-debug-on-error* t
"If non-nil set `debug-on-error' to t in `eval-expression'.
If nil, don't change the value of `debug-on-error'."
:group 'lisp
:type 'boolean
:version "21.1")
(define-condition kill-ring-empty (lice-condition)
() (:documentation "Raised when a yank is attempted but the kill ring is empty"))
;; (when (or (and (< n 0)
;; (< (point (current-buffer)) 0))
;; (> (point (current-buffer))
;; (point-max)))
;; (decf (marker-position (buffer-point (current-buffer))) n))
(defun buffer-beginning-of-line ()
"Return the point in the buffer that is the beginning of the line that P is on."
(if (or (not (char-before))
(char= (char-before) #\Newline))
(point)
(let ((bol (buffer-scan-newline (current-buffer) (point) 0 0)))
(if (and (char= (char-after bol) #\Newline)
(< bol (1- (buffer-size (current-buffer)))))
(1+ bol)
bol))))
(defun buffer-end-of-line ()
"Return the point in the buffer that is the end of the line that P is on."
(if (or (not (char-after))
(char= (char-after) #\Newline))
(point)
(let ((eol (buffer-scan-newline (current-buffer) (point) (1- (buffer-size (current-buffer))) 1)))
;; XXX: a bit of a kludge. if the eol char isn't a newline then it
;; has to be the end of the buffer, so advance the point by one,
;; which is the actual end of the line.
(if (char= (char-after eol) #\Newline)
eol
(1+ eol)))))
(defcommand newline ((&optional n)
:prefix)
"Insert N new lines."
(insert-move-point (current-buffer) (make-string (or n 1) :initial-element #\Newline)))
(defcommand open-line ((n) :prefix)
"Insert a newline and leave point before it.
**If there is a fill prefix and/or a left-margin, insert them on the new line
**if the line would have been blank.
With arg N, insert N newlines."
(let ((loc (point)))
(dotimes (i n) (newline 1))
(goto-char loc)))
(defcommand next-line ((&optional (arg 1))
:prefix)
"Move cursor vertically down N lines."
(let ((col (current-column)))
(forward-line arg)
(if (<= col (- (buffer-end-of-line) (point)))
(goto-char (+ (point) col))
(goto-char (buffer-end-of-line)))))
(defcommand previous-line ((&optional (arg 1))
:prefix)
"Move cursor vertically up N lines."
(let ((col (current-column)))
;; FIXME: this is all fucked
(forward-line (- arg))
;;(forward-line 0)
;;(backward-char 1)
;;(forward-line 0)
(if (<= col (- (buffer-end-of-line) (point)))
(goto-char (+ (point) col))
(goto-char (buffer-end-of-line)))))
(defun line-move-invisible-p (pos)
"Return non-nil if the character after POS is currently invisible."
(let ((prop
(get-char-property pos 'invisible)))
(if (eq *buffer-invisibility-spec* t)
prop
(or (find prop *buffer-invisibility-spec*)
(assoc prop (remove-if 'listp *buffer-invisibility-spec*))))))
(defcustom track-eol nil
"*Non-nil means vertical motion starting at end of line keeps to ends of lines.
This means moving to the end of each line moved onto.
The beginning of a blank line does not count as the end of a line."
:type 'boolean
:group 'editing-basics)
(defcustom *line-move-ignore-invisible* t
"*Non-nil means \\[next-line] and \\[previous-line] ignore invisible lines.
Outline mode sets this."
:type 'boolean
:group 'editing-basics)
(defcustom-buffer-local *goal-column* nil
"*Semipermanent goal column for vertical motion, as set by \\[set-goal-column], or nil."
:type '(choice integer
(const :tag "None" nil))
:group 'editing-basics)
(defvar *temporary-goal-column* 0
"Current goal column for vertical motion.
It is the column where point was
at the start of current run of vertical motion commands.
When the `track-eol' feature is doing its job, the value is 9999.")
(defun line-move (arg &optional noerror to-end try-vscroll)
"This is like line-move-1 except that it also performs
vertical scrolling of tall images if appropriate.
That is not really a clean thing to do, since it mixes
scrolling with cursor motion. But so far we don't have
a cleaner solution to the problem of making C-n do something
useful given a tall image."
(declare (ignore try-vscroll))
;; XXX: Fuckit the vertical scrolling for now
;; (if (and auto-window-vscroll try-vscroll
;; ;; But don't vscroll in a keyboard macro.
;; ;; FIXME: kbd macros
;; ;; (not defining-kbd-macro)
;; ;; (not executing-kbd-macro)
;; )
;; (let ((forward (> arg 0))
;; (part (nth 2 (pos-visible-in-window-p (point) nil t))))
;; (if (and (consp part)
;; (> (if forward (cdr part) (car part)) 0))
;; (set-window-vscroll nil
;; (if forward
;; (+ (window-vscroll nil t)
;; (min (cdr part)
;; (* (frame-char-height) arg)))
;; (max 0
;; (- (window-vscroll nil t)
;; (min (car part)
;; (* (frame-char-height) (- arg))))))
;; t)
;; (set-window-vscroll nil 0)
;; (when (line-move-1 arg noerror to-end)
;; (when (not forward)
;; ;; Update display before calling pos-visible-in-window-p,
;; ;; because it depends on window-start being up-to-date.
;; (sit-for 0)
;; ;; If the current line is partly hidden at the bottom,
;; ;; scroll it partially up so as to unhide the bottom.
;; (if (and (setq part (nth 2 (pos-visible-in-window-p
;; (line-beginning-position) nil t)))
;; (> (cdr part) 0))
;; (set-window-vscroll nil (cdr part) t)))
;; t)))
(line-move-1 arg noerror to-end))
;; ))
(defun line-move-1 (arg &optional noerror to-end)
"This is the guts of next-line and previous-line.
Arg says how many lines to move.
The value is t if we can move the specified number of lines."
;; Don't run any point-motion hooks, and disregard intangibility,
;; for intermediate positions.
(declare (ignore to-end))
(let ((*inhibit-point-motion-hooks* t)
(opoint (point))
(forward (> arg 0)))
(unwind-protect
(progn
(if (not (find *last-command* '(next-line previous-line)))
(setq *temporary-goal-column*
(if (and track-eol (eolp)
;; Don't count beg of empty line as end of line
;; unless we just did explicit end-of-line.
(or (not (bolp)) (eq *last-command* 'move-end-of-line)))
9999
(current-column))))
(if (and (not (integerp *selective-display*))
(not *line-move-ignore-invisible*))
;; Use just newline characters.
;; Set ARG to 0 if we move as many lines as requested.
(or (if (> arg 0)
(progn (if (> arg 1) (forward-line (1- arg)))
;; This way of moving forward ARG lines
;; verifies that we have a newline after the last one.
;; It doesn't get confused by intangible text.
(end-of-line)
(if (zerop (forward-line 1))
(setq arg 0)))
(and (zerop (forward-line arg))
(bolp)
(setq arg 0)))
(unless noerror
(signal (if (< arg 0)
'beginning-of-buffer
'end-of-buffer)
nil)))
;; Move by arg lines, but ignore invisible ones.
(let (done)
(while (and (> arg 0) (not done))
;; If the following character is currently invisible,
;; skip all characters with that same `invisible' property value.
(while (and (not (eobp)) (line-move-invisible-p (point)))
(goto-char (next-char-property-change (point))))
;; Now move a line.
(end-of-line)
;; If there's no invisibility here, move over the newline.
(cond
((eobp)
(if (not noerror)
(signal 'end-of-buffer)
(setq done t)))
((and (> arg 1) ;; Use vertical-motion for last move
(not (integerp *selective-display*))
(not (line-move-invisible-p (point))))
;; We avoid vertical-motion when possible
;; because that has to fontify.
(forward-line 1))
;; Otherwise move a more sophisticated way.
((zerop (vertical-motion 1))
(if (not noerror)
(signal 'end-of-buffer)
(setq done t))))
(unless done
(setq arg (1- arg))))
;; The logic of this is the same as the loop above,
;; it just goes in the other direction.
(while (and (< arg 0) (not done))
(beginning-of-line)
(cond
((bobp)
(if (not noerror)
(signal 'beginning-of-buffer nil)
(setq done t)))
((and (< arg -1) ;; Use vertical-motion for last move
(not (integerp *selective-display*))
(not (line-move-invisible-p (1- (point)))))
(forward-line -1))
((zerop (vertical-motion -1))
(if (not noerror)
(signal 'beginning-of-buffer nil)
(setq done t))))
(unless done
(setq arg (1+ arg))
(while (and ;; Don't move over previous invis lines
;; if our target is the middle of this line.
(or (zerop (or *goal-column* *temporary-goal-column*))
(< arg 0))
(not (bobp)) (line-move-invisible-p (1- (point))))
(goto-char (previous-char-property-change (point))))))))
;; This is the value the function returns.
(= arg 0))
(cond ((> arg 0)
;; If we did not move down as far as desired,
;; at least go to end of line.
(end-of-line))
((< arg 0)
;; If we did not move up as far as desired,
;; at least go to beginning of line.
(beginning-of-line))
(t
(line-move-finish (or *goal-column* *temporary-goal-column*)
opoint forward))))))
(defun line-move-finish (column opoint forward)
(let ((repeat t))
(while repeat
;; Set REPEAT to t to repeat the whole thing.
(setq repeat nil)
(let (new
(line-beg (save-excursion (beginning-of-line) (point)))
(line-end
;; Compute the end of the line
;; ignoring effectively invisible newlines.
(save-excursion
;; Like end-of-line but ignores fields.
(skip-chars-forward "^\n")
(while (and (not (eobp)) (line-move-invisible-p (point)))
(goto-char (next-char-property-change (point)))
(skip-chars-forward "^\n"))
(point))))
;; Move to the desired column.
(line-move-to-column column)
(setq new (point))
;; Process intangibility within a line.
;; With inhibit-point-motion-hooks bound to nil, a call to
;; goto-char moves point past intangible text.
;; However, inhibit-point-motion-hooks controls both the
;; intangibility and the point-entered/point-left hooks. The
;; following hack avoids calling the point-* hooks
;; unnecessarily. Note that we move *forward* past intangible
;; text when the initial and final points are the same.
(goto-char new)
(let ((*inhibit-point-motion-hooks* nil))
(goto-char new)
;; If intangibility moves us to a different (later) place
;; in the same line, use that as the destination.
(if (<= (point) line-end)
(setq new (point))
;; If that position is "too late",
;; try the previous allowable position.
;; See if it is ok.
(progn
(backward-char)
(if (if forward
;; If going forward, don't accept the previous
;; allowable position if it is before the target line.
(< line-beg (point))
;; If going backward, don't accept the previous
;; allowable position if it is still after the target line.
(<= (point) line-end))
(setq new (point))
;; As a last resort, use the end of the line.
(setq new line-end)))))
;; Now move to the updated destination, processing fields
;; as well as intangibility.
(goto-char opoint)
(let ((*inhibit-point-motion-hooks* nil))
(goto-char
(constrain-to-field new opoint nil t
'inhibit-line-move-field-capture)))
;; If all this moved us to a different line,
;; retry everything within that new line.
(when (or (< (point) line-beg) (> (point) line-end))
;; Repeat the intangibility and field processing.
(setq repeat t))))))
(defun line-move-to-column (col)
"Try to find column COL, considering invisibility.
This function works only in certain cases,
because what we really need is for `move-to-column'
and `current-column' to be able to ignore invisible text."
(if (zerop col)
(beginning-of-line)
(let ((opoint (point)))
(move-to-column col)
;; move-to-column doesn't respect field boundaries.
(goto-char (constrain-to-field (point) opoint))))
(when (and *line-move-ignore-invisible*
(not (bolp)) (line-move-invisible-p (1- (point))))
(let ((normal-location (point))
(normal-column (current-column)))
;; If the following character is currently invisible,
;; skip all characters with that same `invisible' property value.
(while (and (not (eobp))
(line-move-invisible-p (point)))
(goto-char (next-char-property-change (point))))
;; Have we advanced to a larger column position?
(if (> (current-column) normal-column)
;; We have made some progress towards the desired column.
;; See if we can make any further progress.
(line-move-to-column (+ (current-column) (- col normal-column)))
;; Otherwise, go to the place we originally found
;; and move back over invisible text.
;; that will get us to the same place on the screen
;; but with a more reasonable buffer position.
(progn
(goto-char normal-location)
(let ((line-beg (save-excursion (beginning-of-line) (point))))
(while (and (not (bolp)) (line-move-invisible-p (1- (point))))
(goto-char (previous-char-property-change (point) line-beg)))))))))
(defcommand beginning-of-line ((&optional (n 1))
:prefix)
"Move the point to the beginning of the line in the current buffer."
(check-type n number)
(set-point (line-beginning-position n)))
(defcommand move-beginning-of-line ((arg)
:prefix)
"Move point to beginning of current line as displayed.
\(If there's an image in the line, this disregards newlines
which are part of the text that the image rests on.)
With argument ARG not nil or 1, move forward ARG - 1 lines first.
If point reaches the beginning or end of buffer, it stops there.
To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
(or arg (setq arg 1))
(let ((orig (point))
start first-vis first-vis-field-value)
;; Move by lines, if ARG is not 1 (the default).
(if (/= arg 1)
(line-move (1- arg) t))
;; Move to beginning-of-line, ignoring fields and invisibles.
(skip-chars-backward "^\n")
(while (and (not (bobp)) (line-move-invisible-p (1- (point))))
(goto-char (previous-char-property-change (point)))
(skip-chars-backward "^\n"))
(setq start (point))
;; Now find first visible char in the line
(while (and (not (eobp)) (line-move-invisible-p (point)))
(goto-char (next-char-property-change (point))))
(setq first-vis (point))
;; See if fields would stop us from reaching FIRST-VIS.
(setq first-vis-field-value
(constrain-to-field first-vis orig (/= arg 1) t nil))
(goto-char (if (/= first-vis-field-value first-vis)
;; If yes, obey them.
first-vis-field-value
;; Otherwise, move to START with attention to fields.
;; (It is possible that fields never matter in this case.)
(constrain-to-field (point) orig
(/= arg 1) t nil)))))
(defcommand end-of-line ((&optional (n 1))
:prefix)
"Move point to end of current line.
With argument N not nil or 1, move forward N - 1 lines first.
If point reaches the beginning or end of buffer, it stops there.
To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
This function constrains point to the current field unless this moves
point to a different line than the original, unconstrained result. If
N is nil or 1, and a rear-sticky field ends at point, the point does
not move. To ignore field boundaries bind `inhibit-field-text-motion'
to t."
(let (newpos)
(loop
(setf newpos (line-end-position n))
(set-point newpos)
(cond
((and (> (point) newpos)
(char= (buffer-fetch-char (1- (point)) (current-buffer))
#\Newline))
;; If we skipped over a newline that follows an invisible
;; intangible run, move back to the last tangible position
;; within the line.
(set-point (1- (point)))
(return))
((and (> (point) newpos)
(< (point) (zv))
(char/= (buffer-fetch-char (point) (current-buffer))
#\Newline))
;; If we skipped something intangible and now we're not
;; really at eol, keep going.
(setf n 1))
(t (return))))
nil))
(defcommand move-end-of-line ((arg)
:prefix)
"Move point to end of current line as displayed.
\(If there's an image in the line, this disregards newlines
which are part of the text that the image rests on.)
With argument ARG not nil or 1, move forward ARG - 1 lines first.
If point reaches the beginning or end of buffer, it stops there.
To ignore intangibility, bind `inhibit-point-motion-hooks' to t."
(or arg (setq arg 1))
(let (done)
(while (not done)
(let ((newpos
(save-excursion
(let ((goal-column 0))
(and (line-move arg t)
(not (bobp))
(progn
(while (and (not (bobp)) (line-move-invisible-p (1- (point))))
(goto-char (previous-char-property-change (point))))
(backward-char 1)))
(point)))))
(goto-char newpos)
(if (and (> (point) newpos)
(eq (preceding-char) #\Newline))
(backward-char 1)
(if (and (> (point) newpos) (not (eobp))
(not (eq (following-char) #\Newline)))
;; If we skipped something intangible
;; and now we're not really at eol,
;; keep going.
(setq arg 1)
(setq done t)))))))
(defcommand execute-extended-command ((prefix)
:raw-prefix)
"Read a user command from the minibuffer."
(let* ((name (read-command (case (prefix-numeric-value prefix)
(1 "M-x ")
(4 "C-u M-x ")
(t (format nil "~a M-x " prefix)))))
(cmd (lookup-command name)))
(if cmd
(let ((*prefix-arg* prefix))
(dispatch-command name)
(setf *this-command* (command-name cmd)))
(message "No Match"))))
(defcommand switch-to-buffer ((buffer &optional norecord)
(:buffer "Switch To Buffer: " (buffer-name (other-buffer (current-buffer)))))
"Select buffer buffer in the current window.
If buffer does not identify an existing buffer,
then this function creates a buffer with that name.
When called from Lisp, buffer may be a buffer, a string (a buffer name),
or nil. If buffer is nil, then this function chooses a buffer
using `other-buffer'.
Optional second arg norecord non-nil means
do not put this buffer at the front of the list of recently selected ones.
This function returns the buffer it switched to.
WARNING: This is NOT the way to work on another buffer temporarily
within a Lisp program! Use `set-buffer' instead. That avoids messing with
the window-buffer correspondences."
(unless buffer
(setf buffer (other-buffer (current-buffer))))
(let ((w (frame-selected-window (selected-frame))))
(when (typep w 'minibuffer-window)
(error "its a minibuffer"))
(setf buffer (get-buffer-create buffer))
(set-buffer buffer)
(unless norecord
(record-buffer buffer))
(set-window-buffer w buffer)))
(defun eval-echo (string)
;; FIXME: don't just abandon the output
(let* ((stream (make-string-output-stream))
(*standard-output* stream)
(*error-output* stream)
(*debug-io* stream))
(multiple-value-bind (sexpr pos) (read-from-string string)
(if (= pos (length string))
(message "~s" (eval sexpr))
(error "Trailing garbage is ~a" string)))))
(defun eval-print (string)
(multiple-value-bind (sexpr pos) (read-from-string string)
(if (= pos (length string))
(insert (format nil "~%~s~%" (eval sexpr)))
(error "Trailing garbage is ~a" string))))
(defcommand eval-expression ((s)
(:string "Eval: "))
;;(handler-case
(eval-echo s))
;;(error (c) (message "Eval error: ~s" c))))
(defcommand exchange-point-and-mark ()
(let ((p (point)))
(goto-char (marker-position (mark-marker)))
(set-marker (mark-marker) p)))
;; FIXME: this variable is here just so code compiles. we still need
;; to implement it.
(defvar transient-mark-mode nil)
(defcommand set-mark-command ()
(set-marker (mark-marker) (point))
(message "Mark set"))
(defun push-mark (&optional location nomsg activate)
"Set mark at LOCATION (point, by default) and push old mark on mark ring.
If the last global mark pushed was not in the current buffer,
also push LOCATION on the global mark ring.
Display `Mark set' unless the optional second arg NOMSG is non-nil.
In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
Novice Emacs Lisp programmers often try to use the mark for the wrong
purposes. See the documentation of `set-mark' for more information.
In Transient Mark mode, this does not activate the mark."
(declare (ignore location activate))
;; TODO implement
(set-marker (mark-marker) (point))
(unless nomsg
(message "Mark set")))
;; (defun kill-ring-save (beg end)
;; "Save the region to the kill ring."
(defcommand scroll-up ((&optional arg)
:raw-prefix)
(let ((win (selected-window)))
(window-scroll-up win (max 1 (or (and arg (prefix-numeric-value arg))
(- (window-height win nil)
*next-screen-context-lines*))))))
(defcommand scroll-down ((&optional arg)
:raw-prefix)
(let ((win (selected-window)))
(window-scroll-down win (max 1 (or (and arg (prefix-numeric-value arg))
(- (window-height win nil)
*next-screen-context-lines*))))))
(defcommand end-of-buffer ()
"Move point to the end of the buffer; leave mark at previous position.
With arg N, put point N/10 of the way from the end.
If the buffer is narrowed, this command uses the beginning and size
of the accessible part of the buffer."
(set-mark-command)
(goto-char (point-max)))
(defcommand just-one-space ((&optional (n 1))
:prefix)
"Delete all spaces and tabs around point, leaving one space (or N spaces)."
(let ((orig-pos (point)))
(skip-chars-backward (coerce '(#\Space #\Tab) 'string))
(constrain-to-field nil orig-pos)
(dotimes (i n)
(if (char= (following-char) #\Space)
(forward-char 1)
(insert #\Space)))
(delete-region
(point)
(progn
(skip-whitespace-forward)
(constrain-to-field nil orig-pos t)))))
(defcommand beginning-of-buffer ()
"Move point to the beginning of the buffer; leave mark at previous position.
With arg N, put point N/10 of the way from the beginning.
If the buffer is narrowed, this command uses the beginning and size
of the accessible part of the buffer."
(set-mark-command)
(goto-char (point-min)))
(defcommand split-window ()
(split-window-internal (selected-window)))
(defcommand split-window-horizontally ()
(split-window-internal (selected-window) nil t))
(defcommand switch-to-buffer-other-window ((buffer)
(:buffer "Switch to buffer in other window: " (buffer-name (other-buffer (current-buffer)))))
(let* ((cw (selected-window))
(w (or (next-window cw)
(split-window-internal cw))))
(select-window w)
(switch-to-buffer buffer)))
(defcommand keyboard-quit ()
(signal 'quit))
;;; kill ring
(defun kill-new (string &optional replace)
"Make STRING the latest kill in the kill ring.
Set the kill-ring-yank pointer to point to it.
Optional second argument REPLACE non-nil means that STRING will replace
the front of the kill ring, rather than being added to the list."
(if (and replace
*kill-ring*)
(setf (car *kill-ring*) string)
(push string *kill-ring*))
(when (> (length *kill-ring*) *kill-ring-max*)
(setf (cdr (nthcdr (1- *kill-ring-max*) *kill-ring*)) nil))
(setf *kill-ring-yank-pointer* *kill-ring*))
(defun copy-region-as-kill (start end &optional (buffer (current-buffer)))
(multiple-value-setq (start end) (validate-region start end buffer))
(kill-new (buffer-substring start end buffer)))
(defcommand kill-ring-save ()
(copy-region-as-kill (mark) (point)))
(defcommand kill-region ((beg end)
:region-beginning
:region-end)
"Kill between point and mark.
The text is deleted but saved in the kill ring.
The command C-y can retrieve it from there.
(If you want to kill and then yank immediately, use M-w.)"
(copy-region-as-kill beg end)
(delete-region beg end))
(defcommand kill-line ()
(kill-region (point)
(progn
(when (eobp)
(signal 'end-of-buffer))
(if (char= (buffer-char-after (current-buffer) (point)) #\Newline)
(forward-line 1)
(goto-char (buffer-end-of-line)))
(point))))
(defun current-kill (n &optional do-not-move)
"Rotate the yanking point by N places, and then return that kill.
If optional arg DO-NOT-MOVE is non-nil, then don't actually move the
yanking point; just return the Nth kill forward."
(unless *kill-ring*
(signal 'kill-ring-empty))
(let ((argth-kill-element
(nthcdr (mod (- n (length *kill-ring-yank-pointer*))
(length *kill-ring*))
*kill-ring*)))
(unless do-not-move
(setf *kill-ring-yank-pointer* argth-kill-element))
(car argth-kill-element)))
(defcommand yank ()
(set-mark-command)
(insert (current-kill 0)))
(defcommand yank-pop ()
(unless (eq *last-command* 'yank)
(error "Previous command was not a yank: ~a" *last-command*))
(setf *this-command* 'yank)
(delete-region (mark) (point))
(insert (current-kill 1)))
;;; universal argument
(defun prefix-arg ()
"Return numeric meaning of *prefix-arg*"
(prefix-numeric-value *prefix-arg*))
(defun raw-prefix-arg ()
"Return the current prefix arg in raw form."
*prefix-arg*)
(defvar *overriding-map-is-bound* nil)
(defvar *saved-overriding-map* nil)
(defvar *universal-argument-num-events* nil)
(defvar *universal-argument-map*
(let ((map (make-sparse-keymap)))
;;(define-key map (kbd "t") 'universal-argument-other-key)
(define-key map t 'universal-argument-other-key)
;;(define-key map [switch-frame] nil)
(define-key map (kbd "C-u") 'universal-argument-more)
(define-key map (kbd "-") 'universal-argument-minus)
(define-key map (kbd "0") 'digit-argument)
(define-key map (kbd "1") 'digit-argument)
(define-key map (kbd "2") 'digit-argument)
(define-key map (kbd "3") 'digit-argument)
(define-key map (kbd "4") 'digit-argument)
(define-key map (kbd "5") 'digit-argument)
(define-key map (kbd "6") 'digit-argument)
(define-key map (kbd "7") 'digit-argument)
(define-key map (kbd "8") 'digit-argument)
(define-key map (kbd "9") 'digit-argument)
;; (define-key map [kp-0] 'digit-argument)
;; (define-key map [kp-1] 'digit-argument)
;; (define-key map [kp-2] 'digit-argument)
;; (define-key map [kp-3] 'digit-argument)
;; (define-key map [kp-4] 'digit-argument)
;; (define-key map [kp-5] 'digit-argument)
;; (define-key map [kp-6] 'digit-argument)
;; (define-key map [kp-7] 'digit-argument)
;; (define-key map [kp-8] 'digit-argument)
;; (define-key map [kp-9] 'digit-argument)
;; (define-key map [kp-subtract] 'universal-argument-minus)
map)
"Keymap used while processing \\[universal-argument].")
(defun ensure-overriding-map-is-bound ()
"Check `*overriding-terminal-local-map*' is `*universal-argument-map*'."
(unless *overriding-map-is-bound*
(setf *saved-overriding-map* *overriding-terminal-local-map*
*overriding-terminal-local-map* *universal-argument-map*
*overriding-map-is-bound* t)))
(defun restore-overriding-map ()
"Restore `*overriding-terminal-local-map*' to its saved value."
(setf *overriding-terminal-local-map* *saved-overriding-map*
*overriding-map-is-bound* nil))
(defcommand universal-argument ()
(setf *prefix-arg* (list 4)
*universal-argument-num-events* (length (this-command-keys)))
(ensure-overriding-map-is-bound))
(defcommand universal-argument-more ((arg)
:raw-prefix)
(if (consp arg)
(setf *prefix-arg* (list (* 4 (car arg))))
(if (eq arg '-)
(setf *prefix-arg* (list -4))
(progn
(setf *prefix-arg* arg)
(restore-overriding-map))))
(setf *universal-argument-num-events* (length (this-command-keys))))
(defcommand negative-argument ((arg)
:raw-prefix)
"Begin a negative numeric argument for the next command.
\\[universal-argument] following digits or minus sign ends the argument."
(cond ((integerp arg)
(setf *prefix-arg* (- arg)))
((eq arg '-)
(setf *prefix-arg* nil))
(t
(setf *prefix-arg* '-)))
(setf *universal-argument-num-events* (length (this-command-keys)))
(ensure-overriding-map-is-bound))
(defcommand digit-argument ((arg)
:raw-prefix)
"Part of the numeric argument for the next command.
\\[universal-argument] following digits or minus sign ends the argument."
(let* ((char (last-command-char))
(digit (- (logand (char-code char) #o177) (char-code #\0))))
(cond ((integerp arg)
(setf *prefix-arg* (+ (* arg 10)
(if (< arg 0) (- digit) digit))))
((eq arg '-)
;; Treat -0 as just -, so that -01 will work.
(setf *prefix-arg* (if (zerop digit) '- (- digit))))
(t
(setf *prefix-arg* digit))))
(setf *universal-argument-num-events* (length (this-command-keys)))
(ensure-overriding-map-is-bound))
;; For backward compatibility, minus with no modifiers is an ordinary
;; command if digits have already been entered.
(defcommand universal-argument-minus ((arg)
:raw-prefix)
(if (integerp arg)
(universal-argument-other-key arg)
(negative-argument arg)))
;; Anything else terminates the argument and is left in the queue to be
;; executed as a command.
(defcommand universal-argument-other-key ((arg)
:raw-prefix)
(setf *prefix-arg* arg)
(let* ((keylist (this-command-keys)))
(setf *unread-command-events* keylist))
;; (append (nthcdr *universal-argument-num-events* keylist)
;; *unread-command-events*)))
;;FIXME: (reset-this-command-lengths)
(restore-overriding-map))
;; (defcommand append-to-buffer ((buffer :buffer "Append to buffer: " (buffer-name (other-buffer (current-buffer))))
;; (start :region-beginning)
;; (end :region-end))
;; "Append to specified buffer the text of the region.
;; It is inserted into that buffer before its point.
;; When calling from a program, give three arguments:
;; buffer (or buffer name), start and end.
;; start and end specify the portion of the current buffer to be copied."
;; (let ((oldbuf (current-buffer)))
;; (save-excursion
;; (let* ((append-to (get-buffer-create buffer))
;; (windows (get-buffer-window-list append-to t t))
;; point)
;; (set-buffer append-to)
;; (setf point (point))
;; (barf-if-buffer-read-only)
;; (insert-buffer-substring oldbuf start end)
;; (dolist (window windows)
;; (when (= (window-point window) point)
;; (set-window-point window (point))))))))
(defcommand transpose-chars ((arg)
:prefix)
"Interchange characters around point, moving forward one character.
With prefix arg ARG, effect is to take character before point
and drag it forward past ARG other characters (backward if ARG negative).
If no argument and at end of line, the previous two chars are exchanged."
(and (null arg) (eolp) (forward-char -1))
(transpose-subr 'forward-char (prefix-numeric-value arg)))
(defcommand transpose-words ((arg)
:prefix)
"Interchange words around point, leaving point at end of them.
With prefix arg ARG, effect is to take word before or around point
and drag it forward past ARG other words (backward if ARG negative).
If ARG is zero, the words around or after point and around or after mark
are interchanged."
;; FIXME: `foo a!nd bar' should transpose into `bar and foo'.
(transpose-subr 'forward-word arg))
;; (defun transpose-sexps ((arg)
;; :prefix)
;; "Like \\[transpose-words] but applies to sexps.
;; Does not work on a sexp that point is in the middle of
;; if it is a list or string."
;; (transpose-subr
;; (lambda (arg)
;; ;; Here we should try to simulate the behavior of
;; ;; (cons (progn (forward-sexp x) (point))
;; ;; (progn (forward-sexp (- x)) (point)))
;; ;; Except that we don't want to rely on the second forward-sexp
;; ;; putting us back to where we want to be, since forward-sexp-function
;; ;; might do funny things like infix-precedence.
;; (if (if (> arg 0)
;; ;;(looking-at "\\sw\\|\\s_")
;; ;; FIXME: we don't have looking-at or syntax classes. Fake it for now
;; (or (alpha-char-p (char-after (point)))
;; (find (char-after (point)) "*/+-%$!@&"))
;; (and (not (bobp))
;; (save-excursion (forward-char -1)
;; ;; (looking-at "\\sw\\|\\s_")
;; ;; FIXME: we don't have looking-at or syntax classes. Fake it for now
;; (or (alpha-char-p (char-after (point)))
;; (find (char-after (point)) "*/+-%$!@&"))
;; )))
;; ;; Jumping over a symbol. We might be inside it, mind you.
;; (progn (funcall (if (> arg 0)
;; 'skip-syntax-backward 'skip-syntax-forward)
;; "w_")
;; (cons (save-excursion (forward-sexp arg) (point)) (point)))
;; ;; Otherwise, we're between sexps. Take a step back before jumping
;; ;; to make sure we'll obey the same precedence no matter which direction
;; ;; we're going.
;; (funcall (if (> arg 0) 'skip-syntax-backward 'skip-syntax-forward) " .")
;; (cons (save-excursion (forward-sexp arg) (point))
;; (progn (while (or (forward-comment (if (> arg 0) 1 -1))
;; (not (zerop (funcall (if (> arg 0)
;; 'skip-syntax-forward
;; 'skip-syntax-backward)
;; ".")))))
;; (point)))))
;; arg 'special))
(defcommand transpose-lines ((arg)
:prefix)
"Exchange current line and previous line, leaving point after both.
With argument ARG, takes previous line and moves it past ARG lines.
With argument 0, interchanges line point is in with line mark is in."
(transpose-subr (function
(lambda (arg)
(if (> arg 0)
(progn
;; Move forward over ARG lines,
;; but create newlines if necessary.
(setq arg (forward-line arg))
(if (char/= (preceding-char) #\Newline)
(setq arg (1+ arg)))
(if (> arg 0)
(newline arg)))
(forward-line arg))))
arg))
(defun transpose-subr (mover arg &optional special)
(let ((aux (if special mover
(lambda (x)
(cons (progn (funcall mover x) (point))
(progn (funcall mover (- x)) (point))))))
pos1 pos2)
(cond
((= arg 0)
(save-excursion
(setq pos1 (funcall aux 1))
(goto-char (mark))
(setq pos2 (funcall aux 1))
(transpose-subr-1 pos1 pos2))
(exchange-point-and-mark))
((> arg 0)
(setq pos1 (funcall aux -1))
(setq pos2 (funcall aux arg))
(transpose-subr-1 pos1 pos2)
(goto-char (car pos2)))
(t
(setq pos1 (funcall aux -1))
(goto-char (car pos1))
(setq pos2 (funcall aux arg))
(transpose-subr-1 pos1 pos2)))))
(defun transpose-subr-1 (pos1 pos2)
(when (> (car pos1) (cdr pos1)) (setq pos1 (cons (cdr pos1) (car pos1))))
(when (> (car pos2) (cdr pos2)) (setq pos2 (cons (cdr pos2) (car pos2))))
(when (> (car pos1) (car pos2))
(let ((swap pos1))
(setq pos1 pos2 pos2 swap)))
(if (> (cdr pos1) (car pos2)) (error "Don't have two things to transpose"))
;; (atomic-change-group
(let (word2)
;; FIXME: We first delete the two pieces of text, so markers that
;; used to point to after the text end up pointing to before it :-(
(setq word2 (delete-and-extract-region (car pos2) (cdr pos2)))
(goto-char (car pos2))
(insert (delete-and-extract-region (car pos1) (cdr pos1)))
(goto-char (car pos1))
(insert word2)))
;;;
(defcustom-buffer-local *fill-prefix* nil
"*String for filling to insert at front of new line, or nil for none."
:type '(choice (const :tag "None" nil)
string)
:group 'fill)
(defvar *fundamental-mode*
(make-instance 'major-mode
:name "Fundamental")
"Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one.")
(defun fundamental-mode ()
(set-major-mode '*fundamental-mode*))
(defun turn-on-auto-fill ()
"Unconditionally turn on Auto Fill mode."
;; FIXME: implement
)
(define-buffer-local comment-line-break-function 'comment-indent-new-line
"*Mode-specific function which line breaks and continues a comment.
This function is only called during auto-filling of a comment section.
The function should take a single optional argument, which is a flag
indicating whether it should use soft newlines.")
(defun do-auto-fill ()
"This function is used as the auto-fill-function of a buffer
when Auto-Fill mode is enabled.
It returns t if it really did any work.
\(Actually some major modes use a different auto-fill function,
but this one is the default one.)"
(let (fc justify give-up
(*fill-prefix* *fill-prefix*))
(el:if (or (not (setq justify (current-justification)))
(null (setq fc (current-fill-column)))
(and (eq justify 'left)
(<= (current-column) fc))
(and auto-fill-inhibit-regexp
(save-excursion (beginning-of-line)
(looking-at auto-fill-inhibit-regexp))))
nil ;; Auto-filling not required
(el:if (memq justify '(full center right))
(save-excursion (unjustify-current-line)))
;; Choose a *fill-prefix* automatically.
(when (and adaptive-fill-mode
(or (null *fill-prefix*) (string= *fill-prefix* "")))
(let ((prefix
(fill-context-prefix
(save-excursion (backward-paragraph 1) (point))
(save-excursion (forward-paragraph 1) (point)))))
(and prefix (not (equal prefix ""))
;; Use auto-indentation rather than a guessed empty prefix.
(not (and fill-indent-according-to-mode
(string-match "\\`[ \t]*\\'" prefix)))
(setq *fill-prefix* prefix))))
(while (and (not give-up) (> (current-column) fc))
;; Determine where to split the line.
(let* (after-prefix
(fill-point
(save-excursion
(beginning-of-line)
(setq after-prefix (point))
(and *fill-prefix*
(looking-at (regexp-quote *fill-prefix*))
(setq after-prefix (match-end 0)))
(move-to-column (1+ fc))
(fill-move-to-break-point after-prefix)
(point))))
;; See whether the place we found is any good.
(el:if (save-excursion
(goto-char fill-point)
(or (bolp)
;; There is no use breaking at end of line.
(save-excursion (skip-chars-forward " ") (eolp))
;; It is futile to split at the end of the prefix
;; since we would just insert the prefix again.
(and after-prefix (<= (point) after-prefix))
;; Don't split right after a comment starter
;; since we would just make another comment starter.
(and comment-start-skip
(let ((limit (point)))
(beginning-of-line)
(and (re-search-forward comment-start-skip
limit t)
(eq (point) limit))))))
;; No good place to break => stop trying.
(setq give-up t)
;; Ok, we have a useful place to break the line. Do it.
(let ((prev-column (current-column)))
;; If point is at the fill-point, do not `save-excursion'.
;; Otherwise, if a comment prefix or *fill-prefix* is inserted,
;; point will end up before it rather than after it.
(el:if (save-excursion
(skip-chars-backward " \t")
(= (point) fill-point))
(funcall comment-line-break-function t)
(save-excursion
(goto-char fill-point)
(funcall comment-line-break-function t)))
;; Now do justification, if required
(el:if (not (eq justify 'left))
(save-excursion
(end-of-line 0)
(justify-current-line justify nil t)))
;; If making the new line didn't reduce the hpos of
;; the end of the line, then give up now;
;; trying again will not help.
(el:if (>= (current-column) prev-column)
(setq give-up t))))))
;; Justify last line.
(justify-current-line justify t t)
t)))
;; FIXME: put this info in the following condition
;; (put 'mark-inactive 'error-conditions '(mark-inactive error))
;; (put 'mark-inactive 'error-message "The mark is not active now")
(define-condition mark-inactive (lice-condition)
())
(defvar activate-mark-hook nil
"Hook run when the mark becomes active.
It is also run at the end of a command, if the mark is active and
it is possible that the region may have changed")
(defvar deactivate-mark-hook nil
"Hook run when the mark becomes inactive.")
(defun mark (&optional force)
"Return this buffer's mark value as integer, or nil if never set.
In Transient Mark mode, this function signals an error if
the mark is not active. However, if `mark-even-if-inactive' is non-nil,
or the argument FORCE is non-nil, it disregards whether the mark
is active, and returns an integer or nil in the usual way.
If you are using this in an editing command, you are most likely making
a mistake; see the documentation of `set-mark'."
(if (or force (not transient-mark-mode) mark-active mark-even-if-inactive)
(marker-position (mark-marker))
(signal 'mark-inactive nil)))
;; ;; Many places set mark-active directly, and several of them failed to also
;; ;; run deactivate-mark-hook. This shorthand should simplify.
;; (defsubst deactivate-mark ()
;; "Deactivate the mark by setting `mark-active' to nil.
;; \(That makes a difference only in Transient Mark mode.)
;; Also runs the hook `deactivate-mark-hook'."
;; (cond
;; ((eq transient-mark-mode 'lambda)
;; (setq transient-mark-mode nil))
;; (transient-mark-mode
;; (setq mark-active nil)
;; (run-hooks 'deactivate-mark-hook))))
(defun set-mark (pos)
"Set this buffer's mark to POS. Don't use this function!
That is to say, don't use this function unless you want
the user to see that the mark has moved, and you want the previous
mark position to be lost.
Normally, when a new mark is set, the old one should go on the stack.
This is why most applications should use `push-mark', not `set-mark'.
Novice Emacs Lisp programmers often try to use the mark for the wrong
purposes. The mark saves a location for the user's convenience.
Most editing commands should not alter the mark.
To remember a location for internal use in the Lisp program,
store it in a Lisp variable. Example:
(let ((beg (point))) (forward-line 1) (delete-region beg (point)))."
(if pos
(progn
(setq mark-active t)
(run-hooks 'activate-mark-hook)
(set-marker (mark-marker) pos (current-buffer)))
;; Normally we never clear mark-active except in Transient Mark mode.
;; But when we actually clear out the mark value too,
;; we must clear mark-active in any mode.
(progn
(setq mark-active nil)
(run-hooks 'deactivate-mark-hook)
(set-marker (mark-marker) nil))))
(define-buffer-local mark-ring nil
"The list of former marks of the current buffer, most recent first.")
(make-variable-buffer-local 'mark-ring)
(setf (get 'mark-ring 'permanent-local) t)
(defcustom mark-ring-max 16
"*Maximum size of mark ring. Start discarding off end if gets this big."
:type 'integer
:group 'editing-basics)
(defvar global-mark-ring nil
"The list of saved global marks, most recent first.")
(defcustom global-mark-ring-max 16
"*Maximum size of global mark ring. \
Start discarding off end if gets this big."
:type 'integer
:group 'editing-basics)
(defcommand pop-to-mark-command ()
"Jump to mark, and pop a new position for mark off the ring
\(does not affect global mark ring\)."
(if (null (mark t))
(error "No mark set in this buffer")
(progn
(goto-char (mark t))
(pop-mark))))
;; (defun push-mark-command (arg &optional nomsg)
;; "Set mark at where point is.
;; If no prefix arg and mark is already set there, just activate it.
;; Display `Mark set' unless the optional second arg NOMSG is non-nil."
;; (interactive "P")
;; (let ((mark (marker-position (mark-marker))))
;; (if (or arg (null mark) (/= mark (point)))
;; (push-mark nil nomsg t)
;; (setq mark-active t)
;; (run-hooks 'activate-mark-hook)
;; (unless nomsg
;; (message "Mark activated")))))
(defcustom set-mark-command-repeat-pop nil
"*Non-nil means that repeating \\[set-mark-command] after popping will pop.
This means that if you type C-u \\[set-mark-command] \\[set-mark-command]
will pop twice."
:type 'boolean
:group 'editing)
;; (defun set-mark-command (arg)
;; "Set mark at where point is, or jump to mark.
;; With no prefix argument, set mark, and push old mark position on local
;; mark ring; also push mark on global mark ring if last mark was set in
;; another buffer. Immediately repeating the command activates
;; `transient-mark-mode' temporarily.
;; With argument, e.g. \\[universal-argument] \\[set-mark-command], \
;; jump to mark, and pop a new position
;; for mark off the local mark ring \(this does not affect the global
;; mark ring\). Use \\[pop-global-mark] to jump to a mark off the global
;; mark ring \(see `pop-global-mark'\).
;; If `set-mark-command-repeat-pop' is non-nil, repeating
;; the \\[set-mark-command] command with no prefix pops the next position
;; off the local (or global) mark ring and jumps there.
;; With a double \\[universal-argument] prefix argument, e.g. \\[universal-argument] \
;; \\[universal-argument] \\[set-mark-command], unconditionally
;; set mark where point is.
;; Setting the mark also sets the \"region\", which is the closest
;; equivalent in Emacs to what some editors call the \"selection\".
;; Novice Emacs Lisp programmers often try to use the mark for the wrong
;; purposes. See the documentation of `set-mark' for more information."
;; (interactive "P")
;; (if (eq transient-mark-mode 'lambda)
;; (setq transient-mark-mode nil))
;; (cond
;; ((and (consp arg) (> (prefix-numeric-value arg) 4))
;; (push-mark-command nil))
;; ((not (eq this-command 'set-mark-command))
;; (if arg
;; (pop-to-mark-command)
;; (push-mark-command t)))
;; ((and set-mark-command-repeat-pop
;; (eq last-command 'pop-to-mark-command))
;; (setq this-command 'pop-to-mark-command)
;; (pop-to-mark-command))
;; ((and set-mark-command-repeat-pop
;; (eq last-command 'pop-global-mark)
;; (not arg))
;; (setq this-command 'pop-global-mark)
;; (pop-global-mark))
;; (arg
;; (setq this-command 'pop-to-mark-command)
;; (pop-to-mark-command))
;; ((and (eq last-command 'set-mark-command)
;; mark-active (null transient-mark-mode))
;; (setq transient-mark-mode 'lambda)
;; (message "Transient-mark-mode temporarily enabled"))
;; (t
;; (push-mark-command nil))))
;; (defun push-mark (&optional location nomsg activate)
;; "Set mark at LOCATION (point, by default) and push old mark on mark ring.
;; If the last global mark pushed was not in the current buffer,
;; also push LOCATION on the global mark ring.
;; Display `Mark set' unless the optional second arg NOMSG is non-nil.
;; In Transient Mark mode, activate mark if optional third arg ACTIVATE non-nil.
;; Novice Emacs Lisp programmers often try to use the mark for the wrong
;; purposes. See the documentation of `set-mark' for more information.
;; In Transient Mark mode, this does not activate the mark."
;; (unless (null (mark t))
;; (setq mark-ring (cons (copy-marker (mark-marker)) mark-ring))
;; (when (> (length mark-ring) mark-ring-max)
;; (move-marker (car (nthcdr mark-ring-max mark-ring)) nil)
;; (setcdr (nthcdr (1- mark-ring-max) mark-ring) nil)))
;; (set-marker (mark-marker) (or location (point)) (current-buffer))
;; ;; Now push the mark on the global mark ring.
;; (if (and global-mark-ring
;; (eq (marker-buffer (car global-mark-ring)) (current-buffer)))
;; ;; The last global mark pushed was in this same buffer.
;; ;; Don't push another one.
;; nil
;; (setq global-mark-ring (cons (copy-marker (mark-marker)) global-mark-ring))
;; (when (> (length global-mark-ring) global-mark-ring-max)
;; (move-marker (car (nthcdr global-mark-ring-max global-mark-ring)) nil)
;; (setcdr (nthcdr (1- global-mark-ring-max) global-mark-ring) nil)))
;; (or nomsg executing-kbd-macro (> (minibuffer-depth) 0)
;; (message "Mark set"))
;; (if (or activate (not transient-mark-mode))
;; (set-mark (mark t)))
;; nil)
;; (defun pop-mark ()
;; "Pop off mark ring into the buffer's actual mark.
;; Does not set point. Does nothing if mark ring is empty."
;; (when mark-ring
;; (setq mark-ring (nconc mark-ring (list (copy-marker (mark-marker)))))
;; (set-marker (mark-marker) (+ 0 (car mark-ring)) (current-buffer))
;; (move-marker (car mark-ring) nil)
;; (if (null (mark t)) (ding))
;; (setq mark-ring (cdr mark-ring)))
;; (deactivate-mark))
(defcommand back-to-indentation ()
"Move point to the first non-whitespace character on this line."
(beginning-of-line 1)
(skip-syntax-forward '(:whitespace) (line-end-position))
;; Move back over chars that have whitespace syntax but have the p flag.
(backward-prefix-chars))
;;; undo
;; XXX: gnu emacs uses a weak hashtable that automatically removes
;; references. We need some mechanism to do similar.
(defvar undo-equiv-table (make-hash-table :test 'eq #|:weakness t|#)
"Table mapping redo records to the corresponding undo one.
A redo record for undo-in-region maps to t.
A redo record for ordinary undo maps to the following (earlier) undo.")
(defvar undo-in-region nil
"Non-nil if `pending-undo-list' is not just a tail of `buffer-undo-list'.")
(defvar undo-no-redo nil
"If t, `undo' doesn't go through redo entries.")
(defvar pending-undo-list nil
"Within a run of consecutive undo commands, list remaining to be undone.
If t, we undid all the way to the end of it.")
(defcommand undo ((&optional arg)
;; XXX: what about the *?
:raw-prefix)
"Undo some previous changes.
Repeat this command to undo more changes.
A numeric argument serves as a repeat count.
In Transient Mark mode when the mark is active, only undo changes within
the current region. Similarly, when not in Transient Mark mode, just \\[universal-argument]
as an argument limits undo to changes within the current region."
;;(interactive "*P")
;; Make last-command indicate for the next command that this was an undo.
;; That way, another undo will undo more.
;; If we get to the end of the undo history and get an error,
;; another undo command will find the undo history empty
;; and will get another error. To begin undoing the undos,
;; you must type some other command.
(let ((modified (buffer-modified-p (current-buffer)))
(recent-save (recent-auto-save-p))
message)
;; If we get an error in undo-start,
;; the next command should not be a "consecutive undo".
;; So set `this-command' to something other than `undo'.
(setq *this-command* 'undo-start)
(unless (and (eq *last-command* 'undo)
(or (eq pending-undo-list t)
;; If something (a timer or filter?) changed the buffer
;; since the previous command, don't continue the undo seq.
(let ((list (buffer-undo-list (current-buffer))))
(while (eq (car list) nil)
(setq list (cdr list)))
;; If the last undo record made was made by undo
;; it shows nothing else happened in between.
(gethash list undo-equiv-table))))
(message "guuuungh")
(setq undo-in-region
(if transient-mark-mode *mark-active* (and arg (not (numberp arg)))))
(if undo-in-region
(undo-start (region-beginning) (region-end))
(undo-start))
;; get rid of initial undo boundary
(undo-more 1))
;; If we got this far, the next command should be a consecutive undo.
(setq *this-command* 'undo)
;; Check to see whether we're hitting a redo record, and if
;; so, ask the user whether she wants to skip the redo/undo pair.
(let ((equiv (gethash pending-undo-list undo-equiv-table)))
(or (eq (selected-window) (minibuffer-window))
(setq message (if undo-in-region
(if equiv "Redo in region!" "Undo in region!")
(if equiv "Redo!" "Undo!"))))
(when (and (consp equiv) undo-no-redo)
;; The equiv entry might point to another redo record if we have done
;; undo-redo-undo-redo-... so skip to the very last equiv.
(while (let ((next (gethash equiv undo-equiv-table)))
(if next (setq equiv next))))
(setq pending-undo-list equiv)))
(undo-more
(if (or transient-mark-mode (numberp arg))
(prefix-numeric-value arg)
1))
;; Record the fact that the just-generated undo records come from an
;; undo operation--that is, they are redo records.
;; In the ordinary case (not within a region), map the redo
;; record to the following undos.
;; I don't know how to do that in the undo-in-region case.
(setf (gethash (buffer-undo-list (current-buffer)) undo-equiv-table)
(if undo-in-region t pending-undo-list))
;; Don't specify a position in the undo record for the undo command.
;; Instead, undoing this should move point to where the change is.
(let ((tail (buffer-undo-list (current-buffer)))
(prev nil))
(message "its: ~s" tail)
(while (car tail)
(when (integerp (car tail))
(let ((pos (car tail)))
(if prev
(setf (cdr prev) (cdr tail))
(setf (buffer-undo-list (current-buffer)) (cdr tail)))
(setq tail (cdr tail))
(while (car tail)
(if (eql pos (car tail))
(if prev
(setf (cdr prev) (cdr tail))
(setf (buffer-undo-list (current-buffer)) (cdr tail)))
(setq prev tail))
(setq tail (cdr tail)))
(setq tail nil)))
(setq prev tail
tail (cdr tail))))
;; Record what the current undo list says,
;; so the next command can tell if the buffer was modified in between.
(and modified (not (buffer-modified-p (current-buffer)))
(delete-auto-save-file-if-necessary recent-save))
;; Display a message announcing success.
(if message
(message message))))
(defcommand buffer-disable-undo ((&optional buffer))
"Make BUFFER stop keeping undo information.
No argument or nil as argument means do this for the current buffer."
(with-current-buffer (if buffer (get-buffer buffer) (current-buffer))
(setf (buffer-undo-list (current-buffer)) t)))
(defcommand undo-only ((&optional arg)
;; XXX what about *
:prefix)
"Undo some previous changes.
Repeat this command to undo more changes.
A numeric argument serves as a repeat count.
Contrary to `undo', this will not redo a previous undo."
;;(interactive "*p")
(let ((undo-no-redo t)) (undo arg)))
(defvar undo-in-progress nil
"Non-nil while performing an undo.
Some change-hooks test this variable to do something different.")
(defun undo-more (n)
"Undo back N undo-boundaries beyond what was already undone recently.
Call `undo-start' to get ready to undo recent changes,
then call `undo-more' one or more times to undo them."
(or (listp pending-undo-list)
(error (concat "No further undo information"
(and transient-mark-mode *mark-active*
" for region"))))
(let ((undo-in-progress t))
(setq pending-undo-list (primitive-undo n pending-undo-list))
(if (null pending-undo-list)
(setq pending-undo-list t))))
;; Deep copy of a list
(defun undo-copy-list (list)
"Make a copy of undo list LIST."
(labels ((helper (elt)
(if (typep elt 'structure-object)
(copy-structure elt)
elt)))
(mapcar #'helper list)))
(defun undo-start (&optional beg end)
"Set `pending-undo-list' to the front of the undo list.
The next call to `undo-more' will undo the most recently made change.
If BEG and END are specified, then only undo elements
that apply to text between BEG and END are used; other undo elements
are ignored. If BEG and END are nil, all undo elements are used."
(if (eq (buffer-undo-list (current-buffer)) t)
(error "No undo information in this buffer"))
(setq pending-undo-list
(if (and beg end (not (= beg end)))
(undo-make-selective-list (min beg end) (max beg end))
(buffer-undo-list (current-buffer)))))
(defvar undo-adjusted-markers)
(defun undo-make-selective-list (start end)
"Return a list of undo elements for the region START to END.
The elements come from `buffer-undo-list', but we keep only
the elements inside this region, and discard those outside this region.
If we find an element that crosses an edge of this region,
we stop and ignore all further elements."
(let ((undo-list-copy (undo-copy-list (buffer-undo-list (current-buffer))))
(undo-list (list nil))
undo-adjusted-markers
some-rejected
undo-elt temp-undo-list delta)
(while undo-list-copy
(setq undo-elt (car undo-list-copy))
(let ((keep-this
(cond ((typep undo-elt 'undo-entry-modified) ;;(and (consp undo-elt) (eq (car undo-elt) t))
;; This is a "was unmodified" element.
;; Keep it if we have kept everything thus far.
(not some-rejected))
(t
(undo-elt-in-region undo-elt start end)))))
(if keep-this
(progn
(setq end (+ end (cdr (undo-delta undo-elt))))
;; Don't put two nils together in the list
(if (not (and (eq (car undo-list) nil)
(eq undo-elt nil)))
(setq undo-list (cons undo-elt undo-list))))
(if (undo-elt-crosses-region undo-elt start end)
(setq undo-list-copy nil)
(progn
(setq some-rejected t)
(setq temp-undo-list (cdr undo-list-copy))
(setq delta (undo-delta undo-elt))
(when (/= (cdr delta) 0)
(let ((position (car delta))
(offset (cdr delta)))
;; Loop down the earlier events adjusting their buffer
;; positions to reflect the fact that a change to the buffer
;; isn't being undone. We only need to process those element
;; types which undo-elt-in-region will return as being in
;; the region since only those types can ever get into the
;; output
(dolist (undo-elt temp-undo-list)
(cond ((integerp undo-elt)
(if (>= undo-elt position)
(setf (car temp-undo-list) (- undo-elt offset))))
;;((atom undo-elt) nil)
((typep undo-elt 'undo-entry-delete) ;(stringp (car undo-elt))
;; (TEXT . POSITION)
(let ((text-pos (abs (undo-entry-delete-position undo-elt)))
(point-at-end (< (undo-entry-delete-position undo-elt) 0 )))
(if (>= text-pos position)
(setf (undo-entry-delete-position undo-elt) (* (if point-at-end -1 1)
(- text-pos offset))))))
((typep undo-elt 'undo-entry-insertion) ;(integerp (car undo-elt))
;; (BEGIN . END)
(when (>= (undo-entry-insertion-beg undo-elt) position)
(setf (undo-entry-insertion-beg undo-elt) (- (undo-entry-insertion-beg undo-elt) offset))
(setf (undo-entry-insertion-end undo-elt) (- (undo-entry-insertion-end undo-elt) offset))))
((typep undo-elt 'undo-entry-property) ;(null (car undo-elt))
;; (nil PROPERTY VALUE BEG . END)
(when (>= (undo-entry-property-beg undo-elt) position)
(setf (undo-entry-property-beg undo-elt) (- (undo-entry-property-beg undo-elt) offset))
(setf (undo-entry-property-end undo-elt) (- (undo-entry-property-end undo-elt) offset))))))))))))
(setq undo-list-copy (cdr undo-list-copy)))
(nreverse undo-list)))
(defun undo-elt-in-region (undo-elt start end)
"Determine whether UNDO-ELT falls inside the region START ... END.
If it crosses the edge, we return nil."
(cond ((integerp undo-elt)
(and (>= undo-elt start)
(<= undo-elt end)))
((eq undo-elt nil)
t)
;; ((atom undo-elt)
;; nil)
((typep undo-elt 'undo-entry-delete) ; (stringp (car undo-elt))
;; (TEXT . POSITION)
(and (>= (abs (undo-entry-delete-position undo-elt)) start)
(< (abs (undo-entry-delete-position undo-elt)) end)))
((typep undo-elt 'undo-entry-marker) ;(and (consp undo-elt) (markerp (car undo-elt)))
;; This is a marker-adjustment element (MARKER . ADJUSTMENT).
;; See if MARKER is inside the region.
(let ((alist-elt (assq (undo-entry-marker-marker undo-elt) undo-adjusted-markers)))
(unless alist-elt
(setq alist-elt (make-undo-entry-marker :marker (undo-entry-marker-marker undo-elt)
:distance (marker-position (undo-entry-marker-marker undo-elt))))
(setq undo-adjusted-markers
(cons alist-elt undo-adjusted-markers)))
(and (undo-entry-marker-distance alist-elt) ;(cdr alist-elt)
(>= (undo-entry-marker-distance alist-elt) start)
(<= (undo-entry-marker-distance alist-elt) end))))
((typep undo-elt 'undo-entry-property) ;(null (car undo-elt))
;; (nil PROPERTY VALUE BEG . END)
(and (>= (undo-entry-property-beg undo-elt) start)
(<= (undo-entry-property-end undo-elt) end)))
((typep undo-elt 'undo-entry-insertion) ;(integerp (car undo-elt))
;; (BEGIN . END)
(and (>= (undo-entry-insertion-beg undo-elt) start)
(<= (undo-entry-insertion-end undo-elt) end)))))
(defun undo-elt-crosses-region (undo-elt start end)
"Test whether UNDO-ELT crosses one edge of that region START ... END.
This assumes we have already decided that UNDO-ELT
is not *inside* the region START...END."
(cond ;; (atom undo-elt) nil)
((typep undo-elt 'undo-entry-property) ;(null (car undo-elt))
;; (nil PROPERTY VALUE BEG . END)
;;(let ((tail (nthcdr 3 undo-elt)))
(not (or (< (undo-entry-property-beg undo-elt) end)
(> (undo-entry-property-end undo-elt) start))))
((typep undo-elt 'undo-entry-insertion) ;(integerp (car undo-elt))
;; (BEGIN . END)
(not (or (< (undo-entry-insertion-beg undo-elt) end)
(> (undo-entry-insertion-end undo-elt) start))))))
;; Return the first affected buffer position and the delta for an undo element
;; delta is defined as the change in subsequent buffer positions if we *did*
;; the undo.
(defun undo-delta (undo-elt)
(cond ((typep undo-elt 'undo-entry-delete) ;(stringp (car undo-elt))
;; (TEXT . POSITION)
(cons (abs (undo-entry-delete-position undo-elt)) (length (undo-entry-delete-text undo-elt))))
((typep undo-elt 'undo-entry-insertion) ;(integerp (car undo-elt))
;; (BEGIN . END)
(cons (undo-entry-insertion-beg undo-elt) (- (undo-entry-insertion-beg undo-elt) (undo-entry-insertion-end undo-elt))))
(t
'(0 . 0))))
(defcustom undo-ask-before-discard nil
"If non-nil ask about discarding undo info for the current command.
Normally, Emacs discards the undo info for the current command if
it exceeds `undo-outer-limit'. But if you set this option
non-nil, it asks in the echo area whether to discard the info.
If you answer no, there a slight risk that Emacs might crash, so
only do it if you really want to undo the command.
This option is mainly intended for debugging. You have to be
careful if you use it for other purposes. Garbage collection is
inhibited while the question is asked, meaning that Emacs might
leak memory. So you should make sure that you do not wait
excessively long before answering the question."
:type 'boolean
:group 'undo
:version "22.1")
(define-buffer-local *undo-extra-outer-limit* 'undo-outer-limit-truncate ;;nil
"If non-nil, an extra level of size that's ok in an undo item.
We don't ask the user about truncating the undo list until the
current item gets bigger than this amount.
This variable only matters if `undo-ask-before-discard' is non-nil.")
;;(make-variable-buffer-local 'undo-extra-outer-limit)
;; When the first undo batch in an undo list is longer than
;; undo-outer-limit, this function gets called to warn the user that
;; the undo info for the current command was discarded. Garbage
;; collection is inhibited around the call, so it had better not do a
;; lot of consing.
;;(setq undo-outer-limit-function 'undo-outer-limit-truncate)
(defun undo-outer-limit-truncate (size)
(if undo-ask-before-discard
(when (or (null *undo-extra-outer-limit*)
(> size *undo-extra-outer-limit*))
;; Don't ask the question again unless it gets even bigger.
;; This applies, in particular, if the user quits from the question.
;; Such a quit quits out of GC, but something else will call GC
;; again momentarily. It will call this function again,
;; but we don't want to ask the question again.
(setf *undo-extra-outer-limit* (+ size 50000))
(if (let (*use-dialog-box* *track-mouse* *executing-kbd-macro* )
(yes-or-no-p (format nil "Buffer `~a' undo info is ~d bytes long; discard it? "
(buffer-name (current-buffer)) size)))
(progn (setf (buffer-undo-list (current-buffer)) nil)
(setf *undo-extra-outer-limit* nil)
t)
nil))
(progn
(display-warning '(undo discard-info)
(concat
(format nil "Buffer `~a' undo info was ~d bytes long.~%"
(buffer-name (current-buffer)) size)
"The undo info was discarded because it exceeded \
`undo-outer-limit'.
This is normal if you executed a command that made a huge change
to the buffer. In that case, to prevent similar problems in the
future, set `undo-outer-limit' to a value that is large enough to
cover the maximum size of normal changes you expect a single
command to make, but not so large that it might exceed the
maximum memory allotted to Emacs.
If you did not execute any such command, the situation is
probably due to a bug and you should report it.
You can disable the popping up of this buffer by adding the entry
\(undo discard-info) to the user option `warning-suppress-types'.
")
:warning)
(setf (buffer-undo-list (current-buffer)) nil)
t)))
(defcommand kill-word ((arg)
:prefix)
"Kill characters forward until encountering the end of a word.
With argument, do this that many times."
(kill-region (point) (progn (forward-word arg) (point))))
(defcommand backward-kill-word ((arg)
:prefix)
"Kill characters backward until encountering the end of a word.
With argument, do this that many times."
(kill-word (- arg)))
(defcommand backward-word ((n) :prefix)
"Move point forward ARG words (backward if ARG is negative).
Normally returns t.
If an edge of the buffer or a field boundary is reached, point is left there
and the function returns nil. Field boundaries are not noticed if
`inhibit-field-text-motion' is non-nil."
(forward-word (- n)))
(defcommand forward-word ((n) :prefix)
"Move point forward ARG words (backward if ARG is negative).
Normally returns t.
If an edge of the buffer or a field boundary is reached, point is left there
and the function returns nil. Field boundaries are not noticed if
`inhibit-field-text-motion' is non-nil."
(labels ((isaword (c)
(find c +word-constituents+ :test #'char=)))
(let ((buffer (current-buffer)))
(cond ((> n 0)
(gap-move-to buffer (buffer-point-aref buffer))
;; do it n times
(loop for i from 0 below n
while (let (p1 p2)
;; search forward for a word constituent
(setf p1 (position-if #'isaword (buffer-data buffer)
:start (buffer-point-aref buffer)))
;; search forward for a non word constituent
(when p1
(setf p2 (position-if (complement #'isaword) (buffer-data buffer) :start p1)))
(if p2
(goto-char (buffer-aref-to-char buffer p2))
(goto-char (point-max)))
p2)))
((< n 0)
(setf n (- n))
(gap-move-to buffer (buffer-point-aref buffer))
;; do it n times
(loop for i from 0 below n
for start = (buffer-gap-start buffer) then (buffer-point-aref buffer)
while (let (p1 p2)
;; search backward for a word constituent
(setf p1 (position-if #'isaword (buffer-data buffer)
:from-end t
:end start))
;; search backward for a non word constituent
(when p1
(setf p2 (position-if (complement #'isaword) (buffer-data buffer) :from-end t :end p1)))
(if p2
(goto-char (1+ (buffer-aref-to-char buffer p2)))
(goto-char (point-min)))
p2)))))))
(defvar line-number-mode nil
)
(defvar column-number-mode nil
)
(defun line-number-mode (&optional arg)
""
(warn "Unimplemented line-number-mode"))
(defun column-number-mode (&optional arg)
""
(warn "Unimplemented column-number-mode"))
(provide :lice-0.1/simple)
| 71,111 | Common Lisp | .lisp | 1,632 | 38.495098 | 128 | 0.653416 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | bb9e5a1027d8df852bce58f1a2e0931f7d2f6184004672592e5e1a6a27f7bffd | 18,481 | [
-1
] |
18,482 | text-mode.lisp | spacebat_lice/src/textmodes/text-mode.lisp | ;;; text-mode.el --- text mode, and its idiosyncratic commands
;; Copyright (C) 1985, 1992, 1994, 2002, 2003, 2004,
;; 2005, 2006 Free Software Foundation, Inc.
;; Maintainer: FSF
;; Keywords: wp
;; This file is part of GNU Emacs.
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; This package provides the fundamental text mode documented in the
;; Emacs user's manual.
;;; Code:
(in-package "LICE")
(defcustom *text-mode-hook* nil
"Normal hook run when entering Text mode and many related modes."
:type 'hook
:options '(turn-on-auto-fill turn-on-flyspell)
:group 'data)
(define-buffer-local *text-mode-variant* nil
"Non-nil if this buffer's major mode is a variant of Text mode.
Use (derived-mode-p 'text-mode) instead.")
(defvar *text-mode-syntax-table*
(let ((st (make-syntax-table)))
(modify-syntax-entry #\" :punctuation :table st)
(modify-syntax-entry #\\ :punctuation :table st)
;; We add `p' so that M-c on 'hello' leads to 'Hello' rather than 'hello'.
(modify-syntax-entry #\' :word-constituent :flags '(:prefix) :table st)
st)
"Syntax table used while in `text-mode'.")
(defvar *text-mode-map*
(let ((map (make-sparse-keymap)))
(define-key map (kbd "M-TAB") 'ispell-complete-word)
(define-key map (kbd "M-s") 'center-line)
(define-key map (kbd "M-S") 'center-paragraph)
map)
"Keymap for `text-mode'.
Many other modes, such as `mail-mode', `outline-mode' and `indented-text-mode',
inherit all the commands defined in this map.")
(defvar *text-mode*
(make-instance 'major-mode
:name "Text"
:map *text-mode-map*
:syntax-table *text-mode-syntax-table*
:hook '*text-mode-hook*
:init
(lambda ()
(setf (make-local-variable '*text-mode-variant*) t
(make-local-variable '*require-final-newline*)
*mode-require-final-newline*
(make-local-variable '*indent-line-function*)
'indent-relative)))
"Major mode for editing text written for humans to read.
In this mode, paragraphs are delimited only by blank or white lines.
You can thus get the full benefit of adaptive filling
(see the variable `adaptive-fill-mode').
\\{text-mode-map}.")
(defcommand text-mode ()
"See `*text-mode*'."
(set-major-mode '*text-mode*))
(defvar *paragraph-indent-text-mode*
(make-instance 'major-mode
:name "parindent"
:inherit-map '(*text-mode*)
:inherit-syntax '(*text-mode*)
:inherit-init '(*text-mode*)
:init (lambda ()
(paragraph-indent-minor-mode)))
"Major mode for editing text, with leading spaces starting a paragraph.
In this mode, you do not need blank lines between paragraphs
when the first line of the following paragraph starts with whitespace.
`paragraph-indent-minor-mode' provides a similar facility as a minor mode.
Special commands:
\\{text-mode-map}
Turning on Paragraph-Indent Text mode runs the normal hooks
`text-mode-hook' and `paragraph-indent-text-mode-hook'.")
(defcommand paragraph-indent-text-mode ()
"see `*paragraph-indent-text-mode*'."
(set-major-mode '*paragraph-indent-text-mode*))
(defcommand paragraph-indent-minor-mode ()
"Minor mode for editing text, with leading spaces starting a paragraph.
In this mode, you do not need blank lines between paragraphs when the
first line of the following paragraph starts with whitespace, as with
`paragraph-indent-text-mode'.
Turning on Paragraph-Indent minor mode runs the normal hook
`paragraph-indent-text-mode-hook'."
(setf (make-local-variable 'paragraph-start)
(concat "[ \t\n\f]\\|" paragraph-start))
(set (make-local-variable 'indent-line-function) 'indent-to-left-margin)
(run-hooks '*paragraph-indent-text-mode-hook*))
;;(defalias 'indented-text-mode 'text-mode)
;; This can be made a no-op once all modes that use text-mode-hook
;; are "derived" from text-mode.
(defun text-mode-hook-identify ()
"Mark that this mode has run `text-mode-hook'.
This is how `toggle-text-mode-auto-fill' knows which buffers to operate on."
(setf (make-local-variable *text-mode-variant*) t))
(add-hook '*text-mode-hook* 'text-mode-hook-identify)
(defcommand toggle-text-mode-auto-fill ()
"Toggle whether to use Auto Fill in Text mode and related modes.
This command affects all buffers that use modes related to Text mode,
both existing buffers and buffers that you subsequently create."
(let ((enable-mode (not (find 'turn-on-auto-fill *text-mode-hook*))))
(if enable-mode
(add-hook '*text-mode-hook* 'turn-on-auto-fill)
(remove-hook '*text-mode-hook* 'turn-on-auto-fill))
(dolist (buffer (buffer-list))
(with-current-buffer buffer
(if (or (eq (buffer-major-mode (current-buffer)) *text-mode*)
*text-mode-variant*)
(auto-fill-mode (if enable-mode 1 0)))))
(message "Auto Fill %s in Text modes"
(if enable-mode "enabled" "disabled"))))
(defcommand center-paragraph ()
"Center each nonblank line in the paragraph at or after point.
See `center-line' for more info."
(save-excursion
(forward-paragraph)
(or (bolp) (newline 1))
(let ((end (point)))
(backward-paragraph)
(center-region (point) end))))
(defcommand center-region ((from to)
:region-beginning :region-end)
"Center each nonblank line starting in the region.
See `center-line' for more info."
(if (> from to)
(let ((tem to))
(setq to from from tem)))
(save-excursion
(save-restriction
(narrow-to-region from to)
(goto-char from)
(while (not (eobp))
(or (save-excursion (skip-chars-forward " \t") (eolp))
(center-line))
(forward-line 1)))))
(defcommand center-line ((&optional nlines)
:raw-prefix)
"Center the line point is on, within the width specified by `fill-column'.
This means adjusting the indentation so that it equals
the distance between the end of the text and `fill-column'.
The argument NLINES says how many lines to center."
(if nlines (setq nlines (prefix-numeric-value nlines)))
(while (not (eq nlines 0))
(save-excursion
(let ((lm (current-left-margin))
line-length)
(beginning-of-line)
(delete-horizontal-space)
(end-of-line)
(delete-horizontal-space)
(setq line-length (current-column))
(if (> (- fill-column lm line-length) 0)
(indent-line-to
(+ lm (/ (- fill-column lm line-length) 2))))))
(cond ((null nlines)
(setq nlines 0))
((> nlines 0)
(setq nlines (1- nlines))
(forward-line 1))
((< nlines 0)
(setq nlines (1+ nlines))
(forward-line -1)))))
;;; arch-tag: a07ccaad-da13-4d7b-9c61-cd04f5926aab
;;; text-mode.el ends here
| 7,536 | Common Lisp | .lisp | 175 | 38.04 | 79 | 0.680535 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d3d499d2a1f024950ad50e17cfb0cc72214c89c7222427d71bf5124ca321f16e | 18,482 | [
-1
] |
18,483 | easy-mmode.lisp | spacebat_lice/src/emacs-lisp/easy-mmode.lisp | ;;; easy-mmode.el --- easy definition for major and minor modes
;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005,
;; 2006 Free Software Foundation, Inc.
;; Author: Georges Brun-Cottan <[email protected]>
;; Maintainer: Stefan Monnier <[email protected]>
;; Keywords: extensions lisp
;; This file is part of GNU Emacs.
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; Minor modes are useful and common. This package makes defining a
;; minor mode easy, by focusing on the writing of the minor mode
;; functionalities themselves. Moreover, this package enforces a
;; conventional naming of user interface primitives, making things
;; natural for the minor-mode end-users.
;; For each mode, easy-mmode defines the following:
;; <mode> : The minor mode predicate. A buffer-local variable.
;; <mode>-map : The keymap possibly associated to <mode>.
;; see `define-minor-mode' documentation
;;
;; eval
;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
;; to check the result before using it.
;; The order in which minor modes are installed is important. Keymap
;; lookup proceeds down minor-mode-map-alist, and the order there
;; tends to be the reverse of the order in which the modes were
;; installed. Perhaps there should be a feature to let you specify
;; orderings.
;; Additionally to `define-minor-mode', the package provides convenient
;; ways to define keymaps, and other helper functions for major and minor modes.
;;; Code:
(in-package "LICE")
(defun easy-mmode-pretty-mode-name (mode &optional lighter)
"Turn the symbol MODE into a string intended for the user.
If provided, LIGHTER will be used to help choose capitalization by,
replacing its case-insensitive matches with the literal string in LIGHTER."
(let* ((case-fold-search t)
;; Produce "Foo-Bar minor mode" from foo-bar-minor-mode.
(name (concat (replace-regexp-in-string
;; If the original mode name included "-minor" (some
;; of them don't, e.g. auto-revert-mode), then
;; replace it with " minor".
"-Minor" " minor"
;; "foo-bar-minor" -> "Foo-Bar-Minor"
(capitalize (replace-regexp-in-string
;; "foo-bar-minor-mode" -> "foo-bar-minor"
"-mode\\'" "" (symbol-name mode))))
" mode")))
(el:if (not (stringp lighter)) name
;; Strip leading and trailing whitespace from LIGHTER.
(setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
lighter))
;; Replace any (case-insensitive) matches for LIGHTER in NAME
;; with a literal LIGHTER. E.g., if NAME is "Iimage mode" and
;; LIGHTER is " iImag", then this will produce "iImage mode".
;; (LIGHTER normally comes from the mode-line string passed to
;; define-minor-mode, and normally includes at least one leading
;; space.)
(replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
;;;###autoload
;; FIXME: when aliases really work maybe uncomment this
;;(defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
;;;###autoload
(defmacro define-minor-mode ((mode doc ;;&optional init-value lighter keymap
&key init-value lighter ((:global globalp)) extra-args set
initialize group type (require t) keymap
;; FIXME: in the original any keys not
;; above were added to extra-keywords,
;; but i'm too lazy to do it that way
;; atm. -sabetts
extra-keywords)
&body body)
"Define a new minor mode MODE.
This function defines the associated control variable MODE, keymap MODE-map,
and toggle command MODE.
DOC is the documentation for the mode toggle command.
Optional INIT-VALUE is the initial value of the mode's variable.
Optional LIGHTER is displayed in the modeline when the mode is on.
Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
If it is a list, it is passed to `easy-mmode-define-keymap'
in order to build a valid keymap. It's generally better to use
a separate MODE-map variable than to use this argument.
The above three arguments can be skipped if keyword arguments are
used (see below).
BODY contains code to execute each time the mode is activated or deactivated.
It is executed after toggling the mode,
and before running the hook variable `mode-HOOK'.
Before the actual body code, you can write keyword arguments (alternating
keywords and values). These following keyword arguments are supported (other
keywords will be passed to `defcustom' if the minor mode is global):
:group GROUP Custom group name to use in all generated `defcustom' forms.
Defaults to MODE without the possible trailing \"-mode\".
Don't use this default group name unless you have written a
`defgroup' to define that group properly.
:global GLOBAL If non-nil specifies that the minor mode is not meant to be
buffer-local, so don't make the variable MODE buffer-local.
By default, the mode is buffer-local.
:init-value VAL Same as the INIT-VALUE argument.
:lighter SPEC Same as the LIGHTER argument.
:keymap MAP Same as the KEYMAP argument.
:require SYM Same as in `defcustom'.
For example, you could write
(define-minor-mode foo-mode \"If enabled, foo on you!\"
:lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
...BODY CODE...)"
(let* ((last-message (current-message))
(mode-name (symbol-name mode))
(pretty-name (easy-mmode-pretty-mode-name mode lighter))
(hook (intern (concat mode-name "-hook")))
(hook-on (intern (concat mode-name "-on-hook")))
(hook-off (intern (concat mode-name "-off-hook")))
keymap-sym)
;; ;; Check keys.
;; (while (keywordp (setq keyw (car body)))
;; (setq body (cdr body))
;; (case keyw
;; (:init-value (setq init-value (pop body)))
;; (:lighter (setq lighter (pop body)))
;; (:global (setq globalp (pop body)))
;; (:extra-args (setq extra-args (pop body)))
;; (:set (setq set (list :set (pop body))))
;; (:initialize (setq initialize (list :initialize (pop body))))
;; (:group (setq group (nconc group (list :group (pop body)))))
;; (:type (setq type (list :type (pop body))))
;; (:require (setq require (pop body)))
;; (:keymap (setq keymap (pop body)))
;; (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
;; XXX: :group can occur many times in the original. here only once.
(setf keymap-sym (if (and keymap (symbolp keymap)) keymap
(intern (concat mode-name "-MAP")))
set `(:set ,(or set 'custom-set-minor-mode))
initialize `(:initialize ,(or initialize 'custom-initialize-default))
;; We might as well provide a best-guess default group.
group `(:group (or ,group '(intern (replace-regexp-in-string
"-mode\\'" "" mode-name))))
type `(:type ,(or type 'boolean)))
`(progn
;; Define the variable to enable or disable the mode.
,(if (not globalp)
`(progn
(define-buffer-local ,mode ,init-value ,(format "Non-nil if %s is enabled.
Use the command `%s' to change this variable." pretty-name mode))
(make-variable-buffer-local ',mode))
(let ((base-doc-string
(concat "Non-nil if %s is enabled.
See the command `%s' for a description of this minor-mode."
(if body "
Setting this variable directly does not take effect;
use either \\[customize] or the function `%s'."))))
`(defcustom ,mode ,init-value
,(format base-doc-string pretty-name mode mode)
,@set
,@initialize
,@group
,@type
,@(unless (eq require t) `(:require ,require))
,@(nreverse extra-keywords))))
;; The actual function.
(defcommand ,mode ((&optional arg ,@extra-args)
:raw-prefix)
,(or doc
(format nil (concat "Toggle ~a on or off.
Interactively, with no prefix argument, toggle the mode.
With universal prefix ARG turn mode on.
With zero or negative ARG turn mode off.
\\{~s}") pretty-name keymap-sym))
;; Use `toggle' rather than (if ,mode 0 1) so that using
;; repeat-command still does the toggling correctly.
;;(interactive (list (or current-prefix-arg 'toggle)))
(unless arg (setf arg 'toggle))
(setq ,mode
(cond
((eq arg 'toggle) (not ,mode))
(arg (> (prefix-numeric-value arg) 0))
(t
(el:if (null ,mode) t
(message
"Toggling %s off; better pass an explicit argument."
',mode)
nil))))
,@body
;; The on/off hooks are here for backward compatibility only.
(run-hooks ',hook (if ,mode ',hook-on ',hook-off))
(if (called-interactively-p)
(progn
,(if globalp `(customize-mark-as-set ',mode))
;; Avoid overwriting a message shown by the body,
;; but do overwrite previous messages.
(unless ,(and (current-message)
(not (equal last-message (current-message))))
(message ,(format "~a ~~aabled" pretty-name)
(if ,mode "en" "dis")))))
(force-mode-line-update)
;; Return the new setting.
,mode)
;; XXX: What do we do with this? -sabetts
;; ;; Autoloading a define-minor-mode autoloads everything
;; ;; up-to-here.
;; :autoload-end
;; Define the minor-mode keymap.
,(unless (symbolp keymap) ;nil is also a symbol.
`(defvar ,keymap-sym
(let ((m ,keymap))
(cond ((keymapp m) m)
((listp m) (easy-mmode-define-keymap m))
(t (error "Invalid keymap %S" ,keymap))))
,(format nil "Keymap for `~s'." mode-name)))
(add-minor-mode ',mode ',lighter
,(if keymap keymap-sym
`(if (boundp ',keymap-sym)
(symbol-value ',keymap-sym)))))))
;;;
;;; make global minor mode
;;;
;;;###autoload
(defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
;;;###autoload
(defmacro define-global-minor-mode (global-mode mode turn-on &key group global extra-keywords)
"Make GLOBAL-MODE out of the buffer-local minor MODE.
TURN-ON is a function that will be called with no args in every buffer
and that should try to turn MODE on if applicable for that buffer.
KEYS is a list of CL-style keyword arguments. As the minor mode
defined by this function is always global, any :global keyword is
ignored. Other keywords have the same meaning as in `define-minor-mode',
which see. In particular, :group specifies the custom group.
The most useful keywords are those that are passed on to the
`defcustom'. It normally makes no sense to pass the :lighter
or :keymap keywords to `define-global-minor-mode', since these
are usually passed to the buffer-local version of the minor mode.
If MODE's set-up depends on the major mode in effect when it was
enabled, then disabling and reenabling MODE should make MODE work
correctly with the current major mode. This is important to
prevent problems with derived modes, that is, major modes that
call another major mode in their body."
(let* ((global-mode-name (symbol-name global-mode))
(pretty-name (easy-mmode-pretty-mode-name mode))
(pretty-global-name (easy-mmode-pretty-mode-name global-mode))
(MODE-buffers (intern (concat global-mode-name "-buffers")))
(MODE-enable-in-buffers
(intern (concat global-mode-name "-enable-in-buffers")))
(MODE-check-buffers
(intern (concat global-mode-name "-check-buffers")))
(MODE-cmhh (intern (concat global-mode-name "-cmhh")))
(MODE-major-mode (intern (concat (symbol-name mode) "-major-mode"))))
;; FIXME: :group can occur multiple times in the emacs version but not in this one.
;; We might as well provide a best-guess default group.
(setq group
`(:group ,(or group '(intern (replace-regexp-in-string
"-mode\\'" "" (symbol-name mode))))))
`(progn
(defvar ,MODE-major-mode nil)
(make-variable-buffer-local ',MODE-major-mode)
;; The actual global minor-mode
(define-minor-mode ,global-mode
,(format nil "Toggle ~a in every buffer.
With prefix ARG, turn ~a on if and only if ARG is positive.
~a is actually not turned on in every buffer but only in those
in which `~s' turns it on."
pretty-name pretty-global-name pretty-name turn-on)
(:global t ,@group ,@(nreverse extra-keywords))
;; Setup hook to handle future mode changes and new buffers.
(el:if ,global-mode
(progn
(add-hook 'after-change-major-mode-hook
',MODE-enable-in-buffers)
(add-hook 'find-file-hook ',MODE-check-buffers)
(add-hook 'change-major-mode-hook ',MODE-cmhh))
(remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
(remove-hook 'find-file-hook ',MODE-check-buffers)
(remove-hook 'change-major-mode-hook ',MODE-cmhh))
;; Go through existing buffers.
(dolist (buf (buffer-list))
(with-current-buffer buf
(if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
;; FIXME: when we figure out autoload stuff maybe uncomment this -sabetts
;; ;; Autoloading define-global-minor-mode autoloads everything
;; ;; up-to-here.
;; :autoload-end
;; List of buffers left to process.
(defvar ,MODE-buffers nil)
;; The function that calls TURN-ON in each buffer.
(defun ,MODE-enable-in-buffers ()
(dolist (buf ,MODE-buffers)
(when (buffer-live-p buf)
(with-current-buffer buf
(el:if ,mode
(unless (eq ,MODE-major-mode major-mode)
(,mode -1)
(,turn-on)
(setq ,MODE-major-mode major-mode))
(,turn-on)
(setq ,MODE-major-mode major-mode))))))
(put ',MODE-enable-in-buffers 'definition-name ',global-mode)
(defun ,MODE-check-buffers ()
(,MODE-enable-in-buffers)
(setq ,MODE-buffers nil)
(remove-hook 'post-command-hook ',MODE-check-buffers))
(put ',MODE-check-buffers 'definition-name ',global-mode)
;; The function that catches kill-all-local-variables.
(defun ,MODE-cmhh ()
(add-to-list ',MODE-buffers (current-buffer))
(add-hook 'post-command-hook ',MODE-check-buffers))
(put ',MODE-cmhh 'definition-name ',global-mode))))
;;;
;;; easy-mmode-defmap
;;;
(if (fboundp 'set-keymap-parents)
(defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
(defun easy-mmode-set-keymap-parents (m parents)
(set-keymap-parent
m
(cond
((not (consp parents)) parents)
((not (cdr parents)) (car parents))
(t (let ((m (copy-keymap (pop parents))))
(easy-mmode-set-keymap-parents m parents)
m))))))
;;;###autoload
(defun easy-mmode-define-keymap (bs &optional name m args)
"Return a keymap built from bindings BS.
BS must be a list of (KEY . BINDING) where
KEY and BINDINGS are suitable for `define-key'.
Optional NAME is passed to `make-sparse-keymap'.
Optional map M can be used to modify an existing map.
ARGS is a list of additional keyword arguments."
(let (inherit dense)
(while args
(let ((key (pop args))
(val (pop args)))
(case key
(:name (setq name val))
(:dense (setq dense val))
(:inherit (setq inherit val))
(:group)
(t (message "Unknown argument %s in defmap" key)))))
(unless (keymapp m)
(setq bs (append m bs))
(setq m (if dense (make-keymap name) (make-sparse-keymap name))))
(dolist (b bs)
(let ((keys (car b))
(binding (cdr b)))
(dolist (key (if (consp keys) keys (list keys)))
(cond
((symbolp key)
(substitute-key-definition key binding m *global-map*))
((null binding)
(unless (keymapp (lookup-key m key)) (define-key m key binding)))
((let ((o (lookup-key m key)))
(or (null o) (numberp o) (eq o 'undefined)))
(define-key m key binding))))))
(cond
((keymapp inherit) (set-keymap-parent m inherit))
((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
m))
;;;###autoload
(defmacro easy-mmode-defmap (m bs doc &rest args)
`(defconst ,m
(easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
,doc))
;;;
;;; easy-mmode-defsyntax
;;;
(defun easy-mmode-define-syntax (css args)
(let ((st (make-syntax-table (plist-get args :copy)))
(parent (plist-get args :inherit)))
(dolist (cs css)
(let ((char (car cs))
(syntax (cdr cs)))
(if (sequencep char)
(mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
(modify-syntax-entry char syntax st))))
(if parent (set-char-table-parent
st (if (symbolp parent) (symbol-value parent) parent)))
st))
;;;###autoload
(defmacro easy-mmode-defsyntax (st css doc &rest args)
"Define variable ST as a syntax-table.
CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
`(progn
(autoload 'easy-mmode-define-syntax "easy-mmode")
(defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
;;;
;;; easy-mmode-define-navigation
;;;
(defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
"Define BASE-next and BASE-prev to navigate in the buffer.
RE determines the places the commands should move point to.
NAME should describe the entities matched by RE. It is used to build
the docstrings of the two functions.
BASE-next also tries to make sure that the whole entry is visible by
searching for its end (by calling ENDFUN if provided or by looking for
the next entry) and recentering if necessary.
ENDFUN should return the end position (with or without moving point).
NARROWFUN non-nil means to check for narrowing before moving, and if
found, do widen first and then call NARROWFUN with no args after moving."
(let* ((base-name (symbol-name base))
(prev-sym (intern (concat base-name "-prev")))
(next-sym (intern (concat base-name "-next")))
(check-narrow-maybe
(when narrowfun
'(setq was-narrowed
(prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
(widen)))))
(re-narrow-maybe (when narrowfun
`(when was-narrowed (,narrowfun)))))
(unless name (setq name base-name))
`(progn
(add-to-list 'debug-ignored-errors
,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
(defun ,next-sym (&optional count)
,(format "Go to the next COUNT'th %s." name)
(interactive)
(unless count (setq count 1))
(el:if (< count 0) (,prev-sym (- count))
(if (looking-at ,re) (setq count (1+ count)))
(let (was-narrowed)
,check-narrow-maybe
(if (not (re-search-forward ,re nil t count))
(if (looking-at ,re)
(goto-char (or ,(if endfun `(,endfun)) (point-max)))
(error "No next %s" ,name))
(goto-char (match-beginning 0))
(when (and (eq (current-buffer) (window-buffer (selected-window)))
(interactive-p))
(let ((endpt (or (save-excursion
,(if endfun `(,endfun)
`(re-search-forward ,re nil t 2)))
(point-max))))
(unless (pos-visible-in-window-p endpt nil t)
(recenter '(0))))))
,re-narrow-maybe)))
(put ',next-sym 'definition-name ',base)
(defun ,prev-sym (&optional count)
,(format "Go to the previous COUNT'th %s" (or name base-name))
(interactive)
(unless count (setq count 1))
(if (< count 0) (,next-sym (- count))
(let (was-narrowed)
,check-narrow-maybe
(unless (re-search-backward ,re nil t count)
(error "No previous %s" ,name))
,re-narrow-maybe)))
(put ',prev-sym 'definition-name ',base))))
(provide 'easy-mmode)
;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
;;; easy-mmode.el ends here | 20,664 | Common Lisp | .lisp | 456 | 39.605263 | 94 | 0.657618 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d4ab8d63f9e027d5d5bf2e775e23255bf3a157b0375cbe900477da4498243e6e | 18,483 | [
-1
] |
18,484 | lisp-mode.lisp | spacebat_lice/src/emacs-lisp/lisp-mode.lisp | ;;; This is a cheap, pigeon lisp mode. One Day, it'll be replaced with
;;; something amazing.
(in-package "LICE")
(defcustom *defun-prompt-regexp* nil
"*If non-nil, a regexp to ignore before a defun.
This is only necessary if the opening paren or brace is not in column 0.
See function `beginning-of-defun'."
:type '(choice (const nil)
regexp)
:group 'lisp)
(defvar *emacs-lisp-mode-syntax-table*
(let ((table (make-syntax-table)))
(loop for i from (char-code #\0) to (char-code #\9) do
(modify-syntax-entry (code-char i) :symbol-constituent :table table))
(loop for i from (char-code #\A) to (char-code #\Z) do
(modify-syntax-entry (code-char i) :symbol-constituent :table table))
(loop for i from (char-code #\a) to (char-code #\z) do
(modify-syntax-entry (code-char i) :symbol-constituent :table table))
(loop for c in '(#\{ #\| #\} #\~ #| 127 |#) do
(modify-syntax-entry c :symbol-constituent :table table))
(modify-syntax-entry #\Space :whitespace :table table)
(modify-syntax-entry #\Tab :whitespace :table table)
;; XXX what is \f ? (modify-syntax-entry ?\f :whitespace :table table)
(modify-syntax-entry #\Newline :end-comment :table table)
;; This is probably obsolete since nowadays such features use overlays.
;; ;; Give CR the same syntax as newline, for selective-display.
;; (modify-syntax-entry ?\^m "> " :table table)
(modify-syntax-entry #\; :comment :table table)
(modify-syntax-entry #\` :quote :table table)
(modify-syntax-entry #\' :quote :table table)
(modify-syntax-entry #\, :quote :table table)
(modify-syntax-entry #\@ :quote :table table)
;; Used to be singlequote; changed for flonums.
(modify-syntax-entry #\. :symbol-constituent :table table)
(modify-syntax-entry #\# :quote :table table)
(modify-syntax-entry #\" :string :table table)
(modify-syntax-entry #\\ :escape :table table)
(modify-syntax-entry #\( :open :extra #\) :table table)
(modify-syntax-entry #\) :close :extra #\( :table table)
(modify-syntax-entry #\[ :open :extra #\] :table table)
(modify-syntax-entry #\] :close :extra #\[ :table table)
table))
(defvar *lisp-mode-syntax-table*
(let ((table (copy-syntax-table *emacs-lisp-mode-syntax-table*)))
(modify-syntax-entry #\[ :symbol-constituent :table table)
(modify-syntax-entry #\] :symbol-constituent :table table)
(modify-syntax-entry #\# :quote :flags '(:comment-start-first :comment-end-second :comment-style) :table table)
(modify-syntax-entry #\| :string :flags '(:comment-start-second :comment-end-first :comment-style :comment-nested) :table table)
table))
(defvar *lisp-interaction-mode*
(make-instance 'major-mode
:name "Lisp Interaction"
:map (let ((m (make-sparse-keymap)))
(define-key m (kbd "C-j") 'eval-print-last-sexp)
(define-key m (make-key :char #\Tab) 'lisp-indent-line)
(define-key m (kbd "C-i") 'lisp-indent-line)
(define-key m (kbd "C-M-q") 'indent-sexp)
(define-key m (kbd "C-M-x") 'eval-defun)
m)
:syntax-table *lisp-mode-syntax-table*)
"Lisp mode.")
(defvar *lisp-mode*
(make-instance 'major-mode
:name "Lisp"
:map (let ((m (make-sparse-keymap)))
(define-key m (make-key :char #\Tab) 'lisp-indent-line)
(define-key m (kbd "C-i") 'lisp-indent-line)
(define-key m (kbd "C-M-q") 'indent-sexp)
(define-key m (kbd "C-M-x") 'eval-defun)
m)
:syntax-table *lisp-mode-syntax-table*))
(defcommand lisp-mode ()
"Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
Commands:
Delete converts tabs to spaces as it moves back.
Blank lines separate paragraphs. Semicolons start comments.
\\{lisp-mode-map}
Note that `run-lisp' may be used either to start an inferior Lisp job
or to switch back to an existing one.
Entry to this mode calls the value of `lisp-mode-hook'
if that value is non-nil."
(set-major-mode '*lisp-mode*))
(defun buffer-end (arg)
"Return the \"far end\" position of the buffer, in direction ARG.
If ARG is positive, that's the end of the buffer.
Otherwise, that's the beginning of the buffer."
(if (> arg 0) (point-max) (point-min)))
(defvar *end-of-defun-function* nil
"If non-nil, function for function `end-of-defun' to call.
This is used to find the end of the defun instead of using the normal
recipe (see `end-of-defun'). Major modes can define this if the
normal method is not appropriate.")
(defcommand end-of-defun ((&optional arg)
:prefix)
"Move forward to next end of defun.
With argument, do it that many times.
Negative argument -N means move back to Nth preceding end of defun.
An end of a defun occurs right after the close-parenthesis that
matches the open-parenthesis that starts a defun; see function
`beginning-of-defun'.
If variable `*end-of-defun-function*' is non-nil, its value
is called as a function to find the defun's end."
(or (not (eq *this-command* 'end-of-defun))
(eq *last-command* 'end-of-defun)
;;XXX (and transient-mark-mode mark-active)
(push-mark))
(if (or (null arg) (= arg 0)) (setq arg 1))
(if *end-of-defun-function*
(if (> arg 0)
(dotimes (i arg)
(funcall *end-of-defun-function*))
;; Better not call beginning-of-defun-function
;; directly, in case it's not defined.
(beginning-of-defun (- arg)))
(let ((first t))
(while (and (> arg 0) (< (point) (point-max)))
(let ((pos (point)))
(while (progn
(if (and first
(progn
(end-of-line 1)
(beginning-of-defun-raw 1)))
nil
(progn
(or (bobp) (forward-char -1))
(beginning-of-defun-raw -1)))
(setq first nil)
(forward-list 1)
(skip-whitespace-forward)
(if (looking-at ";|\\n") ; XXX: used to be comment starter \\s<
(forward-line 1))
(<= (point) pos))
(message "point: ~d ~d" (point) pos)))
(setq arg (1- arg)))
(while (< arg 0)
(let ((pos (point)))
(beginning-of-defun-raw 1)
(forward-sexp 1)
(forward-line 1)
(if (>= (point) pos)
(if (beginning-of-defun-raw 2)
(progn
(forward-list 1)
(skip-whitespace-forward)
(if (looking-at ";|\\n") ; XXX: used to be comment starter \\s<
(forward-line 1)))
(goto-char (point-min)))))
(setq arg (1+ arg))))))
(defvar *forward-sexp-function* nil
"If non-nil, `forward-sexp' delegates to this function.
Should take the same arguments and behave similarly to `forward-sexp'.")
(defcommand forward-sexp ((&optional (arg 1))
:prefix)
"Move forward across one balanced expression (sexp).
With ARG, do it that many times. Negative arg -N means
move backward across N balanced expressions."
(if *forward-sexp-function*
(funcall *forward-sexp-function* arg)
(progn
(goto-char (or (scan-sexps (point) arg) (buffer-end arg)))
(if (< arg 0) (backward-prefix-chars)))))
(defcommand backward-sexp ((&optional (arg 1))
:prefix)
"Move backward across one balanced expression (sexp).
With ARG, do it that many times. Negative arg -N means
move forward across N balanced expressions."
(forward-sexp (- arg)))
(defcommand forward-list ((&optional arg)
:prefix)
"Move forward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move backward across N groups of parentheses."
(or arg (setq arg 1))
(goto-char (or (scan-lists (point) arg 0) (buffer-end arg))))
(defcommand backward-list ((&optional arg)
:prefix)
"Move backward across one balanced group of parentheses.
With ARG, do it that many times.
Negative arg -N means move forward across N groups of parentheses."
(or arg (setq arg 1))
(forward-list (- arg)))
(defcommand eval-last-sexp ()
(let ((start (point))
end)
;; some nice'n'gross point handling
(backward-sexp)
(setf end (point))
(goto-char start)
(handler-case (eval-echo (buffer-substring-no-properties start end))
(error (c) (message "Eval error: ~a" c)))))
(defcommand eval-print-last-sexp ()
(let ((start (point))
end)
;; some nice'n'gross point handling
(backward-sexp)
(setf end (point))
(goto-char start)
(handler-case (eval-print (buffer-substring-no-properties start end))
(error (c) (message "Eval error: ~a" c)))))
(defcommand lisp-interaction-mode ()
(set-major-mode '*lisp-interaction-mode*))
(defvar *lisp-indent-offset* nil
"If non-nil, indent second line of expressions that many more columns.")
(defvar *lisp-indent-function* 'common-lisp-indent-function)
(defcommand lisp-indent-line ((&optional whole-exp)
:raw-prefix)
"Indent current line as Lisp code.
With argument, indent any additional lines of the same expression
rigidly along with this one."
(let ((indent (calculate-lisp-indent)) shift-amt end
(pos (- (point-max) (point)))
(beg (progn (beginning-of-line) (point))))
(skip-whitespace-forward)
(if (or (null indent) (looking-at ";;;")) ; XXX: used to be comment starter \\s<
;; Don't alter indentation of a ;;; comment line
;; or a line that starts in a string.
(goto-char (- (point-max) pos))
(progn
(if (and (looking-at ";") (not (looking-at ";;"))) ; XXX: used to be comment starter \\s<
;; Single-semicolon comment lines should be indented
;; as comment lines, not as code.
(progn (indent-for-comment) (forward-char -1))
(progn
(if (listp indent) (setq indent (car indent)))
(setq shift-amt (- indent (current-column)))
(if (zerop shift-amt)
nil
(progn
(delete-region beg (point))
(indent-to indent)))))
;; If initial point was within line's indentation,
;; position after the indentation. Else stay at same point in text.
(if (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos)))
;; If desired, shift remaining lines of expression the same amount.
(and whole-exp (not (zerop shift-amt))
(save-excursion
(goto-char beg)
(message "this111")
(forward-sexp 1)
(message "done 11")
(setq end (point))
(goto-char beg)
(forward-line 1)
(setq beg (point))
(> end beg))
(indent-code-rigidly beg end shift-amt))))))
(defvar *calculate-lisp-indent-last-sexp*)
(defun calculate-lisp-indent (&optional parse-start)
"Return appropriate indentation for current line as Lisp code.
In usual case returns an integer: the column to indent to.
If the value is nil, that means don't change the indentation
because the line starts inside a string.
The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
This means that following lines at the same level of indentation
should not necessarily be indented the same as this line.
Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
is the buffer position of the start of the containing expression."
(save-excursion
(beginning-of-line)
(let ((indent-point (point))
state paren-depth
;; setting this to a number inhibits calling hook
(desired-indent nil)
(retry t)
*calculate-lisp-indent-last-sexp* containing-sexp)
(if parse-start
(goto-char parse-start)
(beginning-of-defun))
;; Find outermost containing sexp
(while (< (point) indent-point)
(message "flitz ~d" indent-point (point))
(setq state (parse-partial-sexp (point) indent-point :target-depth 0)))
;; Find innermost containing sexp
(while (and retry
state
(> (setq paren-depth (parse-state-depth state)) 0))
(setq retry nil)
(setq *calculate-lisp-indent-last-sexp* (parse-state-this-level-start state))
(message "gaah ~d" *calculate-lisp-indent-last-sexp*)
(setq containing-sexp (parse-state-prev-level-start state))
;; Position following last unclosed open.
(goto-char (1+ containing-sexp))
;; Is there a complete sexp since then?
(if (and *calculate-lisp-indent-last-sexp*
(> *calculate-lisp-indent-last-sexp* (point)))
;; Yes, but is there a containing sexp after that?
(let ((peek (parse-partial-sexp *calculate-lisp-indent-last-sexp*
indent-point :target-depth 0)))
(if (setq retry (parse-state-prev-level-start peek)) (setq state peek)))))
(message "retry ~a" retry)
(if retry
nil
;; Innermost containing sexp found
(progn
(goto-char (1+ containing-sexp))
(if (not *calculate-lisp-indent-last-sexp*)
;; indent-point immediately follows open paren.
;; Don't call hook.
(setq desired-indent (current-column))
(progn
;; Find the start of first element of containing sexp.
(parse-partial-sexp (point) *calculate-lisp-indent-last-sexp* :target-depth 0 :stop-before t)
(cond ((looking-at "\\(") ; XXX used to be open \\s(
;; First element of containing sexp is a list.
;; Indent under that list.
)
((> (save-excursion (forward-line 1) (point))
*calculate-lisp-indent-last-sexp*)
;; This is the first line to start within the containing sexp.
;; It's almost certainly a function call.
(if (= (point) *calculate-lisp-indent-last-sexp*)
;; Containing sexp has nothing before this line
;; except the first element. Indent under that element.
nil
;; Skip the first element, find start of second (the first
;; argument of the function call) and indent under.
(progn (forward-sexp 1)
(parse-partial-sexp (point)
*calculate-lisp-indent-last-sexp*
:target-depth 0 :stop-before t)))
(backward-prefix-chars))
(t
;; Indent beneath first sexp on same line as
;; `*calculate-lisp-indent-last-sexp*'. Again, it's
;; almost certainly a function call.
(goto-char *calculate-lisp-indent-last-sexp*)
(beginning-of-line)
(parse-partial-sexp (point) *calculate-lisp-indent-last-sexp*
:target-depth 0 :stop-before t)
(backward-prefix-chars)))))))
;; Point is at the point to indent under unless we are inside a string.
;; Call indentation hook except when overridden by *lisp-indent-offset*
;; or if the desired indentation has already been computed.
(let ((normal-indent (current-column)))
(cond ((parse-state-in-string state)
;; Inside a string, don't change indentation.
nil)
((and (integerp *lisp-indent-offset*) containing-sexp)
;; Indent by constant offset
(goto-char containing-sexp)
(+ (current-column) *lisp-indent-offset*))
(desired-indent)
((and (boundp '*lisp-indent-function*)
*lisp-indent-function*
(not retry))
(or (funcall *lisp-indent-function* indent-point state)
normal-indent))
(t
normal-indent))))))
(defvar *beginning-of-defun-function* nil
"If non-nil, function for `beginning-of-defun-raw' to call.
This is used to find the beginning of the defun instead of using the
normal recipe (see `beginning-of-defun'). Major modes can define this
if defining `*defun-prompt-regexp*' is not sufficient to handle the mode's
needs.
The function (of no args) should go to the line on which the current
defun starts, and return non-nil, or should return nil if it can't
find the beginning.")
(defcommand beginning-of-defun-raw ((&optional (arg 1))
:prefix)
"Move point to the character that starts a defun.
This is identical to function `beginning-of-defun', except that point
does not move to the beginning of the line when `*defun-prompt-regexp*'
is non-nil.
If variable `*beginning-of-defun-function*' is non-nil, its value
is called as a function to find the defun's beginning."
(if *beginning-of-defun-function*
(if (> arg 0)
(dotimes (i arg)
(funcall *beginning-of-defun-function*))
;; Better not call *end-of-defun-function* directly, in case
;; it's not defined.
(end-of-defun (- arg)))
(progn
(when (and (< arg 0)
(not (eobp)))
(forward-char 1))
(with-match-data
(and (if *defun-prompt-regexp*
(re-search-backward (concat (if *open-paren-in-column-0-is-defun-start*
"^\\(|" "")
"(?:" *defun-prompt-regexp* ")\\(")
:error 'move :count (or arg 1))
(search-backward (format nil "~%(") ;; FIXME: doesn't match beginning of buffer
:error 'move :count (or arg 1))) ;; used to be ^\\(
(progn (goto-char (1- (match-end 0))) t))))))
(defcommand beginning-of-defun ((&optional (arg 1))
:prefix)
"Move backward to the beginning of a defun.
With ARG, do it that many times. Negative arg -N
means move forward to Nth following beginning of defun.
Returns t unless search stops due to beginning or end of buffer.
Normally a defun starts when there is a char with open-parenthesis
syntax at the beginning of a line. If `*defun-prompt-regexp*' is
non-nil, then a string which matches that regexp may precede the
open-parenthesis, and point ends up at the beginning of the line.
If variable `*beginning-of-defun-function*' is non-nil, its value
is called as a function to find the defun's beginning."
(or (not (eq *this-command* 'beginning-of-defun))
(eq *last-command* 'beginning-of-defun)
;;XXX (and transient-mark-mode mark-active)
(push-mark))
(and (beginning-of-defun-raw arg)
(progn (beginning-of-line) t)))
(defcommand indent-code-rigidly ((start end arg &optional nochange-regexp)
:region-beginning :region-end :prefix)
"Indent all lines of code, starting in the region, sideways by ARG columns.
Does not affect lines starting inside comments or strings, assuming that
the start of the region is not inside them.
Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
The last is a regexp which, if matched at the beginning of a line,
means don't indent that line."
(let (state)
(save-excursion
(goto-char end)
(setq end (point-marker))
(goto-char start)
(or (bolp)
(setq state (parse-partial-sexp (point)
(progn
(forward-line 1) (point))
:old-state state)))
(while (< (point) end)
(or (car (nthcdr 3 state))
(and nochange-regexp
(looking-at nochange-regexp))
;; If line does not start in string, indent it
(let ((indent (current-indentation)))
(delete-region (point) (progn (skip-whitespace-forward) (point)))
(or (eolp)
(indent-to (max 0 (+ indent arg)) 0))))
(setq state (parse-partial-sexp (point)
(progn
(forward-line 1) (point))
:old-state state))))))
(defcommand indent-sexp ((&optional endpos))
"Indent each line of the list starting just after point.
If optional arg ENDPOS is given, indent each line, stopping when
ENDPOS is encountered."
(let ((indent-stack (list nil))
(next-depth 0)
;; If ENDPOS is non-nil, use nil as STARTING-POINT
;; so that calculate-lisp-indent will find the beginning of
;; the defun we are in.
;; If ENDPOS is nil, it is safe not to scan before point
;; since every line we indent is more deeply nested than point is.
(starting-point (if endpos nil (point)))
(last-point (point))
last-depth bol outer-loop-done inner-loop-done state this-indent)
(or endpos
;; Get error now if we don't have a complete sexp after point.
(save-excursion (forward-sexp 1)))
(save-excursion
(setq outer-loop-done nil)
(while (if endpos (< (point) (ensure-number endpos))
(not outer-loop-done))
(setq last-depth next-depth
inner-loop-done nil)
;; Parse this line so we can learn the state
;; to indent the next line.
;; This inner loop goes through only once
;; unless a line ends inside a string.
(while (and (not inner-loop-done)
(not (setq outer-loop-done (eobp))))
(setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
:old-state state))
(setq next-depth (parse-state-depth state))
;; If the line contains a comment other than the sort
;; that is indented like code,
;; indent it now with indent-for-comment.
;; Comments indented like code are right already.
;; In any case clear the in-comment flag in the state
;; because parse-partial-sexp never sees the newlines.
(if (parse-state-in-comment state) ;;(car (nthcdr 4 state))
(progn (indent-for-comment)
(end-of-line)
(setf (parse-state-in-comment state) nil))) ;;(setcar (nthcdr 4 state) nil)))
;; If this line ends inside a string,
;; go straight to next line, remaining within the inner loop,
;; and turn off the \-flag.
(if (parse-state-in-string state) ;;(car (nthcdr 3 state))
(progn
(forward-line 1)
(setf (parse-state-in-string state) nil));;(setf (car (nthcdr 5 state)) nil))
(setq inner-loop-done t)))
(and endpos
(<= next-depth 0)
(progn
(setq indent-stack (nconc indent-stack
(make-list (- next-depth) :initial-element nil))
last-depth (- last-depth next-depth)
next-depth 0)))
(or outer-loop-done endpos
(setq outer-loop-done (<= next-depth 0)))
(if outer-loop-done
(forward-line 1)
(progn
(while (> last-depth next-depth)
(setq indent-stack (cdr indent-stack)
last-depth (1- last-depth)))
(while (< last-depth next-depth)
(setq indent-stack (cons nil indent-stack)
last-depth (1+ last-depth)))
;; Now go to the next line and indent it according
;; to what we learned from parsing the previous one.
(forward-line 1)
(setq bol (point))
(skip-whitespace-forward)
;; But not if the line is blank, or just a comment
;; (except for double-semi comments; indent them as usual).
(if (or (eobp) (looking-at "\\w|\\n")) ;; FIXME: used to be "\\s<|\\n"
nil
(progn
(if (and (car indent-stack)
(>= (car indent-stack) 0))
(setq this-indent (car indent-stack))
(let ((val (calculate-lisp-indent
(if (car indent-stack) (- (car indent-stack))
starting-point))))
(if (null val)
(setq this-indent val)
(if (integerp val)
(setf (car indent-stack)
(setq this-indent val))
(progn
(setf (car indent-stack) (- (car (cdr val))))
(setq this-indent (car val)))))))
(if (and this-indent (/= (current-column) this-indent))
(progn (delete-region bol (point))
(indent-to this-indent)))))))
(or outer-loop-done
(setq outer-loop-done (= (point) last-point))
(setq last-point (point)))))))
(defun lisp-indent-region (start end)
"Indent every line whose first char is between START and END inclusive."
(save-excursion
(let ((endmark (copy-marker end)))
(goto-char start)
(and (bolp) (not (eolp))
(lisp-indent-line))
(indent-sexp endmark)
(set-marker endmark nil))))
(defun eval-defun-1 (form)
"Treat some expressions specially.
Reset the `defvar' and `defcustom' variables to the initial value.
Reinitialize the face according to the `defface' specification."
;; The code in edebug-defun should be consistent with this, but not
;; the same, since this gets a macroexpended form.
(cond ((not (listp form))
form)
((and (eq (car form) 'defvar)
(cdr-safe (cdr-safe form))
(boundp (cadr form)))
;; Force variable to be re-set.
`(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
(setf ,(nth 1 form) ,(nth 2 form)))) ;; used to be setq-default
;; `defcustom' is now macroexpanded to
;; `custom-declare-variable' with a quoted value arg.
((and (eq (car form) 'custom-declare-variable)
(boundp (eval (nth 1 form)))) ;; used to be default-boundp
;; Force variable to be bound.
;; XXX: we can't handle defcustom
;;(set-default (eval (nth 1 form)) (eval (nth 1 (nth 2 form))))
form)
;; `defface' is macroexpanded to `custom-declare-face'.
((eq (car form) 'custom-declare-face)
;; Reset the face.
;; XXX: what do we do with this?
;; (setq face-new-frame-defaults
;; (assq-delete-all (eval (nth 1 form)) face-new-frame-defaults))
;; (put (eval (nth 1 form)) 'face-defface-spec nil)
;; ;; Setting `customized-face' to the new spec after calling
;; ;; the form, but preserving the old saved spec in `saved-face',
;; ;; imitates the situation when the new face spec is set
;; ;; temporarily for the current session in the customize
;; ;; buffer, thus allowing `face-user-default-spec' to use the
;; ;; new customized spec instead of the saved spec.
;; ;; Resetting `saved-face' temporarily to nil is needed to let
;; ;; `defface' change the spec, regardless of a saved spec.
;; (prog1 `(prog1 ,form
;; (put ,(nth 1 form) 'saved-face
;; ',(get (eval (nth 1 form)) 'saved-face))
;; (put ,(nth 1 form) 'customized-face
;; ,(nth 2 form)))
;; (put (eval (nth 1 form)) 'saved-face nil))
)
((eq (car form) 'progn)
(cons 'progn (mapcar 'eval-defun-1 (cdr form))))
(t form)))
(defcommand eval-defun-2 ()
"Evaluate defun that point is in or before.
The value is displayed in the minibuffer.
If the current defun is actually a call to `defvar',
then reset the variable using the initial value expression
even if the variable already has some other value.
\(Normally `defvar' does not change the variable's value
if it already has a value.\)
With argument, insert value in current buffer after the defun.
Return the result of evaluation."
(let* ((*debug-on-error* *eval-expression-debug-on-error*)
(*print-length* *eval-expression-print-length*)
(*print-level* *eval-expression-print-level*)
;; FIXME: accum the eval/compiler output and i guess do
;; something with it, cept in this case we don't.
(*debug-io* (make-string-output-stream))
(*standard-output* *debug-io*)
(*error-output* *debug-io*))
(save-excursion
;; FIXME: In gnu emacs eval-region handles recording which file defines
;; a function or variable. How do we do that in CL?
(let ( ;;XXX (standard-output t)
beg end form)
;; Read the form from the buffer, and record where it ends.
(save-excursion
(end-of-defun)
(beginning-of-defun)
(setq beg (point))
(setq form (read-from-buffer))
(setq end (point)))
;; Alter the form if necessary. FIXME: we don't macroexpand
;; but really we want to macroexpand down to defvar (and
;; friends) which could be several layers of expansion
;; down. We don't want to go all the way since defvar is
;; itself a macro.
(setq form (eval-defun-1 form ;; (macroexpand form)
))
(eval form)))))
(defcommand eval-defun ((edebug-it)
:prefix)
"Evaluate the top-level form containing point, or after point.
If the current defun is actually a call to `defvar' or `defcustom',
evaluating it this way resets the variable using its initial value
expression even if the variable already has some other value.
\(Normally `defvar' and `defcustom' do not alter the value if there
already is one.)
If `eval-expression-debug-on-error' is non-nil, which is the default,
this command arranges for all errors to enter the debugger.
With a prefix argument, instrument the code for Edebug.
If acting on a `defun' for FUNCTION, and the function was
instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
instrumented, just FUNCTION is printed.
If not acting on a `defun', the result of evaluation is displayed in
the minibuffer. This display is controlled by the variables
`eval-expression-print-length' and `eval-expression-print-level',
which see."
;; FIXME: edebug?
(declare (ignore edebug-it))
(cond ;; (edebug-it
;; (require 'edebug)
;; (eval-defun (not edebug-all-defs)))
(t
(if (null *eval-expression-debug-on-error*)
(eval-defun-2)
(let ((old-value (gensym "t")) new-value value)
(let ((*debug-on-error* old-value))
(setq value (eval-defun-2))
(setq new-value *debug-on-error*))
(unless (eq old-value new-value)
(setq *debug-on-error* new-value))
value)))))
(provide :lice-0.1/lisp-mode) | 30,949 | Common Lisp | .lisp | 662 | 37.699396 | 132 | 0.606688 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 000f7a17db5501145794ba33b8b072cbf8cb95d9a03e479edb8431a48e186d47 | 18,484 | [
-1
] |
18,485 | dissociate.lisp | spacebat_lice/src/play/dissociate.lisp | ;;; dissociate.lisp --- scramble text amusingly for Emacs
;; Copyright (C) 1985, 2002, 2003, 2004, 2005,
;; 2006 Free Software Foundation, Inc.
;; Maintainer: FSF
;; Keywords: games
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; The single entry point, `dissociated-press', applies a travesty
;; generator to the current buffer. The results can be quite amusing.
;;; Code:
(in-package "LICE")
;;;###autoload
(defcommand dissociated-press ((&optional arg)
:raw-prefix)
"Dissociate the text of the current buffer.
Output goes in buffer named *Dissociation*,
which is redisplayed each time text is added to it.
Every so often the user must say whether to continue.
If ARG is positive, require ARG chars of continuity.
If ARG is negative, require -ARG words of continuity.
Default is 2."
(setq arg (if arg (prefix-numeric-value arg) 2))
(let* ((inbuf (current-buffer))
(outbuf (get-buffer-create "*Dissociation*"))
(move-function (if (> arg 0) 'forward-char 'forward-word))
(move-amount (if (> arg 0) arg (- arg)))
(search-function (if (> arg 0) 'search-forward 'word-search-forward))
(last-query-point 0))
(if (= (point-max) (point-min))
(error "The buffer contains no text to start from"))
(switch-to-buffer outbuf)
(erase-buffer)
(while
(save-excursion
(goto-char last-query-point)
(vertical-motion (- (window-height) 4))
(or (= (point) (point-max))
(and (progn (goto-char (point-max))
(y-or-n-p "Continue dissociation? "))
(progn
(message "")
(recenter 1)
(setq last-query-point (point-max))
t))))
(let (start end)
(save-excursion
(set-buffer inbuf)
(setq start (point))
(if (eq move-function 'forward-char)
(progn
(setq end (+ start (+ move-amount (random 16))))
(if (> end (point-max))
(setq end (+ 1 move-amount (random 16))))
(goto-char end))
(funcall move-function
(+ move-amount (random 16))))
(setq end (point)))
(let ((opoint (point)))
(insert-buffer-substring inbuf start end)
(save-excursion
(goto-char opoint)
(end-of-line)
(and (> (current-column) *fill-column*)
(do-auto-fill)))))
(save-excursion
(set-buffer inbuf)
(if (eobp)
(goto-char (point-min))
(let ((overlap
(buffer-substring (prog1 (point)
(funcall move-function
(- move-amount)))
(point))))
(goto-char (1+ (random (1- (point-max)))))
(or (funcall search-function overlap :error nil)
(let ((opoint (point)))
(goto-char 1)
(funcall search-function overlap :bound opoint :error nil))))))
(sit-for 0))))
(provide 'dissociate)
;;; arch-tag: 90d197d1-409b-45c5-a0b5-fbfb2e06334f
;;; dissociate.el ends here
| 3,436 | Common Lisp | .lisp | 93 | 33.010753 | 71 | 0.675173 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e50780c3d0d94985bccc47bc5769eb0a1554ddf860ab115bd54921ef9ae49944 | 18,485 | [
-1
] |
18,486 | doctor.lisp | spacebat_lice/src/play/doctor.lisp | ;;; doctor.el --- psychological help for frustrated users
;; Copyright (C) 1985, 1987, 1994, 1996, 2000, 2002, 2003, 2004,
;; 2005, 2006 Free Software Foundation, Inc.
;; Maintainer: FSF
;; Keywords: games
;; This file is part of GNU Emacs.
;; GNU Emacs 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 2, or (at your option)
;; any later version.
;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; The single entry point `doctor', simulates a Rogerian analyst using
;; phrase-production techniques similar to the classic ELIZA demonstration
;; of pseudo-AI.
;; This file was for a while censored by the Communications Decency Act.
;; Some of its features were removed. The law was promoted as a ban
;; on pornography, but it bans far more than that. The doctor program
;; did not contain pornography, but part of it was prohibited
;; nonetheless.
;; The Supreme Court overturned the Communications Decency Act, but
;; Congress is sure to look for some other way to try to end free speech.
;; For information on US government censorship of the Internet, and
;; what you can do to protect freedom of the press, see the web
;; site http://www.vtw.org/
;; See also the file etc/CENSORSHIP in the Emacs distribution
;; for a discussion of why and how this file was censored, and the
;; political implications of the issue.
;;; Code:
;; (cl:defpackage "LICE.DOCTOR"
;; (:use "CL" "LICE")
;; (:export #:doctor))
;;
;; (in-package "LICE.DOCTOR")
(in-package "LICE")
;; shadow: continue describe
(define-buffer-local **mad** nil) (define-buffer-local *debug* nil) (define-buffer-local *print-space* nil)
(define-buffer-local *print-upcase* nil) (define-buffer-local abuselst nil) (define-buffer-local abusewords nil)
(define-buffer-local account nil) (define-buffer-local afraidof nil) (define-buffer-local arerelated nil)
(define-buffer-local areyou nil) (define-buffer-local bak nil) (define-buffer-local beclst nil)
(define-buffer-local bother nil) (define-buffer-local bye nil) (define-buffer-local canyou nil)
(define-buffer-local chatlst nil) (define-buffer-local doc-continue nil) (define-buffer-local deathlst nil)
(define-buffer-local doc-describe nil) (define-buffer-local drnk nil) (define-buffer-local drugs nil)
(define-buffer-local eliza-flag nil) (define-buffer-local elizalst nil) (define-buffer-local famlst nil)
(define-buffer-local feared nil) (define-buffer-local fears nil) (define-buffer-local feelings-about nil)
(define-buffer-local foullst nil) (define-buffer-local found nil) (define-buffer-local hello nil)
(define-buffer-local history nil) (define-buffer-local howareyoulst nil) (define-buffer-local howdyflag nil)
(define-buffer-local huhlst nil) (define-buffer-local ibelieve nil) (define-buffer-local improve nil)
(define-buffer-local inter nil) (define-buffer-local isee nil) (define-buffer-local isrelated nil)
(define-buffer-local lincount nil) (define-buffer-local longhuhlst nil) (define-buffer-local lover nil)
(define-buffer-local machlst nil) (define-buffer-local mathlst nil) (define-buffer-local maybe nil)
(define-buffer-local moods nil) (define-buffer-local neglst nil) (define-buffer-local obj nil)
(define-buffer-local object nil) (define-buffer-local owner nil) (define-buffer-local please nil)
(define-buffer-local problems nil) (define-buffer-local qlist nil) (define-buffer-local random-adjective nil)
(define-buffer-local relation nil) (define-buffer-local remlst nil) (define-buffer-local repetitive-shortness nil)
(define-buffer-local replist nil) (define-buffer-local rms-flag nil) (define-buffer-local schoollst nil)
(define-buffer-local sent nil) (define-buffer-local sexlst nil) (define-buffer-local shortbeclst nil)
(define-buffer-local shortlst nil) (define-buffer-local something nil) (define-buffer-local sportslst nil)
(define-buffer-local stallmanlst nil) (define-buffer-local states nil) (define-buffer-local subj nil)
(define-buffer-local suicide-flag nil) (define-buffer-local sure nil) (define-buffer-local things nil)
(define-buffer-local thlst nil) (define-buffer-local toklst nil) (define-buffer-local typos nil)
(define-buffer-local verb nil) (define-buffer-local want nil) (define-buffer-local whatwhen nil)
(define-buffer-local whereoutp nil) (define-buffer-local whysay nil) (define-buffer-local whywant nil)
(define-buffer-local zippy-flag nil) (define-buffer-local zippylst nil)
(defun doc// (x) x)
(defmacro doc$ (what)
"quoted arg form of doctor-$"
(list 'doctor-$ (list 'quote what)))
(defun doctor-$ (what)
"Return the car of a list, rotating the list each time"
(let* ((vv (buffer-local what))
(first (car vv))
(ww (append (cdr vv) (list first))))
(set what ww)
first))
(defvar *doctor-mode-map*
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-j") 'doctor-read-print)
(define-key map (make-key :char #\Return) 'doctor-ret-or-read)
(define-key map (kbd "RET") 'doctor-ret-or-read)
(define-key map (kbd "C-m") 'doctor-ret-or-read)
map))
(defvar *doctor-mode*
(make-instance 'major-mode
:name "Doctor"
:inherit-map '(*text-mode*)
:inherit-syntax '(*text-mode*)
:inherit-init '(*text-mode*)
:map *doctor-mode-map*
:init (lambda ()
(make-doctor-variables)
(turn-on-auto-fill)
(doctor-type '(i am the psychotherapist \.
(doc$ please) (doc$ doc-describe) your (doc$ problems) \.
each time you are finished |talking,| type |RET| twice \.))
(insert "\n")))
"Major mode for running the Doctor (Eliza) program.
Like Text mode with Auto Fill mode
except that RET when point is after a newline, or LFD at any time,
reads the sentence before point, and prints the Doctor's answer.")
(defcommand doctor-mode ()
"See `*doctor-mode*'."
(set-major-mode '*doctor-mode*))
(defun make-doctor-variables ()
(make-local-variable 'typos)
(setq typos
(mapcar (function (lambda (x)
(setf (get (car x) 'doctor-correction) (cadr x))
(setf (get (cadr x) 'doctor-expansion) (car (cddr x)))
(car x)))
'((theyll they\'ll (they will))
(theyre they\'re (they are))
(hes he\'s (he is))
(he7s he\'s (he is))
(im i\'m (you are))
(i7m i\'m (you are))
(isa is\ a (is a))
(thier their (their))
(dont don\'t (do not))
(don7t don\'t (do not))
(you7re you\'re (i am))
(you7ve you\'ve (i have))
(you7ll you\'ll (i will)))))
(make-local-variable 'found)
(setq found nil)
(make-local-variable 'owner)
(setq owner nil)
(make-local-variable 'history)
(setq history nil)
(make-local-variable '*debug*)
(setq *debug* nil)
(make-local-variable 'inter)
(setq inter
'((well\,)
(hmmm \.\.\.\ so\,)
(so)
(\.\.\.and)
(then)))
(make-local-variable 'doc-continue)
(setq doc-continue
'((continue)
(proceed)
(go on)
(keep going) ))
(make-local-variable 'relation)
(setq relation
'((your relationship with)
(something you remember about)
(your feelings toward)
(some experiences you have had with)
(how you feel about)))
(make-local-variable 'fears)
(setq fears '( ((doc$ whysay) you are (doc$ afraidof) (doc// feared) \?)
(you seem terrified by (doc// feared) \.)
(when did you first feel (doc$ afraidof) (doc// feared) \?) ))
(make-local-variable 'sure)
(setq sure '((sure)(positive)(certain)(absolutely sure)))
(make-local-variable 'afraidof)
(setq afraidof '( (afraid of) (frightened by) (scared of) ))
(make-local-variable 'areyou)
(setq areyou '( (are you)(have you been)(have you been) ))
(make-local-variable 'isrelated)
(setq isrelated '( (has something to do with)(is related to)
(could be the reason for) (is caused by)(is because of)))
(make-local-variable 'arerelated)
(setq arerelated '((have something to do with)(are related to)
(could have caused)(could be the reason for) (are caused by)
(are because of)))
(make-local-variable 'moods)
(setq moods '( ((doc$ areyou)(doc// found) often \?)
(what causes you to be (doc// found) \?)
((doc$ whysay) you are (doc// found) \?) ))
(make-local-variable 'maybe)
(setq maybe
'((maybe)
(perhaps)
(possibly)))
(make-local-variable 'whatwhen)
(setq whatwhen
'((what happened when)
(what would happen if)))
(make-local-variable 'hello)
(setq hello
'((how do you do \?) (hello \.) (howdy!) (hello \.) (hi \.) (hi there \.)))
(make-local-variable 'drnk)
(setq drnk
'((do you drink a lot of (doc// found) \?)
(do you get drunk often \?)
((doc$ doc-describe) your drinking habits \.) ))
(make-local-variable 'drugs)
(setq drugs '( (do you use (doc// found) often \?)((doc$ areyou)
addicted to (doc// found) \?)(do you realize that drugs can
be very harmful \?)((doc$ maybe) you should try to quit using (doc// found)
\.)))
(make-local-variable 'whywant)
(setq whywant '( ((doc$ whysay) (doc// subj) might (doc$ want) (doc// obj) \?)
(how does it feel to want \?)
(why should (doc// subj) get (doc// obj) \?)
(when did (doc// subj) first (doc$ want) (doc// obj) \?)
((doc$ areyou) obsessed with (doc// obj) \?)
(why should i give (doc// obj) to (doc// subj) \?)
(have you ever gotten (doc// obj) \?) ))
(make-local-variable 'canyou)
(setq canyou '((of course i can \.)
(why should i \?)
(what makes you think i would even want to \?)
(i am the doctor\, i can do anything i damn please \.)
(not really\, it\'s not up to me \.)
(depends\, how important is it \?)
(i could\, but i don\'t think it would be a wise thing to do \.)
(can you \?)
(maybe i can\, maybe i can\'t \.\.\.)
(i don\'t think i should do that \.)))
(make-local-variable 'want)
(setq want '( (want) (desire) (wish) (want) (hope) ))
(make-local-variable 'shortlst)
(setq shortlst
'((can you elaborate on that \?)
((doc$ please) continue \.)
(go on\, don\'t be afraid \.)
(i need a little more detail please \.)
(you\'re being a bit brief\, (doc$ please) go into detail \.)
(can you be more explicit \?)
(and \?)
((doc$ please) go into more detail \?)
(you aren\'t being very talkative today\!)
(is that all there is to it \?)
(why must you respond so briefly \?)))
(make-local-variable 'famlst)
(setq famlst
'((tell me (doc$ something) about (doc// owner) family \.)
(you seem to dwell on (doc// owner) family \.)
((doc$ areyou) hung up on (doc// owner) family \?)))
(make-local-variable 'huhlst)
(setq huhlst
'(((doc$ whysay)(doc// sent) \?)
(is it because of (doc$ things) that you say (doc// sent) \?) ))
(make-local-variable 'longhuhlst)
(setq longhuhlst
'(((doc$ whysay) that \?)
(i don\'t understand \.)
((doc$ thlst))
((doc$ areyou) (doc$ afraidof) that \?)))
(make-local-variable 'feelings-about)
(setq feelings-about
'((feelings about)
(apprehensions toward)
(thoughts on)
(emotions toward)))
(make-local-variable 'random-adjective)
(setq random-adjective
'((vivid)
(emotionally stimulating)
(exciting)
(boring)
(interesting)
(recent)
(random) ;How can we omit this?
(unusual)
(shocking)
(embarrassing)))
(make-local-variable 'whysay)
(setq whysay
'((why do you say)
(what makes you believe)
(are you sure that)
(do you really think)
(what makes you think) ))
(make-local-variable 'isee)
(setq isee
'((i see \.\.\.)
(yes\,)
(i understand \.)
(oh \.) ))
(make-local-variable 'please)
(setq please
'((please\,)
(i would appreciate it if you would)
(perhaps you could)
(please\,)
(would you please)
(why don\'t you)
(could you)))
(make-local-variable 'bye)
(setq bye
'((my secretary will send you a bill \.)
(bye bye \.)
(see ya \.)
(ok\, talk to you some other time \.)
(talk to you later \.)
(ok\, have fun \.)
(ciao \.)))
(make-local-variable 'something)
(setq something
'((something)
(more)
(how you feel)))
(make-local-variable 'things)
(setq things
'(;(your interests in computers) ;; let's make this less computer oriented
;(the machines you use)
(your plans)
;(your use of computers)
(your life)
;(other machines you use)
(the people you hang around with)
;(computers you like)
(problems at school)
(any hobbies you have)
;(other computers you use)
(your sex life)
(hangups you have)
(your inhibitions)
(some problems in your childhood)
;(knowledge of computers)
(some problems at home)))
(make-local-variable 'doc-describe)
(setq doc-describe
'((describe)
(tell me about)
(talk about)
(discuss)
(tell me more about)
(elaborate on)))
(make-local-variable 'ibelieve)
(setq ibelieve
'((i believe) (i think) (i have a feeling) (it seems to me that)
(it looks like)))
(make-local-variable 'problems)
(setq problems '( (problems)
(inhibitions)
(hangups)
(difficulties)
(anxieties)
(frustrations) ))
(make-local-variable 'bother)
(setq bother
'((does it bother you that)
(are you annoyed that)
(did you ever regret)
(are you sorry)
(are you satisfied with the fact that)))
(make-local-variable 'machlst)
(setq machlst
'((you have your mind on (doc// found) \, it seems \.)
(you think too much about (doc// found) \.)
(you should try taking your mind off of (doc// found)\.)
(are you a computer hacker \?)))
(make-local-variable 'qlist)
(setq qlist
'((what do you think \?)
(i\'ll ask the questions\, if you don\'t mind!)
(i could ask the same thing myself \.)
((doc$ please) allow me to do the questioning \.)
(i have asked myself that question many times \.)
((doc$ please) try to answer that question yourself \.)))
(make-local-variable 'foullst)
(setq foullst
'(((doc$ please) watch your tongue!)
((doc$ please) avoid such unwholesome thoughts \.)
((doc$ please) get your mind out of the gutter \.)
(such lewdness is not appreciated \.)))
(make-local-variable 'deathlst)
(setq deathlst
'((this is not a healthy way of thinking \.)
((doc$ bother) you\, too\, may die someday \?)
(i am worried by your obsession with this topic!)
(did you watch a lot of crime and violence on television as a child \?))
)
(make-local-variable 'sexlst)
(setq sexlst
'(((doc$ areyou) (doc$ afraidof) sex \?)
((doc$ doc-describe)(doc$ something) about your sexual history \.)
((doc$ please)(doc$ doc-describe) your sex life \.\.\.)
((doc$ doc-describe) your (doc$ feelings-about) your sexual partner \.)
((doc$ doc-describe) your most (doc$ random-adjective) sexual experience \.)
((doc$ areyou) satisfied with (doc// lover) \.\.\. \?)))
(make-local-variable 'neglst)
(setq neglst
'((why not \?)
((doc$ bother) i ask that \?)
(why not \?)
(why not \?)
(how come \?)
((doc$ bother) i ask that \?)))
(make-local-variable 'beclst)
(setq beclst '(
(is it because (doc// sent) that you came to me \?)
((doc$ bother)(doc// sent) \?)
(when did you first know that (doc// sent) \?)
(is the fact that (doc// sent) the real reason \?)
(does the fact that (doc// sent) explain anything else \?)
((doc$ areyou)(doc$ sure)(doc// sent) \? ) ))
(make-local-variable 'shortbeclst)
(setq shortbeclst '(
((doc$ bother) i ask you that \?)
(that\'s not much of an answer!)
((doc$ inter) why won\'t you talk about it \?)
(speak up!)
((doc$ areyou) (doc$ afraidof) talking about it \?)
(don\'t be (doc$ afraidof) elaborating \.)
((doc$ please) go into more detail \.)))
(make-local-variable 'thlst)
(setq thlst '(
((doc$ maybe)(doc$ things)(doc$ arerelated) this \.)
(is it because of (doc$ things) that you are going through all this \?)
(how do you reconcile (doc$ things) \? )
((doc$ maybe) this (doc$ isrelated)(doc$ things) \?) ))
(make-local-variable 'remlst)
(setq remlst '( (earlier you said (doc$ history) \?)
(you mentioned that (doc$ history) \?)
((doc$ whysay)(doc$ history) \? ) ))
(make-local-variable 'toklst)
(setq toklst
'((is this how you relax \?)
(how long have you been smoking grass \?)
((doc$ areyou) (doc$ afraidof) of being drawn to using harder stuff \?)))
(make-local-variable 'states)
(setq states
'((do you get (doc// found) often \?)
(do you enjoy being (doc// found) \?)
(what makes you (doc// found) \?)
(how often (doc$ areyou)(doc// found) \?)
(when were you last (doc// found) \?)))
(make-local-variable 'replist)
(setq replist
'((i . (you))
(my . (your))
(me . (you))
(you . (me))
(your . (my))
(mine . (yours))
(yours . (mine))
(our . (your))
(ours . (yours))
(we . (you))
(dunno . (do not know))
;; (yes . ())
(no\, . ())
(yes\, . ())
(ya . (i))
(aint . (am not))
(wanna . (want to))
(gimme . (give me))
(gotta . (have to))
(gonna . (going to))
(never . (not ever))
(doesn\'t . (does not))
(don\'t . (do not))
(aren\'t . (are not))
(isn\'t . (is not))
(won\'t . (will not))
(can\'t . (cannot))
(haven\'t . (have not))
(i\'m . (you are))
(ourselves . (yourselves))
(myself . (yourself))
(yourself . (myself))
(you\'re . (i am))
(you\'ve . (i have))
(i\'ve . (you have))
(i\'ll . (you will))
(you\'ll . (i shall))
(i\'d . (you would))
(you\'d . (i would))
(here . (there))
(please . ())
(eh\, . ())
(eh . ())
(oh\, . ())
(oh . ())
(shouldn\'t . (should not))
(wouldn\'t . (would not))
(won\'t . (will not))
(hasn\'t . (has not))))
(make-local-variable 'stallmanlst)
(setq stallmanlst '(
((doc$ doc-describe) your (doc$ feelings-about) him \.)
((doc$ areyou) a friend of Stallman \?)
((doc$ bother) Stallman is (doc$ random-adjective) \?)
((doc$ ibelieve) you are (doc$ afraidof) him \.)))
(make-local-variable 'schoollst)
(setq schoollst '(
((doc$ doc-describe) your (doc// found) \.)
((doc$ bother) your grades could (doc$ improve) \?)
((doc$ areyou) (doc$ afraidof) (doc// found) \?)
((doc$ maybe) this (doc$ isrelated) to your attitude \.)
((doc$ areyou) absent often \?)
((doc$ maybe) you should study (doc$ something) \.)))
(make-local-variable 'improve)
(setq improve '((improve) (be better) (be improved) (be higher)))
(make-local-variable 'elizalst)
(setq elizalst '(
((doc$ areyou) (doc$ sure) \?)
((doc$ ibelieve) you have (doc$ problems) with (doc// found) \.)
((doc$ whysay) (doc// sent) \?)))
(make-local-variable 'sportslst)
(setq sportslst '(
(tell me (doc$ something) about (doc// found) \.)
((doc$ doc-describe) (doc$ relation) (doc// found) \.)
(do you find (doc// found) (doc$ random-adjective) \?)))
(make-local-variable 'mathlst)
(setq mathlst '(
((doc$ doc-describe) (doc$ something) about math \.)
((doc$ maybe) your (doc$ problems) (doc$ arerelated) (doc// found) \.)
(i don\'t know much (doc// found) \, but (doc$ doc-continue)
anyway \.)))
(make-local-variable 'zippylst)
(setq zippylst '(
((doc$ areyou) Zippy \?)
((doc$ ibelieve) you have some serious (doc$ problems) \.)
((doc$ bother) you are a pinhead \?)))
(make-local-variable 'chatlst)
(setq chatlst '(
((doc$ maybe) we could chat \.)
((doc$ please) (doc$ doc-describe) (doc$ something) about chat mode \.)
((doc$ bother) our discussion is so (doc$ random-adjective) \?)))
(make-local-variable 'abuselst)
(setq abuselst '(
((doc$ please) try to be less abusive \.)
((doc$ doc-describe) why you call me (doc// found) \.)
(i\'ve had enough of you!)))
(make-local-variable 'abusewords)
(setq abusewords '(boring bozo clown clumsy cretin dumb dummy
fool foolish gnerd gnurd idiot jerk
lose loser louse lousy luse luser
moron nerd nurd oaf oafish reek
stink stupid tool toolish twit))
(make-local-variable 'howareyoulst)
(setq howareyoulst '((how are you) (hows it going) (hows it going eh)
(how\'s it going) (how\'s it going eh) (how goes it)
(whats up) (whats new) (what\'s up) (what\'s new)
(howre you) (how\'re you) (how\'s everything)
(how is everything) (how do you do)
(how\'s it hanging) (que pasa)
(how are you doing) (what do you say)))
(make-local-variable 'whereoutp)
(setq whereoutp '( huh remem rthing ) )
(make-local-variable 'subj)
(setq subj nil)
(make-local-variable 'verb)
(setq verb nil)
(make-local-variable 'obj)
(setq obj nil)
(make-local-variable 'feared)
(setq feared nil)
(make-local-variable 'repetitive-shortness)
(setq repetitive-shortness '(0 . 0))
(make-local-variable '**mad**)
(setq **mad** nil)
(make-local-variable 'rms-flag)
(setq rms-flag nil)
(make-local-variable 'eliza-flag)
(setq eliza-flag nil)
(make-local-variable 'zippy-flag)
(setq zippy-flag nil)
(make-local-variable 'suicide-flag)
(setq suicide-flag nil)
(make-local-variable 'lover)
(setq lover '(your partner))
(make-local-variable 'bak)
(setq bak nil)
(make-local-variable 'lincount)
(setq lincount 0)
(make-local-variable '*print-upcase*)
(setq *print-upcase* nil)
(make-local-variable '*print-space*)
(setq *print-space* nil)
(make-local-variable 'howdyflag)
(setq howdyflag nil)
(make-local-variable 'object)
(setq object nil))
;; Define equivalence classes of words that get treated alike.
(defun doctor-meaning (x) (get x 'doctor-meaning))
(defmacro doctor-put-meaning (symb val)
"Store the base meaning of a word on the property list."
`(setf (get (quote ,symb) 'doctor-meaning) ,val))
(doctor-put-meaning howdy 'howdy)
(doctor-put-meaning hi 'howdy)
(doctor-put-meaning greetings 'howdy)
(doctor-put-meaning hello 'howdy)
(doctor-put-meaning tops20 'mach)
(doctor-put-meaning tops-20 'mach)
(doctor-put-meaning tops 'mach)
(doctor-put-meaning pdp11 'mach)
(doctor-put-meaning computer 'mach)
(doctor-put-meaning unix 'mach)
(doctor-put-meaning machine 'mach)
(doctor-put-meaning computers 'mach)
(doctor-put-meaning machines 'mach)
(doctor-put-meaning pdp11s 'mach)
(doctor-put-meaning foo 'mach)
(doctor-put-meaning foobar 'mach)
(doctor-put-meaning multics 'mach)
(doctor-put-meaning macsyma 'mach)
(doctor-put-meaning teletype 'mach)
(doctor-put-meaning la36 'mach)
(doctor-put-meaning vt52 'mach)
(doctor-put-meaning zork 'mach)
(doctor-put-meaning trek 'mach)
(doctor-put-meaning startrek 'mach)
(doctor-put-meaning advent 'mach)
(doctor-put-meaning pdp 'mach)
(doctor-put-meaning dec 'mach)
(doctor-put-meaning commodore 'mach)
(doctor-put-meaning vic 'mach)
(doctor-put-meaning bbs 'mach)
(doctor-put-meaning modem 'mach)
(doctor-put-meaning baud 'mach)
(doctor-put-meaning macintosh 'mach)
(doctor-put-meaning vax 'mach)
(doctor-put-meaning vms 'mach)
(doctor-put-meaning ibm 'mach)
(doctor-put-meaning pc 'mach)
(doctor-put-meaning bitching 'foul)
(doctor-put-meaning shit 'foul)
(doctor-put-meaning bastard 'foul)
(doctor-put-meaning damn 'foul)
(doctor-put-meaning damned 'foul)
(doctor-put-meaning hell 'foul)
(doctor-put-meaning suck 'foul)
(doctor-put-meaning sucking 'foul)
(doctor-put-meaning sux 'foul)
(doctor-put-meaning ass 'foul)
(doctor-put-meaning whore 'foul)
(doctor-put-meaning bitch 'foul)
(doctor-put-meaning asshole 'foul)
(doctor-put-meaning shrink 'foul)
(doctor-put-meaning pot 'toke)
(doctor-put-meaning grass 'toke)
(doctor-put-meaning weed 'toke)
(doctor-put-meaning marijuana 'toke)
(doctor-put-meaning acapulco 'toke)
(doctor-put-meaning columbian 'toke)
(doctor-put-meaning tokin 'toke)
(doctor-put-meaning joint 'toke)
(doctor-put-meaning toke 'toke)
(doctor-put-meaning toking 'toke)
(doctor-put-meaning tokin\' 'toke)
(doctor-put-meaning toked 'toke)
(doctor-put-meaning roach 'toke)
(doctor-put-meaning pills 'drug)
(doctor-put-meaning dope 'drug)
(doctor-put-meaning acid 'drug)
(doctor-put-meaning lsd 'drug)
(doctor-put-meaning speed 'drug)
(doctor-put-meaning heroin 'drug)
(doctor-put-meaning hash 'drug)
(doctor-put-meaning cocaine 'drug)
(doctor-put-meaning uppers 'drug)
(doctor-put-meaning downers 'drug)
(doctor-put-meaning loves 'loves)
(doctor-put-meaning love 'love)
(doctor-put-meaning loved 'love)
(doctor-put-meaning hates 'hates)
(doctor-put-meaning dislikes 'hates)
(doctor-put-meaning hate 'hate)
(doctor-put-meaning hated 'hate)
(doctor-put-meaning dislike 'hate)
(doctor-put-meaning stoned 'state)
(doctor-put-meaning drunk 'state)
(doctor-put-meaning drunken 'state)
(doctor-put-meaning high 'state)
(doctor-put-meaning horny 'state)
(doctor-put-meaning blasted 'state)
(doctor-put-meaning happy 'state)
(doctor-put-meaning paranoid 'state)
(doctor-put-meaning wish 'desire)
(doctor-put-meaning wishes 'desire)
(doctor-put-meaning want 'desire)
(doctor-put-meaning desire 'desire)
(doctor-put-meaning like 'desire)
(doctor-put-meaning hope 'desire)
(doctor-put-meaning hopes 'desire)
(doctor-put-meaning desires 'desire)
(doctor-put-meaning wants 'desire)
(doctor-put-meaning desires 'desire)
(doctor-put-meaning likes 'desire)
(doctor-put-meaning needs 'desire)
(doctor-put-meaning need 'desire)
(doctor-put-meaning frustrated 'mood)
(doctor-put-meaning depressed 'mood)
(doctor-put-meaning annoyed 'mood)
(doctor-put-meaning upset 'mood)
(doctor-put-meaning unhappy 'mood)
(doctor-put-meaning excited 'mood)
(doctor-put-meaning worried 'mood)
(doctor-put-meaning lonely 'mood)
(doctor-put-meaning angry 'mood)
(doctor-put-meaning mad 'mood)
(doctor-put-meaning pissed 'mood)
(doctor-put-meaning jealous 'mood)
(doctor-put-meaning afraid 'fear)
(doctor-put-meaning terrified 'fear)
(doctor-put-meaning fear 'fear)
(doctor-put-meaning scared 'fear)
(doctor-put-meaning frightened 'fear)
(doctor-put-meaning virginity 'sexnoun)
(doctor-put-meaning virgins 'sexnoun)
(doctor-put-meaning virgin 'sexnoun)
(doctor-put-meaning cock 'sexnoun)
(doctor-put-meaning cocks 'sexnoun)
(doctor-put-meaning dick 'sexnoun)
(doctor-put-meaning dicks 'sexnoun)
(doctor-put-meaning cunt 'sexnoun)
(doctor-put-meaning cunts 'sexnoun)
(doctor-put-meaning prostitute 'sexnoun)
(doctor-put-meaning condom 'sexnoun)
(doctor-put-meaning sex 'sexnoun)
(doctor-put-meaning rapes 'sexnoun)
(doctor-put-meaning wife 'family)
(doctor-put-meaning family 'family)
(doctor-put-meaning brothers 'family)
(doctor-put-meaning sisters 'family)
(doctor-put-meaning parent 'family)
(doctor-put-meaning parents 'family)
(doctor-put-meaning brother 'family)
(doctor-put-meaning sister 'family)
(doctor-put-meaning father 'family)
(doctor-put-meaning mother 'family)
(doctor-put-meaning husband 'family)
(doctor-put-meaning siblings 'family)
(doctor-put-meaning grandmother 'family)
(doctor-put-meaning grandfather 'family)
(doctor-put-meaning maternal 'family)
(doctor-put-meaning paternal 'family)
(doctor-put-meaning stab 'death)
(doctor-put-meaning murder 'death)
(doctor-put-meaning murders 'death)
(doctor-put-meaning suicide 'death)
(doctor-put-meaning suicides 'death)
(doctor-put-meaning kill 'death)
(doctor-put-meaning kills 'death)
(doctor-put-meaning killing 'death)
(doctor-put-meaning die 'death)
(doctor-put-meaning dies 'death)
(doctor-put-meaning died 'death)
(doctor-put-meaning dead 'death)
(doctor-put-meaning death 'death)
(doctor-put-meaning deaths 'death)
(doctor-put-meaning pain 'symptoms)
(doctor-put-meaning ache 'symptoms)
(doctor-put-meaning fever 'symptoms)
(doctor-put-meaning sore 'symptoms)
(doctor-put-meaning aching 'symptoms)
(doctor-put-meaning stomachache 'symptoms)
(doctor-put-meaning headache 'symptoms)
(doctor-put-meaning hurts 'symptoms)
(doctor-put-meaning disease 'symptoms)
(doctor-put-meaning virus 'symptoms)
(doctor-put-meaning vomit 'symptoms)
(doctor-put-meaning vomiting 'symptoms)
(doctor-put-meaning barf 'symptoms)
(doctor-put-meaning toothache 'symptoms)
(doctor-put-meaning hurt 'symptoms)
(doctor-put-meaning rum 'alcohol)
(doctor-put-meaning gin 'alcohol)
(doctor-put-meaning vodka 'alcohol)
(doctor-put-meaning alcohol 'alcohol)
(doctor-put-meaning bourbon 'alcohol)
(doctor-put-meaning beer 'alcohol)
(doctor-put-meaning wine 'alcohol)
(doctor-put-meaning whiskey 'alcohol)
(doctor-put-meaning scotch 'alcohol)
(doctor-put-meaning fuck 'sexverb)
(doctor-put-meaning fucked 'sexverb)
(doctor-put-meaning screw 'sexverb)
(doctor-put-meaning screwing 'sexverb)
(doctor-put-meaning fucking 'sexverb)
(doctor-put-meaning rape 'sexverb)
(doctor-put-meaning raped 'sexverb)
(doctor-put-meaning kiss 'sexverb)
(doctor-put-meaning kissing 'sexverb)
(doctor-put-meaning kisses 'sexverb)
(doctor-put-meaning screws 'sexverb)
(doctor-put-meaning fucks 'sexverb)
(doctor-put-meaning because 'conj)
(doctor-put-meaning but 'conj)
(doctor-put-meaning however 'conj)
(doctor-put-meaning besides 'conj)
(doctor-put-meaning anyway 'conj)
(doctor-put-meaning that 'conj)
(doctor-put-meaning except 'conj)
(doctor-put-meaning why 'conj)
(doctor-put-meaning how 'conj)
(doctor-put-meaning until 'when)
(doctor-put-meaning when 'when)
(doctor-put-meaning whenever 'when)
(doctor-put-meaning while 'when)
(doctor-put-meaning since 'when)
(doctor-put-meaning rms 'rms)
(doctor-put-meaning stallman 'rms)
(doctor-put-meaning school 'school)
(doctor-put-meaning schools 'school)
(doctor-put-meaning skool 'school)
(doctor-put-meaning grade 'school)
(doctor-put-meaning grades 'school)
(doctor-put-meaning teacher 'school)
(doctor-put-meaning teachers 'school)
(doctor-put-meaning classes 'school)
(doctor-put-meaning professor 'school)
(doctor-put-meaning prof 'school)
(doctor-put-meaning profs 'school)
(doctor-put-meaning professors 'school)
(doctor-put-meaning mit 'school)
(doctor-put-meaning emacs 'eliza)
(doctor-put-meaning eliza 'eliza)
(doctor-put-meaning liza 'eliza)
(doctor-put-meaning elisa 'eliza)
(doctor-put-meaning weizenbaum 'eliza)
(doctor-put-meaning doktor 'eliza)
(doctor-put-meaning athletics 'sports)
(doctor-put-meaning baseball 'sports)
(doctor-put-meaning basketball 'sports)
(doctor-put-meaning football 'sports)
(doctor-put-meaning frisbee 'sports)
(doctor-put-meaning gym 'sports)
(doctor-put-meaning gymnastics 'sports)
(doctor-put-meaning hockey 'sports)
(doctor-put-meaning lacrosse 'sports)
(doctor-put-meaning soccer 'sports)
(doctor-put-meaning softball 'sports)
(doctor-put-meaning sports 'sports)
(doctor-put-meaning swimming 'sports)
(doctor-put-meaning swim 'sports)
(doctor-put-meaning tennis 'sports)
(doctor-put-meaning volleyball 'sports)
(doctor-put-meaning math 'math)
(doctor-put-meaning mathematics 'math)
(doctor-put-meaning mathematical 'math)
(doctor-put-meaning theorem 'math)
(doctor-put-meaning axiom 'math)
(doctor-put-meaning lemma 'math)
(doctor-put-meaning algebra 'math)
(doctor-put-meaning algebraic 'math)
(doctor-put-meaning trig 'math)
(doctor-put-meaning trigonometry 'math)
(doctor-put-meaning trigonometric 'math)
(doctor-put-meaning geometry 'math)
(doctor-put-meaning geometric 'math)
(doctor-put-meaning calculus 'math)
(doctor-put-meaning arithmetic 'math)
(doctor-put-meaning zippy 'zippy)
(doctor-put-meaning zippy 'zippy)
(doctor-put-meaning pinhead 'zippy)
(doctor-put-meaning chat 'chat)
;;;###autoload
(defcommand doctor ()
"Switch to *doctor* buffer and start giving psychotherapy."
(switch-to-buffer "*doctor*")
(doctor-mode))
(defcommand doctor-ret-or-read ((arg)
:prefix)
"Insert a newline if preceding character is not a newline.
Otherwise call the Doctor to parse preceding sentence."
;;(interactive "*p")
(if (char= (preceding-char) #\Newline)
(doctor-read-print)
(newline arg)))
(defcommand doctor-read-print ()
"top level loop"
(setf sent (doctor-readin))
(insert "\n")
(setq lincount (1+ lincount))
(doctor-doc)
(insert "\n")
(setq bak sent))
(defun doctor-readin nil
"Read a sentence. Return it as a list of words."
(let (sentence)
(backward-sentence 1)
(while (not (eobp))
(setq sentence (append sentence (list (doctor-read-token)))))
sentence))
(defun doctor-read-token ()
"read one word from buffer"
(prog1 (intern (upcase (buffer-substring (point)
(progn
(forward-word 1)
(point))))
"LICE")
(re-search-forward "\\W*"))) ;;"\\Sw*"
;; Main processing function for sentences that have been read.
;;(declaim (special sent))
(defun doctor-doc ()
;; Old emacs programs actually depended on dynamic scope!
(cond
((equal sent '(foo))
(doctor-type '(bar! (doc$ please)(doc$ doc-continue) \.)))
((member sent howareyoulst)
(doctor-type '(i\'m ok \. (doc$ doc-describe) yourself \.)))
((or (member sent '((good bye) (see you later) (i quit) (so long)
(go away) (get lost)))
(memq (car sent)
'(bye halt break quit done exit goodbye
bye\, stop pause goodbye\, stop pause)))
(doctor-type (doc$ bye)))
((and (eq (car sent) 'you)
(memq (cadr sent) abusewords))
(setq found (cadr sent))
(doctor-type (doc$ abuselst)))
((eq (car sent) 'whatmeans)
(doctor-def (cadr sent)))
((equal sent '(parse))
(doctor-type (list 'subj '= subj ", "
'verb '= verb "\n"
'object 'phrase '= obj ","
'noun 'form '= object "\n"
'current 'keyword 'is found
", "
'most 'recent 'possessive
'is owner "\n"
'sentence 'used 'was
"..."
'(doc// bak))))
((memq (car sent) '(are is do has have how when where who why))
(doctor-type (doc$ qlist)))
;; ((eq (car sent) 'forget)
;; (set (cadr sent) nil)
;; (doctor-type '((doc$ isee)(doc$ please)
;; (doc$ continue)\.)))
(t
(if (doctor-defq sent) (doctor-define sent found))
(if (> (length sent) 12)(setq sent (doctor-shorten sent)))
(setq sent (doctor-correct-spelling (doctor-replace sent replist)))
(cond ((and (not (memq 'me sent))(not (memq 'i sent))
(memq 'am sent))
(setq sent (doctor-replace sent '((am . (are)))))))
(cond ((equal (car sent) 'yow) (doctor-zippy))
((< (length sent) 2)
(cond ((eq (doctor-meaning (car sent)) 'howdy)
(doctor-howdy))
(t (doctor-short))))
(t
(if (memq 'am sent)
(setq sent (doctor-replace sent '((me . (i))))))
(setq sent (doctor-fixup sent))
(if (and (eq (car sent) 'do) (eq (cadr sent) 'not))
(cond ((zerop (random 3))
(doctor-type '(are you (doc$ afraidof) that \?)))
((zerop (random 2))
(doctor-type '(don\'t tell me what to do \. i am the
doctor here!))
(doctor-rthing))
(t
(doctor-type '((doc$ whysay) that i shouldn\'t
(cddr sent)
\?))))
(progn
(message "HERE")
(doctor-go (doctor-wherego sent)))))))))
;; Things done to process sentences once read.
(defun doctor-correct-spelling (sent)
"Correct the spelling and expand each word in sentence."
(if sent
(apply 'append (mapcar (lambda (word)
(if (memq word typos)
(get (get word 'doctor-correction) 'doctor-expansion)
(list word)))
sent))))
(defun doctor-shorten (sent)
"Make a sentence manageably short using a few hacks."
(let (foo
(retval sent)
(temp '(because but however besides anyway until
while that except why how)))
(while temp
(setq foo (memq (car temp) sent))
(if (and foo
(> (length foo) 3))
(setq retval (doctor-fixup foo)
temp nil)
(setq temp (cdr temp))))
retval))
(defun doctor-define (sent found)
(doctor-svo sent found 1 nil)
(and
(doctor-nounp subj)
(not (doctor-pronounp subj))
subj
(doctor-meaning object)
(setf (get subj 'doctor-meaning) (doctor-meaning object))
t))
(defun doctor-defq (sent)
"Set global var FOUND to first keyword found in sentence SENT."
(setq found nil)
(let ((temp '(means applies mean refers refer related
similar defined associated linked like same)))
(while temp
(if (memq (car temp) sent)
(setq found (car temp)
temp nil)
(setq temp (cdr temp)))))
found)
(defun doctor-def (x)
(progn
(doctor-type (list 'the 'word x 'means (doctor-meaning x) 'to 'me))
nil))
(defun doctor-forget ()
"Delete the last element of the history list."
(setq history (reverse (cdr (reverse history)))))
(defun doctor-query (x)
"Prompt for a line of input from the minibuffer until a noun or verb is seen.
Put dialogue in buffer."
(let (a
(prompt (concat (doctor-make-string x)
" what \? "))
retval)
(while (not retval)
(while (not a)
(insert #\Newline
prompt
(read-string prompt)
#\Newline)
(setq a (doctor-readin)))
(while (and a (not retval))
(cond ((doctor-nounp (car a))
(setq retval (car a)))
((doctor-verbp (car a))
(setq retval (doctor-build
(doctor-build x " ")
(car a))))
((setq a (cdr a))))))
retval))
(defun doctor-subjsearch (sent key type)
"Search for the subject of a sentence SENT, looking for the noun closest
to and preceding KEY by at least TYPE words. Set global variable subj to
the subject noun, and return the portion of the sentence following it."
(let ((i (- (length sent) (length (memq key sent)) type)))
(while (and (> i -1) (not (doctor-nounp (nth i sent))))
(setq i (1- i)))
(cond ((> i -1)
(setq subj (nth i sent))
(nthcdr (1+ i) sent))
(t
(setq subj 'you)
nil))))
(defun doctor-nounp (x)
"Returns t if the symbol argument is a noun."
(or (doctor-pronounp x)
(not (or (doctor-verbp x)
(equal x 'not)
(doctor-prepp x)
(doctor-modifierp x) )) ))
(defun doctor-pronounp (x)
"Returns t if the symbol argument is a pronoun."
(memq x '(
i me mine myself
we us ours ourselves ourself
you yours yourself yourselves
he him himself she hers herself
it that those this these things thing
they them themselves theirs
anybody everybody somebody
anyone everyone someone
anything something everything)))
(dolist (x
'(abort aborted aborts ask asked asks am
applied applies apply are associate
associated ate
be became become becomes becoming
been being believe believed believes
bit bite bites bore bored bores boring bought buy buys buying
call called calling calls came can caught catch come
contract contracted contracts control controlled controls
could croak croaks croaked cut cuts
dare dared define defines dial dialed dials did die died dies
dislike disliked
dislikes do does drank drink drinks drinking
drive drives driving drove dying
eat eating eats expand expanded expands
expect expected expects expel expels expelled
explain explained explains
fart farts feel feels felt fight fights find finds finding
forget forgets forgot fought found
fuck fucked fucking fucks
gave get gets getting give gives go goes going gone got gotten
had harm harms has hate hated hates have having
hear heard hears hearing help helped helping helps
hit hits hope hoped hopes hurt hurts
implies imply is
join joined joins jump jumped jumps
keep keeping keeps kept
kill killed killing kills kiss kissed kisses kissing
knew know knows
laid lay lays let lets lie lied lies like liked likes
liking listen listens
login look looked looking looks
lose losing lost
love loved loves loving
luse lusing lust lusts
made make makes making may mean means meant might
move moved moves moving must
need needed needs
order ordered orders ought
paid pay pays pick picked picking picks
placed placing prefer prefers put puts
ran rape raped rapes
read reading reads recall receive received receives
refer refered referred refers
relate related relates remember remembered remembers
romp romped romps run running runs
said sang sat saw say says
screw screwed screwing screws scrod see sees seem seemed
seems seen sell selling sells
send sendind sends sent shall shoot shot should
sing sings sit sits sitting sold studied study
take takes taking talk talked talking talks tell tells telling
think thinks
thought told took tooled touch touched touches touching
transfer transferred transfers transmit transmits transmitted
type types types typing
walk walked walking walks want wanted wants was watch
watched watching went were will wish would work worked works
write writes writing wrote use used uses using))
(setf (get x 'doctor-sentence-type) 'verb))
(defun doctor-verbp (x) (if (symbolp x)
(eq (get x 'doctor-sentence-type) 'verb)))
(defun doctor-plural (x)
"Form the plural of the word argument."
(let ((foo (doctor-make-string x)))
(cond ((string-equal (substring foo -1) "s")
(cond ((string-equal (substring foo -2 -1) "s")
(intern (concat foo "es") "LICE"))
(t x)))
((string-equal (substring foo -1) "y")
(intern (concat (substring foo 0 -1)
"ies") "LICE"))
(t (intern (concat foo "s") "LICE")))))
(defun doctor-setprep (sent key)
(let ((val)
(foo (memq key sent)))
(cond ((doctor-prepp (cadr foo))
(setq val (doctor-getnoun (cddr foo)))
(cond (val val)
(t 'something)))
((doctor-articlep (cadr foo))
(setq val (doctor-getnoun (cddr foo)))
(cond (val (doctor-build (doctor-build (cadr foo) " ") val))
(t 'something)))
(t 'something))))
(defun doctor-getnoun (x)
(cond ((null x)(setq object 'something))
((atom x)(setq object x))
((eq (length x) 1)
(setq object (cond
((doctor-nounp (setq object (car x))) object)
(t (doctor-query object)))))
((eq (car x) 'to)
(doctor-build 'to\ (doctor-getnoun (cdr x))))
((doctor-prepp (car x))
(doctor-getnoun (cdr x)))
((not (doctor-nounp (car x)))
(doctor-build (doctor-build (cdr (assq (car x)
(append
'((a . this)
(some . this)
(one . that))
(list
(cons
(car x) (car x))))))
" ")
(doctor-getnoun (cdr x))))
(t (setq object (car x))
(doctor-build (doctor-build (car x) " ") (doctor-getnoun (cdr x))))
))
(defun doctor-modifierp (x)
(or (doctor-adjectivep x)
(doctor-adverbp x)
(doctor-othermodifierp x)))
(defun doctor-adjectivep (x)
(or (numberp x)
(doctor-nmbrp x)
(doctor-articlep x)
(doctor-colorp x)
(doctor-sizep x)
(doctor-possessivepronounp x)))
(defun doctor-adverbp (xx)
(let ((xxstr (doctor-make-string xx)))
(and (>= (length xxstr) 2)
(string-equal (substring (doctor-make-string xx) -2) "ly"))))
(defun doctor-articlep (x)
(memq x '(the a an)))
(defun doctor-nmbrp (x)
(memq x '(one two three four five six seven eight nine ten
eleven twelve thirteen fourteen fifteen
sixteen seventeen eighteen nineteen
twenty thirty forty fifty sixty seventy eighty ninety
hundred thousand million billion
half quarter
first second third fourth fifth
sixth seventh eighth ninth tenth)))
(defun doctor-colorp (x)
(memq x '(beige black blue brown crimson
gray grey green
orange pink purple red tan tawny
violet white yellow)))
(defun doctor-sizep (x)
(memq x '(big large tall fat wide thick
small petite short thin skinny)))
(defun doctor-possessivepronounp (x)
(memq x '(my your his her our their)))
(defun doctor-othermodifierp (x)
(memq x '(all also always amusing any anyway associated awesome
bad beautiful best better but certain clear
ever every fantastic fun funny
good great grody gross however if ignorant
less linked losing lusing many more much
never nice obnoxious often poor pretty real related rich
similar some stupid super superb
terrible terrific too total tubular ugly very)))
(defun doctor-prepp (x)
(memq x '(about above after around as at
before beneath behind beside between by
for from in inside into
like near next of on onto over
same through thru to toward towards
under underneath with without)))
(defun doctor-remember (thing)
(cond ((null history)
(setq history (list thing)))
(t (setq history (append history (list thing))))))
(defun doctor-type (x)
(setq x (doctor-fix-2 x))
(doctor-txtype (doctor-assm x)))
(defun doctor-fixup (sent)
(setq sent (append
(cdr
(assq (car sent)
(append
'((me i)
(him he)
(her she)
(them they)
(okay)
(well)
(sigh)
(hmm)
(hmmm)
(hmmmm)
(hmmmmm)
(gee)
(sure)
(great)
(oh)
(fine)
(ok)
(no))
(list (list (car sent)
(car sent))))))
(cdr sent)))
(doctor-fix-2 sent))
(defun doctor-fix-2 (sent)
(let ((foo sent))
(while foo
(if (and (eq (car foo) 'me)
(doctor-verbp (cadr foo)))
(rplaca foo 'i)
(progn
(cond ((eq (car foo) 'you)
(cond ((memq (cadr foo) '(am be been is))
(rplaca (cdr foo) 'are))
((memq (cadr foo) '(has))
(rplaca (cdr foo) 'have))
((memq (cadr foo) '(was))
(rplaca (cdr foo) 'were))))
((equal (car foo) 'i)
(cond ((memq (cadr foo) '(are is be been))
(rplaca (cdr foo) 'am))
((memq (cadr foo) '(were))
(rplaca (cdr foo) 'was))
((memq (cadr foo) '(has))
(rplaca (cdr foo) 'have))))
((and (doctor-verbp (car foo))
(eq (cadr foo) 'i)
(not (doctor-verbp (car (cddr foo)))))
(rplaca (cdr foo) 'me))
((and (eq (car foo) 'a)
(doctor-vowelp (string-to-char
(doctor-make-string (cadr foo)))))
(rplaca foo 'an))
((and (eq (car foo) 'an)
(not (doctor-vowelp (string-to-char
(doctor-make-string (cadr foo))))))
(rplaca foo 'a)))
(setq foo (cdr foo)))))
sent))
(defun doctor-vowelp (x)
(memq x '(#\a #\e #\i #\o #\u)))
(defun doctor-replace (sent rlist)
"Replace any element of SENT that is the car of a replacement
element pair in RLIST."
(apply 'append
(mapcar
(function
(lambda (x)
(cdr (or (assq x rlist) ; either find a replacement
(list x x))))) ; or fake an identity mapping
sent)))
(defun doctor-wherego (sent)
(cond ((null sent)(doc$ whereoutp))
((null (doctor-meaning (car sent)))
(doctor-wherego (cond ((zerop (random 2))
(reverse (cdr sent)))
(t (cdr sent)))))
(t
(setq found (car sent))
(doctor-meaning (car sent)))))
(defun doctor-svo (sent key type mem)
"Find subject, verb and object in sentence SENT with focus on word KEY.
TYPE is number of words preceding KEY to start looking for subject.
MEM is t if results are to be put on Doctor's memory stack.
Return in the global variables SUBJ, VERB and OBJECT."
(let ((foo (doctor-subjsearch sent key type)))
(or foo
(setq foo sent
mem nil))
(while (and (null (doctor-verbp (car foo))) (cdr foo))
(setq foo (cdr foo)))
(setq verb (car foo))
(setq obj (doctor-getnoun (cdr foo)))
(cond ((eq object 'i)(setq object 'me))
((eq subj 'me)(setq subj 'i)))
(cond (mem (doctor-remember (list subj verb obj))))))
(defun doctor-possess (sent key)
"Set possessive in SENT for keyword KEY.
Hack on previous word, setting global variable OWNER to correct result."
(let* ((i (- (length sent) (length (memq key sent)) 1))
(prev (if (< i 0) 'your
(nth i sent))))
(setq owner (if (or (doctor-possessivepronounp prev)
(string-equal "s"
(substring (doctor-make-string prev)
-1)))
prev
'your))))
;; Output of replies.
(defun doctor-txtype (ans)
"Output to buffer a list of symbols or strings as a sentence."
(setq *print-upcase* t *print-space* nil)
(mapc 'doctor-type-symbol ans)
(insert "\n"))
(defun doctor-type-symbol (word)
"Output a symbol to the buffer with some fancy case and spacing hacks."
(setq word (doctor-make-string word))
(if (string-equal word "i") (setq word "I"))
(if *print-upcase*
(progn
(setq word (capitalize word))
(if *print-space*
(insert " "))))
(cond ((or (string-match "^[.,;:?! ]" word)
(not *print-space*))
(insert word))
(t (insert #\Space word)))
(and *auto-fill-function*
(> (current-column) *fill-column*)
(apply *auto-fill-function* nil))
(setq *print-upcase* (string-match "[.?!]$" word)
*print-space* t))
(defun doctor-build (str1 str2)
"Make a symbol out of the concatenation of the two non-list arguments."
(cond ((null str1) str2)
((null str2) str1)
((and (atom str1)
(atom str2))
(intern (concat (doctor-make-string str1)
(doctor-make-string str2))
"LICE"))
(t nil)))
(defun doctor-make-string (obj)
(cond ((stringp obj) obj)
((symbolp obj) (symbol-name obj))
((numberp obj) (int-to-string obj))
(t "")))
(defun doctor-concat (x y)
"Like append, but force atomic arguments to be lists."
(append
(if (and x (atom x)) (list x) x)
(if (and y (atom y)) (list y) y)))
(defun doctor-assm (proto)
(cond ((null proto) nil)
((atom proto) (list proto))
((atom (car proto))
(cons (car proto) (doctor-assm (cdr proto))))
(t (doctor-concat (doctor-assm (eval (car proto))) (doctor-assm (cdr proto))))))
;; Functions that handle specific words or meanings when found.
(defun doctor-go (destination)
"Call a `doctor-*' function."
(funcall (intern (concat "DOCTOR-" (doctor-make-string destination)) "LICE")))
(defun doctor-desire1 ()
(doctor-go (doc$ whereoutp)))
(defun doctor-huh ()
(cond ((< (length sent) 9) (doctor-type (doc$ huhlst)))
(t (doctor-type (doc$ longhuhlst)))))
(defun doctor-rthing () (doctor-type (doc$ thlst)))
(defun doctor-remem () (cond ((null history)(doctor-huh))
((doctor-type (doc$ remlst)))))
(defun doctor-howdy ()
(cond ((not howdyflag)
(doctor-type '((doc$ hello) what brings you to see me \?))
(setq howdyflag t))
(t
(doctor-type '((doc$ ibelieve) we\'ve introduced ourselves already \.))
(doctor-type '((doc$ please) (doc$ doc-describe) (doc$ things) \.)))))
(defun doctor-when ()
(cond ((< (length (memq found sent)) 3)(doctor-short))
(t
(setq sent (cdr (memq found sent)))
(setq sent (doctor-fixup sent))
(doctor-type '((doc$ whatwhen)(doc// sent) \?)))))
(defun doctor-conj ()
(cond ((< (length (memq found sent)) 4)(doctor-short))
(t
(setq sent (cdr (memq found sent)))
(setq sent (doctor-fixup sent))
(cond ((eq (car sent) 'of)
(doctor-type '(are you (doc$ sure) that is the real reason \?))
(setq things (cons (cdr sent) things)))
(t
(doctor-remember sent)
(doctor-type (doc$ beclst)))))))
(defun doctor-short ()
(cond ((= (car repetitive-shortness) (1- lincount))
(rplacd repetitive-shortness
(1+ (cdr repetitive-shortness))))
(t
(rplacd repetitive-shortness 1)))
(rplaca repetitive-shortness lincount)
(cond ((> (cdr repetitive-shortness) 6)
(cond ((not **mad**)
(doctor-type '((doc$ areyou)
just trying to see what kind of things
i have in my vocabulary \? please try to
carry on a reasonable conversation!))
(setq **mad** t))
(t
(doctor-type '(i give up \. you need a lesson in creative
writing \.\.\.))
)))
(t
(cond ((equal sent (doctor-assm '(yes)))
(doctor-type '((doc$ isee) (doc$ inter) (doc$ whysay) this is so \?)))
((equal sent (doctor-assm '(because)))
(doctor-type (doc$ shortbeclst)))
((equal sent (doctor-assm '(no)))
(doctor-type (doc$ neglst)))
(t (doctor-type (doc$ shortlst)))))))
(defun doctor-alcohol () (doctor-type (doc$ drnk)))
(defun doctor-desire ()
(let ((foo (memq found sent)))
(cond ((< (length foo) 2)
(doctor-go (doctor-build (doctor-meaning found) 1)))
((memq (cadr foo) '(a an))
(rplacd foo (append '(to have) (cdr foo)))
(doctor-svo sent found 1 nil)
(doctor-remember (list subj 'would 'like obj))
(doctor-type (doc$ whywant)))
((not (eq (cadr foo) 'to))
(doctor-go (doctor-build (doctor-meaning found) 1)))
(t
(doctor-svo sent found 1 nil)
(doctor-remember (list subj 'would 'like obj))
(doctor-type (doc$ whywant))))))
(defun doctor-drug ()
(doctor-type (doc$ drugs))
(doctor-remember (list 'you 'used found)))
(defun doctor-toke ()
(doctor-type (doc$ toklst)))
(defun doctor-state ()
(doctor-type (doc$ states))(doctor-remember (list 'you 'were found)))
(defun doctor-mood ()
(doctor-type (doc$ moods))(doctor-remember (list 'you 'felt found)))
(defun doctor-fear ()
(setq feared (doctor-setprep sent found))
(doctor-type (doc$ fears))
(doctor-remember (list 'you 'were 'afraid 'of feared)))
(defun doctor-hate ()
(doctor-svo sent found 1 t)
(cond ((memq 'not sent) (doctor-forget) (doctor-huh))
((equal subj 'you)
(doctor-type '(why do you (doc// verb)(doc// obj) \?)))
(t (doctor-type '((doc$ whysay)(list subj verb obj))))))
(defun doctor-symptoms ()
(doctor-type '((doc$ maybe) you should consult a medical doctor\;
i am a psychotherapist. \.)))
(defun doctor-hates ()
(doctor-svo sent found 1 t)
(doctor-hates1))
(defun doctor-hates1 ()
(doctor-type '((doc$ whysay)(list subj verb obj) \?)))
(defun doctor-loves ()
(doctor-svo sent found 1 t)
(doctor-qloves))
(defun doctor-qloves ()
(doctor-type '((doc$ bother)(list subj verb obj) \?)))
(defun doctor-love ()
(doctor-svo sent found 1 t)
(cond ((memq 'not sent) (doctor-forget) (doctor-huh))
((memq 'to sent) (doctor-hates1))
(t
(cond ((equal object 'something)
(setq object '(this person you love))))
(cond ((equal subj 'you)
(setq lover obj)
(cond ((equal lover '(this person you love))
(setq lover '(your partner))
(doctor-forget)
(doctor-type '(with whom are you in love \?)))
((doctor-type '((doc$ please)
(doc$ doc-describe)
(doc$ relation)
(doc// lover)
\.)))))
((equal subj 'i)
(doctor-txtype '(we were discussing you!)))
(t (doctor-forget)
(setq obj 'someone)
(setq verb (doctor-build verb 's))
(doctor-qloves))))))
(defun doctor-mach ()
(setq found (doctor-plural found))
(doctor-type (doc$ machlst)))
(defun doctor-sexnoun () (doctor-sexverb))
(defun doctor-sexverb ()
(if (or (memq 'me sent)(memq 'myself sent)(memq 'i sent))
(doctor-foul)
(doctor-type (doc$ sexlst))))
(defun doctor-death ()
(cond (suicide-flag (doctor-type (doc$ deathlst)))
((or (equal found 'suicide)
(and (or (equal found 'kill)
(equal found 'killing))
(memq 'yourself sent)))
(setq suicide-flag t)
(doctor-type '(If you are really |suicidal,| you might
want to contact the Samaritans via
|E-mail:| |[email protected]| |or,| at your |option,|
anonymous |E-mail:| |[email protected]| \.
or find a Befrienders crisis center at
|http://www.befrienders.org/| \.
(doc$ please) (doc$ doc-continue) \.)))
(t (doctor-type (doc$ deathlst)))))
(defun doctor-foul ()
(doctor-type (doc$ foullst)))
(defun doctor-family ()
(doctor-possess sent found)
(doctor-type (doc$ famlst)))
;; I did not add this -- rms.
;; But he might have removed it. I put it back. --roland
(defun doctor-rms ()
(cond (rms-flag (doctor-type (doc$ stallmanlst)))
(t (setq rms-flag t) (doctor-type '(do you know Stallman \?)))))
(defun doctor-school nil (doctor-type (doc$ schoollst)))
(defun doctor-eliza ()
(cond (eliza-flag (doctor-type (doc$ elizalst)))
(t (setq eliza-flag t)
(doctor-type '((doc// found) \? hah !
(doc$ please) (doc$ doc-continue) \.)))))
(defun doctor-sports () (doctor-type (doc$ sportslst)))
(defun doctor-math () (doctor-type (doc$ mathlst)))
(defun doctor-zippy ()
(cond (zippy-flag (doctor-type (doc$ zippylst)))
(t (setq zippy-flag t)
(doctor-type '(yow! are we interactive yet \?)))))
(defun doctor-chat () (doctor-type (doc$ chatlst)))
(provide 'doctor)
;; arch-tag: 579380f6-4902-4ea5-bccb-6339e30e1257
;;; doctor.el ends here
| 57,840 | Common Lisp | .lisp | 1,576 | 32.411168 | 126 | 0.657428 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | cf42b1d91876b4134d045a445af7863b03c8519e4e0a2e858b9ccff79d5ff2e3 | 18,486 | [
-1
] |
18,487 | hanoi.lisp | spacebat_lice/src/play/hanoi.lisp | ;;; hanoi.el --- towers of hanoi in Emacs
;; Author: Damon Anton Permezel
;; Maintainer: FSF
;; Keywords: games
; Author (a) 1985, Damon Anton Permezel
; This is in the public domain
; since he distributed it without copyright notice in 1985.
;; This file is part of GNU Emacs.
;
; Support for horizontal poles, large numbers of rings, real-time,
; faces, defcustom, and Towers of Unix added in 1999 by Alakazam
; Petrofsky <[email protected]>.
;;; Commentary:
;; Solves the Towers of Hanoi puzzle while-U-wait.
;;
;; The puzzle: Start with N rings, decreasing in sizes from bottom to
;; top, stacked around a post. There are two other posts. Your mission,
;; should you choose to accept it, is to shift the pile, stacked in its
;; original order, to another post.
;;
;; The challenge is to do it in the fewest possible moves. Each move
;; shifts one ring to a different post. But there's a rule; you can
;; only stack a ring on top of a larger one.
;;
;; The simplest nontrivial version of this puzzle is N = 3. Solution
;; time rises as 2**N, and programs to solve it have long been considered
;; classic introductory exercises in the use of recursion.
;;
;; The puzzle is called `Towers of Hanoi' because an early popular
;; presentation wove a fanciful legend around it. According to this
;; myth (uttered long before the Vietnam War), there is a Buddhist
;; monastery at Hanoi which contains a large room with three time-worn
;; posts in it surrounded by 21 golden discs. Monks, acting out the
;; command of an ancient prophecy, have been moving these disks, in
;; accordance with the rules of the puzzle, once every day since the
;; monastery was founded over a thousand years ago. They are said to
;; believe that when the last move of the puzzle is completed, the
;; world will end in a clap of thunder. Fortunately, they are nowhere
;; even close to being done...
;;
;; 1999 addition: The `Towers of Unix' command (hanoi-unix) stems from
;; the never-disproven legend of a Eunuch monastery at Princeton that
;; contains a large air-conditioned room with three time-worn posts in
;; it surrounded by 32 silicon discs. Nimble monks, acting out the
;; command of an ancient prophecy, have been moving these disks, in
;; accordance with the rules of the puzzle, once every second since
;; the monastery was founded almost a billion seconds ago. They are
;; said to believe that when the last move of the puzzle is completed,
;; the world will reboot in a clap of thunder. Actually, because the
;; bottom disc is blocked by the "Do not feed the monks" sign, it is
;; believed the End will come at the time that disc is to be moved...
;;; Code:
(in-package "LICE")
;; dynamic bondage:
(defvar baseward-step)
(defvar fly-step)
(defvar fly-row-start)
(defvar pole-width)
(defvar pole-char)
(defvar line-offset)
(defgroup hanoi nil
"The Towers of Hanoi."
:group 'games)
(defcustom hanoi-horizontal-flag nil
"*If non-nil, hanoi poles are oriented horizontally."
:group 'hanoi :type 'boolean)
(defcustom hanoi-move-period 1.0
"*Time, in seconds, for each pole-to-pole move of a ring.
If nil, move rings as fast as possible while displaying all
intermediate positions."
:group 'hanoi :type '(restricted-sexp :match-alternatives (numberp 'nil)))
(defcustom hanoi-use-faces nil
"*If nil, all hanoi-*-face variables are ignored."
:group 'hanoi :type 'boolean)
(defcustom hanoi-pole-face 'highlight
"*Face for poles. Ignored if hanoi-use-faces is nil."
:group 'hanoi :type 'face)
(defcustom hanoi-base-face 'highlight
"*Face for base. Ignored if hanoi-use-faces is nil."
:group 'hanoi :type 'face)
(defcustom hanoi-even-ring-face 'region
"*Face for even-numbered rings. Ignored if hanoi-use-faces is nil."
:group 'hanoi :type 'face)
(defcustom hanoi-odd-ring-face 'secondary-selection
"*Face for odd-numbered rings. Ignored if hanoi-use-faces is nil."
:group 'hanoi :type 'face)
;;;
;;; hanoi - user callable Towers of Hanoi
;;;
;;;###autoload
(defcommand hanoi ((nrings)
:prefix)
"Towers of Hanoi diversion. Use NRINGS rings."
(setf nrings (max 3 nrings))
;; (if (< nrings 0)
;; (error "Negative number of rings"))
(hanoi-internal nrings (make-list nrings :initial-element 0) (hanoi-current-time-float)))
;;;###autoload
(defcommand hanoi-unix ()
"Towers of Hanoi, UNIX doomsday version.
Displays 32-ring towers that have been progressing at one move per
second since 1970-01-01 00:00:00 GMT.
Repent before ring 31 moves."
(let* ((start (ftruncate (hanoi-current-time-float)))
(bits (loop repeat 32
for x = (/ start (expt 2.0 31)) then (* x 2.0)
collect (truncate (mod x 2.0))))
(hanoi-move-period 1.0))
(hanoi-internal 32 bits start)))
;;;###autoload
(defcommand hanoi-unix-64 ()
"Like hanoi-unix, but pretend to have a 64-bit clock.
This is, necessarily (as of emacs 20.3), a crock. When the
current-time interface is made s2G-compliant, hanoi.el will need
to be updated."
(let* ((start (ftruncate (hanoi-current-time-float)))
(bits (loop repeat 64
for x = (/ start (expt 2.0 63)) then (* x 2.0)
collect (truncate (mod x 2.0))))
(hanoi-move-period 1.0))
(hanoi-internal 64 bits start)))
(defun hanoi-internal (nrings bits start-time)
"Towers of Hanoi internal interface. Use NRINGS rings.
Start after n steps, where BITS is a big-endian list of the bits of n.
BITS must be of length nrings. Start at START-TIME."
(switch-to-buffer "*Hanoi*")
(buffer-disable-undo (current-buffer))
(unwind-protect
(let*
(;; These lines can cause emacs to crash if you ask for too
;; many rings. If you uncomment them, on most systems you
;; can get 10,000+ rings.
;;(max-specpdl-size (max max-specpdl-size (* nrings 15)))
;;(max-lisp-eval-depth (max max-lisp-eval-depth (+ nrings 20)))
(vert (not hanoi-horizontal-flag))
(pole-width (length (format nil "~d" (max 0 (1- nrings)))))
(pole-char (if vert #\| #\-))
(base-char (if vert #\= #\|))
(base-len (max (+ 8 (* pole-width 3))
(1- (if vert (window-width) (window-height)))))
(max-ring-diameter (truncate (- base-len 2) 3))
(pole1-coord (truncate max-ring-diameter 2))
(pole2-coord (truncate base-len 2))
(pole3-coord (- base-len (truncate (1+ max-ring-diameter) 2)))
(pole-coords (list pole1-coord pole2-coord pole3-coord))
;; Number of lines displayed below the bottom-most rings.
(base-lines
(min 3 (max 0 (- (1- (if vert (window-height) (window-width)))
(+ 2 nrings)))))
;; These variables will be set according to hanoi-horizontal-flag:
;; line-offset is the number of characters per line in the buffer.
line-offset
;; fly-row-start is the buffer position of the leftmost or
;; uppermost position in the fly row.
fly-row-start
;; Adding fly-step to a buffer position moves you one step
;; along the fly row in the direction from pole1 to pole2.
fly-step
;; Adding baseward-step to a buffer position moves you one step
;; toward the base.
baseward-step
)
(setf (buffer-read-only) nil)
(erase-buffer)
(setq truncate-lines t)
(el:if hanoi-horizontal-flag
(progn
(setq line-offset (+ base-lines nrings 3))
(setq fly-row-start (1- line-offset))
(setq fly-step line-offset)
(setq baseward-step -1)
(loop repeat base-len do
(unless (zerop base-lines)
(insert-char #\Space (1- base-lines))
(insert base-char)
(hanoi-put-face (1- (point)) (point) hanoi-base-face))
(insert-char #\Space (+ 2 nrings))
(insert #\Newline))
(delete-char -1)
(loop for coord in pole-coords do
(loop for row from (- coord (truncate pole-width 2))
for start = (+ (* row line-offset) base-lines 1)
repeat pole-width do
(subst-char-in-region start (+ start nrings 1)
#\Space pole-char)
(hanoi-put-face start (+ start nrings 1)
hanoi-pole-face))))
;; vertical
(setq line-offset (1+ base-len))
(setq fly-step 1)
(setq baseward-step line-offset)
(let ((extra-lines (- (1- (window-height)) (+ nrings 2) base-lines)))
(insert-char #\Newline (max 0 extra-lines))
(setq fly-row-start (point))
(insert-char #\Space base-len)
(insert #\Newline)
(loop repeat (1+ nrings)
with pole-line =
(loop with line = (make-string base-len :initial-element #\Space)
for coord in pole-coords
for start = (- coord (truncate pole-width 2))
for end = (+ start pole-width) do
(hanoi-put-face start end hanoi-pole-face line)
(loop for i from start below end do
(aset line i pole-char))
finally (return line))
do (insert pole-line #\Newline))
(insert-char base-char base-len)
(hanoi-put-face (- (point) base-len) (point) hanoi-base-face)
(set-window-start (selected-window)
(1+ (* baseward-step
(max 0 (- extra-lines)))))))
(let
(;; each pole is a pair of buffer positions:
;; the car is the position of the top ring currently on the pole,
;; (or the base of the pole if it is empty).
;; the cdr is in the fly-row just above the pole.
(poles (loop for coord in pole-coords
for fly-pos = (+ fly-row-start (* fly-step coord))
for base = (+ fly-pos (* baseward-step (+ 2 nrings)))
collect (cons base fly-pos)))
;; compute the string for each ring and make the list of
;; ring pairs. Each ring pair is initially (str . diameter).
;; Once placed in buffer it is changed to (center-pos . diameter).
(rings
(loop
;; radii are measured from the edge of the pole out.
;; So diameter = 2 * radius + pole-width. When
;; there's room, we make each ring's radius =
;; pole-number + 1. If there isn't room, we step
;; evenly from the max radius down to 1.
with max-radius = (min nrings
(truncate (- max-ring-diameter pole-width) 2))
for n from (1- nrings) downto 0
for radius = (1+ (truncate (* n max-radius) nrings))
for diameter = (+ pole-width (* 2 radius))
with format-str = (format nil "~~~d,'0d" pole-width)
for str = (concat (if vert "<" "^")
(make-string (1- radius) :initial-element (if vert #\- #\|))
(format nil format-str n)
(make-string (1- radius) :initial-element (if vert #\- #\|))
(if vert ">" "v"))
for face =
(if (eq (logand n 1) 1) ; oddp would require cl at runtime
hanoi-odd-ring-face hanoi-even-ring-face)
do (hanoi-put-face 0 (length str) face str)
collect (cons str diameter)))
;; Disable display of line and column numbers, for speed.
(line-number-mode nil) (column-number-mode nil))
;; do it!
(hanoi-n bits rings (car poles) (cadr poles) (caddr poles)
start-time))
(message "Done"))
(setf (buffer-read-only) t)
(force-mode-line-update)))
(defun hanoi-current-time-float ()
"Return values from current-time combined into a single float."
(+ (get-universal-time)
(/ (get-internal-real-time)
internal-time-units-per-second)))
(defun hanoi-put-face (start end value &optional object)
"If hanoi-use-faces is non-nil, call put-text-property for face property."
(if hanoi-use-faces
(put-text-property start end 'face value object)))
;;; Functions with a start-time argument (hanoi-0, hanoi-n, and
;;; hanoi-move-ring) start working at start-time and return the ending
;;; time. If hanoi-move-period is nil, start-time is ignored and the
;;; return value is junk.
;;;
;;; hanoi-0 - work horse of hanoi
(defun hanoi-0 (rings from to work start-time)
(if (null rings)
start-time
(hanoi-0 (cdr rings) work to from
(hanoi-move-ring (car rings) from to
(hanoi-0 (cdr rings) from work to start-time)))))
;; start after n moves, where BITS is a big-endian list of the bits of n.
;; BITS must be of same length as rings.
(defun hanoi-n (bits rings from to work start-time)
(cond ((null rings)
;; All rings have been placed in starting positions. Update display.
(hanoi-sit-for 0)
start-time)
((zerop (car bits))
(hanoi-insert-ring (car rings) from)
(hanoi-0 (cdr rings) work to from
(hanoi-move-ring (car rings) from to
(hanoi-n (cdr bits) (cdr rings) from work to
start-time))))
(t
(hanoi-insert-ring (car rings) to)
(hanoi-n (cdr bits) (cdr rings) work to from start-time))))
;; put never-before-placed RING on POLE and update their cars.
(defun hanoi-insert-ring (ring pole)
(decf (car pole) baseward-step)
(let ((str (car ring))
(start (- (car pole) (* (truncate (cdr ring) 2) fly-step))))
(setcar ring (car pole))
(loop for pos upfrom start by fly-step
for i below (cdr ring) do
(subst-char-in-region pos (1+ pos) (char-after pos) (aref str i))
(set-text-properties pos (1+ pos) (text-properties-at i str)))
(hanoi-goto-char (car pole))))
;; like goto-char, but if position is outside the window, then move to
;; corresponding position in the first row displayed.
(defun hanoi-goto-char (pos)
(goto-char (if (or hanoi-horizontal-flag (<= (window-start) pos))
pos
(+ (window-start) (% (- pos fly-row-start) baseward-step)))))
;; do one pole-to-pole move and update the ring and pole pairs.
(defun hanoi-move-ring (ring from to start-time)
(incf (car from) baseward-step)
(decf (car to) baseward-step)
(let* ;; We move flywards-steps steps up the pole to the fly row,
;; then fly fly-steps steps across the fly row, then go
;; baseward-steps steps down the new pole.
((flyward-steps (/ (- (car ring) (cdr from)) baseward-step))
(fly-steps (abs (/ (- (cdr to) (cdr from)) fly-step)))
(directed-fly-step (/ (- (cdr to) (cdr from)) fly-steps))
(baseward-steps (/ (- (car to) (cdr to)) baseward-step))
(total-steps (+ flyward-steps fly-steps baseward-steps))
;; A step is a character cell. A tick is a time-unit. To
;; make horizontal and vertical motion appear roughly the
;; same speed, we allow one tick per horizontal step and two
;; ticks per vertical step.
(ticks-per-pole-step (if hanoi-horizontal-flag 1 2))
(ticks-per-fly-step (if hanoi-horizontal-flag 2 1))
(flyward-ticks (* ticks-per-pole-step flyward-steps))
(fly-ticks (* ticks-per-fly-step fly-steps))
(baseward-ticks (* ticks-per-pole-step baseward-steps))
(total-ticks (+ flyward-ticks fly-ticks baseward-ticks))
(tick-to-pos
;; Return the buffer position of the ring after TICK ticks.
(lambda (tick)
(cond
((<= tick flyward-ticks)
(+ (cdr from)
(* baseward-step
(- flyward-steps (truncate tick ticks-per-pole-step)))))
((<= tick (+ flyward-ticks fly-ticks))
(+ (cdr from)
(* directed-fly-step
(truncate (- tick flyward-ticks) ticks-per-fly-step))))
(t
(+ (cdr to)
(* baseward-step
(truncate (- tick flyward-ticks fly-ticks)
ticks-per-pole-step))))))))
(declare (ignore total-steps))
(if hanoi-move-period
(loop for elapsed = (- (hanoi-current-time-float) start-time)
while (< elapsed hanoi-move-period)
with tick-period = (/ (float hanoi-move-period) total-ticks)
for tick = (ceiling (/ elapsed tick-period)) do
(hanoi-ring-to-pos ring (funcall tick-to-pos tick))
(hanoi-sit-for (- (* tick tick-period) elapsed)))
(loop for tick from 1 to total-ticks by 2 do
(hanoi-ring-to-pos ring (funcall tick-to-pos tick))
(hanoi-sit-for 0)))
;; Always make last move to keep pole and ring data consistent
(hanoi-ring-to-pos ring (car to))
(if hanoi-move-period (+ start-time hanoi-move-period))))
;; update display and pause, quitting with a pithy comment if the user
;; hits a key.
(defun hanoi-sit-for (seconds)
(unless (sit-for seconds)
(signal 'quit '("I can tell you've had enough"))))
;; move ring to a given buffer position and update ring's car.
(defun hanoi-ring-to-pos (ring pos)
(unless (= (car ring) pos)
(let* ((start (- (car ring) (* (truncate (cdr ring) 2) fly-step)))
(new-start (- pos (- (car ring) start))))
(if hanoi-horizontal-flag
(loop for i below (cdr ring)
for j = (if (< new-start start) i (- (cdr ring) i 1))
for old-pos = (+ start (* j fly-step))
for new-pos = (+ new-start (* j fly-step)) do
(transpose-regions old-pos (1+ old-pos) new-pos (1+ new-pos)))
(let ((end (+ start (cdr ring)))
(new-end (+ new-start (cdr ring))))
(if (< (abs (- new-start start)) (- end start))
;; Overlap. Adjust bounds
(if (< start new-start)
(setq new-start end)
(setq new-end start)))
(transpose-regions start end new-start new-end t))))
;; If moved on or off a pole, redraw pole chars.
(unless (eq (hanoi-pos-on-tower-p (car ring)) (hanoi-pos-on-tower-p pos))
(let* ((pole-start (- (car ring) (* fly-step (truncate pole-width 2))))
(pole-end (+ pole-start (* fly-step pole-width)))
(on-pole (hanoi-pos-on-tower-p (car ring)))
(new-char (if on-pole pole-char #\Space))
(curr-char (if on-pole #\Space pole-char))
(face (if on-pole hanoi-pole-face nil)))
(el:if hanoi-horizontal-flag
(loop for pos from pole-start below pole-end by line-offset do
(subst-char-in-region pos (1+ pos) curr-char new-char)
(hanoi-put-face pos (1+ pos) face))
(subst-char-in-region pole-start pole-end curr-char new-char)
(hanoi-put-face pole-start pole-end face))))
(setcar ring pos))
(hanoi-goto-char pos))
;; Check if a buffer position lies on a tower (vis. in the fly row).
(defun hanoi-pos-on-tower-p (pos)
(if hanoi-horizontal-flag
(/= (% pos fly-step) fly-row-start)
(>= pos (+ fly-row-start baseward-step))))
(provide 'hanoi)
;;; arch-tag: 7a901659-4346-495c-8883-14cbf540610c
;;; hanoi.el ends here
| 17,794 | Common Lisp | .lisp | 410 | 39.419512 | 91 | 0.674546 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 40a14756b2c165b74c53dd3fbbcb7d52e3bdd0772eefb5bc5a0752062e027b88 | 18,487 | [
-1
] |
18,488 | lice.asd | spacebat_lice/src/lice.asd | ;; -*- lisp -*-
(defpackage :lice-system (:use :cl :asdf))
(in-package :lice-system)
(defsystem :lice
:depends-on (#-clisp cl-ncurses cl-ppcre #+sbcl sb-posix)
:serial t
:components ((:file "package")
(:file "wrappers")
(:file "emacs")
(:file "callproc")
(:file "elisp")
(:file "global")
(:file "fns")
(:file "data")
(:file "custom")
(:file "commands")
(:file "callint")
(:file "dired")
(:file "data-types")
(:file "charset")
(:file "subprocesses")
(:file "buffer-local")
(:file "keymap")
(:file "casefiddle")
(:file "buffer")
(:file "intervals")
(:file "textprop")
(:file "search")
(:file "frame")
(:file "window")
(:file "render")
(:file "wm")
;; from this point on there are warnings because of two-way dependencies
(:file "insdel")
(:file "cmds")
(:file "editfns")
(:file "undo")
(:file "syntax")
(:file "major-mode")
(:file "keyboard")
(:file "debugger")
(:file "recursive-edit")
(:file "minibuffer")
(:file "files")
(:file "help")
(:file "debug")
#+sbcl (:file "tty-render")
#+clisp (:file "clisp-render")
(:file "indent")
(:module emacs-lisp
:serial t
:components ((:file "easy-mmode")
(:file "lisp-mode")))
(:module lisp
:serial t
:components ((:file "subr")
(:file "simple")
(:file "lisp-indent")
(:file "paragraphs")
(:file "bindings")
;; (:file "paren")
))
(:module textmodes
:serial t
:components (;; (:file "fill" :depends-on ()) ; this one is too advanced for now
(:file "text-mode")))
(:module play
:serial t
:components ((:file "dissociate")
(:file "hanoi")
(:file "doctor")))
(:file "main")))
| 2,899 | Common Lisp | .asd | 72 | 19.972222 | 106 | 0.338418 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e687c4e057a9da8bab66e5630897efa645fd02fc39440d6275d4ecf6b4d45971 | 18,488 | [
-1
] |
18,492 | Makefile.in | spacebat_lice/Makefile.in | # Nothing to do at the top level
all:
cd src && $(MAKE)
| 57 | Common Lisp | .l | 3 | 17.666667 | 32 | 0.666667 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 689f6ec65fa97d010fdddc342ebf728eae7faa29d346c47fb67c9f58328eb4fd | 18,492 | [
-1
] |
18,493 | changelog | spacebat_lice/debian/changelog | lice (2-1) unstable; urgency=low
* Initial release Closes: #nnnn (nnnn is the bug number of your ITP)
-- Trent Buck <[email protected]> Sun, 6 Nov 2005 08:45:08 +1100
| 178 | Common Lisp | .l | 3 | 56.333333 | 71 | 0.709302 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c642e3dc191424f56932320e9b39bb6751d3d67b2fa89e2fa0062ff86a299170 | 18,493 | [
-1
] |
18,494 | rules | spacebat_lice/debian/rules | #!/usr/bin/make -f
pkg := lice
debpkg := $(pkg)
clc-source := usr/share/common-lisp/source
clc-systems := usr/share/common-lisp/systems
clc-files := $(clc-source)/$(pkg)
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build: build-stamp
build-stamp: configure-stamp
dh_testdir
touch build-stamp
clean:
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
dh_clean
install: build
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs $(clc-systems) $(clc-source) $(clc-files)
dh_install $(pkg).asd $(clc-files)
dh_install "*.lisp" $(clc-files)
dh_link $(clc-files)/$(pkg).asd $(clc-systems)/$(pkg).asd
binary-indep: build install
dh_testdir
dh_testroot
dh_installchangelogs
dh_installdocs
dh_installexamples
dh_installman
dh_link
dh_strip
dh_compress
dh_fixperms
dh_lisp
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary-arch: build install
binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configure
| 1,032 | Common Lisp | .l | 47 | 20.191489 | 69 | 0.775407 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b9e91f46f452c5ea79f813341a3db33232396011543f88c551baa3e715af7fa3 | 18,494 | [
-1
] |
18,495 | control | spacebat_lice/debian/control | Source: lice
Section: editors
Priority: optional
Maintainer: Trent Buck <[email protected]>
Build-Depends: debhelper (>= 4.0.0)
Standards-Version: 3.6.2
Package: lice
Architecture: all
Depends: ${shlibs:Depends}, ${misc:Depends}, cl-uffi, cl-ncurses
Description: The Lisp Computing Environment (Emacs for Common Lisp)
LiCE is a GNU Emacs clone written entirely in Common Lisp.
.
It has been tested it on CMUCL, SBCL, and Movitz. With a
little work it could probably run on more.
| 487 | Common Lisp | .l | 14 | 33.357143 | 67 | 0.783898 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d4826129304cb6a503952ec383e0b4435fc9777b9678827540198d42e9b73890 | 18,495 | [
-1
] |
18,525 | Makefile.in | spacebat_lice/src/Makefile.in | # choose your lisp and appropriate lisp_opts
LISP=@LISP_PROGRAM@
clisp_OPTS=-K full -on-error exit -i ~/.clisprc ./make-image.lisp
sbcl_OPTS=--load ./make-image.lisp
LISP_OPTS= $(@LISP@_OPTS)
# This is copied from the .asd file. It'd be nice to have the list in
# one place, but oh well.
FILES=package.lisp wrappers.lisp global.lisp custom.lisp commands.lisp data-types.lisp keymap.lisp casefiddle.lisp subprocesses.lisp buffer-local.lisp buffer.lisp intervals.lisp textprop.lisp search.lisp frame.lisp window.lisp render.lisp wm.lisp insdel.lisp cmds.lisp editfns.lisp undo.lisp syntax.lisp major-mode.lisp keyboard.lisp debugger.lisp recursive-edit.lisp minibuffer.lisp files.lisp help.lisp debug.lisp tty-render.lisp clisp-render.lisp main.lisp lisp/subr.lisp lisp/simple.lisp indent.lisp emacs-lisp/lisp-mode.lisp lisp/lisp-indent.lisp lisp/paragraphs.lisp textmodes/text-mode.lisp play/doctor.lisp play/hanoi.lisp
all: lice
lice: $(FILES)
$(LISP) $(LISP_OPTS)
etags: TAGS
etags `find . -name \*.lisp` # we could use FILES but it just isn't always up to date
clean:
rm -f *.fasl *.fas *.lib lice
| 1,110 | Common Lisp | .l | 15 | 72.333333 | 630 | 0.780331 | spacebat/lice | 3 | 1 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 753a2936ec5ae18a987708f3c57ed312b53d2771ab9423180492aaedf71d312a | 18,525 | [
-1
] |
18,570 | ex-colors.lisp | justjoheinz_controlcl/examples/ex-colors.lisp | (in-package :cl-user)
(uiop:define-package controlcl/ex-colors
(:use :cl :controlcl :cl-sdl2-hershey)
(:export
#:main))
(in-package :controlcl/ex-colors)
(defun main ()
(sdl2:with-init (:everything)
(sdl2:with-window (window :title "ControlCL Example-Colors" :w 700 :h 300 :flags '(:shown))
(sdl2:with-renderer (renderer window :flags '(:accelerated))
(controlcl-init)
(sdl2:with-event-loop (:method :poll)
(:keyup (:keysym keysym)
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape)
(sdl2:push-event :quit)))
(:idle ()
(sdl2:render-clear renderer)
(let ((num-colors (/ (length controlcl:*colors*) 2)))
;; we have 21 colors - I would like to create a 7 x 3 grid when iterating
;; over the colors
;;
(loop for (name color-code) on controlcl:*colors* by #'cddr
for i from 0 below num-colors
for y = (floor (/ i 7))
for x = (mod i 7)
for text = (format nil "~a" name)
do (progn
(set-color-from-code renderer color-code)
(sdl2:with-rects ((rect (* x 100) (* y 100) 100 100))
(sdl2:render-fill-rects renderer rect 1))))
(sdl2:render-present renderer)
(sdl2:delay 40)))
(:quit () t))))))
| 1,570 | Common Lisp | .lisp | 33 | 32.30303 | 95 | 0.494785 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f2f960b3f1ba5ca21ce30e64ae9cdc7048608d478bbaf63d7f090806a51a2abc | 18,570 | [
-1
] |
18,571 | ex-ctrl.lisp | justjoheinz_controlcl/examples/ex-ctrl.lisp | (in-package :cl-user)
(uiop:define-package controlcl/ex-ctrl
(:use :cl :controlcl :sdl2)
(:export
#:main))
(in-package :controlcl/ex-ctrl)
(defmethod on-event ((ctrl controller) (evt event-value))
(let ((source (event-source evt))
(target (controller-id ctrl)))
(if (and (eq target 'rocket)
(or (eq source 'rocket-x) (eq source 'rocket-y)))
(let ((x (controller-value (controlcl-get-ctrl 'rocket-x)))
(y (controller-value (controlcl-get-ctrl 'rocket-y))))
(controller-move-to (controlcl-get-ctrl 'rocket) :x x :y y)))))
;; define an on-event handler if the launch controller is clicked
;; this will move the rocket to the top of the window
(defmethod on-event ((ctrl controller) (evt event-mouse-clicked))
(log4cl:log-info "Handling mouse button down event bang")
(let ((target (controller-id ctrl)))
(if (eq target 'launch)
(controller-move-to (controlcl-get-ctrl 'rocket) :x 400 :y 50))))
(defun main ()
;; Themes can be set globally or with lexical scoping
(setq *current-theme* *theme-cp5blue*)
(sdl2:with-init (:everything)
(sdl2:with-window (window :title "ControlCL Testing" :w 800 :h 600 :flags '(:shown))
(sdl2:with-renderer (renderer window :flags '(:accelerated))
;; set up the lexical scope of the controlcl instance
(controlcl:with-controlcl renderer
(let ((r-x 150)
(r-y 60))
(controlcl-add-slider :id 'rocket-x
:name "Rocket-X"
:x 20 :y 50
:value r-x :min-value 0 :max-value 400)
(controlcl-add-slider :id 'rocket-y
:name "Rocket-Y"
:x 20 :y 100
:value r-y :min-value 0 :max-value 400)
(controlcl-add-checkbox :id 'boarding-complete :name "Boarding Complete"
:x 20 :y 150)
(controlcl-add-bang :id 'launch :name "Launch"
:x 20 :y 200)
(controlcl-add-image :id 'rocket :name "Rocket"
:x r-x :y r-y :w nil :h nil
:sticky t
:rel-image-path "docs/rocket.png"))
(sdl2:with-event-loop (:method :poll)
(:mousemotion (:x x :y y)
(log4cl:log-info "Handling mouse motion event")
(let ((evt (make-instance 'event-mouse :x x :y y)))
(controlcl-emit-event evt)))
(:mousebuttondown (:x x :y y)
(log4cl:log-info "Handling mouse button down event")
(let ((evt (make-instance 'event-mouse-clicked :x x :y y)))
(controlcl-emit-event evt)))
(:keyup (:keysym keysym)
;; ESC - quit
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape)
(sdl2:push-quit-event))
;; h - hide all controllers
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-h)
(controlcl-hide))
;; s - show all controllers
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-s)
(controlcl-show))
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-1)
(let ((ctrl (controlcl-get-ctrl 'rocket-x)))
(decf (controller-value ctrl))))
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-2)
(let ((ctrl (controlcl-get-ctrl 'rocket-x)))
(incf (controller-value ctrl))))
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-3)
(let ((ctrl (controlcl-get-ctrl 'rocket-y)))
(decf (controller-value ctrl))))
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-4)
(let ((ctrl (controlcl-get-ctrl 'rocket-y)))
(incf (controller-value ctrl)))))
(:quit () t)
(:idle ()
(sdl2:mouse-state)
(sdl2:render-clear renderer)
(controlcl-draw)
(set-color-from-palette renderer :black)
(sdl2:render-present renderer)
(sdl2:delay 10))))))))
| 4,629 | Common Lisp | .lisp | 86 | 36.674419 | 89 | 0.505628 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | c4813a16dc0015554f70b77cc71edefe96a1f3b0cf19aa5c115e6b841ffac896 | 18,571 | [
-1
] |
18,572 | ex-theme.lisp | justjoheinz_controlcl/examples/ex-theme.lisp | (uiop:define-package controlcl/ex-theme
(:use :cl :controlcl :sdl2 :cl-sdl2-hershey)
(:export
#:main))
(in-package :controlcl/ex-theme)
(defun render-theme (renderer y &optional (*current-theme* *current-theme*))
(sdl2:with-rects ((rect-000 0 y 100 100)
(rect-100 100 y 100 100)
(rect-200 200 y 100 100)
(rect-300 300 y 100 100)
(rect-400 400 y 100 100))
;; fg, active, value
(set-color-from-theme renderer :fg)
(sdl2:render-fill-rect renderer rect-000)
(with-font (*roman-simplex-font* 0.35)
(set-color-from-theme renderer :value)
(render-hershey-string renderer 25 (+ y 50) "VALUE"))
;;bg
(set-color-from-theme renderer :bg)
(sdl2:render-fill-rect renderer rect-100)
;; active
(set-color-from-theme renderer :active)
(sdl2:render-fill-rect renderer rect-200)
;; caption
(set-color-from-theme renderer :caption)
(sdl2:render-fill-rect renderer rect-300)
;; value
(set-color-from-theme renderer :value)
(sdl2:render-fill-rect renderer rect-400)))
(defun main ()
(sdl2:with-init (:everything)
(sdl2:with-window (window :title "ControlCL Example-Theme" :w 500 :h 600 :flags '(:shown))
(sdl2:with-renderer (renderer window :flags '(:accelerated))
(controlcl-init)
(sdl2:with-event-loop (:method :poll)
(:keyup (:keysym keysym)
(when (sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape)
(sdl2:push-quit-event)))
(:idle ()
(sdl2:render-clear renderer)
(loop for theme in (list *theme-retro* *theme-cp52014* *theme-cp5blue*
*theme-red* *theme-grey* *theme-a*)
for y = 0 then (+ y 100)
do (with-theme (theme)
(render-theme renderer y)))
;; draw background
(sdl2:set-render-draw-color renderer 0 0 0 0)
(sdl2:render-present renderer)
(sdl2:delay 40))
(:quit () t))))))
| 2,163 | Common Lisp | .lisp | 50 | 32.42 | 94 | 0.570409 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 8b9b613421e32bf135b7d241a0d5bb654fcb40031f617c213639cc5a1d477444 | 18,572 | [
-1
] |
18,573 | package.lisp | justjoheinz_controlcl/src/package.lisp | (in-package :cl-user)
(uiop:define-package :controlcl
(:use :cl :cl-sdl2-hershey)
(:import-from :alexandria
#:clamp)
(:import-from :assoc-utils
#:aget
#:alist-values)
(:import-from :event-emitter
#:event-emitter
#:on
#:emit
#:once)
(:export
#:*theme-retro*
#:*theme-cp52014*
#:*theme-cp5blue*
#:*theme-red*
#:*theme-grey*
#:*theme-a*
#:*current-theme*
#:theme-fg-color
#:theme-bg-color
#:theme-active-color
#:theme-caption-color
#:theme-value-color
#:color-values
#:*colors*
#:set-color-from-theme
#:set-color-from-code
#:set-color-from-palette
#:v-factor
#:with-theme
#:point-in-rect
#:controlcl-version
#:controlcl-init
#:render-text
#:slider
#:slider-name
#:slider-min-value
#:slider-max-value
#:bang
#:bang-name
#:controller-mouse-over-p
#:controller-hide
#:controller-show
#:controller-draw
#:controller
#:controller-x
#:controller-y
#:controller-w
#:controller-h
#:controller-value
#:controller-id
#:controller-visible
#:controller-mouse-over
#:controller-set-mouse-over-color
#:controlcl
#:controlcl-controllers
#:controlcl-renderer
#:with-controlcl
#:controlcl-draw
#:controlcl-show
#:controlcl-hide
#:controlcl-add-bang
#:controlcl-add-slider
#:controlcl-mouse-over
#:controlcl-add-image
#:*controlcl*
#:from
#:controlcl-get-ctrl
#:controlcl-move-to
#:controller-move-to
#:event
#:event-id
#:event-source
#:event-target
#:event-mouse
#:event-mouse-x
#:event-mouse-y
#:event-mouse-button
#:event-mouse-modifiers
#:event-key
#:event-key-key
#:event-key-modifiers
#:event-value
#:event-value-old
#:event-value-new
#:controlcl-emit-event
#:on-event
#:checkbox
#:controlcl-add-checkbox
#:event-mouse-clicked
#:event-mouse-clicked-x
#:event-mouse-clicked-y))
| 2,028 | Common Lisp | .lisp | 95 | 16.494737 | 36 | 0.627847 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6c2a47d85cbbf66fe5615de61cb5e34d4286e25304a1e8c7b73ca6f3377756a1 | 18,573 | [
-1
] |
18,574 | checkbox.lisp | justjoheinz_controlcl/src/checkbox.lisp | (in-package :controlcl)
;; BANG
(defclass checkbox (controller)
((name :initarg :name :accessor bang-name :initform nil)
(w :initform (error "you must provide a width"))
(h :initform (error "you must provide a height"))))
(defun set-checkbox-color (ctrl)
(with-slots (value renderer) ctrl
(if value
(set-color-from-theme renderer :active)
(if (controller-mouse-over ctrl)
(set-color-from-theme renderer :fg)
(set-color-from-theme renderer :bg)))))
(defmethod controller-draw ((ctrl checkbox))
(with-slots (x y w h renderer) ctrl
(set-checkbox-color ctrl)
(sdl2:with-rects ((rect x y w h))
(sdl2:render-fill-rect renderer rect))
(set-color-from-theme renderer :caption)
(with-font (*roman-plain-font* 0.6)
(render-text renderer x (+ y h 10) (bang-name ctrl)))))
(defmethod on-event ((ctrl checkbox) (evt event-mouse-clicked))
(with-slots (x y) evt
(if (controller-mouse-over-p ctrl :x x :y y)
(setf (controller-value ctrl) (not (controller-value ctrl))))))
| 1,059 | Common Lisp | .lisp | 25 | 37.24 | 71 | 0.666667 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a8c56f38ce778d28a299e22b814b0ab03297e2dcc1eae1235a95acb84714cc0c | 18,574 | [
-1
] |
18,575 | image.lisp | justjoheinz_controlcl/src/image.lisp | (in-package :controlcl)
;; IMAGE
(defclass image (controller)
((name :initarg :name :accessor image-name :initform nil)
(surface :initarg :surface :accessor image-surface :initform nil)
(w :initform nil)
(h :initform nil)))
(defmethod controller-draw ((ctrl image))
(with-slots (x y w h surface renderer) ctrl
(sdl2:with-rects ((rect x y w h))
(let* ((texture (sdl2:create-texture-from-surface renderer surface)))
(sdl2:render-copy renderer texture :dest-rect rect)
(sdl2:destroy-texture texture)))))
| 543 | Common Lisp | .lisp | 13 | 37.538462 | 75 | 0.70019 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2163595664542683db430d2ccde02949320b69847c33f89aac55dfd3b26daa28 | 18,575 | [
-1
] |
18,576 | utils.lisp | justjoheinz_controlcl/src/utils.lisp | (in-package :controlcl)
;; UTILITIES
(defvar *controlcl-event* (sdl2:register-user-event-type :controlcl))
(declaim (ftype (function (number number number number number number) boolean) point-in-rect))
(defun point-in-rect (x y w h x1 y1)
"Return true if the point x1,y1 is inside the rectangle x,y,w,h"
(and (<= x x1 (+ x w))
(<= y y1 (+ y h))))
(declaim (ftype (function (number number number) boolean) v-float))
(defun v-factor (value min-v max-v)
"Return a value between 0 and 1, expressing the relation of value to min-v and max-v."
(let ((v (- value min-v))
(max (- max-v min-v)))
(/ v max)))
;; helper methods to encapsulate calls to cl-sdl2-hershey
(defgeneric render-text (renderer x y text)
(:documentation "Render text at x,y"))
(defmethod render-text (renderer x y (text string))
(cl-sdl2-hershey:render-hershey-string renderer x y text))
(defun controlcl-init ()
"Initialize the controlcl library"
(hershey-init))
(defun controlcl-version ()
"Return the version of the controlcl library"
(asdf:component-version (asdf:find-system :controlcl)))
(defun renderer-p (obj)
"Return true if obj is a renderer or nil"
(or (null obj) (typep obj 'sdl2-ffi:sdl-renderer)))
| 1,231 | Common Lisp | .lisp | 28 | 41 | 94 | 0.707809 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 49f0e226bda858262086fee1581abcbb5c1daa56d1563f8a1a8e485629096827 | 18,576 | [
-1
] |
18,577 | ctrl.lisp | justjoheinz_controlcl/src/ctrl.lisp | (in-package :controlcl)
;; CONTROLLER
(defclass controller (event-emitter)
((x :initarg :x
:accessor controller-x :initform nil
:documentation "x position of the controller")
(y :initarg :y
:accessor controller-y :initform nil
:documentation "y position of the controller")
(w :initarg :w
:accessor controller-w :initform nil
:documentation "width of the controller")
(h :initarg :h
:accessor controller-h :initform nil
:documentation "height of the controller")
(value :initarg :value
:accessor controller-value :initform nil
:documentation "value of the controller")
(id :initarg :id :accessor controller-id
:initform (error "An id must be provided to a controller")
:documentation "id of the controller.
IDs are symbols and have to be unique across all controllers.
They are used to identify the source and targets of events.")
(visible :initarg :visible :accessor controller-visible
:initform t
:documentation "visible flag of the controller.
Visible controllers are drawn by the renderer.")
(active :initarg :active :accessor controller-active
:initform t
:documentation "active flag of the controller.
Active controllers are currently selected and can decide to render or behave differently.")
(sticky :initarg :sticky :accessor controller-sticky
:initform nil
:documentation "sticky flag of the controller.
Sticky controllers are not hidden when the VISIBLE flag is set to NIL.")
(mouse-over :initarg :mouse-over :accessor controller-mouse-over
:initform nil
:documentation "mouse-over flag of the controller.
Indicates that the mouse hovers over the controller.")
(renderer :initarg :renderer :accessor controller-renderer
:initform nil
:documentation "The renderer associated with the controller."))
(:documentation "A controller is a visual element that can be drawn and interacted with."))
;; check the types after instantiation
(defmethod initialize-instance :after ((ctrl controller) &key)
(with-slots (x y w h id renderer) ctrl
(unless (and (integerp x) (integerp y) (integerp w) (integerp h))
(error "x,y,w,h must be integers"))
(unless (symbolp id)
(error "id must be a symbol"))
(unless (renderer-p renderer)
(error "renderer must be a sdl2 renderer"))
(on :controlcl-event ctrl (lambda (ctrl evt)
(log4cl:log-info "event ~S~&controller ~S~&"
(event-id evt)
(controller-id ctrl))
(on-event ctrl evt))))
)
(defmethod (setf controller-value) :around (new-value (ctrl controller))
(let ((old-value (controller-value ctrl)))
(when (next-method-p)
(when (not (equal old-value new-value))
(let ((event (make-instance 'event-value
:source (controller-id ctrl)
:old old-value
:new new-value)))
(prog1
(call-next-method)
(controlcl-emit-event event)))))))
;; generic function definitions
(defgeneric on-event (controller event))
(defmethod on-event ((ctrl t) (evt t))
nil)
(defmethod on-event :around ((ctrl controller) (evt event-mouse))
(log4cl:log-info "on-event ~S~&controller ~S~&" (event-id evt) (controller-id ctrl))
(with-slots (x y) evt
(let* ((active (controller-active ctrl))
(mouse-over (controller-mouse-over-p ctrl :x x :y y)))
(setf (controller-mouse-over ctrl) (and active mouse-over))
(when (next-method-p)
(call-next-method)))
)
)
(defgeneric controller-draw (controller)
(:documentation "draw the controller to the renderer"))
(defmethod controller-draw :around ((ctrl controller))
(when (and (controller-visible ctrl) (next-method-p))
(call-next-method)))
(defgeneric controller-show (controller)
(:documentation "show the controller.
By default it sets the VISIBLE flag to T.
")
(:method ((ctrl controller))
(setf (controller-visible ctrl) t)))
(defgeneric controller-hide (controller)
(:documentation "Hide the controller.
By default it sets the VISIBLE flag to NIL, unless the STICKY flag for the controller is set.")
(:method ((ctrl controller))
(setf (controller-visible ctrl) (or nil (controller-sticky ctrl)))))
(defgeneric controller-move-to (controller &key x y)
(:documentation "move the controller to the position x,y")
(:method ((ctrl controller) &key x y)
(setf (controller-x ctrl) x
(controller-y ctrl) y)))
(defgeneric controller-mouse-over-p (controller &key x y)
(:documentation "return T if the point x,y is over the controller")
(:method ((ctrl controller) &key x y)
(point-in-rect (controller-x ctrl) (controller-y ctrl)
(controller-w ctrl) (controller-h ctrl) x y)))
(defgeneric controller-set-mouse-over-color (controller)
(:documentation "decide if the active or foreground color should be returned")
(:method ((ctrl controller))
(let ((color-key (if (controller-mouse-over ctrl) :active :fg)))
(set-color-from-theme (controller-renderer ctrl) color-key))))
| 5,364 | Common Lisp | .lisp | 114 | 39.429825 | 95 | 0.662651 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a1d392a52c138442b085a2f9e9693f5b47dddb0846476772e7734cdfb9c6cdfa | 18,577 | [
-1
] |
18,578 | events.lisp | justjoheinz_controlcl/src/events.lisp | (in-package :controlcl)
(defclass event ()
((id :reader event-id :initarg :id :initform nil :allocation :class)
(source :initarg :source :accessor event-source :initform nil)
(target :initarg :target :accessor event-target :initform nil))
(:documentation "An event is a message sent from one object to another.
If the target is nil the event is considered to be a broadcast event."))
(defclass event-mouse (event)
((id :initform :event-mouse)
(x :initarg :x :accessor event-mouse-x)
(y :initarg :y :accessor event-mouse-y)
(button :initarg :button :accessor event-mouse-button :initform nil)
(modifiers :initarg :modifiers :accessor event-mouse-modifiers :initform nil))
(:documentation "A mouse event is an event that is generated by the mouse."))
(defclass event-mouse-clicked (event)
((id :initform :event-mouse-clicked)
(x :initarg :x :accessor event-mouse-clicked-x)
(y :initarg :y :accessor event-mouse-clicked-y))
(:documentation "A mouse clicked event is an event that is generated by the mouse when a button is clicked."))
(defclass event-key (event)
((id :initform :event-key)
(key :initarg :key :accessor event-key-key)
(modifiers :initarg :modifiers :accessor event-key-modifiers))
(:documentation "A key event is an event that is generated by the keyboard."))
(defclass event-value (event)
((id :initform :event-value)
(old :initarg :old :accessor event-value-old)
(new :initarg :new :accessor event-value-new))
(:documentation "A value event is an event that is generated by a value changing."))
| 1,571 | Common Lisp | .lisp | 29 | 51.068966 | 112 | 0.735849 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 30bb6c82eb811340e2cb2c461d7ef69867bcca6a7746c5bcc2c2ff25ceff1b14 | 18,578 | [
-1
] |
18,579 | controlcl.lisp | justjoheinz_controlcl/src/controlcl.lisp | (in-package :controlcl)
;; CONTROLCL
(defclass controlcl (event-emitter)
((controllers :initarg :controllers :accessor controlcl-controllers :initform nil)
(renderer :initarg :renderer :accessor controlcl-renderer :initform nil))
(:documentation "ControlCL main class.
An instance holds references to all controllers and is reponsible for
delegating events to them."))
(declaim (type (or controlcl null) *controlcl*))
(defvar *controlcl* nil
"The global controlcl instance.
This should be created with WITH-CONTROLCL macro.")
(defmacro with-controlcl (renderer &body body)
`(let ((*controlcl* (make-instance 'controlcl :renderer ,renderer)))
(controlcl-init)
(sdl2-image:init '(:png))
(unwind-protect
(progn ,@body))
(sdl2-image:quit)))
(defmacro do-ctrls ((ctrl controlcl) &body body)
`(dolist (,ctrl (alist-values (controlcl-controllers ,controlcl)))
,@body))
(defun controlcl-draw ()
(do-ctrls (ctrl *controlcl*)
(controller-draw ctrl)))
(defun controlcl-show ()
(do-ctrls (ctrl *controlcl*)
(controller-show ctrl)))
(defun controlcl-hide ()
(do-ctrls (ctrl *controlcl*)
(controller-hide ctrl)))
(defun controlcl-get-ctrl (id)
"get the CTRL from *CONTROLCL* with the id"
(aget (controlcl-controllers *controlcl*) id))
(defgeneric controlcl-emit-event (event))
(defmethod controlcl-emit-event ((event event))
(with-slots (id source target) event
(log4cl:log-info "emit-event ~S : ~S -> ~S" id source target)
(if (null target)
(do-ctrls (ctrl *controlcl*)
(unless (eq (controller-id ctrl) source)
(emit :controlcl-event ctrl ctrl event))) ; broadcast
(let ((ctrl (controlcl-get-ctrl target)))
(unless (eq (controller-id ctrl) source)
(emit :controlcl-event ctrl ctrl event))))))
(defun controlcl-add-bang (&key id name x y (w 20) (h 20) sticky)
(let ((bang (make-instance 'bang :id id
:name name :x x :y y :w w :h h
:sticky sticky
:renderer (controlcl-renderer *controlcl*))))
(setf (aget (controlcl-controllers *controlcl*) id) bang)
bang))
(defun controlcl-add-checkbox (&key id name x y (w 20) (h 20) sticky)
(let ((checkbox (make-instance 'checkbox :id id
:name name :x x :y y :w w :h h
:sticky sticky
:renderer (controlcl-renderer *controlcl*))))
(setf (aget (controlcl-controllers *controlcl*) id) checkbox)
checkbox))
(defun controlcl-add-slider (&key id name x y (w 100) (h 20) value min-value max-value sticky)
(assert (<= min-value value max-value)
(min-value value max-value)
"It must be T that MIN-VALUE <= VALUE <= MAX-VALUE (~S <= ~S <= ~S)." min-value value max-value)
(let ((slider (make-instance 'slider :id id
:name name
:x x :y y :w w :h h
:value value
:min-value min-value :max-value max-value
:sticky sticky
:renderer (controlcl-renderer *controlcl*))))
(setf (aget (controlcl-controllers *controlcl*) id) slider)
slider))
(defun controlcl-add-image (&key id name x y w h sticky rel-image-path)
(let* ((image-path (asdf:system-relative-pathname :controlcl rel-image-path))
(surface (sdl2-image:load-image image-path))
(w1 (or w (sdl2:surface-width surface)))
(h1 (or h (sdl2:surface-height surface)))
(image (make-instance 'image :id id
:name name :x x :y y :w w1 :h h1
:sticky sticky
:surface surface
:renderer (controlcl-renderer *controlcl*))))
(setf (aget (controlcl-controllers *controlcl*) id) image)
image))
(defun controlcl-mouse-over (&key x y)
(do-ctrls (ctrl *controlcl*)
(setf (controller-mouse-over ctrl) (controller-mouse-over-p ctrl :x x :y y))))
(defun controlcl-move-to (&key x y)
(do-ctrls (ctrl *controlcl*)
(controller-move-to ctrl :x x :y y)))
| 4,384 | Common Lisp | .lisp | 90 | 37.766667 | 107 | 0.58796 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4b4f0b00bbc4008bc89649066bc30ba27df4c789ecd83a31cac791ba57bdb855 | 18,579 | [
-1
] |
18,580 | bang.lisp | justjoheinz_controlcl/src/bang.lisp | (in-package :controlcl)
;; BANG
(defclass bang (controller)
((name :initarg :name :accessor bang-name :initform nil)
(w :initform (error "you must provide a width"))
(h :initform (error "you must provide a height"))))
(defmethod controller-draw ((ctrl bang))
(with-slots (x y w h renderer) ctrl
(controller-set-mouse-over-color ctrl)
(sdl2:with-rects ((rect x y w h))
(sdl2:render-fill-rect renderer rect))
(set-color-from-theme renderer :caption)
(with-font (*roman-plain-font* 0.6)
(render-text renderer x (+ y h 10) (bang-name ctrl)))))
| 581 | Common Lisp | .lisp | 14 | 37.571429 | 61 | 0.680851 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e69f849076f726f2a6a270cc40efe5a316fe00cbedc2fd6181e0e4caa686fff2 | 18,580 | [
-1
] |
18,581 | slider.lisp | justjoheinz_controlcl/src/slider.lisp | (in-package :controlcl)
;; SLIDER
(defclass slider (controller)
((name :initarg :name :accessor slider-name :initform nil)
(min-value :initarg :min-value :accessor slider-min-value :initform 0)
(max-value :initarg :max-value :accessor slider-max-value :initform 100)
(value :initform 0)
(w :initform (error "you must provide a width"))
(h :initform (error "you must provide a height"))))
(defmethod (setf controller-value) (value (ctrl slider))
(setf (slot-value ctrl 'value)
(clamp value
(slider-min-value ctrl)
(slider-max-value ctrl))))
(defmethod controller-draw ((ctrl slider))
(with-slots (x y w h min-value max-value value renderer) ctrl
(let* ((cv (clamp value min-value max-value))
(v-factor (v-factor cv min-value max-value))
(h2 (/ h 2)))
(sdl2:with-rects ((rect-bg x y w h)
(rect-fg x y (floor (* w v-factor)) h))
(set-color-from-theme renderer :bg)
(sdl2:render-fill-rect renderer rect-bg)
(controller-set-mouse-over-color ctrl)
(sdl2:render-fill-rect renderer rect-fg))
(with-font (*roman-plain-font* 0.6)
(set-color-from-theme renderer :caption)
(render-text renderer (+ x w 10) (+ y h2) (slider-name ctrl))
(set-color-from-theme renderer :value)
(render-text renderer (+ x 5 ) (+ y h2) (format nil "~a" cv))))))
| 1,421 | Common Lisp | .lisp | 30 | 39.933333 | 75 | 0.628344 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f010cc154253fc80ca20016285c6555c7eff64fb4f34f932a906f7f2a8aa7f0c | 18,581 | [
-1
] |
18,582 | theme.lisp | justjoheinz_controlcl/src/theme.lisp | (in-package :controlcl)
;; /* http://clrs.cc/ */
;;other colors: #ff3838 red-salmon; #08ffb4 turquoise; #40afff light-blue; #f3eddb beige;
(defvar *colors* '(:navy #xFF001F3F :blue #xFF0074D9 :aqua #xFF7FDBFF :teal #xFF39CCCC
:olive #xFF3D9970 :green #xFF2ECC40 :lime #xFF01FF70 :yellow #xFFFFDC00
:orange #xFFFF851B :red #xFFFF4136 :maroon #xFF85144B :fuchsia #xFFF012BE
:purple #xFFB10DC9 :white #xFFFFFFFF :silver #xFFDDDDDD :gray #xFFAAAAAA
:black #xFF111111 :red-salmon #xFFff3838 :turquoise #xFF08ffb4
:light-blue #xFF40afff :beige #xFFf3eddb)
"A list of colors with their hexadecimal codes.")
;; Color themes with fg, bg, active, caption, value
(defvar *theme-retro* '(:fg #xFF00698c :bg #xFF003652 :active #xFF08a2cf :caption #xFFFFFFFF :value #xFFFFFFFF))
(defvar *theme-cp52014* '(:fg #xFF0074D9 :bg #xFF002D5A :active #xFF00aaFF :caption #xFFFFFFFF :value #xFFFFFFFF))
(defvar *theme-cp5blue* '(:fg #xFF016c9e :bg #xFF02344d :active #xFF00b4ea :caption #xFFFFFFFF :value #xFFFFFFFF))
(defvar *theme-red* '(:fg #xFFaa0000 :bg #xFF660000 :active #xFFFF0000 :caption #xFFFFFFFF :value #xFFFFFFFF))
(defvar *theme-grey* '(:fg #xFFeeeeee :bg #xFFbbbbbb :active #xFFFFFFFF :caption #xFF555555 :value #xFF555555))
(defvar *theme-a* '(:fg #xFF00FFC8 :bg #xFF00D7FF :active #xFFFFFF00 :caption #xFF00B0FF :value #xFF00B0FF))
(defvar *current-theme* *theme-retro*
"The current theme.")
(defmacro with-theme ((theme) &body body)
"Used to dynamically bind the *CURRENT-THEME* variable to the given theme."
`(let ((*current-theme* ,theme))
,@body))
(defun theme-fg-color (&optional (theme *current-theme*))
"Return the foreground color of the *CURRENT-THEME* or optionally given THEME."
(getf theme :fg))
(defun theme-bg-color (&optional (theme *current-theme*))
"Return the background color of the *CURRENT-THEME* or optionally given THEME."
(getf theme :bg))
(defun theme-active-color (&optional (theme *current-theme*))
"Return the active color of the *CURRENT-THEME* or optionally given THEME."
(getf theme :active))
(defun theme-caption-color (&optional (theme *current-theme*))
"Return the caption color of the *CURRENT-THEME* or optionally given THEME."
(getf theme :caption))
(defun theme-value-color (&optional (theme *current-theme*))
"Return the value color of the *CURRENT-THEME* or optionally given THEME."
(getf theme :value))
(defun color-values (color)
"Return the encoded alpha, red, green, blue values of a color"
(let ((alpha (ash (logand color #xFF000000) -24))
(red (ash (logand color #x00FF0000) -16))
(green (ash (logand color #x0000FF00) -8))
(blue (logand color #x000000FF)))
(values alpha red green blue)))
(defun set-color-from-palette (renderer color-key &optional (colors *colors*))
"Set a color from a palette of colors."
(declare (type keyword color-key))
(set-color-from-code renderer (getf colors color-key)))
(defun set-color-from-code (renderer color-code)
"Set the color from a hexadecimal code, like #xFF0000FF.
The order is a r g b."
(multiple-value-bind (a r g b)
(color-values color-code)
(sdl2:set-render-draw-color renderer r g b a)))
(defun set-color-from-theme (renderer color-key &optional (current-theme *current-theme*))
"Set the color from the *CURRENT-THEME* or THEME when given."
(declare (type keyword color-key))
(set-color-from-code renderer (getf current-theme color-key)))
| 3,532 | Common Lisp | .lisp | 59 | 55.372881 | 114 | 0.709986 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 74535586960b3db6aa4f8ea7fc3b71ec6c1575f8263da41eb32e7c979b7e7fc4 | 18,582 | [
-1
] |
18,583 | tests-slider.lisp | justjoheinz_controlcl/t/tests-slider.lisp | (in-package :controlcl/tests)
(defvar *slider* nil)
(defhook setup :before
(setq *controlcl* (make-instance 'controlcl:controlcl))
(setq *slider* (make-instance 'slider :id 'slider :name "test-slider"
:x 10 :y 10 :w 100 :h 20
:value 50 :min-value 0 :max-value 100)))
(deftest slider-controller
(testing "Slider is correctly initialised"
(ok (= (controller-value *slider*) 50)))
(testing "Setter for value, min-value, max-value. Value cannot be set out of bounds."
(ok (= (setf (controller-value *slider*) -1) 0))
(ok (= (setf (controller-value *slider*) 101) 100))
(ok (= (setf (controller-value *slider*) 50) 50)))
(testing "Instantiation via controlcl-add-slider"
;; since value is out of bounds
(ok (signals (controlcl-add-slider :id 'slider
:name "asdf"
:x 10 :y 10 :w 100 :h 20
:value -5 :min-value 0 :max-value 100)))
;; id is missing
(ok (signals (controlcl-add-slider :name "asdf"
:x 10 :y 10 :w 100 :h 20
:value -5 :min-value 0 :max-value 100)))))
| 1,381 | Common Lisp | .lisp | 24 | 38.958333 | 89 | 0.488166 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0fcabd15c939362fb61d36a92b53f6d1859982aa3934869287a3555e6392066e | 18,583 | [
-1
] |
18,584 | tests-controlcl.lisp | justjoheinz_controlcl/t/tests-controlcl.lisp |
;; internal tests
(in-package :controlcl/tests)
(deftest v-factor-tests
(testing "v-factor"
(ok (= (v-factor 50 0 100) 1/2))
(ok (= (v-factor 100 0 100) 1))
(ok (= (v-factor 0 0 100) 0))))
| 207 | Common Lisp | .lisp | 7 | 26 | 36 | 0.602041 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 25c890acf799d715cf537ecf6b47d7dff610959a04943929494b4077c0475230 | 18,584 | [
-1
] |
18,585 | controlcl.asd | justjoheinz_controlcl/controlcl.asd | (asdf:defsystem controlcl
:version "0.0.1"
:homepage "https://github.com/justjoheinz/controlcl"
:source-control (:git "https://github.com/justjoheinz/controlcl.git")
:license "LGPL V3"
:depends-on ("sdl2"
"cl-sdl2-hershey"
"sdl2-image"
"event-emitter"
"log4cl"
"alexandria"
"assoc-utils")
:serial t
:components ((:module "src"
:components ((:file "package")
(:file "utils")
(:file "theme")
(:file "events")
(:file "ctrl")
(:file "bang")
(:file "slider")
(:file "checkbox")
(:file "image")
(:file "controlcl"))))
:in-order-to ((test-op (test-op :controlcl/tests))))
(asdf:defsystem controlcl/tests
:version "0.1"
:serial t
:depends-on ("controlcl" "rove")
:components ((:module "t"
:components ((:file "package")
(:file "tests-controlcl")
(:file "tests-slider"))))
:perform (test-op (op c) (symbol-call :rove :run c :style :dot)))
(asdf:defsystem controlcl/examples
:version "0.1"
:depends-on ("controlcl" "closer-mop")
;; closer-mop is just required to explore on the repl
:components ((:module "examples"
:components ((:file "ex-theme")
(:file "ex-colors")
(:file "ex-ctrl")))))
| 1,631 | Common Lisp | .asd | 42 | 24.714286 | 71 | 0.463138 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5befdfb6ddeaa1effe06c76ad40082b8391ec6f2c46afcb7e1c441e8fa388e88 | 18,585 | [
-1
] |
18,588 | controlcl.html | justjoheinz_controlcl/docs/controlcl.html | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="default.css" type="text/css" />
<title>controlcl
package</title>
</head>
<body>
<div id="controlcl-package" class="document"><h1 class="title"><tt class="docutils literal">
<span class="pre">controlcl</span></tt> package</h1>
<p><a class="reference" href="index.html"><span><< back to controlcl index</span></a></p>
<p>Exported symbols:</p>
<div id="variables" class="section"><h2><a name="variables">Variables</a></h2>
<a id="variable-2acontrolcl-2a" class="target" name="variable-2acontrolcl-2a"></a><div id="controlcl" class="section"><h3><a name="controlcl"><tt class="docutils literal">
<span class="pre">*controlcl*</span></tt></a></h3>
<p>The global controlcl instance.</p>
<p>This should be created with WITH-CONTROLCL macro.</p>
<a id="variable-2acurrent-theme-2a" class="target" name="variable-2acurrent-theme-2a"></a></div>
<div id="current-theme" class="section"><h3><a name="current-theme"><tt class="docutils literal">
<span class="pre">*current-theme*</span></tt></a></h3>
<p>The current theme.</p>
<a id="variable-2atheme-a-2a" class="target" name="variable-2atheme-a-2a"></a></div>
<div id="theme-a" class="section"><h3><a name="theme-a"><tt class="docutils literal">
<span class="pre">*theme-a*</span></tt></a></h3>
<a id="variable-2atheme-grey-2a" class="target" name="variable-2atheme-grey-2a"></a></div>
<div id="theme-grey" class="section"><h3><a name="theme-grey"><tt class="docutils literal">
<span class="pre">*theme-grey*</span></tt></a></h3>
<a id="variable-2atheme-red-2a" class="target" name="variable-2atheme-red-2a"></a></div>
<div id="theme-red" class="section"><h3><a name="theme-red"><tt class="docutils literal">
<span class="pre">*theme-red*</span></tt></a></h3>
<a id="variable-2atheme-cp5blue-2a" class="target" name="variable-2atheme-cp5blue-2a"></a></div>
<div id="theme-cp5blue" class="section"><h3><a name="theme-cp5blue"><tt class="docutils literal">
<span class="pre">*theme-cp5blue*</span></tt></a></h3>
<a id="variable-2atheme-cp52014-2a" class="target" name="variable-2atheme-cp52014-2a"></a></div>
<div id="theme-cp52014" class="section"><h3><a name="theme-cp52014"><tt class="docutils literal">
<span class="pre">*theme-cp52014*</span></tt></a></h3>
<a id="variable-2atheme-retro-2a" class="target" name="variable-2atheme-retro-2a"></a></div>
<div id="theme-retro" class="section"><h3><a name="theme-retro"><tt class="docutils literal">
<span class="pre">*theme-retro*</span></tt></a></h3>
<a id="variable-2acolors-2a" class="target" name="variable-2acolors-2a"></a></div>
<div id="colors" class="section"><h3><a name="colors"><tt class="docutils literal">
<span class="pre">*colors*</span></tt></a></h3>
<p>A list of colors with their hexadecimal codes.</p>
</div>
</div>
<div id="functions" class="section"><h2><a name="functions">Functions</a></h2>
<a id="function-controlcl-move-to" class="target" name="function-controlcl-move-to"></a><div id="controlcl-move-to" class="section"><h3><a name="controlcl-move-to"><tt class="docutils literal">
<span class="pre">controlcl-move-to</span></tt></a></h3>
<a id="function-controlcl-mouse-over" class="target" name="function-controlcl-mouse-over"></a></div>
<div id="controlcl-mouse-over" class="section"><h3><a name="controlcl-mouse-over"><tt class="docutils literal">
<span class="pre">controlcl-mouse-over</span></tt></a></h3>
<a id="function-controlcl-add-image" class="target" name="function-controlcl-add-image"></a></div>
<div id="controlcl-add-image" class="section"><h3><a name="controlcl-add-image"><tt class="docutils literal">
<span class="pre">controlcl-add-image</span></tt></a></h3>
<a id="function-controlcl-add-slider" class="target" name="function-controlcl-add-slider"></a></div>
<div id="controlcl-add-slider" class="section"><h3><a name="controlcl-add-slider"><tt class="docutils literal">
<span class="pre">controlcl-add-slider</span></tt></a></h3>
<a id="function-controlcl-add-checkbox" class="target" name="function-controlcl-add-checkbox"></a></div>
<div id="controlcl-add-checkbox" class="section"><h3><a name="controlcl-add-checkbox"><tt class="docutils literal">
<span class="pre">controlcl-add-checkbox</span></tt></a></h3>
<a id="function-controlcl-add-bang" class="target" name="function-controlcl-add-bang"></a></div>
<div id="controlcl-add-bang" class="section"><h3><a name="controlcl-add-bang"><tt class="docutils literal">
<span class="pre">controlcl-add-bang</span></tt></a></h3>
<a id="function-controlcl-get-ctrl" class="target" name="function-controlcl-get-ctrl"></a></div>
<div id="controlcl-get-ctrl" class="section"><h3><a name="controlcl-get-ctrl"><tt class="docutils literal">
<span class="pre">controlcl-get-ctrl</span></tt></a></h3>
<p>get the CTRL from <em><span>CONTROLCL</span></em> with the id</p>
<a id="function-controlcl-hide" class="target" name="function-controlcl-hide"></a></div>
<div id="controlcl-hide" class="section"><h3><a name="controlcl-hide"><tt class="docutils literal">
<span class="pre">controlcl-hide</span></tt></a></h3>
<a id="function-controlcl-show" class="target" name="function-controlcl-show"></a></div>
<div id="controlcl-show" class="section"><h3><a name="controlcl-show"><tt class="docutils literal">
<span class="pre">controlcl-show</span></tt></a></h3>
<a id="function-controlcl-draw" class="target" name="function-controlcl-draw"></a></div>
<div id="controlcl-draw" class="section"><h3><a name="controlcl-draw"><tt class="docutils literal">
<span class="pre">controlcl-draw</span></tt></a></h3>
<a id="function-set-color-from-theme" class="target" name="function-set-color-from-theme"></a></div>
<div id="set-color-from-theme" class="section"><h3><a name="set-color-from-theme"><tt class="docutils literal">
<span class="pre">set-color-from-theme</span></tt></a></h3>
<p>Set the color from the <em><span>CURRENT-THEME</span></em> or THEME when given.</p>
<a id="function-set-color-from-code" class="target" name="function-set-color-from-code"></a></div>
<div id="set-color-from-code" class="section"><h3><a name="set-color-from-code"><tt class="docutils literal">
<span class="pre">set-color-from-code</span></tt></a></h3>
<dl class="docutils"><dt>Set the color from a hexadecimal code, like #xFF0000FF.</dt>
<dd>The order is a r g b.</dd>
</dl>
<a id="function-set-color-from-palette" class="target" name="function-set-color-from-palette"></a></div>
<div id="set-color-from-palette" class="section"><h3><a name="set-color-from-palette"><tt class="docutils literal">
<span class="pre">set-color-from-palette</span></tt></a></h3>
<p>Set a color from a palette of colors.</p>
<a id="function-color-values" class="target" name="function-color-values"></a></div>
<div id="color-values" class="section"><h3><a name="color-values"><tt class="docutils literal">
<span class="pre">color-values</span></tt></a></h3>
<p>Return the encoded alpha, red, green, blue values of a color</p>
<a id="function-theme-value-color" class="target" name="function-theme-value-color"></a></div>
<div id="theme-value-color" class="section"><h3><a name="theme-value-color"><tt class="docutils literal">
<span class="pre">theme-value-color</span></tt></a></h3>
<p>Return the value color of the <em><span>CURRENT-THEME</span></em> or optionally given THEME.</p>
<a id="function-theme-caption-color" class="target" name="function-theme-caption-color"></a></div>
<div id="theme-caption-color" class="section"><h3><a name="theme-caption-color"><tt class="docutils literal">
<span class="pre">theme-caption-color</span></tt></a></h3>
<p>Return the caption color of the <em><span>CURRENT-THEME</span></em> or optionally given THEME.</p>
<a id="function-theme-active-color" class="target" name="function-theme-active-color"></a></div>
<div id="theme-active-color" class="section"><h3><a name="theme-active-color"><tt class="docutils literal">
<span class="pre">theme-active-color</span></tt></a></h3>
<p>Return the active color of the <em><span>CURRENT-THEME</span></em> or optionally given THEME.</p>
<a id="function-theme-bg-color" class="target" name="function-theme-bg-color"></a></div>
<div id="theme-bg-color" class="section"><h3><a name="theme-bg-color"><tt class="docutils literal">
<span class="pre">theme-bg-color</span></tt></a></h3>
<p>Return the background color of the <em><span>CURRENT-THEME</span></em> or optionally given THEME.</p>
<a id="function-theme-fg-color" class="target" name="function-theme-fg-color"></a></div>
<div id="theme-fg-color" class="section"><h3><a name="theme-fg-color"><tt class="docutils literal">
<span class="pre">theme-fg-color</span></tt></a></h3>
<p>Return the foreground color of the <em><span>CURRENT-THEME</span></em> or optionally given THEME.</p>
<a id="function-controlcl-version" class="target" name="function-controlcl-version"></a></div>
<div id="controlcl-version" class="section"><h3><a name="controlcl-version"><tt class="docutils literal">
<span class="pre">controlcl-version</span></tt></a></h3>
<p>Return the version of the controlcl library</p>
<a id="function-controlcl-init" class="target" name="function-controlcl-init"></a></div>
<div id="controlcl-init" class="section"><h3><a name="controlcl-init"><tt class="docutils literal">
<span class="pre">controlcl-init</span></tt></a></h3>
<p>Initialize the controlcl library</p>
<a id="function-v-factor" class="target" name="function-v-factor"></a></div>
<div id="v-factor" class="section"><h3><a name="v-factor"><tt class="docutils literal">
<span class="pre">v-factor</span></tt></a></h3>
<p>Return a value between 0 and 1, expressing the relation of value to min-v and max-v.</p>
<a id="function-point-in-rect" class="target" name="function-point-in-rect"></a></div>
<div id="point-in-rect" class="section"><h3><a name="point-in-rect"><tt class="docutils literal">
<span class="pre">point-in-rect</span></tt></a></h3>
<p>Return true if the point x1,y1 is inside the rectangle x,y,w,h</p>
</div>
</div>
<div id="macros" class="section"><h2><a name="macros">Macros</a></h2>
<a id="macro-with-controlcl" class="target" name="macro-with-controlcl"></a><div id="with-controlcl" class="section"><h3><a name="with-controlcl"><tt class="docutils literal">
<span class="pre">with-controlcl</span></tt></a></h3>
<a id="macro-with-theme" class="target" name="macro-with-theme"></a></div>
<div id="with-theme" class="section"><h3><a name="with-theme"><tt class="docutils literal">
<span class="pre">with-theme</span></tt></a></h3>
<p>Used to dynamically bind the <em><span>CURRENT-THEME</span></em> variable to the given theme.</p>
</div>
</div>
<div id="generic-functions" class="section"><h2><a name="generic-functions">Generic Functions</a></h2>
<a id="generic-function-controlcl-emit-event" class="target" name="generic-function-controlcl-emit-event"></a><div id="controlcl-emit-event" class="section"><h3><a name="controlcl-emit-event"><tt class="docutils literal">
<span class="pre">controlcl-emit-event</span></tt></a></h3>
<a id="generic-function-controller-set-mouse-over-color" class="target" name="generic-function-controller-set-mouse-over-color"></a></div>
<div id="controller-set-mouse-over-color" class="section"><h3><a name="controller-set-mouse-over-color"><tt class="docutils literal">
<span class="pre">controller-set-mouse-over-color</span></tt></a></h3>
<p>decide if the active or foreground color should be returned</p>
<a id="generic-function-controller-mouse-over-p" class="target" name="generic-function-controller-mouse-over-p"></a></div>
<div id="controller-mouse-over-p" class="section"><h3><a name="controller-mouse-over-p"><tt class="docutils literal">
<span class="pre">controller-mouse-over-p</span></tt></a></h3>
<p>return T if the point x,y is over the controller</p>
<a id="generic-function-controller-move-to" class="target" name="generic-function-controller-move-to"></a></div>
<div id="controller-move-to" class="section"><h3><a name="controller-move-to"><tt class="docutils literal">
<span class="pre">controller-move-to</span></tt></a></h3>
<p>move the controller to the position x,y</p>
<a id="generic-function-controller-hide" class="target" name="generic-function-controller-hide"></a></div>
<div id="controller-hide" class="section"><h3><a name="controller-hide"><tt class="docutils literal">
<span class="pre">controller-hide</span></tt></a></h3>
<p>Hide the controller. By default it sets the VISIBLE flag to NIL, unless the STICKY flag for the controller is set.</p>
<a id="generic-function-controller-show" class="target" name="generic-function-controller-show"></a></div>
<div id="controller-show" class="section"><h3><a name="controller-show"><tt class="docutils literal">
<span class="pre">controller-show</span></tt></a></h3>
<p>show the controller. By default it sets the VISIBLE flag to T.</p>
<a id="generic-function-controller-draw" class="target" name="generic-function-controller-draw"></a></div>
<div id="controller-draw" class="section"><h3><a name="controller-draw"><tt class="docutils literal">
<span class="pre">controller-draw</span></tt></a></h3>
<p>draw the controller to the renderer</p>
<a id="generic-function-on-event" class="target" name="generic-function-on-event"></a></div>
<div id="on-event" class="section"><h3><a name="on-event"><tt class="docutils literal">
<span class="pre">on-event</span></tt></a></h3>
<a id="generic-function-render-text" class="target" name="generic-function-render-text"></a></div>
<div id="render-text" class="section"><h3><a name="render-text"><tt class="docutils literal">
<span class="pre">render-text</span></tt></a></h3>
<p>Render text at x,y</p>
</div>
</div>
<div id="classes" class="section"><h2><a name="classes">Classes</a></h2>
<a id="class-controlcl" class="target" name="class-controlcl"></a><div id="id1" class="section"><h3><a name="id1"><tt class="docutils literal">
<span class="pre">controlcl</span></tt></a></h3>
<p>ControlCL main class.</p>
<p>An instance holds references to all controllers and is reponsible for delegating events to them.</p>
<a id="class-checkbox" class="target" name="class-checkbox"></a></div>
<div id="checkbox" class="section"><h3><a name="checkbox"><tt class="docutils literal">
<span class="pre">checkbox</span></tt></a></h3>
<a id="class-slider" class="target" name="class-slider"></a></div>
<div id="slider" class="section"><h3><a name="slider"><tt class="docutils literal">
<span class="pre">slider</span></tt></a></h3>
<a id="class-bang" class="target" name="class-bang"></a></div>
<div id="bang" class="section"><h3><a name="bang"><tt class="docutils literal">
<span class="pre">bang</span></tt></a></h3>
<a id="class-controller" class="target" name="class-controller"></a></div>
<div id="controller" class="section"><h3><a name="controller"><tt class="docutils literal">
<span class="pre">controller</span></tt></a></h3>
<p>A controller is a visual element that can be drawn and interacted with.</p>
<a id="class-event-value" class="target" name="class-event-value"></a></div>
<div id="event-value" class="section"><h3><a name="event-value"><tt class="docutils literal">
<span class="pre">event-value</span></tt></a></h3>
<p>A value event is an event that is generated by a value changing.</p>
<a id="class-event-key" class="target" name="class-event-key"></a></div>
<div id="event-key" class="section"><h3><a name="event-key"><tt class="docutils literal">
<span class="pre">event-key</span></tt></a></h3>
<p>A key event is an event that is generated by the keyboard.</p>
<a id="class-event-mouse-clicked" class="target" name="class-event-mouse-clicked"></a></div>
<div id="event-mouse-clicked" class="section"><h3><a name="event-mouse-clicked"><tt class="docutils literal">
<span class="pre">event-mouse-clicked</span></tt></a></h3>
<p>A mouse clicked event is an event that is generated by the mouse when a button is clicked.</p>
<a id="class-event-mouse" class="target" name="class-event-mouse"></a></div>
<div id="event-mouse" class="section"><h3><a name="event-mouse"><tt class="docutils literal">
<span class="pre">event-mouse</span></tt></a></h3>
<p>A mouse event is an event that is generated by the mouse.</p>
<a id="class-event" class="target" name="class-event"></a></div>
<div id="event" class="section"><h3><a name="event"><tt class="docutils literal">
<span class="pre">event</span></tt></a></h3>
<p>An event is a message sent from one object to another. If the target is nil the event is considered to be a broadcast event.</p>
</div>
</div>
<hr class ="docutils footer" /><div class="footer">Generated on : Fri, 31 May 2024 17:11:26 .
</div>
</div>
</body>
</html> | 16,691 | Common Lisp | .cl | 223 | 73.838565 | 221 | 0.7064 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a68c06002f0e94ab53bf9d5392696d66d3abb0ae7f7da71a03873cfd65a2f12b | 18,588 | [
-1
] |
18,591 | Makefile | justjoheinz_controlcl/Makefile |
LISP=qlot exec ros run -- --dynamic-space-size 2048
.PHONY: help all clean ex-colors ex-theme ex-ctrl qlot-update run-all
help: ## show help message
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[$$()% a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
all: ## Compile all artifacts and execute tests
$(LISP) \
--disable-debugger \
--eval '(ql:quickload :controlcl)' \
--eval '(ql:quickload :controlcl/examples)' \
--eval '(ql:quickload :controlcl/tests)' \
--eval '(uiop:quit (if (rove:run "controlcl/tests") 0 1))'
clean: ## Recursively delete fasl file
find ./ -name "*.fasl" -delete
ex-colors: ## Run the ex-colors example
$(LISP) \
--non-interactive \
--eval '(ql:quickload :controlcl/examples)' \
--eval "(sdl2:make-this-thread-main #'controlcl/ex-colors:main)"
ex-theme: ## Run the ex-theme example
$(LISP) \
--non-interactive \
--eval '(ql:quickload :controlcl/examples)' \
--eval "(sdl2:make-this-thread-main #'controlcl/ex-theme:main)"
ex-ctrl: ## Run the ex-ctrl example
$(LISP) \
--non-interactive \
--eval '(ql:quickload :controlcl/examples)' \
--eval "(sdl2:make-this-thread-main #'controlcl/ex-ctrl:main)"
qlot-update: ## update qlot dependencies
qlot update
docs: $(shell find src -name "*.lisp") ## generate the documentation
$(LISP) \
--eval "(ql:quickload '(:coo :controlcl))" \
--eval '(coo:document-system :controlcl :base-path #P"docs/")' \
--eval "(sb-ext:quit)"
run-all: qlot-update ## run all examples sequentially, escape with ESC
make ex-colors
make ex-theme
make ex-ctrl
| 1,690 | Common Lisp | .l | 39 | 40.846154 | 226 | 0.657509 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 871c1762f10eff7d8e0d34c342f6a61044743156b62e28351045ad9d8911ae5d | 18,591 | [
-1
] |
18,592 | qlfile.lock | justjoheinz_controlcl/qlfile.lock | ("quicklisp" .
(:class qlot/source/dist:source-dist
:initargs (:distribution "https://beta.quicklisp.org/dist/quicklisp.txt" :%version :latest)
:version "2023-10-21"))
("ultralisp" .
(:class qlot/source/dist:source-dist
:initargs (:distribution "https://dist.ultralisp.org/" :%version :latest)
:version "20240917102500"))
("alexandria" .
(:class qlot/source/ql:source-ql
:initargs (:%version :latest)
:version "ql-2023-10-21"))
("assoc-utils" .
(:class qlot/source/ql:source-ql
:initargs (:%version :latest)
:version "ql-2023-10-21"))
("cl-sdl2" .
(:class qlot/source/github:source-github
:initargs (:repos "ellisvelo/cl-sdl2" :ref nil :branch nil :tag nil)
:version "github-e127cde090d847f4d811a44631ab0603347c486e"))
("cl-sdl2-image" .
(:class qlot/source/github:source-github
:initargs (:repos "ellisvelo/cl-sdl2-image" :ref nil :branch nil :tag nil)
:version "github-8734b0e24de9ca390c9f763d9d7cd501546d17d4"))
("cl-sdl2-hershey" .
(:class qlot/source/github:source-github
:initargs (:repos "justjoheinz/cl-sdl2-hershey" :ref nil :branch nil :tag nil)
:version "github-3bea54ddc98b93f38d3d07a8347669f56a88cb38"))
("event-emitter" .
(:class qlot/source/github:source-github
:initargs (:repos "justjoheinz/event-emitter" :ref nil :branch nil :tag nil)
:version "github-1de163a8241180082f6149300bf0e1b46fe199cb"))
| 1,355 | Common Lisp | .l | 32 | 40.09375 | 93 | 0.745276 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | ede7d5718e4e086b8427f1587c8590bda308329fbb9a574dc3d1020b9b8bfade | 18,592 | [
-1
] |
18,593 | qlfile | justjoheinz_controlcl/qlfile | dist ultralisp http://dist.ultralisp.org/
ql alexandria
ql assoc-utils
github ellisvelo/cl-sdl2
github ellisvelo/cl-sdl2-image
github justjoheinz/cl-sdl2-hershey
github justjoheinz/event-emitter
| 195 | Common Lisp | .l | 7 | 26.857143 | 41 | 0.867021 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | d1846e9bf8840a99ef6ab770c304c07cf6bd4b0b2cc3fa3c0c57107003db6d44 | 18,593 | [
-1
] |
18,609 | default.css | justjoheinz_controlcl/docs/default.css | /*
:Author: David Goodger ([email protected])
:Id: $Id: html4css1.css 5196 2007-06-03 20:25:28Z wiemann $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
customize this style sheet.
*/
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
dl.docutils dt {
font-weight: bold }
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left {
clear: left }
img.align-right {
clear: right }
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font-family: serif ;
font-size: 100% }
pre.literal-block, pre.doctest-block {
padding: 1em 2em;
border: black solid 1px;
border-radius: .5em;
background-color: #333;
color: #eee;
overflow: auto }
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
table caption { caption-side: bottom; font-weight: bold; font-style: italic; }
p.caption { text-align:center; font-weight: bold; }
table.docutils, table.docutils tr th, table.docutils tr td { outline-width: thin; outline-style: solid; }
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
/* Begin coo customization */
@import url("//fonts.googleapis.com/css?family=Fira+Mono|Fira+Sans");
:root {
font-family: "Fira Sans", sans-serif;
font-size: 16px;
}
.document {
max-width: 1200px;
margin: 0 auto;
}
span.pre {
font-family: "Fira Mono", monospace;
}
h2 {
background: #eee;
border-width: 1px 0;
border-color: black;
border-style: solid;
}
.ref-package {
font-family: "Fira Mono", mono;
background-color: #eee;
color: #ab7967;
padding: 3px;
border-radius: 6px;
}
.ref-class {
font-family: "Fira Mono", mono;
background-color: #eee;
color: #99c794;
padding: 3px;
border-radius: 6px;
}
.ref-variable {
font-family: "Fira Mono", mono;
background-color: #eee;
color: #6699cc;
padding: 3px;
border-radius: 6px;
}
.ref-macro {
font-family: "Fira Mono", mono;
background-color: #eee;
color: #fac863;
padding: 3px;
border-radius: 6px;
}
.ref-function {
font-family: "Fira Mono", mono;
background-color: #eee;
color: #c594c5;
padding: 3px;
border-radius: 6px;
}
.param {
background-color: #eee;
color: #6699cc;
}
p {
color: #343d46;
}
/* End coo customization */
| 7,174 | Common Lisp | .l | 272 | 22.625 | 105 | 0.681338 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 53239bcd00e656c1019392340bcb5d90e0dcc72b875d7f02766d25888d87eed5 | 18,609 | [
-1
] |
18,610 | index.html | justjoheinz_controlcl/docs/index.html | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="default.css" type="text/css" />
<title>controlcl</title>
</head>
<body>
<div id="id1" class="document"><h1 class="title">controlcl</h1>
<table class="docinfo" frame="void" rules="none"><col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Version</th><td>0.0.1</td></tr><tr class="field"><th colspan="1" class="docinfo-name">license:</th><td class="field-body">LGPL V3</td>
</tr>
<tr class="field"><th colspan="1" class="docinfo-name">homepage:</th><td class="field-body"><a class="reference" href="https://github.com/justjoheinz/controlcl"><span>https://github.com/justjoheinz/controlcl</span></a></td>
</tr>
</tbody>
</table>
<div id="packages" class="section"><h2><a name="packages">Packages</a></h2>
<ul>
<li><p class="first last"><a class="reference" href="controlcl.html"><span>controlcl</span></a></p>
</li>
</ul>
</div>
<hr class ="docutils footer" /><div class="footer">Generated on : Fri, 31 May 2024 17:11:26 .
</div>
</div>
</body>
</html> | 1,211 | Common Lisp | .l | 29 | 40.758621 | 223 | 0.689772 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4aeb645a74ea43ce8a0e8e3782767c1670ff33f2b7062d190f84279bae13e4e0 | 18,610 | [
-1
] |
18,613 | ci.yaml | justjoheinz_controlcl/.github/workflows/ci.yaml | name: CI
on:
push:
schedule:
- cron: "0 13 * * FRI"
jobs:
test:
name: ${{ matrix.lisp }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
lisp: [sbcl-bin/2.4.5]
os: [ubuntu-latest]
fail-fast: false
steps:
- uses: actions/checkout@v1
- name: install_dependencies
run: |
sudo add-apt-repository -y "deb http://archive.ubuntu.com/ubuntu `lsb_release -sc` main universe restricted multiverse"
sudo apt-get update -y -qq
sudo apt-get install libsdl2-dev libsdl2-image-dev
- uses: actions/checkout@v4
with:
submodules: true
- name: Install Roswell
env:
LISP: ${{ matrix.lisp }}
ROSWELL_INSTALL_DIR: /usr
run: |
curl -L https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh | sh
echo "$HOME/.roswell/bin" >> $GITHUB_PATH
- name: Install qlot
run: ros install fukamachi/qlot
- name: Install dependencies with qlot
run: qlot install
- name: Install rove
run: ros install fukamachi/rove
- name: Run tests
run: |
qlot exec rove controlcl.asd
| 1,235 | Common Lisp | .l | 40 | 23.375 | 129 | 0.59194 | justjoheinz/controlcl | 3 | 0 | 2 | LGPL-3.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 81e8ea507622c0bc62e112bcc269b4e7524aba508618abc0431c02ede7a9f6a7 | 18,613 | [
-1
] |
18,628 | web-utility.lisp | hbock_periscope/lisp/web-utility.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(hunchentoot:define-easy-handler (service-names :uri "/service-names") ()
(when (zerop (hash-table-count *service-cache*))
(create-service-cache))
(with-periscope-page ("DARPA Internet Service Names")
(:h2 "Table of DARPA Internet Service Names")
(:p "As specified in the system services file.")
(:table
:class "sources"
(:tr (:th "Port Number") (:th "TCP Service") (:th "UDP Service"))
(loop :for port :being :the :hash-keys :in *service-cache* :using (:hash-value names) :do
(htm (:tr (:td (str port)) (:td (str (car names))) (:td (str (cdr names)))))))))
| 1,476 | Common Lisp | .lisp | 26 | 54.115385 | 94 | 0.704782 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1537bbf6ab451d855e00c8c99403782d7648b93595e19fee12c4c051700ebe94 | 18,628 | [
-1
] |
18,629 | utility.lisp | hbock_periscope/lisp/utility.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defun port-number-p (port)
(typep port 'port-number))
(defun vlan-p (vlan)
(typep vlan 'vlan-id))
(defun ip-string (ip &optional subnet)
"Convert an IPv4 address from an integer to a string in dotted quad notation.
If subnet is specified, a CIDR suffix will be appended to the end of the string."
(declare (type (unsigned-byte 32) ip))
(flet ((count-bits (integer)
(loop :for bit :from 0 :upto 31 :counting (logbitp bit integer))))
(format nil "~d.~d.~d.~d~:[~;/~d~]"
(ldb (byte 8 24) ip)
(ldb (byte 8 16) ip)
(ldb (byte 8 8) ip)
(ldb (byte 8 0) ip)
subnet
(when subnet
(count-bits subnet)))))
(defun network-strings (network-list)
(mapcar (lambda (network)
(ip-string (car network) (cdr network))) network-list))
(defun parse-ip-string (string &key junk-allowed)
"Parse an IPv4 string in dotted quad notation, optionally with a CIDR subnet mask,
to a corresponding 32-bit IPv4 address and corresponding subnet mask. If the subnet mask
portion is not specified, the returned subnet mask will be NIL. Throws an error of type
PARSE-ERROR if string is not a valid IPv4 string unless :junk-allowed is T."
(flet ((throw-parse-error (string)
#-sbcl (error 'parse-error)
#+sbcl (error 'sb-int::simple-parse-error
:format-control "Junk in IPv4 string: ~S"
:format-arguments (list string))))
(let ((ip-regex "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(/(\\d{1,2}))?$"))
(when (not (or (ppcre:scan ip-regex string) junk-allowed))
(throw-parse-error string))
(ppcre:register-groups-bind ((#'parse-integer oct1 oct2 oct3 oct4) nil (#'parse-integer subnet))
(ip-regex string)
;; Check to make sure all octets are <= 255, and the bit count for the CIDR subnet mask
;; is less than or equal to 32.
(when (or (some (lambda (octet) (< 255 octet)) (list oct1 oct2 oct3 oct4))
(and subnet (< 32 subnet)))
(if junk-allowed
(return-from parse-ip-string nil)
(throw-parse-error string)))
(values
;; We be throwin' around type-safety like its free or somethin
(the (unsigned-byte 32)
(logior (ash oct1 24) (ash oct2 16) (ash oct3 8) oct4))
(when subnet
(logand #xFFFFFFFF (ash #xFFFFFFFF (- 32 subnet)))))))))
(declaim (inline network-member-p local-host-p remote-host-p
broadcast-address broadcast-address-p))
(defun network-member-p (ip network netmask)
"Returns true if IP is a member of the IPv4 network specified by NETWORK and NETMASK."
(= network (logand ip netmask)))
(defun any-network-member-p (ip &optional (networks *internal-networks*))
"Returns true if IP is a member of the IPv4 network specified by NETWORK and NETMASK."
(some (lambda (network)
(network-member-p ip (car network) (cdr network))) networks))
(defun local-host-p (ip &optional (networks *internal-networks*))
(any-network-member-p ip networks))
(defun remote-host-p (ip &optional (networks *internal-networks*))
(not (any-network-member-p ip networks)))
(defun broadcast-address (network netmask)
"Calculate the broadcast address for a given IP/netmask combination."
(logand #xffffffff (logior (logand network netmask) (lognot netmask))))
(defun broadcast-address-p (ip network netmask)
"Returns true if ip is a broadcast address in netmask, or if it is the universal broadcast
address (255.255.255.255)."
(or (= ip +broadcast-ip+) (= ip (broadcast-address network netmask))))
(defun multicast-address-p (ip)
(and (>= ip +lowest-multicast-address+) (<= ip +highest-multicast-address+)))
(defun any-broadcast-address-p (ip &optional (networks *internal-networks*))
"Returns true if ip is a broadcast address in netmask, or if it is the universal broadcast
address (255.255.255.255)."
(some (lambda (network)
(broadcast-address-p ip (car network) (cdr network))) networks))
(defun create-service-cache (&optional (service-file (pathname "/etc/services")))
"Generate the Internet service name cache for use with SERVICE-NAME. SERVICE-FILE
is parsed to create the cache; by default, it is created using the system file
/etc/services."
(clrhash *service-cache*)
(clrhash *service-reverse-cache*)
(with-open-file (services service-file :direction :input)
(loop :for line = (read-line services nil)
:while line :do
(cl-ppcre:do-register-groups (name (#'parse-integer port) protocol)
("([a-zA-Z\\d-+./]+)[ \\t\\n\\r]+(\\d+)/(udp|tcp)" line)
(let ((service-names (gethash port *service-cache* (cons nil nil))))
(cond ((string= protocol "tcp")
(setf (car service-names) name)
(setf (gethash name *service-reverse-cache*) port))
((string= protocol "udp")
(setf (cdr service-names) name)
(setf (gethash name *service-reverse-cache*) port))
(t (error "Unknown protocol ~a!" protocol)))
(setf (gethash port *service-cache*) service-names))))))
(defun service-name (port &key (protocol :tcp))
"Return the Internet service name for a given PORT and PROTOCOL basic on the system
services file (default is /etc/services). If PORT is not named by the system, by default
the port number is returned."
(when (zerop (hash-table-count *service-cache*))
(create-service-cache))
(let ((service-names (gethash port *service-cache*)))
(if service-names
(case protocol
((:tcp #.+ip-proto-tcp+) (car service-names))
((:udp #.+ip-proto-udp+) (cdr service-names))
(t port))
port)))
(defun service-port (name)
"Given a service name, attempt to look up its associated port number and return that.
Alternatively, if name is a digit string, parse that as the port
number. If a service name cannot be identified, return NIL."
(let ((attempted-parse (handler-case (parse-integer name)
(parse-error () nil))))
(if (and attempted-parse (port-number-p attempted-parse))
attempted-parse
(nth-value 0 (gethash name *service-reverse-cache*)))))
(defun vlan-name (vlan)
"Returns the VLAN name associated with identifier vlan (an integer).
Entries can be added using SETF."
(declare (type vlan-id vlan))
(gethash vlan *vlan-names* vlan))
(defun (setf vlan-name) (name vlan)
(if name
(setf (gethash vlan *vlan-names*) name)
(remhash vlan *vlan-names*)))
(defun vlan-name-list ()
"Returns a list of all VLAN identifiers associated with a name, sorted in ascending
order by VLAN ID."
(sort
(loop :for vid :being :the :hash-keys :in *vlan-names* :using (:hash-value name)
:collect (list vid name)) #'< :key #'first))
(defun name-protocol (protocol)
"Returns a string representation of an internet or transport protocol."
(ecase protocol
(#.+ip-proto-icmp+ "ICMP")
(#.+ip-proto-igmp+ "IGMP")
(#.+ip-proto-tcp+ "TCP")
(#.+ip-proto-udp+ "UDP")))
(defun byte-string (bytes &optional (precision 2))
"Convert BYTES from an integer to a size string, optionally specifying the precision in
digits following the decimal point."
(declare (type integer precision))
(if (< bytes 1024)
(format nil "~:d B" bytes)
(loop :for (boundary name) :in
'((1099511627776 "TB") (1073741824 "GB") (1048576 "MB") (1024 "kB"))
:when (>= bytes boundary) :do
(return (format nil "~v$ ~a" precision (/ bytes boundary) name)))))
(defun date-string (time &key minutes)
"Convert a LOCAL-TIME timestamp to a simple date string in the format YYYY-MM-DD."
(let ((format `((:year 4) #\- (:month 2) #\- (:day 2)
,@(when minutes '(#\Space (:hour 2) #\: (:min 2))))))
(format-timestring nil time :format format)))
(defun long-date-string (time &key (minutes t))
"Convert a LOCAL-TIME timestamp to a simple date string in the format YYYY-MM-DD."
(let ((format `(:long-weekday ", " (:day 2) #\Space :long-month #\Space (:year 4)
,@(when minutes '(#\Space (:hour 2) #\: (:min 2))))))
(format-timestring nil time :format format)))
(defun iso8661-date-string (&optional (time (now)))
"Convert a LOCAL-TIME timestamp to an ISO8661 date string."
(let ((format '((:year 4) #\- (:month 2) #\- (:day 2) #\T (:hour 2) #\: (:min 2) #\: (:sec 2))))
(format-timestring nil time :format format)))
(defmacro string-case (keyform &body clauses)
"Like CASE but for strings. If give the :CASE-INSENSITIVE keyword, differences in character case are ignored."
(let* ((case-insensitive (if (listp keyform) (second keyform)))
(keyform (if (listp keyform) (first keyform) keyform))
(same-string-p (if (eq case-insensitive :case-insensitive) 'string-equal 'string=)))
`(cond
,@(loop for clause in clauses collect
(destructuring-bind (cases* &rest forms) clause
(etypecase cases*
(string
`((,same-string-p ,keyform ,cases*)
,@forms))
(list
`((some (lambda (test-case) (,same-string-p ,keyform test-case))
(list ,@cases*))
,@forms))
(symbol
(if (or (eql cases* t) (eql cases* 'otherwise))
`(t ,@forms)
(error "~a is not one of (T OTHERWISE); cannot test symbols!" cases*)))))))))
(defmacro with-timeout ((expires) &body body)
#+sbcl
`(handler-case
(sb-ext:with-timeout ,expires
,@body)
(sb-ext:timeout () nil))
#-sbcl
`(progn ,@body))
(defun process-create (command status-hook &rest args)
"Create an external process using command and args. Does not wait for the process
to complete."
#+sbcl
(sb-ext:run-program command args :search t :status-hook status-hook :wait nil
:output *standard-output*)
#-sbcl (not-implemented 'process-create))
(defun process-wait (process)
"Block until process exits. Returns the process exit code, pid, and status.
Process status is implementation-specific."
#+sbcl
(progn
(sb-ext:process-wait process)
(values (sb-ext:process-exit-code process)
(sb-ext:process-pid process)
(sb-ext:process-status process)))
#-sbcl (not-implemented 'process-wait))
(defun process-alive-p (process)
"Returns true if process is currently running (i.e., not terminated or stopped)."
#+sbcl (and process (sb-ext:process-alive-p process))
#-sbcl (not-implemented 'process-alive-p))
(defun process-signal (process &optional (sig
#+sbcl sb-unix:sigterm
#-sbcl 15))
"Raise a signal for process. By default, raises SIGTERM."
#+sbcl
(progn
(sb-ext:process-kill process sig)
process)
#-sbcl (not-implemented 'process-signal))
(defun process-pid (process)
#+sbcl (sb-ext:process-pid process)
#-sbcl (not-implemented 'process-pid))
| 11,289 | Common Lisp | .lisp | 240 | 43.4375 | 112 | 0.692461 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | a3ddfc9308a31739ec38238eaf96b540dc7e28e4a15e3cef9e87952563eb299e | 18,629 | [
-1
] |
18,630 | specials.lisp | hbock_periscope/lisp/specials.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
;; Temporary vars (will go away eventually)
(defvar *flow-list* nil)
;; Version and compilation time
(defvar *compilation-time* (now))
(defparameter *periscope-version* "0.10.0 alpha2")
;;; And
;;; here
;;; we
;;; GO!
(defvar *build-string*
(format nil "0.9.95-~a"
(format-timestring nil *compilation-time*
:format '((:year 4) (:month 2) (:day 2)))))
;; Configuration
(defparameter *configuration-file-pathnames*
(list #P"/etc/"
(merge-pathnames ".periscope/" (user-homedir-pathname))))
(defvar *web-port* 20570)
(defvar *web-server* nil)
(defvar *web-show-diag* nil)
(defvar *web-login-required-p* nil)
(defvar *web-user-db* (make-hash-table :test #'equal))
(defvar *redirect-page* nil)
(defvar *collector* nil)
(defvar *collector-script* #P"../racollector")
(defvar *collector-process* nil)
(defvar *collector-default-filter* "tcp or icmp or udp")
(defvar *collector-argus-server* nil)
(defvar *collector-argus-port* 561)
(defvar *collector-shutdown-lock* (bt:make-lock))
(defvar *collector-shutdown-p* nil)
(defvar *dns-available-p* t)
(defvar *swank-port* 20571)
(defvar *enable-swank-p* nil)
(defvar *report-handler-list* nil)
(defvar *report-directory* #P"reports/")
(defvar *notable-ports* (list 22 53 80 443 51413))
(defvar *service-cache* (make-hash-table :size 500))
(defvar *service-reverse-cache* (make-hash-table :test #'equal :size 500))
(defvar *vlan-names* (make-hash-table))
(defparameter *notable-ports* (list 22 53 80 443 51413))
(defparameter *internal-networks* (list (cons #x0a000000 #xffffff00)))
(defconstant +min-session-time+ 300
"Minimum time (in seconds) a user can set HUNCHENTOOT:*MAX-SESSION-TIME*")
(defconstant +lowest-multicast-address+ #xe0000000)
(defconstant +highest-multicast-address+ #xefffffff)
(defconstant +highest-port-number+ #xffff)
(defconstant +broadcast-ip+ #xffffffff)
(defconstant +ip-proto-icmp+ 1)
(defconstant +ip-proto-igmp+ 2)
(defconstant +ip-proto-tcp+ 6)
(defconstant +ip-proto-udp+ 17)
(defconstant +vlan-none+ 0)
(defconstant +vlan-vid-mask+ #x0FFF)
(deftype vlan-id () '(unsigned-byte 12))
(deftype port-number () '(unsigned-byte 16))
| 3,036 | Common Lisp | .lisp | 71 | 41.211268 | 79 | 0.730639 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 36ae66c61aece52e03e36004c9f6f0471a87cdcbe1f19b154168cc475679101a | 18,630 | [
-1
] |
18,631 | main.lisp | hbock_periscope/lisp/main.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defvar *shutdown-cond* (bt:make-condition-variable))
(defvar *shutdown-lock* (bt:make-lock))
(defvar *shutdown-p* nil)
(defun enable-interrupts ()
#+sbcl
(dolist (interrupt (list sb-unix:sigterm sb-unix:sigint sb-unix:sighup))
(sb-sys:enable-interrupt interrupt #'signal-handler))
#-sbcl (not-implemented 'enable-interrupts))
#+sbcl
(defun signal-handler (signal code scp)
(declare (ignore code scp))
(flet ((shutdown ()
;; We call SHUTDOWN in a separate thread because
;; BT:CONDITION-NOTIFY does not seem to work in an interrupt
;; handler (at least on SBCL).
(bt:make-thread #'shutdown)))
(ecase signal
((#.sb-unix:sigint #.sb-unix:sigterm)
(format t "Shutting down on signal.~%")
(shutdown))
;; SIGHUP reloads the configuration file.
(#.sb-unix:sighup
(format t "Reloading configuration file.")
(load-config)))))
(defun shutdown ()
(setf *shutdown-p* t)
(bt:condition-notify *shutdown-cond*))
(defmacro with-debug-step ((message &rest args) &body body)
`(prog2
(format t " * ~50A" (format nil ,message ,@args))
(progn
,@body)
(format t " [OK]~%")))
(defun main ()
(let ((*package* (in-package :periscope)))
;; Ignore no-config-file at load time.
(handler-case (load-config)
(file-error () nil))
(enable-interrupts)
(format t "Starting Periscope ~a...~%" *periscope-version*)
(with-debug-step ("Bringing up web interface.")
(handler-case
(start-web)
(usocket:address-in-use-error ()
(format t "Web address in use - cannot start web interface.~%")
(return-from main 1))))
(with-debug-step ("Initializing internal Argus parser.")
(setf *collector* (init-basic-collector)))
(when *dns-available-p*
(with-debug-step ("Starting DNS reverse lookup thread.")
(start-dns)))
(format t "Periscope is now running.~%")
(loop :named main-wait :do
(bt:with-lock-held (*shutdown-lock*)
(bt:condition-wait *shutdown-cond* *shutdown-lock*)
(when *shutdown-p* (return-from main-wait))))
(format t "Received shutdown command.~%")
(with-debug-step ("Terminating DNS reverse lookup thread.")
(stop-dns))
(when (collector-running-p)
(with-debug-step ("Terminating racollector script.")
(stop-collector *collector-process*)))
;; HUNCHENTOOT:STOP seems to wait for the acceptor process/thread to complete, but
;; it never does until you hit the web server at least once. Force STOP-WEB to timeout
;; within 1 second to let us actually exit, which SHOULD be harmless. [famous last words]
(with-debug-step ("Terminating web interface.")
(with-timeout (1)
(stop-web)))
(return-from main 0)))
| 3,617 | Common Lisp | .lisp | 84 | 38.821429 | 93 | 0.688356 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7118550a104db802f8c87e961733e0e52df06c52f6564989d3eefe36eb62d229 | 18,631 | [
-1
] |
18,632 | argus-cffi.lisp | hbock_periscope/lisp/argus-cffi.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defcstruct argus-dsr-header
(type :uchar)
(subtype :uchar)
(dsr_un :uint16))
(defcstruct argus-ip-flow
(ip-src :uint32)
(ip-dst :uint32)
(ip-proto :uint8)
(tp-proto :uint8)
(source-port :uint16)
(dest-port :uint16)
(pad :uint16))
(defcstruct argus-ipv6-flow
(ip-src :uint32 :count 4)
(ip-dst :uint32 :count 4)
(flow-protocol :uint32)
(source-port :uint16)
(dest-port :uint16))
(defcstruct argus-icmp-flow
(ip-src :uint32)
(ip-dst :uint32)
(ip-proto :uint8)
(tp-proto :uint8)
(type :uint8)
(code :uint8)
(id :uint16)
(ip-id :uint16))
(defcunion argus-flow-union
(ip argus-ip-flow)
(ip6 argus-ipv6-flow)
(icmp argus-icmp-flow))
(defcstruct argus-flow
(hdr argus-dsr-header)
(flow-un argus-flow-union))
(defcstruct argus-uni-stats
#+cffi-features:no-long-long (error "No long long support! Required for statistics.")
(packets :long-long)
(bytes :long-long)
(appbytes :long-long))
(defcstruct argus-metrics
;; I have to specify this manually for this to work on 64-bit SBCL.
;; Might have something to do with :long-long and padding?
(source-stats argus-uni-stats :offset 4)
(dest-stats argus-uni-stats :offset 28))
(defcstruct argus-vlan
(hdr argus-dsr-header)
(sid :uint16)
(did :uint16))
(defcstruct argus-time
(start-sec :int32)
(start-usec :int32)
(end-sec :int32)
(end-usec :int32))
(defcstruct argus-time-object
(hdr argus-dsr-header)
(src argus-time)
(dst argus-time))
(defcstruct argus-queue
(count :uint))
(defcstruct argus-queue-header
(nxt :pointer)
(prv :pointer)
(queue :pointer))
(defcenum argus-flow-types
(:ipv4 #x01)
(:ipv6 #x02)
(:ethernet #x03)
(:arp #x04)
(:rarp #x05)
(:mpls #x06)
(:vlan #x07)
(:ib #x08)
(:lcp #x09)
(:isis #x0A))
(defbitfield argus-tcp-state
(:saw-syn #x00000001)
(:saw-syn-sent #x00000002)
(:established #x00000004)
(:fin #x00000008)
(:fin-ack #x00000010)
(:normal-close #x00000020)
(:close-waiting #x00000040)
(:src-packets-retransmitted #x00000100)
(:dest-packets-retransmitted #x00000200)
(:src-reset #x000001000)
(:dest-reset #x000002000))
(defun argus-queue-count (queue-header)
"Returns the number of elements in the ArgusQueueStruct associated with an ArgusQueueHeader."
(if (not (null-pointer-p queue-header))
(with-foreign-slots ((queue) queue-header argus-queue-header)
(foreign-slot-value queue 'argus-queue 'count))
0))
(defun argus-queue-list (qhdr)
"Build up a list of foreign pointers held in an ArgusQueueHeader structure."
(loop
:with c-count = (argus-queue-count qhdr)
:with count = 0
:while (< count c-count)
:collect qhdr :do
(setf qhdr (foreign-slot-value qhdr 'argus-queue-header 'nxt))
(incf count)))
(declaim (inline get-icmp get-ip get-flow get-metrics get-vlan))
(defun get-ip (flow)
(foreign-slot-value (foreign-slot-value flow 'argus-flow 'flow-un) 'argus-flow-union 'ip))
(defun get-icmp (flow)
(foreign-slot-value (foreign-slot-value flow 'argus-flow 'flow-un) 'argus-flow-union 'icmp))
(defun get-flow (dsrs)
(foreign-slot-value dsrs 'periscope-dsrs 'flow))
(defun get-metrics (dsrs)
(foreign-slot-value dsrs 'periscope-dsrs 'metric))
(defun get-vlan (dsrs)
(foreign-slot-value dsrs 'periscope-dsrs 'vlan))
(defun argus-timestamp (sec usec)
(unix-to-timestamp sec :nsec (* 1000 usec)))
(defun source-time (dsrs)
(let ((time
(foreign-slot-value
(foreign-slot-value dsrs 'periscope-dsrs 'time) 'argus-time-object 'src)))
(with-foreign-slots ((start-sec start-usec end-sec end-usec) time argus-time)
(values (argus-timestamp start-sec start-usec)
(argus-timestamp end-sec end-usec)))))
(defun dest-time (dsrs)
(let ((time
(foreign-slot-value
(foreign-slot-value dsrs 'periscope-dsrs 'time) 'argus-time-object 'dst)))
(with-foreign-slots ((start-sec start-usec end-sec end-usec) time argus-time)
(values (argus-timestamp start-sec start-usec)
(argus-timestamp end-sec end-usec)))))
(defun source-metrics (dsrs)
(let ((stats
(foreign-slot-value
(foreign-slot-value dsrs 'periscope-dsrs 'metric)
'argus-metrics 'source-stats)))
(with-foreign-slots ((packets bytes appbytes) stats argus-uni-stats)
(values packets bytes appbytes))))
(defun dest-metrics (dsrs)
(let ((stats
(foreign-slot-value
(foreign-slot-value dsrs 'periscope-dsrs 'metric)
'argus-metrics 'dest-stats)))
(with-foreign-slots ((packets bytes appbytes) stats argus-uni-stats)
(values packets bytes appbytes)))) | 5,473 | Common Lisp | .lisp | 157 | 31.828025 | 95 | 0.70775 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 019d56df9d1691407b9a2ed6f5d0b35be0e316e388919e47c9d42de744df2c13 | 18,632 | [
-1
] |
18,633 | config.lisp | hbock_periscope/lisp/config.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defun touch (pathname)
(with-open-file (ignoreme (ensure-directories-exist pathname)
:direction :output
:if-does-not-exist :create
:if-exists :error))
(probe-file pathname))
(defun find-config-file (&optional (pathnames *configuration-file-pathnames*))
"Find a suitable configuration file in PATHNAMES."
(declare (type sequence pathnames))
(flet ((config-file (pathname) (merge-pathnames "periscope-rc.lisp" pathname)))
(or
(find-if #'probe-file (mapcar #'config-file pathnames))
(config-file (first (last pathnames))))))
(defun load-config (&optional (pathname *configuration-file-pathnames*))
"Load the configuration Lisp file directly."
(clrhash *web-user-db*)
(load (find-config-file pathname)))
(defun save-config (&optional (pathname *configuration-file-pathnames*))
"Save configuration data to a suitable file as found by FIND-CONFIG-FILE."
(with-open-file (config-stream (ensure-directories-exist (find-config-file pathname))
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(write-config config-stream)))
(defun network-list-forms (list)
"Given a list of dotted lists, create forms to recreate that list."
`(list
,@(loop :for (network . netmask) :in list :collect
`(cons ,network ,netmask))))
(defun write-config (&optional (stream *standard-output*))
"Write the configuration data to a stream."
(format stream "~S~%"
(symbol-value-setf-forms
'(*web-port* *web-show-diag*
*web-login-required-p*
*collector-argus-port*
*collector-argus-server*
*collector-default-filter*
hunchentoot:*show-lisp-errors-p*
hunchentoot:*session-max-time*
*swank-port* *enable-swank-p*
*notable-ports*
*dns-available-p*)))
(format stream "~S~%" `(setf *internal-networks* ,(network-list-forms *internal-networks*)))
(format stream "~S~%" (dump-hash-tables '(*vlan-names*)))
(format stream "~S~%" (create-login-forms))
(dolist (user (user-list))
;; Only print the MAKE-FILTER forms if the user has filters.
(format stream "~:[~;~:*~S~%~]" (create-filter-forms user))))
(defun symbol-value-setf-forms (symbol-list)
"Given a list of symbols, construct a SETF form that will properly set all relevant values."
`(setf
,@(let (pairs)
(dolist (symbol symbol-list)
(push symbol pairs)
(let ((value (symbol-value symbol)))
(typecase value
(list (push (if (null value) nil `(list ,@value)) pairs))
(t (push value pairs)))))
(nreverse pairs))))
(defun dump-hash-tables (symbol-list)
"Given a list of symbols representing hash tables, construct forms that will recreate
the hash table when evaluated. Properly restores hash table size and test."
`(progn
,@(loop :for table-symbol :in symbol-list
:for table = (symbol-value table-symbol) :collect
`(progn
(setf ,table-symbol
(make-hash-table :test (quote ,(hash-table-test table))
:size ,(hash-table-size table)))
(loop :for (key . value) :in
(list
,@(loop :for key :being :the :hash-keys :in table :using (:hash-value value)
:collect `(cons ,key ,value)))
:do (setf (gethash key ,table-symbol) value)))))) | 4,101 | Common Lisp | .lisp | 90 | 41.533333 | 94 | 0.6975 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7cb88891615b294abef21fe5e1f738faba89c9f2c606bf09345a4a0d9b68acc5 | 18,633 | [
-1
] |
18,634 | collector.lisp | hbock_periscope/lisp/collector.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defclass collector ()
((ptr :initform nil :accessor get-ptr)
(remote :initform nil :accessor remote-sources)))
(defclass source ()
((ptr :initarg :ptr :initform nil :accessor get-ptr)
(path :initarg :path :initform nil :accessor source-path)
(major-version :initarg :major-version :reader major-version)
(minor-version :initarg :minor-version :reader minor-version)
(port :initarg :port :reader port)))
(defcallback receive-flow :void ((collector periscope-collector)
(type :uchar)
(record :pointer)
(dsrs periscope-dsrs))
(declare (ignore collector record))
(case (foreign-enum-keyword 'argus-flow-types type :errorp nil)
(:ipv4
(unless (null-pointer-p (get-metrics dsrs))
(let ((ip (get-ip (get-flow dsrs))))
(push (build-flow dsrs ip) *flow-list*))))))
(defmethod initialize-instance :after ((object collector) &key)
(let ((ptr (foreign-alloc 'periscope-collector)))
(setf (get-ptr object) ptr)
(when (minusp (%collector-init ptr))
(foreign-free ptr)
(error "Unable to initialize collector!"))
(tg:finalize object (lambda ()
(%collector-free ptr)
(foreign-free ptr)))))
(defmethod run ((object collector))
"Start the collector."
(when (running-p object)
(error "Collector is already running."))
(when (minusp (%collector-run (get-ptr object)))
(error "Failed to start collector."))
(setf (remote-sources object) nil)
object)
(defmethod stop ((object collector))
"Stop the collector, closing all open files and connections."
(%collector-stop (get-ptr object))
object)
(defmethod add-remote ((collector collector) (host string) &optional (port 561))
"Add a remote host to be processed when START is called."
(let* ((hoststr (format nil "~a:~d" host port))
(ptr (%argus-remote-add (get-ptr collector) hoststr)))
(when (null-pointer-p ptr)
(error "Error adding host ~a to the collector." hoststr))
(let ((source (make-instance 'source :ptr ptr :path host)))
(push source (remote-sources collector)))))
(defgeneric add-file (collector file)
(:documentation "Add a local Argus file to be processed when START is called."))
(defmethod add-file ((collector collector) (file string))
(when (minusp (%argus-local-add (get-ptr collector) file))
(if (not (probe-file file))
(periscope-file-error "File ~a does not exist!" file)
(periscope-file-error "Failed to add file ~a to the collector." file)))
file)
(defmethod add-file ((collector collector) (file pathname))
(add-file collector (namestring file)))
(defmethod connect ((collector collector) (host string))
"Connect directly to a remote Argus server at HOST."
(when (not (running-p collector))
(error "Can't direct connect to hosts when collector is not running!"))
(let ((ptr (%argus-remote-direct-connect (get-ptr collector) host)))
(when (null-pointer-p ptr)
(error "Failed to connect to host ~a!" host))
(let ((source (make-instance 'source :ptr ptr :path host)))
(push source (remote-sources collector)))))
(defmethod running-p ((collector collector))
(plusp (%collector-running-p (get-ptr collector))))
(defmethod connected-p ((object source))
(plusp (%argus-connected-p (get-ptr object))))
(defmethod filter ((object collector))
(%argus-get-filter (get-ptr object)))
(defmethod (setf filter) ((filter string) (object collector))
(when (minusp
(%argus-set-filter (get-ptr object) filter))
(periscope-error "Syntax error in filter: '~a'" filter)))
(defun init-basic-collector (&key (default-filter *collector-default-filter*))
(let ((collector (make-instance 'collector)))
(with-collector-callbacks (process_flow) collector
(setf process_flow (callback receive-flow)))
(when default-filter
(setf (filter collector) default-filter))
collector))
(defun process-local-file (file &key (collector (init-basic-collector)) filter)
(setf *flow-list* nil)
(when filter
(setf (filter collector) filter))
(add-file collector file)
(run collector)
(setf *flow-list* (nreverse *flow-list*)))
;;; Collector stuff for racollector script.
(defun collector-connect-string (&optional (hostname *collector-argus-server*)
(port *collector-argus-port*))
(declare (type (unsigned-byte 16) port))
(format nil "~a:~d" hostname port))
(defun run-collector (server time-period)
"Run the racollector script as a child process, specifying the remote Argus server
and the time period for which it will bin/split its output logs."
(let ((time-period-string
(ecase time-period
(:test "10s")
(:hour "1h")
(:half-hour "30m")))
(output-spec
(in-report-directory (ecase time-period
(:test "test/%Y%m%d-%H:%M:%S")
(:hour "hourly.%Y%m%d-%H")
(:half-hour "halfhour.%Y%m%d-%H.%M")))))
(setf *collector-process*
(process-create (probe-file *collector-script*) nil
;; Arguments
server time-period-string (namestring output-spec)))
(process-wait *collector-process*)))
(defun stop-collector (collector-process)
"Terminate the collector-process by sending it SIGTERM, and wait for it to exit."
(when (process-alive-p collector-process)
(process-wait (process-signal collector-process))))
(defun collector-running-p ()
"Is the collector child process running?"
(process-alive-p *collector-process*))
(defun collector-aborted-p ()
(and *collector-process*
(not (process-alive-p *collector-process*))
(= 4 (process-wait *collector-process*))))
(defun collector-thread ()
"Thread that runs and monitors the collector until *SHUTDOWN-P* is T."
(bt:with-lock-held (*collector-shutdown-lock*)
(setf *collector-shutdown-p* nil))
(loop :named watchdog-loop :do
(run-collector (collector-connect-string) :hour)
(bt:with-lock-held (*collector-shutdown-lock*)
(if *collector-shutdown-p*
(return-from watchdog-loop)
(progn
(when (collector-aborted-p)
(format t "Collector aborted. Terminating thread.~%")
(return-from watchdog-loop))
(format t "Collector stopped unexpectedly. Restarting!~%"))))))
;;; This code is defunct for now - we are no longer handling remote Argus
;;; sources directly.
(defmethod remote-port ((object source))
(%argus-remote-port (get-ptr object)))
(defmethod remote-ip ((object source))
(%argus-remote-ip (get-ptr object)))
(defun get-argus-sources (queue)
(let (sources)
(dolist (input (argus-queue-list queue))
(with-foreign-object (info 'periscope-input-info)
(unless (zerop (%argus-remote-info input info))
(error "Error getting info for ArgusInput ~a" input))
(with-foreign-slots ((major-version minor-version hostname port) info periscope-input-info)
(push (make-instance 'source :major-version major-version
:minor-version minor-version
:hostname hostname
:port port
:ptr input
:path "NONE")
sources))))
sources))
(defmethod remove-source ((src source) (collector collector))
(if (null-pointer-p (get-ptr src))
(error "Cannot remove a NULL source!")
(unless (zerop
(%argus-remote-remove (get-ptr collector) (get-ptr src)))
(error "Failed to remove source at ~a!" (get-ptr src)))))
(defmethod available-sources ((object collector))
(get-argus-sources (%argus-remote-pending-queue (get-ptr object))))
(defmethod active-sources ((object collector))
(get-argus-sources (%argus-remote-active-queue (get-ptr object))))
| 8,347 | Common Lisp | .lisp | 185 | 41.259459 | 92 | 0.705868 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f3156aa0bbfc5317f8083a14cc18fbef903f499e165fce7eb74a905e7f257059 | 18,634 | [
-1
] |
18,635 | conditions.lisp | hbock_periscope/lisp/conditions.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
;;; Shamelessly adapted from Hunchentoot's conditions.lisp.
;;; Hunchentoot copyright notice:
;;; Copyright (c) 2008-2009, Dr. Edmund Weitz. All rights reserved.
(define-condition periscope-condition (condition)
()
(:documentation "Superclass for all conditions specific to Periscope."))
(define-condition periscope-error (periscope-condition error)
()
(:documentation "Superclass for all errors specific to Periscope."))
(define-condition periscope-simple-error (periscope-error simple-condition)
()
(:documentation "Periscope error class with formatting capabilities."))
(defun periscope-error (control &rest args)
(error 'periscope-simple-error :format-control control :format-arguments args))
(define-condition periscope-config-error (periscope-simple-error)
()
(:documentation "Error loading or saving Periscope's configuration."))
(defun periscope-config-error (control &rest args)
(error 'periscope-config-error :format-control control :format-arguments args))
(define-condition periscope-file-error (periscope-simple-error file-error)
()
(:documentation "Error handling files related to Periscope."))
(defun periscope-file-error (control &rest args)
(error 'periscope-file-error :format-control control :format-arguments args))
(define-condition filter-parse-error (periscope-simple-error parse-error)
((error-type :initarg :error-type :reader filter-parse-error-type)
(bad-data :initarg :bad-data :reader filter-parse-error-data))
(:documentation "Specific error information about bad filter specifications.")
(:report
(lambda (condition stream)
(format stream "Error parsing filter with bad ~a data: '~a' is not valid."
(filter-parse-error-type condition)
(filter-parse-error-data condition)))))
(defun filter-parse-error (type data)
(error 'filter-parse-error :error-type type :bad-data data))
(define-condition operation-not-implemented (periscope-error)
((operation :initarg :operation
:reader operation-not-implemented-operation
:documentation "The name of the unimplemented operation."))
(:report (lambda (condition stream)
(format stream "The operation ~A is not yet implemented for the Lisp implementation
~A, version ~A."
(operation-not-implemented-operation condition)
(lisp-implementation-type)
(lisp-implementation-version)))))
(defun not-implemented (name)
(error 'operation-not-implemented :operation name)) | 3,327 | Common Lisp | .lisp | 62 | 50.725806 | 89 | 0.759926 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 1f367f4a9818d317c6d383482d0413e5f7f61fe93505af0e677be7437344866a | 18,635 | [
-1
] |
18,636 | periscope-cffi.lisp | hbock_periscope/lisp/periscope-cffi.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(define-foreign-library libperiscope
(:unix "libperiscope.so"))
(use-foreign-library libperiscope)
(defcstruct periscope-callbacks
(idle :pointer)
(process_flow :pointer)
(input_complete :pointer))
(defcstruct periscope-metrics
(flows :uint32)
(tcp-count :uint32)
(udp-count :uint32)
(icmp-count :uint32)
(other-count :uint32))
(defcstruct periscope-collector
(parser :pointer)
(callbacks periscope-callbacks)
(metrics periscope-metrics)
(sources :uint32)
(running :uint8))
;;; Argus DSR pointers
(defcstruct periscope-dsrs
(flow :pointer)
(vlan :pointer)
(metric :pointer)
(time :pointer)
(net :pointer))
(defcstruct periscope-input-info
(qhdr :pointer)
(major-version :int)
(minor-version :int)
(hostname :string)
(port :ushort))
(defcenum ip-protocols
(:ip 0)
(:icmp 1)
(:igmp 2)
(:ipip 4)
(:tcp 6)
(:udp 17)
(:dccp 33)
(:mtp 92))
(defcfun ("periscope_collector_init" %collector-init) :int
(collector periscope-collector))
(defcfun ("periscope_collector_run" %collector-run) :int
(collector periscope-collector))
(defcfun ("periscope_collector_is_running" %collector-running-p) :int
(collector periscope-collector))
(defcfun ("periscope_collector_stop" %collector-stop) :void
(collector periscope-collector))
(defcfun ("periscope_collector_free" %collector-free) :void
(collector periscope-collector))
(defcfun ("periscope_argus_local_add" %argus-local-add) :int
(collector periscope-collector)
(pathname :string))
(defcfun ("periscope_argus_remote_add" %argus-remote-add) :pointer
(collector periscope-collector)
(hoststr :string))
(defcfun ("periscope_argus_remote_direct_connect" %argus-remote-direct-connect) :pointer
(collector periscope-collector)
(hoststr :string))
(defcfun ("periscope_argus_remote_remove" %argus-remote-remove) :int
(collector periscope-collector)
(input :pointer))
(defcfun ("periscope_argus_remote_info" %argus-remote-info) :int
(collector periscope-collector)
(input :pointer))
(defcfun ("periscope_argus_remote_is_connected" %argus-connected-p) :int
(input :pointer))
(defcfun ("periscope_argus_remote_ip" %argus-remote-ip) :uint32
(input :pointer))
(defcfun ("periscope_argus_remote_port" %argus-remote-port) :uint16
(input :pointer))
(defcfun ("periscope_argus_remote_pending_queue" %argus-remote-pending-queue) :pointer
(collector periscope-collector))
(defcfun ("periscope_argus_remote_active_queue" %argus-remote-active-queue) :pointer
(collector periscope-collector))
(defcfun ("periscope_argus_set_filter" %argus-set-filter) :int
(collector periscope-collector)
(filter :string))
(defcfun ("periscope_argus_get_filter" %argus-get-filter) :string
(collector periscope-collector))
(defcfun ("periscope_argus_debug_dsrs" %argus-debug-dsrs) :void
(dsrs periscope-dsrs))
(defmacro with-collector-callbacks (callbacks collector &body body)
`(with-foreign-slots ((,@callbacks)
(foreign-slot-value (get-ptr ,collector) 'periscope-collector 'callbacks)
periscope-callbacks)
,@body))
| 3,945 | Common Lisp | .lisp | 103 | 35.786408 | 88 | 0.750984 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | b1546ec849a5e7496e51cbd6da3df304525cbe39eccc69c2328edcd40ab62586 | 18,636 | [
-1
] |
18,637 | report-handlers.lisp | hbock_periscope/lisp/report-handlers.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defun make-filtered-reports (flow-list &optional time user)
"Return a list of report structures in the form (time filter &rest reports)
corresponding to user's filters, as applied to the flows in flow-list. If no
filters are defined, a list with the form (time nil &rest reports) is returned."
(if (and user (filters user))
(loop :for flows :in (apply-filters flow-list (filter-predicates user))
:for filter :in (filters user) :collect
(with-slots (internal-networks) filter
;; This is rather inelegant, shadowing *internal-networks*, but it works well
;; without touching anything else.
(let ((*internal-networks* (if internal-networks internal-networks *internal-networks*)))
(list time
filter
(make-periodic-report flows)
(make-service-report flows)))))
(list
(list time
nil
(make-periodic-report flow-list)
(make-service-report flow-list)))))
(defun in-report-directory (filespec &optional (directory *report-directory*))
(merge-pathnames filespec (truename (ensure-directories-exist directory))))
(defun hourly-log (time &optional (directory *report-directory*))
"Return the hourly Argus log pathname corresponding to time, searching in directory."
(multiple-value-bind (sec min hour date month year)
(decode-universal-time time)
(declare (ignore sec min))
(let ((log
(probe-file
(merge-pathnames (format nil "hourly.~d~2,'0d~2,'0d-~2,'0d" year month date hour)
directory))))
(if log
log
(periscope-file-error "Log file for time ~d does not exist in ~a!" time directory)))))
(defun hourly-logs (&optional (pathspec *report-directory*))
"Find all files in pathspec matching the following filename format: hourly.YYYYMMDD-HH, where
Y = year, M = month, D = date, and H = hour. Returns a list of all such hourly Argus logs as a
dotted list with the CAR being the universal time indicated in the filename and the CDR being
the pathname of the log itself."
(let (reports)
(dolist (file (fad:list-directory pathspec))
(let ((time
(ppcre:register-groups-bind ((#'parse-integer year month day hour))
("hourly.(\\d{4})(\\d{2})(\\d{2})-(\\d{2})" (namestring file))
(encode-universal-time 0 0 hour day month year))))
(when time
(push (cons time file) reports))))
(sort (nreverse reports) #'< :key #'car)))
(defun last-hourly-log (&optional (pathspec *report-directory*))
"Return the most newly generated hourly Argus log."
(first (reverse (hourly-logs pathspec))))
(defun daily-split-hourly-logs ()
(let ((logs (hourly-logs)) day-logs log-list)
(when logs
(loop
:with day = (this-day (car (first logs)))
:for log :in logs
:if (= (this-day (car log)) day)
:do (push log day-logs)
:else :do
(push (nreverse day-logs) log-list)
(setf day-logs nil)
(setf day (this-day (car log)))
(push log day-logs))
(when day-logs
(push (nreverse day-logs) log-list))
log-list)))
(defun print-hourly-list ()
"Print out the hourly log list HTML, with newest logs first."
(with-html-output (*standard-output*)
(:div
:class "report-listing"
(:h2 "Hourly Report Listing")
(let ((daily-logs (daily-split-hourly-logs)))
(when (null daily-logs)
(htm (:br) "No hourly reports available!")
(return-from print-hourly-list nil))
(dolist (logs daily-logs)
(let ((log-day (this-day (car (first logs)))))
(htm (:br)
(:b (str (long-date-string (universal-to-timestamp log-day) :minutes nil)))
(:br)))
(loop
:for first = t :then nil
:for log :in logs :do
(let ((log-time (car log)))
(multiple-value-bind (sec min hour)
(decode-universal-time log-time)
(declare (ignore sec min))
(if first
(if (< hour 12)
(htm (:b "AM "))
(htm (:b "PM ")))
(when (= 12 hour)
(htm (:br) (:b "PM "))))
(htm (:a :href (format nil "/hourly?time=~d" log-time)
(fmt "~2,'0d:00" hour))))))
(htm (:br)))))))
(define-report-handler (hourly "/hourly" "Hourly Traffic")
((time :parameter-type 'integer))
(with-periscope-page ("Hourly Traffic Reports")
(if time
(handler-case
(let* ((flows (process-local-file (hourly-log time)))
(report-lists (make-filtered-reports flows time (user)))
(logs (mapcar #'car (hourly-logs)))
(position (position time logs))
(previous-time
(when (plusp position)
(nth (1- position) logs)))
(next-time (nth (1+ position) logs)))
(htm
(:h2 "Hourly Report")
(if previous-time
(htm (:a :href (format nil "/hourly?time=~d" previous-time) "Previous Report"))
(htm "Previous Report"))
" | "
(:a :href "/hourly" "Back to all hourly reports")
" | "
(if next-time
(htm (:a :href (format nil "/hourly?time=~d" next-time) "Next Report"))
(htm "Next Report"))
(:div :class "stats"
(dolist (report-list report-lists)
(destructuring-bind (time filter &rest reports) report-list
(htm
(:h3 (str (long-date-string (universal-to-timestamp time))))
(when filter (print-html filter)))
(dolist (report reports)
(print-html report)))
(htm (:hr))))))
;; PROCESS-LOCAL-FILE and HOURLY-LOG can throw PERISCOPE-FILE-ERROR
;; to indicate file-not-found
(file-error () (hunchentoot:redirect "/nothingtoseehere")))
;; When 'time' GET parameter is not specified, print the list of all available
;; reports.
(print-hourly-list))))
| 6,391 | Common Lisp | .lisp | 152 | 37.394737 | 95 | 0.66715 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7069528e2172b80220ee3ba064f0fee89547b922ab06cecceea11bab05a231bc | 18,637 | [
-1
] |
18,638 | time.lisp | hbock_periscope/lisp/time.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(deftype universal-time () '(integer 536870912))
(defun leap-year-p (year)
"Returns true if year is a leap year."
(and (zerop (mod year 4))
(or (zerop (mod year 400))
(not (zerop (mod year 100))))))
(defun normalize-hour (hour)
(mod hour 24))
(defun normalize-day (day month year)
(declare (type (integer 1 12) month))
(if (plusp day)
(let ((month-days (days-in-month month year)))
(if (> day month-days) (mod day month-days) day))
(let ((month-days (days-in-month
(normalize-month (1- month)) year)))
(+ month-days day))))
(defun normalize-month (month)
"Returns a corrected month (1 - 12) given an integer from -11 to 23."
(declare (type (integer -11 23)))
(cond
((plusp month)
(if (> month 12) (mod month 12) month))
(t (+ 12 (1- month)))))
(defmacro define-time-method (name (time-var &rest lambda-rest) vars &body body)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod ,name ((,time-var integer) ,@lambda-rest)
(multiple-value-bind (,@vars)
(decode-universal-time ,time-var)
,@body))
(defmethod ,name ((,time-var timestamp) ,@lambda-rest)
(universal-to-timestamp (,name (timestamp-to-universal ,time-var) ,@lambda-rest)))))
(define-time-method this-half-hour (time)
(sec min hour date month year)
(declare (ignore sec))
(encode-universal-time 0 (if (>= min 30) 30 0) hour date month year))
(define-time-method next-half-hour (time)
(sec min hour date month year)
(declare (ignore sec))
(let* ((new-min (if (>= min 30) 0 30))
(new-hour (normalize-hour (if (< new-min min) (1+ hour) hour)))
(new-date (normalize-day (if (< new-hour hour) (1+ date) date) month year))
(new-month (normalize-month (if (< new-date date) (1+ month) month)))
(new-year (if (< new-month month) (1+ year) year)))
(encode-universal-time 0 new-min new-hour new-date new-month new-year)))
(define-time-method this-hour (time)
(sec min hour date month year)
(declare (ignore sec min))
(encode-universal-time 0 0 hour date month year))
(define-time-method next-hour (time)
(sec min hour date month year)
(declare (ignore sec min))
(let* ((new-hour (normalize-hour (1+ hour)))
(new-date (normalize-day (if (< new-hour hour) (1+ date) date) month year))
(new-month (normalize-month (if (< new-date date) (1+ month) month)))
(new-year (if (< new-month month) (1+ year) year)))
(encode-universal-time 0 0 new-hour new-date new-month new-year)))
(define-time-method this-day (time)
(sec min hour date month year)
(declare (ignore sec min hour))
(encode-universal-time 0 0 0 date month year))
(define-time-method next-day (time)
(sec min hour date month year day)
(declare (ignore sec min hour day))
(let* ((new-date (normalize-day (1+ date) month year))
(new-month (normalize-month (if (< new-date date) (1+ month) month)))
(new-year (if (< new-month month) (1+ year) year)))
(encode-universal-time 0 0 0 new-date new-month new-year)))
(define-time-method this-week (time)
(sec min hour date month year day)
(declare (ignore sec min hour))
(let* ((new-date (normalize-day (- date (if (= 6 day) 0 (1+ day))) month year))
(new-month (normalize-month (if (> new-date date) (1- month) month)))
(new-year (if (> new-month month) (1- year) year)))
(encode-universal-time 0 0 0 new-date new-month new-year)))
(define-time-method next-week (time)
(sec min hour date month year day)
(declare (ignore sec min hour))
(let* ((new-date (normalize-day (+ date (if (= 6 day) 7 (- 6 day))) month year))
(new-month (normalize-month (if (< new-date date) (1+ month) month)))
(new-year (if (< new-month month) (1+ year) year)))
(encode-universal-time 0 0 0 new-date new-month new-year)))
(define-time-method this-month (time)
(sec min hour date month year)
(declare (ignore sec min hour date))
(encode-universal-time 0 0 0 1 month year))
(define-time-method next-month (time)
(sec min hour date month year)
(declare (ignore sec min hour date))
(let* ((new-month (normalize-month (1+ month)))
(new-year (if (< new-month month) (1+ year) year)))
(encode-universal-time 0 0 0 1 new-month new-year)))
(define-time-method this-time (time window) ()
(ecase window
(:half-hour (this-half-hour time))
(:hour (this-hour time))
(:day (this-day time))
(:week (this-week time))
(:month (this-month time))))
(define-time-method next-time (time window) ()
(ecase window
(:half-hour (next-half-hour time))
(:hour (next-hour time))
(:day (next-day time))
(:week (next-week time))
(:month (next-month time))))
(defun time-split (flow-sequence next-time-fun)
(flet ((%time-split (flow-sequence timestamp)
(loop
:for flow :in flow-sequence
:if (< (timestamp-to-universal (start-time flow)) timestamp)
:collect flow :into before
:else
:collect flow :into after
:finally (return (list before after)))))
(let (split-list)
(do* ((time
(funcall next-time-fun (timestamp-to-universal (start-time (first flow-sequence))))
(funcall next-time-fun time))
(split (%time-split flow-sequence time)
(%time-split (second split) time)))
((and (null (car split)) (null (second split)))
(nreverse split-list))
(when (car split)
(push (first split) split-list)))))) | 6,270 | Common Lisp | .lisp | 139 | 41.23741 | 91 | 0.668524 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | f8f8ad801df9c34d88c07cf841e0228f97eaa1c48bda50778fda0da2b02cca52 | 18,638 | [
-1
] |
18,639 | dns.lisp | hbock_periscope/lisp/dns.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defvar *dns-thread*)
(defvar *dns-lock* (bt:make-lock "dns"))
(defvar *dns-cond* (bt:make-condition-variable))
(defvar *dns-requests* nil)
(defvar *dns-cache* (make-hash-table :size 10000))
(defun ip-to-vector (ip)
"Convert an integer IP address to a 4-element vector as required by SB-BSD-SOCKETS."
(declare (type (unsigned-byte 32) ip))
(vector
(ldb (byte 8 24) ip)
(ldb (byte 8 16) ip)
(ldb (byte 8 8) ip)
(ldb (byte 8 0) ip)))
(defun vector-to-ip (vector)
"Convert an IPv4 address in vector form to a 32-bit integer."
(the (unsigned-byte 32)
(logior
(ash (aref vector 0) 24)
(ash (aref vector 1) 16)
(ash (aref vector 2) 8)
(ash (aref vector 3) 0))))
(defun start-dns ()
"Start the DNS resolver thread."
(unless (and (boundp '*dns-thread*) (bt:thread-alive-p *dns-thread*))
(setf *dns-available-p* t)
(setf *dns-thread* (bt:make-thread #'dns-thread :name "DNS Reverse Lookups"))))
(defun stop-dns (&key (join t))
"Stop and optionally join the DNS resolver thread."
(setf *dns-available-p* nil)
(bt:condition-notify *dns-cond*)
(when join
(bt:join-thread *dns-thread*)))
(defun clear-dns ()
"Clear the current DNS cache."
(clrhash *dns-cache*))
(defun dns-thread ()
(loop :while *dns-available-p* :do
(let ((host
(bt:with-lock-held (*dns-lock*)
(cond
((null *dns-requests*) (bt:condition-wait *dns-cond* *dns-lock*))
(t (setf *dns-requests* (remove-duplicates *dns-requests*))
(pop *dns-requests*))))))
(when host
(let ((hostname
;; Attempt to force a 1-second timeout on all DNS requests.
;; Most lookups that take more than that end up being NXDOMAIN.
(with-timeout (1)
(reverse-lookup host))))
(bt:with-lock-held (*dns-lock*)
(setf (gethash host *dns-cache*) hostname)))))))
(defun reverse-lookup (ip)
#+sbcl
(handler-case
(sb-bsd-sockets:host-ent-name
(sb-bsd-sockets:get-host-by-address (ip-to-vector ip)))
(sb-bsd-sockets:name-service-error (e)
(declare (ignore e)) nil))
#-sbcl (not-implemented 'reverse-lookup))
(defun lookup (hostname)
#+sbcl
(handler-case
(vector-to-ip
(sb-bsd-sockets:host-ent-address
(sb-bsd-sockets:get-host-by-name hostname)))
(sb-bsd-sockets:name-service-error (e)
(declare (ignore e)) nil))
#-sbcl (not-implemented 'reverse-lookup))
(defun hostname (ip)
"Given an IP address, lookup the hostname of the corresponding machine, if available.
Returns the IP address as a string on lookup failure."
(cond
((any-broadcast-address-p ip)
(format nil "~a [Broadcast]" (ip-string ip)))
((multicast-address-p ip)
(format nil "~a [Multicast]" (ip-string ip)))
(*dns-available-p*
(bt:with-lock-held (*dns-lock*)
(multiple-value-bind (hostname existp)
(gethash ip *dns-cache*)
(if existp
(if hostname
(values hostname :found)
(values (ip-string ip) :nxdomain))
(progn
(push ip *dns-requests*)
(bt:condition-notify *dns-cond*)
(values (ip-string ip) :processing))))))
(t (values (ip-string ip) :unavailable)))) | 4,013 | Common Lisp | .lisp | 104 | 34.701923 | 87 | 0.674807 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 2efb397ab99b9e2be7c8c6a47d36f713b10b70bd05296f4e53e6d2207fc31440 | 18,639 | [
-1
] |
18,640 | unit-tests.lisp | hbock_periscope/lisp/unit-tests.lisp | ;;; Some code borrowed from BABEL-TESTS.
;;; Copyright (C) 2007-2008, Luis Oliveira <[email protected]>
(defpackage :periscope-test
(:use :common-lisp :periscope :cffi :stefil))
(in-package :periscope-test)
(in-root-suite)
(defsuite* utility-tests)
(defmacro returns (form &rest values)
"Asserts, through EQUALP, that FORM returns VALUES."
`(is (equalp (multiple-value-list ,form) (list ,@values))))
(defmacro defstest (name form &body return-values)
"Similar to RT's DEFTEST."
`(deftest ,name ()
(returns ,form ,@(mapcar (lambda (x) `',x) return-values))))
(defun fail (control-string &rest arguments)
(stefil::record-failure 'stefil::failed-assertion
:format-control control-string
:format-arguments arguments))
(defun expected (expected &key got)
(fail "expected ~A, got ~A instead" expected got))
(deftest ip-string-equal (ip desired-result)
(is (string= (periscope::ip-string ip) desired-result)))
(deftest ip-netmask-string-equal (ip netmask desired-result)
(is (string= (periscope::ip-string ip netmask) desired-result)))
(deftest ip-strings ()
(ip-string-equal #x0a000001 "10.0.0.1")
(ip-string-equal #xC0A80A0A "192.168.10.10")
(ip-string-equal #xC0A8FFFE "192.168.255.254")
(ip-netmask-string-equal #xc0a80a00 #xffffff00 "192.168.10.0/24")
(ip-netmask-string-equal #xc0a80a00 #xfffffff0 "192.168.10.0/28")
(ip-netmask-string-equal #x0a000000 #xff000000 "10.0.0.0/8")
(ip-netmask-string-equal 3322406913 4294901760 "198.7.232.1/16"))
(deftest parse-ip-equals (string expected-network expected-netmask &key expected-error junk-allowed)
(handler-case
(multiple-value-bind (network netmask)
(periscope::parse-ip-string string :junk-allowed junk-allowed)
(is (eql network expected-network))
(is (eql netmask expected-netmask)))
(parse-error (c)
(is expected-error
"Expected network ~a, netmask ~a, got ~a instead."
(periscope::ip-string expected-network) (periscope::ip-string expected-netmask) c))
(:no-error (result)
(when expected-error
(expected 'parse-error :got result)))))
(deftest parse-ip-test ()
(parse-ip-equals "192.168.10.0/24" #xc0a80a00 #xffffff00)
(parse-ip-equals "192.168.10.0" #xc0a80a00 nil)
(parse-ip-equals "198.7.232.1" #xc607e801 nil)
(parse-ip-equals "10.10.50.1000" nil nil :junk-allowed t)
(parse-ip-equals "192.168/24" nil nil :expected-error t)
(parse-ip-equals "192.168.1000.10/24" nil nil :expected-error t)
(parse-ip-equals "10.10.50.1000/24" nil nil :expected-error t)
(parse-ip-equals "10.10.50.1000/" nil nil :expected-error t)
(parse-ip-equals "10.10.50.1024/2057" nil nil :expected-error t)
(parse-ip-equals "10.10./.1024/2057" nil nil :expected-error t)
(parse-ip-equals "1.1.1.888/23" nil nil :expected-error t)
(parse-ip-equals "1.1.1.1/34" nil nil :expected-error t)
(parse-ip-equals "1.1.1.1/34" nil nil :junk-allowed t))
(deftest service-name-test ()
#+linux
(progn
(is (string-equal (periscope::service-name 22) "ssh"))
(is (string-equal (periscope::service-name 21) "ftp"))
(is (string-equal (periscope::service-name 123 :protocol :tcp) "ntp"))
(is (string-equal (periscope::service-name 123 :protocol :udp) "ntp"))
(is (string-equal (periscope::service-name 161) "snmp"))
(is (= 161 (periscope::service-name 161 :protocol periscope::+ip-proto-igmp+)))
(is (= 20570 (periscope::service-name 20570)))))
(deftest byte-string-equal (bytes desired-result &key (precision 2))
(is (string= (periscope::byte-string bytes precision) desired-result)))
(deftest byte-string-test ()
(byte-string-equal 1024 "1.00 kB")
(byte-string-equal 1023 "1,023 B")
(byte-string-equal 10240 "10.00000 kB" :precision 5)
(byte-string-equal 124125161 "118.37 MB"))
(deftest any-network-member-test (ip network-list expected-result)
(is (eq (periscope::any-network-member-p ip network-list) expected-result)))
(deftest network-member-test ()
(is (periscope::network-member-p #x0a000001 #x0a000000 #xffffff00))
(is (not (periscope::network-member-p #x0a010001 #x0a000000 #xffffff00)))
(is (not (periscope::network-member-p #x0f000001 #x0a000000 #xffffff00)))
(is (periscope::network-member-p #xc0a80a0f #xc0a80000 #xffff0000))
(let ((test-networks '((#x0a000000 . #xff000000)
(#x0a0a0000 . #xffff0000)
(#xc0a80a00 . #xffffff00))))
(any-network-member-test #x0a0000cc test-networks t)
(any-network-member-test #x0a0a000b test-networks t)
(any-network-member-test #xc0a80a01 test-networks t)
(any-network-member-test #x0b0000cc test-networks nil)
(any-network-member-test #x0c0f000b test-networks nil)
(any-network-member-test #xc0a90a01 test-networks nil)))
(deftest vlan-name-tests ()
(let ((periscope::*vlan-names* (make-hash-table)))
(is (= 100 (periscope::vlan-name 100)))
(is (= 2000 (periscope::vlan-name 2000)))
(is (string= (setf (periscope::vlan-name 400) "TEST1") "TEST1"))
(is (string= (periscope::vlan-name 400) "TEST1"))
(setf (periscope::vlan-name 400) nil)
(is (= 400 (periscope::vlan-name 400)))))
(deftest broadcast-test (ip netmask expected-result)
(is (= expected-result (periscope::broadcast-address ip netmask))))
(deftest broadcast-p-test (ip network netmask expected-result)
(is (eq expected-result (periscope::broadcast-address-p ip network netmask))))
(deftest any-broadcast-p-test (ip network-list expected-result)
(is (eq expected-result (periscope::any-broadcast-address-p ip network-list))))
(deftest broadcast-tests ()
(broadcast-test #x0a000001 #xffffff00 #x0a0000ff)
(broadcast-test #x0a123456 #xff000000 #x0affffff)
(broadcast-test #xc0987654 #xffff0000 #xc098ffff)
;; Test 'universal' broadcast address
(broadcast-p-test #xffffffff #x0a000000 #xff000000 t)
(broadcast-p-test #xffffffff #x0a0a0000 #xffff0000 t)
(broadcast-p-test #xffffffff #xc8c9ff00 #xffffff00 t)
(broadcast-p-test #x0a0000ff #x0a000000 #xffffff00 t)
;; Subnet address should be #x0a00ffff
(broadcast-p-test #x0a0000ff #x0a000000 #xffff0000 nil)
;;
(let ((test-networks '((#x0a000000 . #xff000000)
(#x0a0a0000 . #xffff0000)
(#xc0a80a00 . #xffffff00))))
(any-broadcast-p-test #x0a0000ff test-networks nil)
(any-broadcast-p-test #x0a0affff test-networks t)
(any-broadcast-p-test #xc0a80aff test-networks t)))
(deftest network-strings-test (networks expected-results)
(is (equalp expected-results (periscope::network-strings networks))))
(deftest network-strings-tests ()
(network-strings-test '((#x0a000000 . #xff000000)
(#x0a0a0000 . #xffff0000)
(#xc0a80a00 . #xffffff00))
'("10.0.0.0/8" "10.10.0.0/16" "192.168.10.0/24"))
(network-strings-test '((3322406913 . 4294901760)
(#xc0a8ff00 . #xffffff00))
'("198.7.232.1/16" "192.168.255.0/24")))
(deftest vlan-string-test (vlan-string expected-result &key expected-error)
(if expected-error
(signals parse-error (periscope::vlans-from-string vlan-string))
(let ((result (periscope::vlans-from-string vlan-string)))
(is (equalp result expected-result)))))
(deftest vlan-string-tests ()
(vlan-string-test "100 200 300 400" (list 100 200 300 400))
(vlan-string-test "100 200 400 300" (list 100 200 300 400))
(vlan-string-test "100 100, 100 100" (list 100))
(vlan-string-test "12400 100, 100, 100" nil :expected-error t)
;; Bad VLAN ID (> 4095)
(vlan-string-test "12400, 100, 100, 100" nil :expected-error t)
;; Junk
(vlan-string-test "1200, 12asdasg, 200" nil :expected-error t)
(vlan-string-test "1200, 12asdasg, 200" nil :expected-error t))
(deftest subnet-string-test (subnet-string expected-result &key expected-error)
(if expected-error
(signals parse-error (periscope::subnets-from-string subnet-string))
(let ((result (periscope::subnets-from-string subnet-string)))
(is (equalp result expected-result)))))
(deftest subnet-string-tests ()
(subnet-string-test "192.168.10.0/24" '((#xC0A80A00 . #xFFFFFF00)))
(subnet-string-test "10.0.0.0/8 192.168.10.0/24"
'((#x0A000000 . #xFF000000) (#xC0A80A00 . #xFFFFFF00)))
(subnet-string-test "192.168.10.0/" nil :expected-error t)
(subnet-string-test "192.168.0.0/120" nil :expected-error t)
(subnet-string-test "198.7.0.0/16, 192.168.10.0/24, 10.0.0.0/24"
'((#xC6070000 . #xFFFF0000) (#xC0A80A00 . #xFFFFFF00) (#xA000000 . #xFFFFFF00))
:expected-error nil)
(subnet-string-test "198.7.0.0/16, 192.168.10.0/24, 10.0.0.0/240" nil :expected-error t)
(subnet-string-test "198.7.0.400/16, 192.168.10.0/24, 10.0.0.0/24" nil :expected-error t)
(subnet-string-test "1aldgajha, asdfa1231, 99ar9gag" nil :expected-error t)
(subnet-string-test "10.0.0.8/25, asdfa1231, 99ar9gag" nil :expected-error t))
(deftest execute-command-test (expected-code-predicate command)
;; No implementation other than SBCL yet...
#+sbcl
(multiple-value-bind (code pid status)
(periscope::process-wait (periscope::process-create command nil))
(is (plusp pid))
(is (eq :exited status))
(is (funcall expected-code-predicate code))))
(deftest execute-command-tests ()
;; These return codes might be different in other *nixes... best be safe for now.
#+linux
(progn
(execute-command-test #'zerop "ls")
(execute-command-test #'plusp "asdfasdfa")
(execute-command-test #'plusp "grep")))
(defsuite* time-tests)
(defmacro time-is (form time time2)
`(is ,form "Failed with times ~a -> ~a~%"
(local-time:universal-to-timestamp ,time)
(local-time:universal-to-timestamp ,time2)))
(deftest half-hour-test ()
(flet ((half-hour (time) (periscope::next-half-hour time)))
(loop :for time = (half-hour (get-universal-time)) :then (half-hour time) :repeat 1000
:for time2 = (half-hour time) :then (half-hour time) :do
(time-is (= 1800 (abs (- time time2))) time time2))))
(deftest hour-test ()
(flet ((hour (time) (periscope::next-hour time)))
(loop :for time = (hour (get-universal-time)) :then (hour time) :repeat 1000
:for time2 = (hour time) :then (hour time) :do
(time-is (= 3600 (abs (- time time2))) time time2))))
(deftest day-test ()
(flet ((day (time) (periscope::next-day time)))
(loop :for time = (day (get-universal-time)) :then (day time) :repeat 1000
:for time2 = (day time) :then (day time) :do
(multiple-value-bind (sec min hour date month year) (decode-universal-time time)
(multiple-value-bind (sec2 min2 hour2 date2 month2 year2) (decode-universal-time time2)
;; This conditional makes little babies cry.
(time-is
(and (= 0 sec sec2 min min2 hour hour2)
(or (and (= (1+ date) date2) (= month month2) (= year year2))
(and (= 1 date2) (= (1+ month) month2)
(or (= year year2) (= (1+ year) year2)))
(and (= 12 month) (= 1 month2))))
time time2))))))
(deftest week-test ()
(flet ((week (time) (periscope::next-week time)))
(loop :for time = (week (get-universal-time)) :then (week time) :repeat 1000
:for time2 = (week time) :then (week time) :do
(multiple-value-bind (sec min hour date month year day) (decode-universal-time time)
(multiple-value-bind (sec2 min2 hour2 date2 month2 year2 day2) (decode-universal-time time2)
(time-is
(and (= 0 sec sec2 min min2 hour hour2)
(= 6 day day2)
(or (> date2 date)
(= (1+ month) month2)
(= (1+ year) year2)))
time time2))))))
(deftest month-test ()
(flet ((month (time) (periscope::next-month time)))
(loop :for time = (month (get-universal-time)) :then (month time) :repeat 1000
:for time2 = (month time) :then (month time) :do
(multiple-value-bind (sec min hour date month year) (decode-universal-time time)
(multiple-value-bind (sec2 min2 hour2 date2 month2 year2) (decode-universal-time time2)
(time-is
(and (= 0 sec sec2 min min2 hour hour2)
(= 1 date date2)
(or (= (1+ month) month2)
(and (= 12 month) (= 1 month2) (= (1+ year) year2))))
time time2)))))) | 12,067 | Common Lisp | .lisp | 236 | 47.016949 | 100 | 0.686673 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 4d7042fe3567153a08b17d1c8e70fe2f1fe32d824fb97d519d2b3cc904389a8f | 18,640 | [
-1
] |
18,641 | periodic-report.lisp | hbock_periscope/lisp/periodic-report.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defvar *periodic-report-format-version* 0
"Current version of the PERIOD-REPORT file/class format. Used to ensure older report formats
are processed correctly, or a proper error is signalled when a report format is no longer
supported.")
(defclass periodic-report (report)
((total :accessor total :type stats)
(internal :accessor internal :type stats :initform (make-instance 'stats))
(external :accessor external :type stats :initform (make-instance 'stats))
(incoming :accessor incoming :type stats :initform (make-instance 'stats))
(outgoing :accessor outgoing :type stats :initform (make-instance 'stats))
(host-stats :initform (make-hash-table :size 1000))
(format-version :initarg :version :initform *periodic-report-format-version*)
(filter :initarg :filter :reader filter :initform nil :type filter)
(report-time :initarg :time :reader report-time :initform (now))))
(defclass host-stats ()
((ip :initarg :ip :accessor host-ip :initform (error "Must provide IP!"))
(total :accessor total :type stats)
(sending :accessor sending :type stats :initform (make-instance 'stats))
(receiving :accessor receiving :type stats :initform (make-instance 'stats))
(local-contacts :initform (make-hash-table))
(remote-contacts :initform (make-hash-table))))
(defmethod add-host-stats ((table hash-table) (host flow-host) (other flow-host))
(multiple-value-bind (host-stat existsp)
(gethash (host-ip host) table (make-instance 'host-stats :ip (host-ip host)))
(with-slots (sending receiving local-contacts remote-contacts) host-stat
(let ((other-ip (host-ip other)))
(incf (gethash other-ip (if (remote-host-p other-ip) remote-contacts local-contacts) 0)))
(add-stats sending :bytes (host-bytes host) :packets (host-packets host))
(add-stats receiving :bytes (host-bytes other) :packets (host-packets other)))
(unless existsp
(setf (gethash (host-ip host) table) host-stat))))
(defmethod initialize-instance :after ((object periodic-report) &key (flow-list nil flow-list-p))
;; Report is pre-generated, loaded from a file.
(unless flow-list-p
(return-from initialize-instance nil))
(with-slots (total internal external incoming outgoing host-stats format-version) object
(setf format-version *periodic-report-format-version*)
(setf (total object)
(make-instance 'stats
:flows (length flow-list)
:packets
(reduce #'+ flow-list
:key (lambda (flow)
(+ (host-packets (source flow)) (host-packets (dest flow)))))
:bytes
(reduce #'+ flow-list
:key (lambda (flow)
(+ (host-bytes (source flow)) (host-bytes (dest flow)))))))
(dolist (flow flow-list)
(with-slots (source dest) flow
(let ((bytes (+ (host-bytes source) (host-bytes dest)))
(packets (+ (host-packets source) (host-packets dest))))
(case (classify flow)
(:internal-only (add-stats internal :bytes bytes :packets packets))
(:external-only (add-stats external :bytes bytes :packets packets))
(:incoming (add-stats incoming :bytes bytes :packets packets))
(:outgoing (add-stats outgoing :bytes bytes :packets packets)))
(add-host-stats host-stats source dest)
(add-host-stats host-stats dest source))))))
(defmethod local-contact-count ((host host-stats))
(hash-table-count (slot-value host 'local-contacts)))
(defmethod remote-contact-count ((host host-stats))
(hash-table-count (slot-value host 'remote-contacts)))
(defmethod hosts-collect-if ((object periodic-report) predicate)
(with-slots (host-stats) object
(loop :for host-ip :being :the :hash-keys :in host-stats :using (:hash-value stats)
:when (funcall predicate host-ip)
:collect stats)))
(defmethod remote-hosts ((object periodic-report))
(hosts-collect-if object #'remote-host-p))
(defmethod local-hosts ((object periodic-report))
(hosts-collect-if object #'local-host-p))
(defun busiest-hosts (stat-list)
(sort stat-list #'> :key (lambda (stats)
(+ (bytes (receiving stats)) (bytes (sending stats))))))
(defmethod incoming-scan-hosts ((report periodic-report))
(sort (remove-if #'zerop (remote-hosts report) :key #'local-contact-count)
#'> :key #'local-contact-count))
(defmethod outgoing-scan-hosts ((report periodic-report))
(sort (remove-if #'zerop (local-hosts report) :key #'remote-contact-count)
#'> :key #'remote-contact-count))
(defun print-scan-hosts (title host-type list &key key)
(with-html-output (*standard-output*)
(:table
(:tr (:th :colspan 4 (str title)))
(:tr (:th "Host") (:th "Hostname") (:th (fmt "~a Hosts Contacted" host-type)))
(loop :with row-switch = t
:for host :in list :repeat 15 :do
(htm
(:tr
:class (if row-switch "rowa" "rowb")
(:td (str (ip-string (host-ip host))))
(:td (str (hostname (host-ip host))))
(:td (str (funcall key host)))))
(setf row-switch (not row-switch))))))
(defun print-busiest-hosts (title list)
(with-html-output (*standard-output*)
(:table
(:tr (:th :colspan 9 (str title)))
(:tr (:th) (:th)
(:th :colspan 2 "Sending")
(:th :colspan 2 "Receiving")
(:th :colspan 3 "Total"))
(:tr (:th "Host") (:th "Hostname")
(:th "Packets") (:th "Bytes")
(:th "Packets") (:th "Bytes")
(:th "Packets") (:th "Bytes") (:th "Flows"))
(loop :with row-switch = t
:for host :in list :repeat 15 :do
(htm
(:tr
:class (if row-switch "rowa" "rowb")
(:td (str (ip-string (host-ip host))))
(:td (str (hostname (host-ip host))))
(print-html (receiving host) :with-row nil :flows nil)
(print-html (sending host) :with-row nil :flows nil)
(print-html (combine-stats (receiving host) (sending host)) :with-row nil)))
(setf row-switch (not row-switch))))))
(defmethod object-forms ((object stats))
(with-slots (flows bytes packets) object
`(make-instance 'stats :flows ,flows :bytes ,bytes :packets ,packets)))
(defmethod object-forms ((report periodic-report))
(with-slots (total internal external incoming outgoing) report
`(let ((report (make-instance 'periodic-report
:time ,(report-time report)
:version ,(report-format-version report))))
(with-slots (total internal external incoming outgoing) report
(setf total ,(object-forms total))
(setf internal ,(object-forms internal))
(setf external ,(object-forms external))
(setf incoming ,(object-forms incoming))
(setf outgoing ,(object-forms incoming)))
report)))
(defmethod print-object ((report periodic-report) stream)
(print-unreadable-object (report stream :type t :identity t)
(format stream "~:[~;~:*Filter ~S, ~]version ~d"
(when (filter report) (filter-title (filter report)))
(report-format-version report))))
(defmethod save-report ((object report))
(with-open-file (stream (in-report-directory (format nil "report-~d" (report-time object)))
:direction :output :if-does-not-exist :create :if-exists :supersede)
(format stream "~S" (object-forms object))))
(defmethod load-report (file)
(with-open-file (stream file :direction :input)
(eval (read stream))))
(defmethod print-html ((report periodic-report) &key title)
(with-html-output (*standard-output*)
(:h3 "General Statistics")
(with-slots (host-stats) report
(fmt "Report generated at ~a" (iso8661-date-string (generation-time report))))
(cond
((zerop (flows (total report)))
(htm (:b "No flows matched this filter.")))
(t
(htm
(:table
(:tr (:th "") (:th "Packets") (:th "Bytes") (:th "Flows"))
(print-html (internal report) :title "Internal Only")
(print-html (external report) :title "External Only")
(print-html (incoming report) :title "Incoming")
(print-html (outgoing report) :title "Outgoing")
(print-html (total report) :title "Total")))
(print-scan-hosts "Possible Incoming Scan Hosts" "Local"
(incoming-scan-hosts report) :key #'local-contact-count)
(print-scan-hosts "Possible Outgoing Scan Hosts" "Remote"
(outgoing-scan-hosts report) :key #'remote-contact-count)
(print-busiest-hosts "Busiest Local Hosts" (busiest-hosts (local-hosts report)))
(print-busiest-hosts "Busiest Remote Hosts" (busiest-hosts (remote-hosts report)))))))
(defun combine-stats (&rest stats)
(make-instance 'stats
:flows (flows (first stats));(reduce #'+ stats :key #'flows)
:bytes (reduce #'+ stats :key #'bytes)
:packets (reduce #'+ stats :key #'packets)))
(defun make-periodic-report (flow-list &optional filter)
(make-instance 'periodic-report :flow-list flow-list :filter filter))
| 9,475 | Common Lisp | .lisp | 190 | 45.857895 | 97 | 0.694712 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | fe574a45e72893f554566ce89ff102d29dece2d87093f80f628e35005e8b54a6 | 18,641 | [
-1
] |
18,642 | web-index.lisp | hbock_periscope/lisp/web-index.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(hunchentoot:define-easy-handler (index :uri "/") ()
(with-periscope-page ("Home")
(:h2 "Periscope Start Page")
(warning-box
"This is pre-release software. Use at your own risk! "
"Keep up-to-date with the latest releases "
(:a :href "http://nautilus.oshean.org/wiki/Periscope" :target "_blank" "here."))
(:br)
(:table
(:tr
(:td
:valign "top"
(:b "View Traffic Reports")
(:ul
(:li (:a :href "/hourly" "Hourly traffic reports")
(let ((last (last-hourly-log)))
(when last
(htm
"[Last: "
(:a :href (format nil "/hourly?time=~d" (car last))
(str (date-string (universal-to-timestamp (car last)) :minutes t)))
"]"))))
(:li "Daily traffic reports")
(:li "Weekly traffic reports")))
(when (login-available-p)
(htm
(:td
:valign "top"
(:b (if (valid-session-p)
(fmt "User Session (Logged in as ~a)" (display-name (user)))
(str "User Session")))
(if (valid-session-p)
(let ((user (user)))
(htm
(:ul (:li
(:a :href "/do-login?action=logout" "Log out of Periscope"))
(when (admin-p user)
(htm (:li (:a :href (format nil "/edit-user?user=~a" (username user))
(fmt "Modify your account"))))))))
(htm
(:ul
(:li (:a :href "/login" "Login to Periscope")))))))))
(:tr
(when (configure-p)
(htm
(:td
:valign "top"
(:b "Configure Periscope")
(:ul
(:li (:a :href "/periscope-config" "Manage Periscope settings"))
(:li (:a :href "/network-config" "Default network settings"))
(:li (:a :href "/users" "Manage user logins and filters"))
(when *web-show-diag*
(htm (:li (:a :href "/uuddlrlrbastart" "Diagnose problems with
Periscope internals"))))))))
))))
(hunchentoot:define-easy-handler (about :uri "/about") ()
(with-periscope-page ("About Periscope")
(:h2 "About Periscope")
(:p (:b "Periscope")
"is a network conversation monitor inspired by the popular free-software project "
(:a :href "http://ipaudit.sourceforge.net" "IPAudit.")
"Periscope is written in C and Common Lisp. It is designed to be an integral part of OSHEAN's "
(:a :href "http://nautilus.oshean.org/" "Nautilus")
" system. Periscope monitors, logs, and analyzes network activity according to flows.")
(:p "Periscope is built on top of the" (:a :href "http://qosient.com/argus" "Argus")
"real-time flow monitor, developed by Carter Bullard of QoSient, LLC.")
(:p "Periscope is " (:i "free software;") "it is licensed under the GNU GPLv2, and is free to study, modify, and "
"redistribute. For more information, please visit the "
(:a :href "http://nautilus.oshean.org/wiki/Periscope" "Nautilus wiki") "page on Periscope."
(:p
(:h3 "Core Developers")
(:ul
(:li "Harry Bock (OSHEAN)"))
(:h3 "Special Thanks")
(:ul
(:li "Carter Bullard (QoSient, LLC)"))))))
(defun web-default ()
(with-periscope-page ("Page not found")
(:h2 "Requested page not found!") (:br)
(:p (:i "I'm sorry, Dave. I'm afraid I can't do that."))))
(setf hunchentoot:*default-handler* #'web-default) | 4,053 | Common Lisp | .lisp | 97 | 37.041237 | 118 | 0.640791 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | dba01d3bd9b9216d79c0d53dbaeb3078bc4958b6393b47ebe1d8886e66ea4e45 | 18,642 | [
-1
] |
18,643 | flow.lisp | hbock_periscope/lisp/flow.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defclass flow ()
((source :initarg :source :reader source)
(dest :initarg :dest :reader dest)
(protocol :initarg :protocol :reader protocol :initform (error "Must supply IP protocol!"))))
(defclass flow-host ()
((ip :initarg :ip :reader host-ip :initform (error "Must supply IP addresss!"))
(port :initarg :port :reader host-port :type port-number)
(packets :initarg :packets :reader host-packets)
(bytes :initarg :bytes :reader host-bytes)
(vlan :accessor host-vlan :type vlan-id :initform +vlan-none+)
(start-time :reader start-time :type local-time:timestamp)
(end-time :reader end-time :type local-time:timestamp)))
(defmethod start-time ((object flow))
(local-time:timestamp-minimum
(start-time (source object)) (start-time (dest object))))
(defmethod end-time ((object flow))
(local-time:timestamp-maximum
(end-time (source object)) (end-time (dest object))))
(defun build-flow (dsrs ip)
"Create a FLOW object given a set of Argus DSRs and an ArgusIPFlow structure."
(with-foreign-slots ((ip-src ip-dst ip-proto source-port dest-port) ip argus-ip-flow)
(let* ((source (make-instance 'flow-host :ip ip-src :port source-port))
(dest (make-instance 'flow-host :ip ip-dst :port dest-port))
(flow (make-instance 'flow :source source :dest dest :protocol ip-proto)))
(with-slots (packets bytes start-time end-time) source
(multiple-value-setq (packets bytes) (source-metrics dsrs))
(multiple-value-setq (start-time end-time) (source-time dsrs)))
(with-slots (packets bytes start-time end-time) dest
(multiple-value-setq (packets bytes) (dest-metrics dsrs))
(multiple-value-setq (start-time end-time) (dest-time dsrs)))
(unless (null-pointer-p (get-vlan dsrs))
(with-foreign-slots ((sid did) (get-vlan dsrs) argus-vlan)
(setf (host-vlan source) (logand sid +vlan-vid-mask+)
(host-vlan dest) (logand did +vlan-vid-mask+))))
flow)))
(defmethod classify ((object flow) &key (networks *internal-networks*))
(with-slots (source dest) object
(cond
((or (any-broadcast-address-p (host-ip source) networks)
(any-broadcast-address-p (host-ip dest) networks))
:internal-only)
((any-network-member-p (host-ip source) networks)
(if (any-network-member-p (host-ip dest) networks)
:internal-only
:outgoing))
((any-network-member-p (host-ip dest) networks)
:incoming)
(t :external-only))))
(let ((row-switch t))
(defmethod print-html ((object flow) &key)
(flet ((print-host (host)
(with-html-output (*standard-output*)
(:td (str (hostname (host-ip host))))
(:td (fmt "~d" (service-name (host-port host))))
(:td (fmt "~:d" (host-packets host)))
(:td (str (if (= +vlan-none+ (host-vlan host)) "" (vlan-name (host-vlan host))))))))
(setf row-switch (not row-switch))
(with-slots (source dest protocol) object
(with-html-output (*standard-output*)
(:tr :class (if row-switch "rowa" "rowb")
(print-host source)
(print-host dest)
(:td (str (case protocol
(#.+ip-proto-icmp+ "ICMP")
(#.+ip-proto-igmp+ "IGMP")
(#.+ip-proto-tcp+ "TCP")
(#.+ip-proto-udp+ "UDP"))))
(:td (str (iso8661-date-string (start-time object))))
(:td (str (iso8661-date-string (end-time object)))))))))) | 4,247 | Common Lisp | .lisp | 84 | 45.904762 | 96 | 0.678286 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 9917282c3d563c48d1c9356d0ffccd2e732523a8cd1edcb3040bcc9a00cbac09 | 18,643 | [
-1
] |
18,644 | packages.lisp | hbock_periscope/lisp/packages.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :cl-user)
(defpackage :periscope
(:use #:common-lisp #:cffi #:cl-who #:local-time)
(:import-from #:hunchentoot
#:url-encode
#:define-easy-handler
#:session-value
#:delete-session-value))
(in-package :periscope)
(declaim (optimize (debug 3) (speed 1))) | 1,133 | Common Lisp | .lisp | 24 | 45.458333 | 79 | 0.734361 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6efc2c6ad72df24d49dff2206cd47ec005d2984a83245c31fe51d3c71a616fc3 | 18,644 | [
-1
] |
18,645 | reports.lisp | hbock_periscope/lisp/reports.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(defclass report ()
((generated :reader generation-time :initform (now))
(format-version :reader report-format-version)))
(defclass stats ()
((flows :initarg :flows :accessor flows :initform 0)
(bytes :initarg :bytes :accessor bytes :initform 0)
(packets :initarg :packets :accessor packets :initform 0)))
(defmethod add-stats ((object stats) &key (flows 1) (bytes 0) (packets 0))
(incf (flows object) flows)
(incf (bytes object) bytes)
(incf (packets object) packets))
(defmethod print-html ((object stats) &key (title "General Stats") (with-row t) (flows t))
(with-html-output (*standard-output*)
(if with-row
(htm
(:tr (:th (str title))
(:td (fmt "~:d" (packets object)))
(:td (str (byte-string (bytes object))))
(:td (fmt "~:d" (flows object)))))
(htm
(:td (fmt "~:d" (packets object)))
(:td (str (byte-string (bytes object))))
(when flows
(htm (:td (fmt "~:d" (flows object)))))))))
(defgeneric print-html (object &key)
(:documentation "Print a report object in HTML format."))
(defun report-handlers (request)
"Handle Periscope-specific report requests. Returns the report's handler function as
defined using DEFINE-REPORT-HANDLER."
(loop :for (symbol uri desc handler) :in *report-handler-list*
:when (string-equal (hunchentoot:script-name request) uri)
:do (return handler)))
(defmacro define-report-handler ((type uri description) lambda-list &body body)
"Define a Periscope report page as if by DEFUN."
`(prog1
(defun ,type (&key ,@(loop :for part :in lambda-list :collect
(hunchentoot::make-defun-parameter part 'string :get)))
,@body)
(setf *report-handler-list*
(delete-if (lambda (report)
(or (eql (first report) (quote ,type))
(string-equal (second report) ,uri)))
*report-handler-list*))
(unless (find #'report-handlers hunchentoot:*dispatch-table*)
(push #'report-handlers hunchentoot:*dispatch-table*))
(push (list (quote ,type) ,uri ,description (function ,type)) *report-handler-list*)))
| 2,939 | Common Lisp | .lisp | 61 | 44.622951 | 91 | 0.696684 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | bfe4b1294d916995adacef15bbf0e43ec6d6612e5f097c6a94a1d4833c396315 | 18,645 | [
-1
] |
18,646 | test.lisp | hbock_periscope/lisp/test.lisp | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :periscope)
(define-report-handler (split-test "/time-split" "Time Split Test") ()
(with-periscope-page ("TIME-SPLIT test")
(when *flow-list*
(let* ((time-list
(time-split *flow-list* #'next-hour))
(reports
(mapcar
(lambda (list)
(make-instance 'periodic-report :flow-list list :time
(this-hour (end-time (first list)))))
time-list)))
(htm
(:div
:class "stats"
(loop
for i from 0 upto (min 5 (length time-list))
for report in reports do
(print-html report)
(htm
(:table
(:tr (:th :colspan 4 "Source") (:th :colspan 4 "Destination")
(:th :colspan 3 "Flow information"))
(:tr (:th "IP") (:th "Port") (:th "Packets") (:th "VLAN")
(:th "IP") (:th "Port") (:th "Packets") (:th "VLAN")
(:th "Protocol") (:th "First Seen") (:th "Last Seen"))
(loop :for flow :in (nth i time-list) :repeat 100 :do
(print-html flow)))))))))))
(define-report-handler (test "/vlan-test" "VLAN Filter Test") ()
(with-periscope-page ("VLAN Filter Test")
(:h2 "VLAN Filter Test")
(when *flow-list*
(htm
(:div
:class "stats"
(loop :for report :in (make-filtered-reports *flow-list* (user))
:do (print-html report)))))))
(defun print-flows (flow-list &optional (limit 100))
(with-html-output (*standard-output*)
(:table
(:tr (:th :colspan 4 "Source")
(:th :colspan 4 "Destination")
(:th :colspan 3 "Flow information"))
(:tr (:th "IP") (:th "Port") (:th "Packets") (:th "VLAN")
(:th "IP") (:th "Port") (:th "Packets") (:th "VLAN")
(:th "Protocol") (:th "First Seen") (:th "Last Seen"))
(loop :for flow :in flow-list :repeat limit :do
(print-html flow))))) | 2,595 | Common Lisp | .lisp | 62 | 37.467742 | 79 | 0.63514 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 5bd7698a4a67252d5b76a89ba0057341cc420bbcc3cfda40b9a7bae5d6be8d24 | 18,646 | [
-1
] |
18,647 | build.lisp | hbock_periscope/lisp/build.lisp | (require 'asdf)
(require 'periscope)
(defun build-periscope ()
#+sbcl (sb-ext:save-lisp-and-die "periscope" :toplevel #'periscope::main :executable t
:save-runtime-options t)
#-sbcl (error "Cannot build stand-alone binary on this system!")
t) | 256 | Common Lisp | .lisp | 7 | 33.714286 | 88 | 0.714859 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 0e149b1b30befa5bc97f0626fc907df1877dc18ba015bf17a12eb3a113903a38 | 18,647 | [
-1
] |
18,648 | periscope.asd | hbock_periscope/lisp/periscope.asd | ;;;; Periscope - Network auditing tool
;;;; Copyright (C) 2009 Harry Bock <[email protected]>
;;;; This file is part of Periscope.
;;;; periscope 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 2 of the License, or
;;;; (at your option) any later version.
;;;; periscope 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 periscope; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(in-package :cl-user)
(asdf:defsystem periscope
:name "Periscope"
:author "Harry Bock <[email protected]>"
:version "0.10.0-pre-alpha"
:description "Network auditing tool"
:depends-on (:cffi
:cl-fad
:cl-who
:cl-ppcre
:md5
:local-time
:hunchentoot
:trivial-garbage
:bordeaux-threads)
:serial t
:components
((:file "packages")
(:file "specials")
(:file "conditions")
(:file "config")
;; Foreign function interface for libperiscope/Argus
(:file "periscope-cffi")
(:file "argus-cffi")
(:file "collector")
(:file "utility")
(:file "dns")
;; Central classes
(:file "reports")
(:file "flow")
(:file "filter")
(:file "time")
;; Web interface
(:file "web")
(:file "web-index")
(:file "web-config")
(:file "web-utility")
(:file "diagnostics")
(:file "users")
;; Reports
(:file "periodic-report")
(:file "service")
(:file "report-handlers")
;; Entry point(s?)
(:file "main"))) | 1,881 | Common Lisp | .asd | 59 | 28.084746 | 79 | 0.665017 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 6c2c57de582e1806016c2444d0299c7572c473129b724a06058db298a2408895 | 18,648 | [
-1
] |
18,650 | common-Makefile.in.patch | hbock_periscope/common-Makefile.in.patch | --- common/Makefile.in 2009-03-02 16:20:03.000000000 -0500
+++ ../../development/argus-periscope/common/Makefile.in 2009-05-29 19:15:39.342323093 -0400
@@ -42,6 +42,8 @@
srcdir = @srcdir@
VPATH = @srcdir@
+COMPATLIB = @COMPATLIB@ @LIB_SASL@ @LIBS@ @V_THREADS@ @V_GEOIPDEP@
+
#
# You shouldn't need to edit anything below.
#
@@ -72,6 +74,11 @@
@rm -f $@
$(CC) $(CFLAGS) -c $(srcdir)/$*.c
+# libtool compilation
+%.lo : %.c
+ @rm -f $@
+ libtool --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$<
+
# We would like to say "OBJ = $(SRC:.c=.o)" but Ultrix's make cannot
# hack the extra indirection
@@ -87,6 +94,7 @@
TAGFILES = $(SRC) $(HDR) $(TAGHDR)
LIBS = @INSTALL_LIB@/argus_parse.a @INSTALL_LIB@/argus_common.a @INSTALL_LIB@/argus_client.a @INSTALL_LIB@/argus_event.a
+SOLIBS = @INSTALL_LIB@/libargus_client.la
OBJ = $(COMMONOBJ) $(PARSEOBJ) $(CLIENTOBJ) $(EVENTOBJ)
CLEANFILES = $(LIBS) $(OBJ) $(GENSRC) $(GENHDR) $(VSRC) lex.yy.c
@@ -100,6 +108,7 @@
CLIENTSRC = argus_client.c argus_label.c argus_grep.c
CLIENTOBJ = argus_client.o argus_label.o argus_grep.o
+CLIENTSO = $(COMMONOBJ:.o=.lo) $(CLIENTOBJ:.o=.lo)
EVENTSRC = argus_event.c
EVENTOBJ = argus_event.o
@@ -107,7 +116,11 @@
SRC = $(COMMONSRC) $(PARSESRC) $(CLIENTSRC) $(EVENTSRC)
-all: $(LIBS)
+all: $(LIBS) $(SOLIBS)
+
+@INSTALL_LIB@/libargus_client.la: $(CLIENTSO)
+ rm -f $@
+ libtool --mode=link $(CC) $(CCOPT) -o $@ -rpath $(DESTDIR)$(LIBDEST) $(CLIENTSO) $(COMPATLIB)
@INSTALL_LIB@/argus_common.a: $(COMMONOBJ)
rm -f $@; ar qc $@ $(COMMONOBJ)
| 1,552 | Common Lisp | .l | 42 | 34.904762 | 121 | 0.647651 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | e55345484044f1ecca1eebce6b019f214605fc1c885f0ccb95f5d967252c386b | 18,650 | [
-1
] |
18,651 | Makefile.in | hbock_periscope/Makefile.in | #
# Argus Software
# Copyright (c) 2000-2008 QoSient, LLC
# All rights reserved.
#
# This program 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 2, or (at your option)
# any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
# Various configurable paths (remember to edit Makefile.in, not Makefile)
#
# Top level hierarchy
prefix = @prefix@
exec_prefix = @exec_prefix@
datarootdir = @datarootdir@
# Pathname of install directory
DESTDIR = @prefix@
# Pathname of directory to install the system binaries
SBINDIR = @sbindir@
# Pathname of directory to install the system binaries
BINDIR = @bindir@
# Pathname of directory to install the include files
INCLDEST = @includedir@
# Pathname of directory to install the library
LIBDEST = @libdir@
# Pathname of directory to install the man page
MANDEST = @mandir@
# VPATH
srcdir = @srcdir@
VPATH = @srcdir@
#
# You shouldn't need to edit anything below.
#
CC = @CC@
CCOPT = @V_CCOPT@
INCLS = @INCLS@ -I. -I../include -I../common @V_INCLS@ @MYSQL_INCLS@
DEFS = @DEFS@
COMPATLIB = @COMPATLIB@ @LIB_SASL@ @LIBS@ @V_THREADS@ @V_GEOIPDEP@
MYSQLLIB = @MYSQL_LDFLAGS@
CURSESLIB = @CURSESLIB@ @V_READLINE@
# Standard CFLAGS
CFLAGS = $(CCOPT) $(INCLS) $(DEFS) -Wall -g
INSTALL = @INSTALL@
RANLIB = @V_RANLIB@
#
# Flex and bison allow you to specify the prefixes of the global symbols
# used by the generated parser. This allows programs to use lex/yacc
# and link against libpcap. If you don't have flex or bison, get them.
#
LEX = @V_LEX@
YACC = @V_YACC@
# Explicitly define compilation rule since SunOS 4's make doesn't like gcc.
# Also, gcc does not remove the .o before forking 'as', which can be a
# problem if you don't own the file but can write to the directory.
%.lo: %.c
libtool --mode=compile $(CC) $(CFLAGS) -c $(srcdir)/$<
.c.o:
@rm -f $@
$(CC) $(CFLAGS) -c $(srcdir)/$*.c
LIB = @INSTALL_LIB@/libargus_client.la
SRC = periscope-argus.c periscope.c
PROGS = @INSTALL_BIN@/periscope-test
OBJ = $(SRC:.c=.lo)
all: $(PROGS)
@INSTALL_BIN@/periscope-test: $(OBJ) $(LIB) periscope-test.c
libtool --tag=disable-static --mode=link $(CC) $(CCOPT) -o libperiscope.la -rpath \
$(LIBDEST) $(OBJ) $(LIB) $(COMPATLIB)
libtool --mode=link $(CC) $(CFLAGS) $(CCOPT) -o $@ periscope-test.c libperiscope.la
# We would like to say "OBJ = $(SRC:.c=.o)" but Ultrix's make cannot
# hack the extra indirection
CLEANFILES = $(OBJ) $(PROGS) libperiscope.la
install: force all
[ -d $(DESTDIR) ] || \
(mkdir -p $(DESTDIR); chmod 755 $(DESTDIR))
[ -d $(BINDIR) ] || \
(mkdir -p $(BINDIR); chmod 755 $(BINDIR))
libtool --mode=install $(INSTALL) $(srcdir)/../bin/periscope-test $(BINDIR)
libtool --mode=install $(INSTALL) libperiscope.la $(LIBDEST)/libperiscope.la
clean:
rm -f $(CLEANFILES)
distclean:
rm -f $(CLEANFILES) Makefile
tags: $(TAGFILES)
ctags -wtd $(TAGFILES)
force: /tmp
depend: $(GENSRC) force
../bin/mkdep -c $(CC) $(DEFS) $(INCLS) $(SRC)
| 3,465 | Common Lisp | .l | 98 | 33.867347 | 84 | 0.720359 | hbock/periscope | 3 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:27:44 AM (Europe/Amsterdam) | 7f595293840dde7acaa22c2ff0837c0af1cd9104b95ed7fcdad334e6f4df708a | 18,651 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.