;;AUTODOC: quote-string-for-regexp "quote regular expression special chars"
;;(quote-string-for-regexp string [:crlf t])
;;
;;takes a string and returns a copy with all characters having a special
;;signification for regular expressions quoted
;;chars are: ? * | + . ^ $ \ [ ] ( )
;;chars are quoted by including them in square brackets []
;;except ^ which must be quoted as \^
;;e.g.: "*foo*" ==> "[*]foo[*]"
;;
;;If :crlf is true, newlines are expressed as \r?\n to match newlines in unix
;;or MSDOS style

;;AUTOLOAD: quote-string-for-regexp

(defun quote-string-for-regexp (s &key crlf &aux
    (l (coerce s List))
    (res (list))
    c
  )
  (if crlf
    (dolist (c l)
      (if 
	(seek '(#\? #\* #\| #\+ #\. #\$ #\\ #\[ #\] #\( #\) ) c)
	(nconc res (list #\[ c #\] ))

	(= #\^ c) 
	(nconc res [#\\ #\^ ])

	(= 13 c) ()			;skips \r

	(= #\newline c)			;newline is \r?\n
	(nconc res [ 13 #\? #\newline ])
	
	(put res -1 c)
    ))
    (dolist (c l)
      (if 
	(seek '(#\? #\* #\| #\+ #\. #\$ #\\ #\[ #\] #\( #\) ) c) 
	(nconc res (list #\[ c #\] ))

	(= #\^ c) 
	(nconc res [#\\ #\^ ])
	
	(put res -1 c)
    ))
  )
  (coerce res String)
)
  
